hash
stringlengths
64
64
content
stringlengths
0
1.51M
f541eb26b2033e101c36daab0dca97226f59f8287af56fe02863817c329dbaba
"""Prime ideals in number fields. """ from sympy.polys.polytools import Poly from sympy.polys.domains.finitefield import FF from sympy.polys.domains.rationalfield import QQ from sympy.polys.domains.integerring import ZZ from sympy.polys.matrices.domainmatrix import DomainMatrix from sympy.polys.polyerrors import CoercionFailed from sympy.polys.polyutils import IntegerPowerable from sympy.utilities.decorator import public from .basis import round_two, nilradical_mod_p from .exceptions import StructureError from .modules import ModuleEndomorphism, find_min_poly from .utilities import coeff_search, supplement_a_subspace def _check_formal_conditions_for_maximal_order(submodule): r""" Several functions in this module accept an argument which is to be a :py:class:`~.Submodule` representing the maximal order in a number field, such as returned by the :py:func:`~sympy.polys.numberfields.basis.round_two` algorithm. We do not attempt to check that the given ``Submodule`` actually represents a maximal order, but we do check a basic set of formal conditions that the ``Submodule`` must satisfy, at a minimum. The purpose is to catch an obviously ill-formed argument. """ prefix = 'The submodule representing the maximal order should ' cond = None if not submodule.is_power_basis_submodule(): cond = 'be a direct submodule of a power basis.' elif not submodule.starts_with_unity(): cond = 'have 1 as its first generator.' elif not submodule.is_sq_maxrank_HNF(): cond = 'have square matrix, of maximal rank, in Hermite Normal Form.' if cond is not None: raise StructureError(prefix + cond) class PrimeIdeal(IntegerPowerable): r""" A prime ideal in a ring of algebraic integers. """ def __init__(self, ZK, p, alpha, f, e=None): """ Parameters ========== ZK : :py:class:`~.Submodule` The maximal order where this ideal lives. p : int The rational prime this ideal divides. alpha : :py:class:`~.PowerBasisElement` Such that the ideal is equal to ``p*ZK + alpha*ZK``. f : int The inertia degree. e : int, ``None``, optional The ramification index, if already known. If ``None``, we will compute it here. """ _check_formal_conditions_for_maximal_order(ZK) self.ZK = ZK self.p = p self.alpha = alpha self.f = f self._test_factor = None self.e = e if e is not None else self.valuation(p * ZK) def __str__(self): if self.is_inert: return f'({self.p})' return f'({self.p}, {self.alpha.as_expr()})' @property def is_inert(self): """ Say whether the rational prime we divide is inert, i.e. stays prime in our ring of integers. """ return self.f == self.ZK.n def repr(self, field_gen=None, just_gens=False): """ Print a representation of this prime ideal. Examples ======== >>> from sympy import cyclotomic_poly, QQ >>> from sympy.abc import x, zeta >>> T = cyclotomic_poly(7, x) >>> K = QQ.algebraic_field((T, zeta)) >>> P = K.primes_above(11) >>> print(P[0].repr()) [ (11, x**3 + 5*x**2 + 4*x - 1) e=1, f=3 ] >>> print(P[0].repr(field_gen=zeta)) [ (11, zeta**3 + 5*zeta**2 + 4*zeta - 1) e=1, f=3 ] >>> print(P[0].repr(field_gen=zeta, just_gens=True)) (11, zeta**3 + 5*zeta**2 + 4*zeta - 1) Parameters ========== field_gen : :py:class:`~.Symbol`, ``None``, optional (default=None) The symbol to use for the generator of the field. This will appear in our representation of ``self.alpha``. If ``None``, we use the variable of the defining polynomial of ``self.ZK``. just_gens : bool, optional (default=False) If ``True``, just print the "(p, alpha)" part, showing "just the generators" of the prime ideal. Otherwise, print a string of the form "[ (p, alpha) e=..., f=... ]", giving the ramification index and inertia degree, along with the generators. """ field_gen = field_gen or self.ZK.parent.T.gen p, alpha, e, f = self.p, self.alpha, self.e, self.f alpha_rep = str(alpha.numerator(x=field_gen).as_expr()) if alpha.denom > 1: alpha_rep = f'({alpha_rep})/{alpha.denom}' gens = f'({p}, {alpha_rep})' if just_gens: return gens return f'[ {gens} e={e}, f={f} ]' def __repr__(self): return self.repr() def as_submodule(self): r""" Represent this prime ideal as a :py:class:`~.Submodule`. Explanation =========== The :py:class:`~.PrimeIdeal` class serves to bundle information about a prime ideal, such as its inertia degree, ramification index, and two-generator representation, as well as to offer helpful methods like :py:meth:`~.PrimeIdeal.valuation` and :py:meth:`~.PrimeIdeal.test_factor`. However, in order to be added and multiplied by other ideals or rational numbers, it must first be converted into a :py:class:`~.Submodule`, which is a class that supports these operations. In many cases, the user need not perform this conversion deliberately, since it is automatically performed by the arithmetic operator methods :py:meth:`~.PrimeIdeal.__add__` and :py:meth:`~.PrimeIdeal.__mul__`. Raising a :py:class:`~.PrimeIdeal` to a non-negative integer power is also supported. Examples ======== >>> from sympy import Poly, cyclotomic_poly, prime_decomp >>> T = Poly(cyclotomic_poly(7)) >>> P0 = prime_decomp(7, T)[0] >>> print(P0**6 == 7*P0.ZK) True Note that, on both sides of the equation above, we had a :py:class:`~.Submodule`. In the next equation we recall that adding ideals yields their GCD. This time, we need a deliberate conversion to :py:class:`~.Submodule` on the right: >>> print(P0 + 7*P0.ZK == P0.as_submodule()) True Returns ======= :py:class:`~.Submodule` Will be equal to ``self.p * self.ZK + self.alpha * self.ZK``. See Also ======== __add__ __mul__ """ M = self.p * self.ZK + self.alpha * self.ZK # Pre-set expensive boolean properties whose value we already know: M._starts_with_unity = False M._is_sq_maxrank_HNF = True return M def __eq__(self, other): if isinstance(other, PrimeIdeal): return self.as_submodule() == other.as_submodule() return NotImplemented def __add__(self, other): """ Convert to a :py:class:`~.Submodule` and add to another :py:class:`~.Submodule`. See Also ======== as_submodule """ return self.as_submodule() + other __radd__ = __add__ def __mul__(self, other): """ Convert to a :py:class:`~.Submodule` and multiply by another :py:class:`~.Submodule` or a rational number. See Also ======== as_submodule """ return self.as_submodule() * other __rmul__ = __mul__ def _zeroth_power(self): return self.ZK def _first_power(self): return self def test_factor(self): r""" Compute a test factor for this prime ideal. Explanation =========== Write $\mathfrak{p}$ for this prime ideal, $p$ for the rational prime it divides. Then, for computing $\mathfrak{p}$-adic valuations it is useful to have a number $\beta \in \mathbb{Z}_K$ such that $p/\mathfrak{p} = p \mathbb{Z}_K + \beta \mathbb{Z}_K$. Essentially, this is the same as the number $\Psi$ (or the "reagent") from Kummer's 1847 paper (*Ueber die Zerlegung...*, Crelle vol. 35) in which ideal divisors were invented. """ if self._test_factor is None: self._test_factor = _compute_test_factor(self.p, [self.alpha], self.ZK) return self._test_factor def valuation(self, I): r""" Compute the $\mathfrak{p}$-adic valuation of integral ideal I at this prime ideal. Parameters ========== I : :py:class:`~.Submodule` See Also ======== prime_valuation """ return prime_valuation(I, self) def reduce_element(self, elt): """ Reduce a :py:class:`~.PowerBasisElement` to a "small representative" modulo this prime ideal. Parameters ========== elt : :py:class:`~.PowerBasisElement` The element to be reduced. Returns ======= :py:class:`~.PowerBasisElement` The reduced element. See Also ======== reduce_ANP reduce_alg_num .Submodule.reduce_element """ return self.as_submodule().reduce_element(elt) def reduce_ANP(self, a): """ Reduce an :py:class:`~.ANP` to a "small representative" modulo this prime ideal. Parameters ========== elt : :py:class:`~.ANP` The element to be reduced. Returns ======= :py:class:`~.ANP` The reduced element. See Also ======== reduce_element reduce_alg_num .Submodule.reduce_element """ elt = self.ZK.parent.element_from_ANP(a) red = self.reduce_element(elt) return red.to_ANP() def reduce_alg_num(self, a): """ Reduce an :py:class:`~.AlgebraicNumber` to a "small representative" modulo this prime ideal. Parameters ========== elt : :py:class:`~.AlgebraicNumber` The element to be reduced. Returns ======= :py:class:`~.AlgebraicNumber` The reduced element. See Also ======== reduce_element reduce_ANP .Submodule.reduce_element """ elt = self.ZK.parent.element_from_alg_num(a) red = self.reduce_element(elt) return a.field_element(list(reversed(red.QQ_col.flat()))) def _compute_test_factor(p, gens, ZK): r""" Compute the test factor for a :py:class:`~.PrimeIdeal` $\mathfrak{p}$. Parameters ========== p : int The rational prime $\mathfrak{p}$ divides gens : list of :py:class:`PowerBasisElement` A complete set of generators for $\mathfrak{p}$ over *ZK*, EXCEPT that an element equivalent to rational *p* can and should be omitted (since it has no effect except to waste time). ZK : :py:class:`~.Submodule` The maximal order where the prime ideal $\mathfrak{p}$ lives. Returns ======= :py:class:`~.PowerBasisElement` References ========== .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.* (See Proposition 4.8.15.) """ _check_formal_conditions_for_maximal_order(ZK) E = ZK.endomorphism_ring() matrices = [E.inner_endomorphism(g).matrix(modulus=p) for g in gens] B = DomainMatrix.zeros((0, ZK.n), FF(p)).vstack(*matrices) # A nonzero element of the nullspace of B will represent a # lin comb over the omegas which (i) is not a multiple of p # (since it is nonzero over FF(p)), while (ii) is such that # its product with each g in gens _is_ a multiple of p (since # B represents multiplication by these generators). Theory # predicts that such an element must exist, so nullspace should # be non-trivial. x = B.nullspace()[0, :].transpose() beta = ZK.parent(ZK.matrix * x, denom=ZK.denom) return beta @public def prime_valuation(I, P): r""" Compute the *P*-adic valuation for an integral ideal *I*. Examples ======== >>> from sympy import QQ >>> from sympy.polys.numberfields import prime_valuation >>> K = QQ.cyclotomic_field(5) >>> P = K.primes_above(5) >>> ZK = K.maximal_order() >>> print(prime_valuation(25*ZK, P[0])) 8 Parameters ========== I : :py:class:`~.Submodule` An integral ideal whose valuation is desired. P : :py:class:`~.PrimeIdeal` The prime at which to compute the valuation. Returns ======= int See Also ======== .PrimeIdeal.valuation References ========== .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.* (See Algorithm 4.8.17.) """ p, ZK = P.p, P.ZK n, W, d = ZK.n, ZK.matrix, ZK.denom A = W.convert_to(QQ).inv() * I.matrix * d / I.denom # Although A must have integer entries, given that I is an integral ideal, # as a DomainMatrix it will still be over QQ, so we convert back: A = A.convert_to(ZZ) D = A.det() if D % p != 0: return 0 beta = P.test_factor() f = d ** n // W.det() need_complete_test = (f % p == 0) v = 0 while True: # Entering the loop, the cols of A represent lin combs of omegas. # Turn them into lin combs of thetas: A = W * A # And then one column at a time... for j in range(n): c = ZK.parent(A[:, j], denom=d) c *= beta # ...turn back into lin combs of omegas, after multiplying by beta: c = ZK.represent(c).flat() for i in range(n): A[i, j] = c[i] if A[n - 1, n - 1].element % p != 0: break A = A / p # As noted above, domain converts to QQ even when division goes evenly. # So must convert back, even when we don't "need_complete_test". if need_complete_test: # In this case, having a non-integer entry is actually just our # halting condition. try: A = A.convert_to(ZZ) except CoercionFailed: break else: # In this case theory says we should not have any non-integer entries. A = A.convert_to(ZZ) v += 1 return v def _two_elt_rep(gens, ZK, p, f=None, Np=None): r""" Given a set of *ZK*-generators of a prime ideal, compute a set of just two *ZK*-generators for the same ideal, one of which is *p* itself. Parameters ========== gens : list of :py:class:`PowerBasisElement` Generators for the prime ideal over *ZK*, the ring of integers of the field $K$. ZK : :py:class:`~.Submodule` The maximal order in $K$. p : int The rational prime divided by the prime ideal. f : int, optional The inertia degree of the prime ideal, if known. Np : int, optional The norm $p^f$ of the prime ideal, if known. NOTE: There is no reason to supply both *f* and *Np*. Either one will save us from having to compute the norm *Np* ourselves. If both are known, *Np* is preferred since it saves one exponentiation. Returns ======= :py:class:`~.PowerBasisElement` representing a single algebraic integer alpha such that the prime ideal is equal to ``p*ZK + alpha*ZK``. References ========== .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.* (See Algorithm 4.7.10.) """ _check_formal_conditions_for_maximal_order(ZK) pb = ZK.parent T = pb.T # Detect the special cases in which either (a) all generators are multiples # of p, or (b) there are no generators (so `all` is vacuously true): if all((g % p).equiv(0) for g in gens): return pb.zero() if Np is None: if f is not None: Np = p**f else: Np = abs(pb.submodule_from_gens(gens).matrix.det()) omega = ZK.basis_element_pullbacks() beta = [p*om for om in omega[1:]] # note: we omit omega[0] == 1 beta += gens search = coeff_search(len(beta), 1) for c in search: alpha = sum(ci*betai for ci, betai in zip(c, beta)) # Note: It may be tempting to reduce alpha mod p here, to try to work # with smaller numbers, but must not do that, as it can result in an # infinite loop! E.g. try factoring 2 in Q(sqrt(-7)). n = alpha.norm(T) // Np if n % p != 0: # Now can reduce alpha mod p. return alpha % p def _prime_decomp_easy_case(p, ZK): r""" Compute the decomposition of rational prime *p* in the ring of integers *ZK* (given as a :py:class:`~.Submodule`), in the "easy case", i.e. the case where *p* does not divide the index of $\theta$ in *ZK*, where $\theta$ is the generator of the ``PowerBasis`` of which *ZK* is a ``Submodule``. """ T = ZK.parent.T T_bar = Poly(T, modulus=p) lc, fl = T_bar.factor_list() if len(fl) == 1 and fl[0][1] == 1: return [PrimeIdeal(ZK, p, ZK.parent.zero(), ZK.n, 1)] return [PrimeIdeal(ZK, p, ZK.parent.element_from_poly(Poly(t, domain=ZZ)), t.degree(), e) for t, e in fl] def _prime_decomp_compute_kernel(I, p, ZK): r""" Parameters ========== I : :py:class:`~.Module` An ideal of ``ZK/pZK``. p : int The rational prime being factored. ZK : :py:class:`~.Submodule` The maximal order. Returns ======= Pair ``(N, G)``, where: ``N`` is a :py:class:`~.Module` representing the kernel of the map ``a |--> a**p - a`` on ``(O/pO)/I``, guaranteed to be a module with unity. ``G`` is a :py:class:`~.Module` representing a basis for the separable algebra ``A = O/I`` (see Cohen). """ W = I.matrix n, r = W.shape # Want to take the Fp-basis given by the columns of I, adjoin (1, 0, ..., 0) # (which we know is not already in there since I is a basis for a prime ideal) # and then supplement this with additional columns to make an invertible n x n # matrix. This will then represent a full basis for ZK, whose first r columns # are pullbacks of the basis for I. if r == 0: B = W.eye(n, ZZ) else: B = W.hstack(W.eye(n, ZZ)[:, 0]) if B.shape[1] < n: B = supplement_a_subspace(B.convert_to(FF(p))).convert_to(ZZ) G = ZK.submodule_from_matrix(B) # Must compute G's multiplication table _before_ discarding the first r # columns. (See Step 9 in Alg 6.2.9 in Cohen, where the betas are actually # needed in order to represent each product of gammas. However, once we've # found the representations, then we can ignore the betas.) G.compute_mult_tab() G = G.discard_before(r) phi = ModuleEndomorphism(G, lambda x: x**p - x) N = phi.kernel(modulus=p) assert N.starts_with_unity() return N, G def _prime_decomp_maximal_ideal(I, p, ZK): r""" We have reached the case where we have a maximal (hence prime) ideal *I*, which we know because the quotient ``O/I`` is a field. Parameters ========== I : :py:class:`~.Module` An ideal of ``O/pO``. p : int The rational prime being factored. ZK : :py:class:`~.Submodule` The maximal order. Returns ======= :py:class:`~.PrimeIdeal` instance representing this prime """ m, n = I.matrix.shape f = m - n G = ZK.matrix * I.matrix gens = [ZK.parent(G[:, j], denom=ZK.denom) for j in range(G.shape[1])] alpha = _two_elt_rep(gens, ZK, p, f=f) return PrimeIdeal(ZK, p, alpha, f) def _prime_decomp_split_ideal(I, p, N, G, ZK): r""" Perform the step in the prime decomposition algorithm where we have determined the the quotient ``ZK/I`` is _not_ a field, and we want to perform a non-trivial factorization of *I* by locating an idempotent element of ``ZK/I``. """ assert I.parent == ZK and G.parent is ZK and N.parent is G # Since ZK/I is not a field, the kernel computed in the previous step contains # more than just the prime field Fp, and our basis N for the nullspace therefore # contains at least a second column (which represents an element outside Fp). # Let alpha be such an element: alpha = N(1).to_parent() assert alpha.module is G alpha_powers = [] m = find_min_poly(alpha, FF(p), powers=alpha_powers) # TODO (future work): # We don't actually need full factorization, so might use a faster method # to just break off a single non-constant factor m1? lc, fl = m.factor_list() m1 = fl[0][0] m2 = m.quo(m1) U, V, g = m1.gcdex(m2) # Sanity check: theory says m is squarefree, so m1, m2 should be coprime: assert g == 1 E = list(reversed(Poly(U * m1, domain=ZZ).rep.rep)) eps1 = sum(E[i]*alpha_powers[i] for i in range(len(E))) eps2 = 1 - eps1 idemps = [eps1, eps2] factors = [] for eps in idemps: e = eps.to_parent() assert e.module is ZK D = I.matrix.convert_to(FF(p)).hstack(*[ (e * om).column(domain=FF(p)) for om in ZK.basis_elements() ]) W = D.columnspace().convert_to(ZZ) H = ZK.submodule_from_matrix(W) factors.append(H) return factors @public def prime_decomp(p, T=None, ZK=None, dK=None, radical=None): r""" Compute the decomposition of rational prime *p* in a number field. Explanation =========== Ordinarily this should be accessed through the :py:meth:`~.AlgebraicField.primes_above` method of an :py:class:`~.AlgebraicField`. Examples ======== >>> from sympy import Poly, QQ >>> from sympy.abc import x, theta >>> T = Poly(x ** 3 + x ** 2 - 2 * x + 8) >>> K = QQ.algebraic_field((T, theta)) >>> print(K.primes_above(2)) [[ (2, x**2 + 1) e=1, f=1 ], [ (2, (x**2 + 3*x + 2)/2) e=1, f=1 ], [ (2, (3*x**2 + 3*x)/2) e=1, f=1 ]] Parameters ========== p : int The rational prime whose decomposition is desired. T : :py:class:`~.Poly`, optional Monic irreducible polynomial defining the number field $K$ in which to factor. NOTE: at least one of *T* or *ZK* must be provided. ZK : :py:class:`~.Submodule`, optional The maximal order for $K$, if already known. NOTE: at least one of *T* or *ZK* must be provided. dK : int, optional The discriminant of the field $K$, if already known. radical : :py:class:`~.Submodule`, optional The nilradical mod *p* in the integers of $K$, if already known. Returns ======= List of :py:class:`~.PrimeIdeal` instances. References ========== .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.* (See Algorithm 6.2.9.) """ if T is None and ZK is None: raise ValueError('At least one of T or ZK must be provided.') if ZK is not None: _check_formal_conditions_for_maximal_order(ZK) if T is None: T = ZK.parent.T radicals = {} if dK is None or ZK is None: ZK, dK = round_two(T, radicals=radicals) dT = T.discriminant() f_squared = dT // dK if f_squared % p != 0: return _prime_decomp_easy_case(p, ZK) radical = radical or radicals.get(p) or nilradical_mod_p(ZK, p) stack = [radical] primes = [] while stack: I = stack.pop() N, G = _prime_decomp_compute_kernel(I, p, ZK) if N.n == 1: P = _prime_decomp_maximal_ideal(I, p, ZK) primes.append(P) else: I1, I2 = _prime_decomp_split_ideal(I, p, N, G, ZK) stack.extend([I1, I2]) return primes
a4aebd32d11be4172b49653d13d8eda55c46844711fb95c1f3fa9ab69b241559
r"""Modules in number fields. The classes defined here allow us to work with finitely generated, free modules, whose generators are algebraic numbers. There is an abstract base class called :py:class:`~.Module`, which has two concrete subclasses, :py:class:`~.PowerBasis` and :py:class:`~.Submodule`. Every module is defined by its basis, or set of generators: * For a :py:class:`~.PowerBasis`, the generators are the first $n$ powers (starting with the zeroth) of an algebraic integer $\theta$ of degree $n$. The :py:class:`~.PowerBasis` is constructed by passing either the minimal polynomial of $\theta$, or an :py:class:`~.AlgebraicField` having $\theta$ as its primitive element. * For a :py:class:`~.Submodule`, the generators are a set of $\mathbb{Q}$-linear combinations of the generators of another module. That other module is then the "parent" of the :py:class:`~.Submodule`. The coefficients of the $\mathbb{Q}$-linear combinations may be given by an integer matrix, and a positive integer denominator. Each column of the matrix defines a generator. >>> from sympy.polys import Poly, cyclotomic_poly, ZZ >>> from sympy.abc import x >>> from sympy.polys.matrices import DomainMatrix, DM >>> from sympy.polys.numberfields.modules import PowerBasis >>> T = Poly(cyclotomic_poly(5, x)) >>> A = PowerBasis(T) >>> print(A) PowerBasis(x**4 + x**3 + x**2 + x + 1) >>> B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ), denom=3) >>> print(B) Submodule[[2, 0, 0, 0], [0, 2, 0, 0], [0, 0, 2, 0], [0, 0, 0, 2]]/3 >>> print(B.parent) PowerBasis(x**4 + x**3 + x**2 + x + 1) Thus, every module is either a :py:class:`~.PowerBasis`, or a :py:class:`~.Submodule`, some ancestor of which is a :py:class:`~.PowerBasis`. (If ``S`` is a :py:class:`~.Submodule`, then its ancestors are ``S.parent``, ``S.parent.parent``, and so on). The :py:class:`~.ModuleElement` class represents a linear combination of the generators of any module. Critically, the coefficients of this linear combination are not restricted to be integers, but may be any rational numbers. This is necessary so that any and all algebraic integers be representable, starting from the power basis in a primitive element $\theta$ for the number field in question. For example, in a quadratic field $\mathbb{Q}(\sqrt{d})$ where $d \equiv 1 \mod{4}$, a denominator of $2$ is needed. A :py:class:`~.ModuleElement` can be constructed from an integer column vector and a denominator: >>> U = Poly(x**2 - 5) >>> M = PowerBasis(U) >>> e = M(DM([[1], [1]], ZZ), denom=2) >>> print(e) [1, 1]/2 >>> print(e.module) PowerBasis(x**2 - 5) The :py:class:`~.PowerBasisElement` class is a subclass of :py:class:`~.ModuleElement` that represents elements of a :py:class:`~.PowerBasis`, and adds functionality pertinent to elements represented directly over powers of the primitive element $\theta$. Arithmetic with module elements =============================== While a :py:class:`~.ModuleElement` represents a linear combination over the generators of a particular module, recall that every module is either a :py:class:`~.PowerBasis` or a descendant (along a chain of :py:class:`~.Submodule` objects) thereof, so that in fact every :py:class:`~.ModuleElement` represents an algebraic number in some field $\mathbb{Q}(\theta)$, where $\theta$ is the defining element of some :py:class:`~.PowerBasis`. It thus makes sense to talk about the number field to which a given :py:class:`~.ModuleElement` belongs. This means that any two :py:class:`~.ModuleElement` instances can be added, subtracted, multiplied, or divided, provided they belong to the same number field. Similarly, since $\mathbb{Q}$ is a subfield of every number field, any :py:class:`~.ModuleElement` may be added, multiplied, etc. by any rational number. >>> from sympy import QQ >>> from sympy.polys.numberfields.modules import to_col >>> T = Poly(cyclotomic_poly(5)) >>> A = PowerBasis(T) >>> C = A.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ)) >>> e = A(to_col([0, 2, 0, 0]), denom=3) >>> f = A(to_col([0, 0, 0, 7]), denom=5) >>> g = C(to_col([1, 1, 1, 1])) >>> e + f [0, 10, 0, 21]/15 >>> e - f [0, 10, 0, -21]/15 >>> e - g [-9, -7, -9, -9]/3 >>> e + QQ(7, 10) [21, 20, 0, 0]/30 >>> e * f [-14, -14, -14, -14]/15 >>> e ** 2 [0, 0, 4, 0]/9 >>> f // g [7, 7, 7, 7]/15 >>> f * QQ(2, 3) [0, 0, 0, 14]/15 However, care must be taken with arithmetic operations on :py:class:`~.ModuleElement`, because the module $C$ to which the result will belong will be the nearest common ancestor (NCA) of the modules $A$, $B$ to which the two operands belong, and $C$ may be different from either or both of $A$ and $B$. >>> A = PowerBasis(T) >>> B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ)) >>> C = A.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ)) >>> print((B(0) * C(0)).module == A) True Before the arithmetic operation is performed, copies of the two operands are automatically converted into elements of the NCA (the operands themselves are not modified). This upward conversion along an ancestor chain is easy: it just requires the successive multiplication by the defining matrix of each :py:class:`~.Submodule`. Conversely, downward conversion, i.e. representing a given :py:class:`~.ModuleElement` in a submodule, is also supported -- namely by the :py:meth:`~sympy.polys.numberfields.modules.Submodule.represent` method -- but is not guaranteed to succeed in general, since the given element may not belong to the submodule. The main circumstance in which this issue tends to arise is with multiplication, since modules, while closed under addition, need not be closed under multiplication. Multiplication -------------- Generally speaking, a module need not be closed under multiplication, i.e. need not form a ring. However, many of the modules we work with in the context of number fields are in fact rings, and our classes do support multiplication. Specifically, any :py:class:`~.Module` can attempt to compute its own multiplication table, but this does not happen unless an attempt is made to multiply two :py:class:`~.ModuleElement` instances belonging to it. >>> A = PowerBasis(T) >>> print(A._mult_tab is None) True >>> a = A(0)*A(1) >>> print(A._mult_tab is None) False Every :py:class:`~.PowerBasis` is, by its nature, closed under multiplication, so instances of :py:class:`~.PowerBasis` can always successfully compute their multiplication table. When a :py:class:`~.Submodule` attempts to compute its multiplication table, it converts each of its own generators into elements of its parent module, multiplies them there, in every possible pairing, and then tries to represent the results in itself, i.e. as $\mathbb{Z}$-linear combinations over its own generators. This will succeed if and only if the submodule is in fact closed under multiplication. Module Homomorphisms ==================== Many important number theoretic algorithms require the calculation of the kernel of one or more module homomorphisms. Accordingly we have several lightweight classes, :py:class:`~.ModuleHomomorphism`, :py:class:`~.ModuleEndomorphism`, :py:class:`~.InnerEndomorphism`, and :py:class:`~.EndomorphismRing`, which provide the minimal necessary machinery to support this. """ from sympy.core.numbers import igcd, ilcm from sympy.core.symbol import Dummy from sympy.polys.polyclasses import ANP from sympy.polys.polytools import Poly from sympy.polys.densetools import dup_clear_denoms from sympy.polys.domains.algebraicfield import AlgebraicField from sympy.polys.domains.finitefield import FF from sympy.polys.domains.rationalfield import QQ from sympy.polys.domains.integerring import ZZ from sympy.polys.matrices.domainmatrix import DomainMatrix from sympy.polys.matrices.exceptions import DMBadInputError from sympy.polys.matrices.normalforms import hermite_normal_form from sympy.polys.polyerrors import CoercionFailed, UnificationFailed from sympy.polys.polyutils import IntegerPowerable from .exceptions import ClosureFailure, MissingUnityError, StructureError from .utilities import AlgIntPowers, is_rat, get_num_denom def to_col(coeffs): r"""Transform a list of integer coefficients into a column vector.""" return DomainMatrix([[ZZ(c) for c in coeffs]], (1, len(coeffs)), ZZ).transpose() class Module: """ Generic finitely-generated module. This is an abstract base class, and should not be instantiated directly. The two concrete subclasses are :py:class:`~.PowerBasis` and :py:class:`~.Submodule`. Every :py:class:`~.Submodule` is derived from another module, referenced by its ``parent`` attribute. If ``S`` is a submodule, then we refer to ``S.parent``, ``S.parent.parent``, and so on, as the "ancestors" of ``S``. Thus, every :py:class:`~.Module` is either a :py:class:`~.PowerBasis` or a :py:class:`~.Submodule`, some ancestor of which is a :py:class:`~.PowerBasis`. """ @property def n(self): """The number of generators of this module.""" raise NotImplementedError def mult_tab(self): """ Get the multiplication table for this module (if closed under mult). Explanation =========== Computes a dictionary ``M`` of dictionaries of lists, representing the upper triangular half of the multiplication table. In other words, if ``0 <= i <= j < self.n``, then ``M[i][j]`` is the list ``c`` of coefficients such that ``g[i] * g[j] == sum(c[k]*g[k], k in range(self.n))``, where ``g`` is the list of generators of this module. If ``j < i`` then ``M[i][j]`` is undefined. Examples ======== >>> from sympy.polys import Poly, cyclotomic_poly >>> from sympy.polys.numberfields.modules import PowerBasis >>> T = Poly(cyclotomic_poly(5)) >>> A = PowerBasis(T) >>> print(A.mult_tab()) # doctest: +SKIP {0: {0: [1, 0, 0, 0], 1: [0, 1, 0, 0], 2: [0, 0, 1, 0], 3: [0, 0, 0, 1]}, 1: {1: [0, 0, 1, 0], 2: [0, 0, 0, 1], 3: [-1, -1, -1, -1]}, 2: {2: [-1, -1, -1, -1], 3: [1, 0, 0, 0]}, 3: {3: [0, 1, 0, 0]}} Returns ======= dict of dict of lists Raises ====== ClosureFailure If the module is not closed under multiplication. """ raise NotImplementedError @property def parent(self): """ The parent module, if any, for this module. Explanation =========== For a :py:class:`~.Submodule` this is its ``parent`` attribute; for a :py:class:`~.PowerBasis` this is ``None``. Returns ======= :py:class:`~.Module`, ``None`` See Also ======== Module """ return None def represent(self, elt): r""" Represent a module element as an integer-linear combination over the generators of this module. Explanation =========== In our system, to "represent" always means to write a :py:class:`~.ModuleElement` as a :ref:`ZZ`-linear combination over the generators of the present :py:class:`~.Module`. Furthermore, the incoming :py:class:`~.ModuleElement` must belong to an ancestor of the present :py:class:`~.Module` (or to the present :py:class:`~.Module` itself). The most common application is to represent a :py:class:`~.ModuleElement` in a :py:class:`~.Submodule`. For example, this is involved in computing multiplication tables. On the other hand, representing in a :py:class:`~.PowerBasis` is an odd case, and one which tends not to arise in practice, except for example when using a :py:class:`~.ModuleEndomorphism` on a :py:class:`~.PowerBasis`. In such a case, (1) the incoming :py:class:`~.ModuleElement` must belong to the :py:class:`~.PowerBasis` itself (since the latter has no proper ancestors) and (2) it is "representable" iff it belongs to $\mathbb{Z}[\theta]$ (although generally a :py:class:`~.PowerBasisElement` may represent any element of $\mathbb{Q}(\theta)$, i.e. any algebraic number). Examples ======== >>> from sympy import Poly, cyclotomic_poly >>> from sympy.polys.numberfields.modules import PowerBasis, to_col >>> from sympy.abc import zeta >>> T = Poly(cyclotomic_poly(5)) >>> A = PowerBasis(T) >>> a = A(to_col([2, 4, 6, 8])) The :py:class:`~.ModuleElement` ``a`` has all even coefficients. If we represent ``a`` in the submodule ``B = 2*A``, the coefficients in the column vector will be halved: >>> B = A.submodule_from_gens([2*A(i) for i in range(4)]) >>> b = B.represent(a) >>> print(b.transpose()) # doctest: +SKIP DomainMatrix([[1, 2, 3, 4]], (1, 4), ZZ) However, the element of ``B`` so defined still represents the same algebraic number: >>> print(a.poly(zeta).as_expr()) 8*zeta**3 + 6*zeta**2 + 4*zeta + 2 >>> print(B(b).over_power_basis().poly(zeta).as_expr()) 8*zeta**3 + 6*zeta**2 + 4*zeta + 2 Parameters ========== elt : :py:class:`~.ModuleElement` The module element to be represented. Must belong to some ancestor module of this module (including this module itself). Returns ======= :py:class:`~.DomainMatrix` over :ref:`ZZ` This will be a column vector, representing the coefficients of a linear combination of this module's generators, which equals the given element. Raises ====== ClosureFailure If the given element cannot be represented as a :ref:`ZZ`-linear combination over this module. See Also ======== .Submodule.represent .PowerBasis.represent """ raise NotImplementedError def ancestors(self, include_self=False): """ Return the list of ancestor modules of this module, from the foundational :py:class:`~.PowerBasis` downward, optionally including ``self``. See Also ======== Module """ c = self.parent a = [] if c is None else c.ancestors(include_self=True) if include_self: a.append(self) return a def power_basis_ancestor(self): """ Return the :py:class:`~.PowerBasis` that is an ancestor of this module. See Also ======== Module """ if isinstance(self, PowerBasis): return self c = self.parent if c is not None: return c.power_basis_ancestor() return None def nearest_common_ancestor(self, other): """ Locate the nearest common ancestor of this module and another. Returns ======= :py:class:`~.Module`, ``None`` See Also ======== Module """ sA = self.ancestors(include_self=True) oA = other.ancestors(include_self=True) nca = None for sa, oa in zip(sA, oA): if sa == oa: nca = sa else: break return nca @property def number_field(self): r""" Return the associated :py:class:`~.AlgebraicField`, if any. Explanation =========== A :py:class:`~.PowerBasis` can be constructed on a :py:class:`~.Poly` $f$ or on an :py:class:`~.AlgebraicField` $K$. In the latter case, the :py:class:`~.PowerBasis` and all its descendant modules will return $K$ as their ``.number_field`` property, while in the former case they will all return ``None``. Returns ======= :py:class:`~.AlgebraicField`, ``None`` """ return self.power_basis_ancestor().number_field def is_compat_col(self, col): """Say whether *col* is a suitable column vector for this module.""" return isinstance(col, DomainMatrix) and col.shape == (self.n, 1) and col.domain.is_ZZ def __call__(self, spec, denom=1): r""" Generate a :py:class:`~.ModuleElement` belonging to this module. Examples ======== >>> from sympy.polys import Poly, cyclotomic_poly >>> from sympy.polys.numberfields.modules import PowerBasis, to_col >>> T = Poly(cyclotomic_poly(5)) >>> A = PowerBasis(T) >>> e = A(to_col([1, 2, 3, 4]), denom=3) >>> print(e) # doctest: +SKIP [1, 2, 3, 4]/3 >>> f = A(2) >>> print(f) # doctest: +SKIP [0, 0, 1, 0] Parameters ========== spec : :py:class:`~.DomainMatrix`, int Specifies the numerators of the coefficients of the :py:class:`~.ModuleElement`. Can be either a column vector over :ref:`ZZ`, whose length must equal the number $n$ of generators of this module, or else an integer ``j``, $0 \leq j < n$, which is a shorthand for column $j$ of $I_n$, the $n \times n$ identity matrix. denom : int, optional (default=1) Denominator for the coefficients of the :py:class:`~.ModuleElement`. Returns ======= :py:class:`~.ModuleElement` The coefficients are the entries of the *spec* vector, divided by *denom*. """ if isinstance(spec, int) and 0 <= spec < self.n: spec = DomainMatrix.eye(self.n, ZZ)[:, spec].to_dense() if not self.is_compat_col(spec): raise ValueError('Compatible column vector required.') return make_mod_elt(self, spec, denom=denom) def starts_with_unity(self): """Say whether the module's first generator equals unity.""" raise NotImplementedError def basis_elements(self): """ Get list of :py:class:`~.ModuleElement` being the generators of this module. """ return [self(j) for j in range(self.n)] def zero(self): """Return a :py:class:`~.ModuleElement` representing zero.""" return self(0) * 0 def one(self): """ Return a :py:class:`~.ModuleElement` representing unity, and belonging to the first ancestor of this module (including itself) that starts with unity. """ return self.element_from_rational(1) def element_from_rational(self, a): """ Return a :py:class:`~.ModuleElement` representing a rational number. Explanation =========== The returned :py:class:`~.ModuleElement` will belong to the first module on this module's ancestor chain (including this module itself) that starts with unity. Examples ======== >>> from sympy.polys import Poly, cyclotomic_poly, QQ >>> from sympy.polys.numberfields.modules import PowerBasis >>> T = Poly(cyclotomic_poly(5)) >>> A = PowerBasis(T) >>> a = A.element_from_rational(QQ(2, 3)) >>> print(a) # doctest: +SKIP [2, 0, 0, 0]/3 Parameters ========== a : int, :ref:`ZZ`, :ref:`QQ` Returns ======= :py:class:`~.ModuleElement` """ raise NotImplementedError def submodule_from_gens(self, gens, hnf=True, hnf_modulus=None): """ Form the submodule generated by a list of :py:class:`~.ModuleElement` belonging to this module. Examples ======== >>> from sympy.polys import Poly, cyclotomic_poly >>> from sympy.polys.numberfields.modules import PowerBasis >>> T = Poly(cyclotomic_poly(5)) >>> A = PowerBasis(T) >>> gens = [A(0), 2*A(1), 3*A(2), 4*A(3)//5] >>> B = A.submodule_from_gens(gens) >>> print(B) # doctest: +SKIP Submodule[[5, 0, 0, 0], [0, 10, 0, 0], [0, 0, 15, 0], [0, 0, 0, 4]]/5 Parameters ========== gens : list of :py:class:`~.ModuleElement` belonging to this module. hnf : boolean, optional (default=True) If True, we will reduce the matrix into Hermite Normal Form before forming the :py:class:`~.Submodule`. hnf_modulus : int, None, optional (default=None) Modulus for use in the HNF reduction algorithm. See :py:func:`~sympy.polys.matrices.normalforms.hermite_normal_form`. Returns ======= :py:class:`~.Submodule` See Also ======== submodule_from_matrix """ if not all(g.module == self for g in gens): raise ValueError('Generators must belong to this module.') n = len(gens) if n == 0: raise ValueError('Need at least one generator.') m = gens[0].n d = gens[0].denom if n == 1 else ilcm(*[g.denom for g in gens]) B = DomainMatrix.zeros((m, 0), ZZ).hstack(*[(d // g.denom) * g.col for g in gens]) if hnf: B = hermite_normal_form(B, D=hnf_modulus) return self.submodule_from_matrix(B, denom=d) def submodule_from_matrix(self, B, denom=1): """ Form the submodule generated by the elements of this module indicated by the columns of a matrix, with an optional denominator. Examples ======== >>> from sympy.polys import Poly, cyclotomic_poly, ZZ >>> from sympy.polys.matrices import DM >>> from sympy.polys.numberfields.modules import PowerBasis >>> T = Poly(cyclotomic_poly(5)) >>> A = PowerBasis(T) >>> B = A.submodule_from_matrix(DM([ ... [0, 10, 0, 0], ... [0, 0, 7, 0], ... ], ZZ).transpose(), denom=15) >>> print(B) # doctest: +SKIP Submodule[[0, 10, 0, 0], [0, 0, 7, 0]]/15 Parameters ========== B : :py:class:`~.DomainMatrix` over :ref:`ZZ` Each column gives the numerators of the coefficients of one generator of the submodule. Thus, the number of rows of *B* must equal the number of generators of the present module. denom : int, optional (default=1) Common denominator for all generators of the submodule. Returns ======= :py:class:`~.Submodule` Raises ====== ValueError If the given matrix *B* is not over :ref:`ZZ` or its number of rows does not equal the number of generators of the present module. See Also ======== submodule_from_gens """ m, n = B.shape if not B.domain.is_ZZ: raise ValueError('Matrix must be over ZZ.') if not m == self.n: raise ValueError('Matrix row count must match base module.') return Submodule(self, B, denom=denom) def whole_submodule(self): """ Return a submodule equal to this entire module. Explanation =========== This is useful when you have a :py:class:`~.PowerBasis` and want to turn it into a :py:class:`~.Submodule` (in order to use methods belonging to the latter). """ B = DomainMatrix.eye(self.n, ZZ) return self.submodule_from_matrix(B) def endomorphism_ring(self): """Form the :py:class:`~.EndomorphismRing` for this module.""" return EndomorphismRing(self) class PowerBasis(Module): """The module generated by the powers of an algebraic integer.""" def __init__(self, T): """ Parameters ========== T : :py:class:`~.Poly`, :py:class:`~.AlgebraicField` Either (1) the monic, irreducible, univariate polynomial over :ref:`ZZ`, a root of which is the generator of the power basis, or (2) an :py:class:`~.AlgebraicField` whose primitive element is the generator of the power basis. """ K = None if isinstance(T, AlgebraicField): K, T = T, T.ext.minpoly_of_element() # Sometimes incoming Polys are formally over QQ, although all their # coeffs are integral. We want them to be formally over ZZ. T = T.set_domain(ZZ) self.K = K self.T = T self._n = T.degree() self._mult_tab = None @property def number_field(self): return self.K def __repr__(self): return f'PowerBasis({self.T.as_expr()})' def __eq__(self, other): if isinstance(other, PowerBasis): return self.T == other.T return NotImplemented @property def n(self): return self._n def mult_tab(self): if self._mult_tab is None: self.compute_mult_tab() return self._mult_tab def compute_mult_tab(self): theta_pow = AlgIntPowers(self.T) M = {} n = self.n for u in range(n): M[u] = {} for v in range(u, n): M[u][v] = theta_pow[u + v] self._mult_tab = M def represent(self, elt): r""" Represent a module element as an integer-linear combination over the generators of this module. See Also ======== .Module.represent .Submodule.represent """ if elt.module == self and elt.denom == 1: return elt.column() else: raise ClosureFailure('Element not representable in ZZ[theta].') def starts_with_unity(self): return True def element_from_rational(self, a): return self(0) * a def element_from_poly(self, f): """ Produce an element of this module, representing *f* after reduction mod our defining minimal polynomial. Parameters ========== f : :py:class:`~.Poly` over :ref:`ZZ` in same var as our defining poly. Returns ======= :py:class:`~.PowerBasisElement` """ n, k = self.n, f.degree() if k >= n: f = f % self.T if f == 0: return self.zero() d, c = dup_clear_denoms(f.rep.rep, QQ, convert=True) c = list(reversed(c)) ell = len(c) z = [ZZ(0)] * (n - ell) col = to_col(c + z) return self(col, denom=d) def _element_from_rep_and_mod(self, rep, mod): """ Produce a PowerBasisElement representing a given algebraic number. Parameters ========== rep : list of coeffs Represents the number as polynomial in the primitive element of the field. mod : list of coeffs Represents the minimal polynomial of the primitive element of the field. Returns ======= :py:class:`~.PowerBasisElement` """ if mod != self.T.rep.rep: raise UnificationFailed('Element does not appear to be in the same field.') return self.element_from_poly(Poly(rep, self.T.gen)) def element_from_ANP(self, a): """Convert an ANP into a PowerBasisElement. """ return self._element_from_rep_and_mod(a.rep, a.mod) def element_from_alg_num(self, a): """Convert an AlgebraicNumber into a PowerBasisElement. """ return self._element_from_rep_and_mod(a.rep.rep, a.minpoly.rep.rep) class Submodule(Module, IntegerPowerable): """A submodule of another module.""" def __init__(self, parent, matrix, denom=1, mult_tab=None): """ Parameters ========== parent : :py:class:`~.Module` The module from which this one is derived. matrix : :py:class:`~.DomainMatrix` over :ref:`ZZ` The matrix whose columns define this submodule's generators as linear combinations over the parent's generators. denom : int, optional (default=1) Denominator for the coefficients given by the matrix. mult_tab : dict, ``None``, optional If already known, the multiplication table for this module may be supplied. """ self._parent = parent self._matrix = matrix self._denom = denom self._mult_tab = mult_tab self._n = matrix.shape[1] self._QQ_matrix = None self._starts_with_unity = None self._is_sq_maxrank_HNF = None def __repr__(self): r = 'Submodule' + repr(self.matrix.transpose().to_Matrix().tolist()) if self.denom > 1: r += f'/{self.denom}' return r def reduced(self): """ Produce a reduced version of this submodule. Explanation =========== In the reduced version, it is guaranteed that 1 is the only positive integer dividing both the submodule's denominator, and every entry in the submodule's matrix. Returns ======= :py:class:`~.Submodule` """ if self.denom == 1: return self g = igcd(self.denom, *self.coeffs) if g == 1: return self return type(self)(self.parent, (self.matrix / g).convert_to(ZZ), denom=self.denom // g, mult_tab=self._mult_tab) def discard_before(self, r): """ Produce a new module by discarding all generators before a given index *r*. """ W = self.matrix[:, r:] s = self.n - r M = None mt = self._mult_tab if mt is not None: M = {} for u in range(s): M[u] = {} for v in range(u, s): M[u][v] = mt[r + u][r + v][r:] return Submodule(self.parent, W, denom=self.denom, mult_tab=M) @property def n(self): return self._n def mult_tab(self): if self._mult_tab is None: self.compute_mult_tab() return self._mult_tab def compute_mult_tab(self): gens = self.basis_element_pullbacks() M = {} n = self.n for u in range(n): M[u] = {} for v in range(u, n): M[u][v] = self.represent(gens[u] * gens[v]).flat() self._mult_tab = M @property def parent(self): return self._parent @property def matrix(self): return self._matrix @property def coeffs(self): return self.matrix.flat() @property def denom(self): return self._denom @property def QQ_matrix(self): """ :py:class:`~.DomainMatrix` over :ref:`QQ`, equal to ``self.matrix / self.denom``, and guaranteed to be dense. Explanation =========== Depending on how it is formed, a :py:class:`~.DomainMatrix` may have an internal representation that is sparse or dense. We guarantee a dense representation here, so that tests for equivalence of submodules always come out as expected. Examples ======== >>> from sympy.polys import Poly, cyclotomic_poly, ZZ >>> from sympy.abc import x >>> from sympy.polys.matrices import DomainMatrix >>> from sympy.polys.numberfields.modules import PowerBasis >>> T = Poly(cyclotomic_poly(5, x)) >>> A = PowerBasis(T) >>> B = A.submodule_from_matrix(3*DomainMatrix.eye(4, ZZ), denom=6) >>> C = A.submodule_from_matrix(DomainMatrix.eye(4, ZZ), denom=2) >>> print(B.QQ_matrix == C.QQ_matrix) True Returns ======= :py:class:`~.DomainMatrix` over :ref:`QQ` """ if self._QQ_matrix is None: self._QQ_matrix = (self.matrix / self.denom).to_dense() return self._QQ_matrix def starts_with_unity(self): if self._starts_with_unity is None: self._starts_with_unity = self(0).equiv(1) return self._starts_with_unity def is_sq_maxrank_HNF(self): if self._is_sq_maxrank_HNF is None: self._is_sq_maxrank_HNF = is_sq_maxrank_HNF(self._matrix) return self._is_sq_maxrank_HNF def is_power_basis_submodule(self): return isinstance(self.parent, PowerBasis) def element_from_rational(self, a): if self.starts_with_unity(): return self(0) * a else: return self.parent.element_from_rational(a) def basis_element_pullbacks(self): """ Return list of this submodule's basis elements as elements of the submodule's parent module. """ return [e.to_parent() for e in self.basis_elements()] def represent(self, elt): """ Represent a module element as an integer-linear combination over the generators of this module. See Also ======== .Module.represent .PowerBasis.represent """ if elt.module == self: return elt.column() elif elt.module == self.parent: try: # The given element should be a ZZ-linear combination over our # basis vectors; however, due to the presence of denominators, # we need to solve over QQ. A = self.QQ_matrix b = elt.QQ_col x = A._solve(b)[0].transpose() x = x.convert_to(ZZ) except DMBadInputError: raise ClosureFailure('Element outside QQ-span of this basis.') except CoercionFailed: raise ClosureFailure('Element in QQ-span but not ZZ-span of this basis.') return x elif isinstance(self.parent, Submodule): coeffs_in_parent = self.parent.represent(elt) parent_element = self.parent(coeffs_in_parent) return self.represent(parent_element) else: raise ClosureFailure('Element outside ancestor chain of this module.') def is_compat_submodule(self, other): return isinstance(other, Submodule) and other.parent == self.parent def __eq__(self, other): if self.is_compat_submodule(other): return other.QQ_matrix == self.QQ_matrix return NotImplemented def add(self, other, hnf=True, hnf_modulus=None): """ Add this :py:class:`~.Submodule` to another. Explanation =========== This represents the module generated by the union of the two modules' sets of generators. Parameters ========== other : :py:class:`~.Submodule` hnf : boolean, optional (default=True) If ``True``, reduce the matrix of the combined module to its Hermite Normal Form. hnf_modulus : :ref:`ZZ`, None, optional If a positive integer is provided, use this as modulus in the HNF reduction. See :py:func:`~sympy.polys.matrices.normalforms.hermite_normal_form`. Returns ======= :py:class:`~.Submodule` """ d, e = self.denom, other.denom m = ilcm(d, e) a, b = m // d, m // e B = (a * self.matrix).hstack(b * other.matrix) if hnf: B = hermite_normal_form(B, D=hnf_modulus) return self.parent.submodule_from_matrix(B, denom=m) def __add__(self, other): if self.is_compat_submodule(other): return self.add(other) return NotImplemented __radd__ = __add__ def mul(self, other, hnf=True, hnf_modulus=None): """ Multiply this :py:class:`~.Submodule` by a rational number, a :py:class:`~.ModuleElement`, or another :py:class:`~.Submodule`. Explanation =========== To multiply by a rational number or :py:class:`~.ModuleElement` means to form the submodule whose generators are the products of this quantity with all the generators of the present submodule. To multiply by another :py:class:`~.Submodule` means to form the submodule whose generators are all the products of one generator from the one submodule, and one generator from the other. Parameters ========== other : int, :ref:`ZZ`, :ref:`QQ`, :py:class:`~.ModuleElement`, :py:class:`~.Submodule` hnf : boolean, optional (default=True) If ``True``, reduce the matrix of the product module to its Hermite Normal Form. hnf_modulus : :ref:`ZZ`, None, optional If a positive integer is provided, use this as modulus in the HNF reduction. See :py:func:`~sympy.polys.matrices.normalforms.hermite_normal_form`. Returns ======= :py:class:`~.Submodule` """ if is_rat(other): a, b = get_num_denom(other) if a == b == 1: return self else: return Submodule(self.parent, self.matrix * a, denom=self.denom * b, mult_tab=None).reduced() elif isinstance(other, ModuleElement) and other.module == self.parent: # The submodule is multiplied by an element of the parent module. # We presume this means we want a new submodule of the parent module. gens = [other * e for e in self.basis_element_pullbacks()] return self.parent.submodule_from_gens(gens, hnf=hnf, hnf_modulus=hnf_modulus) elif self.is_compat_submodule(other): # This case usually means you're multiplying ideals, and want another # ideal, i.e. another submodule of the same parent module. alphas, betas = self.basis_element_pullbacks(), other.basis_element_pullbacks() gens = [a * b for a in alphas for b in betas] return self.parent.submodule_from_gens(gens, hnf=hnf, hnf_modulus=hnf_modulus) return NotImplemented def __mul__(self, other): return self.mul(other) __rmul__ = __mul__ def _first_power(self): return self def reduce_element(self, elt): r""" If this submodule $B$ has defining matrix $W$ in square, maximal-rank Hermite normal form, then, given an element $x$ of the parent module $A$, we produce an element $y \in A$ such that $x - y \in B$, and the $i$th coordinate of $y$ satisfies $0 \leq y_i < w_{i,i}$. This representative $y$ is unique, in the sense that every element of the coset $x + B$ reduces to it under this procedure. Explanation =========== In the special case where $A$ is a power basis for a number field $K$, and $B$ is a submodule representing an ideal $I$, this operation represents one of a few important ways of reducing an element of $K$ modulo $I$ to obtain a "small" representative. See [Cohen00]_ Section 1.4.3. Examples ======== >>> from sympy import QQ, Poly, symbols >>> t = symbols('t') >>> k = QQ.alg_field_from_poly(Poly(t**3 + t**2 - 2*t + 8)) >>> Zk = k.maximal_order() >>> A = Zk.parent >>> B = (A(2) - 3*A(0))*Zk >>> B.reduce_element(A(2)) [3, 0, 0] Parameters ========== elt : :py:class:`~.ModuleElement` An element of this submodule's parent module. Returns ======= elt : :py:class:`~.ModuleElement` An element of this submodule's parent module. Raises ====== NotImplementedError If the given :py:class:`~.ModuleElement` does not belong to this submodule's parent module. StructureError If this submodule's defining matrix is not in square, maximal-rank Hermite normal form. References ========== .. [Cohen00] Cohen, H. *Advanced Topics in Computational Number Theory.* """ if not elt.module == self.parent: raise NotImplementedError if not self.is_sq_maxrank_HNF(): msg = "Reduction not implemented unless matrix square max-rank HNF" raise StructureError(msg) B = self.basis_element_pullbacks() a = elt for i in range(self.n - 1, -1, -1): b = B[i] q = a.coeffs[i]*b.denom // (b.coeffs[i]*a.denom) a -= q*b return a def is_sq_maxrank_HNF(dm): r""" Say whether a :py:class:`~.DomainMatrix` is in that special case of Hermite Normal Form, in which the matrix is also square and of maximal rank. Explanation =========== We commonly work with :py:class:`~.Submodule` instances whose matrix is in this form, and it can be useful to be able to check that this condition is satisfied. For example this is the case with the :py:class:`~.Submodule` ``ZK`` returned by :py:func:`~sympy.polys.numberfields.basis.round_two`, which represents the maximal order in a number field, and with ideals formed therefrom, such as ``2 * ZK``. """ if dm.domain.is_ZZ and dm.is_square and dm.is_upper: n = dm.shape[0] for i in range(n): d = dm[i, i].element if d <= 0: return False for j in range(i + 1, n): if not (0 <= dm[i, j].element < d): return False return True return False def make_mod_elt(module, col, denom=1): r""" Factory function which builds a :py:class:`~.ModuleElement`, but ensures that it is a :py:class:`~.PowerBasisElement` if the module is a :py:class:`~.PowerBasis`. """ if isinstance(module, PowerBasis): return PowerBasisElement(module, col, denom=denom) else: return ModuleElement(module, col, denom=denom) class ModuleElement(IntegerPowerable): r""" Represents an element of a :py:class:`~.Module`. NOTE: Should not be constructed directly. Use the :py:meth:`~.Module.__call__` method or the :py:func:`make_mod_elt()` factory function instead. """ def __init__(self, module, col, denom=1): """ Parameters ========== module : :py:class:`~.Module` The module to which this element belongs. col : :py:class:`~.DomainMatrix` over :ref:`ZZ` Column vector giving the numerators of the coefficients of this element. denom : int, optional (default=1) Denominator for the coefficients of this element. """ self.module = module self.col = col self.denom = denom self._QQ_col = None def __repr__(self): r = str([int(c) for c in self.col.flat()]) if self.denom > 1: r += f'/{self.denom}' return r def reduced(self): """ Produce a reduced version of this ModuleElement, i.e. one in which the gcd of the denominator together with all numerator coefficients is 1. """ if self.denom == 1: return self g = igcd(self.denom, *self.coeffs) if g == 1: return self return type(self)(self.module, (self.col / g).convert_to(ZZ), denom=self.denom // g) def reduced_mod_p(self, p): """ Produce a version of this :py:class:`~.ModuleElement` in which all numerator coefficients have been reduced mod *p*. """ return make_mod_elt(self.module, self.col.convert_to(FF(p)).convert_to(ZZ), denom=self.denom) @classmethod def from_int_list(cls, module, coeffs, denom=1): """ Make a :py:class:`~.ModuleElement` from a list of ints (instead of a column vector). """ col = to_col(coeffs) return cls(module, col, denom=denom) @property def n(self): """The length of this element's column.""" return self.module.n def __len__(self): return self.n def column(self, domain=None): """ Get a copy of this element's column, optionally converting to a domain. """ return self.col.convert_to(domain) @property def coeffs(self): return self.col.flat() @property def QQ_col(self): """ :py:class:`~.DomainMatrix` over :ref:`QQ`, equal to ``self.col / self.denom``, and guaranteed to be dense. See Also ======== .Submodule.QQ_matrix """ if self._QQ_col is None: self._QQ_col = (self.col / self.denom).to_dense() return self._QQ_col def to_parent(self): """ Transform into a :py:class:`~.ModuleElement` belonging to the parent of this element's module. """ if not isinstance(self.module, Submodule): raise ValueError('Not an element of a Submodule.') return make_mod_elt( self.module.parent, self.module.matrix * self.col, denom=self.module.denom * self.denom) def to_ancestor(self, anc): """ Transform into a :py:class:`~.ModuleElement` belonging to a given ancestor of this element's module. Parameters ========== anc : :py:class:`~.Module` """ if anc == self.module: return self else: return self.to_parent().to_ancestor(anc) def over_power_basis(self): """ Transform into a :py:class:`~.PowerBasisElement` over our :py:class:`~.PowerBasis` ancestor. """ e = self while not isinstance(e.module, PowerBasis): e = e.to_parent() return e def is_compat(self, other): """ Test whether other is another :py:class:`~.ModuleElement` with same module. """ return isinstance(other, ModuleElement) and other.module == self.module def unify(self, other): """ Try to make a compatible pair of :py:class:`~.ModuleElement`, one equivalent to this one, and one equivalent to the other. Explanation =========== We search for the nearest common ancestor module for the pair of elements, and represent each one there. Returns ======= Pair ``(e1, e2)`` Each ``ei`` is a :py:class:`~.ModuleElement`, they belong to the same :py:class:`~.Module`, ``e1`` is equivalent to ``self``, and ``e2`` is equivalent to ``other``. Raises ====== UnificationFailed If ``self`` and ``other`` have no common ancestor module. """ if self.module == other.module: return self, other nca = self.module.nearest_common_ancestor(other.module) if nca is not None: return self.to_ancestor(nca), other.to_ancestor(nca) raise UnificationFailed(f"Cannot unify {self} with {other}") def __eq__(self, other): if self.is_compat(other): return self.QQ_col == other.QQ_col return NotImplemented def equiv(self, other): """ A :py:class:`~.ModuleElement` may test as equivalent to a rational number or another :py:class:`~.ModuleElement`, if they represent the same algebraic number. Explanation =========== This method is intended to check equivalence only in those cases in which it is easy to test; namely, when *other* is either a :py:class:`~.ModuleElement` that can be unified with this one (i.e. one which shares a common :py:class:`~.PowerBasis` ancestor), or else a rational number (which is easy because every :py:class:`~.PowerBasis` represents every rational number). Parameters ========== other : int, :ref:`ZZ`, :ref:`QQ`, :py:class:`~.ModuleElement` Returns ======= bool Raises ====== UnificationFailed If ``self`` and ``other`` do not share a common :py:class:`~.PowerBasis` ancestor. """ if self == other: return True elif isinstance(other, ModuleElement): a, b = self.unify(other) return a == b elif is_rat(other): if isinstance(self, PowerBasisElement): return self == self.module(0) * other else: return self.over_power_basis().equiv(other) return False def __add__(self, other): """ A :py:class:`~.ModuleElement` can be added to a rational number, or to another :py:class:`~.ModuleElement`. Explanation =========== When the other summand is a rational number, it will be converted into a :py:class:`~.ModuleElement` (belonging to the first ancestor of this module that starts with unity). In all cases, the sum belongs to the nearest common ancestor (NCA) of the modules of the two summands. If the NCA does not exist, we return ``NotImplemented``. """ if self.is_compat(other): d, e = self.denom, other.denom m = ilcm(d, e) u, v = m // d, m // e col = to_col([u * a + v * b for a, b in zip(self.coeffs, other.coeffs)]) return type(self)(self.module, col, denom=m).reduced() elif isinstance(other, ModuleElement): try: a, b = self.unify(other) except UnificationFailed: return NotImplemented return a + b elif is_rat(other): return self + self.module.element_from_rational(other) return NotImplemented __radd__ = __add__ def __neg__(self): return self * -1 def __sub__(self, other): return self + (-other) def __rsub__(self, other): return -self + other def __mul__(self, other): """ A :py:class:`~.ModuleElement` can be multiplied by a rational number, or by another :py:class:`~.ModuleElement`. Explanation =========== When the multiplier is a rational number, the product is computed by operating directly on the coefficients of this :py:class:`~.ModuleElement`. When the multiplier is another :py:class:`~.ModuleElement`, the product will belong to the nearest common ancestor (NCA) of the modules of the two operands, and that NCA must have a multiplication table. If the NCA does not exist, we return ``NotImplemented``. If the NCA does not have a mult. table, ``ClosureFailure`` will be raised. """ if self.is_compat(other): M = self.module.mult_tab() A, B = self.col.flat(), other.col.flat() n = self.n C = [0] * n for u in range(n): for v in range(u, n): c = A[u] * B[v] if v > u: c += A[v] * B[u] if c != 0: R = M[u][v] for k in range(n): C[k] += c * R[k] d = self.denom * other.denom return self.from_int_list(self.module, C, denom=d) elif isinstance(other, ModuleElement): try: a, b = self.unify(other) except UnificationFailed: return NotImplemented return a * b elif is_rat(other): a, b = get_num_denom(other) if a == b == 1: return self else: return make_mod_elt(self.module, self.col * a, denom=self.denom * b).reduced() return NotImplemented __rmul__ = __mul__ def _zeroth_power(self): return self.module.one() def _first_power(self): return self def __floordiv__(self, a): if is_rat(a): a = QQ(a) return self * (1/a) elif isinstance(a, ModuleElement): return self * (1//a) return NotImplemented def __rfloordiv__(self, a): return a // self.over_power_basis() def __mod__(self, m): r""" Reduce this :py:class:`~.ModuleElement` mod a :py:class:`~.Submodule`. Parameters ========== m : int, :ref:`ZZ`, :ref:`QQ`, :py:class:`~.Submodule` If a :py:class:`~.Submodule`, reduce ``self`` relative to this. If an integer or rational, reduce relative to the :py:class:`~.Submodule` that is our own module times this constant. See Also ======== .Submodule.reduce_element """ if is_rat(m): m = m * self.module.whole_submodule() if isinstance(m, Submodule) and m.parent == self.module: return m.reduce_element(self) return NotImplemented class PowerBasisElement(ModuleElement): r""" Subclass for :py:class:`~.ModuleElement` instances whose module is a :py:class:`~.PowerBasis`. """ @property def T(self): """Access the defining polynomial of the :py:class:`~.PowerBasis`.""" return self.module.T def numerator(self, x=None): """Obtain the numerator as a polynomial over :ref:`ZZ`.""" x = x or self.T.gen return Poly(reversed(self.coeffs), x, domain=ZZ) def poly(self, x=None): """Obtain the number as a polynomial over :ref:`QQ`.""" return self.numerator(x=x) // self.denom @property def is_rational(self): """Say whether this element represents a rational number.""" return self.col[1:, :].is_zero_matrix @property def generator(self): """ Return a :py:class:`~.Symbol` to be used when expressing this element as a polynomial. If we have an associated :py:class:`~.AlgebraicField` whose primitive element has an alias symbol, we use that. Otherwise we use the variable of the minimal polynomial defining the power basis to which we belong. """ K = self.module.number_field return K.ext.alias if K and K.ext.is_aliased else self.T.gen def as_expr(self, x=None): """Create a Basic expression from ``self``. """ return self.poly(x or self.generator).as_expr() def norm(self, T=None): """Compute the norm of this number.""" T = T or self.T x = T.gen A = self.numerator(x=x) return T.resultant(A) // self.denom ** self.n def inverse(self): f = self.poly() f_inv = f.invert(self.T) return self.module.element_from_poly(f_inv) def __rfloordiv__(self, a): return self.inverse() * a def _negative_power(self, e, modulo=None): return self.inverse() ** abs(e) def to_ANP(self): """Convert to an equivalent :py:class:`~.ANP`. """ return ANP(list(reversed(self.QQ_col.flat())), QQ.map(self.T.rep.rep), QQ) def to_alg_num(self): """ Try to convert to an equivalent :py:class:`~.AlgebraicNumber`. Explanation =========== In general, the conversion from an :py:class:`~.AlgebraicNumber` to a :py:class:`~.PowerBasisElement` throws away information, because an :py:class:`~.AlgebraicNumber` specifies a complex embedding, while a :py:class:`~.PowerBasisElement` does not. However, in some cases it is possible to convert a :py:class:`~.PowerBasisElement` back into an :py:class:`~.AlgebraicNumber`, namely when the associated :py:class:`~.PowerBasis` has a reference to an :py:class:`~.AlgebraicField`. Returns ======= :py:class:`~.AlgebraicNumber` Raises ====== StructureError If the :py:class:`~.PowerBasis` to which this element belongs does not have an associated :py:class:`~.AlgebraicField`. """ K = self.module.number_field if K: return K.to_alg_num(self.to_ANP()) raise StructureError("No associated AlgebraicField") class ModuleHomomorphism: r"""A homomorphism from one module to another.""" def __init__(self, domain, codomain, mapping): r""" Parameters ========== domain : :py:class:`~.Module` The domain of the mapping. codomain : :py:class:`~.Module` The codomain of the mapping. mapping : callable An arbitrary callable is accepted, but should be chosen so as to represent an actual module homomorphism. In particular, should accept elements of *domain* and return elements of *codomain*. Examples ======== >>> from sympy import Poly, cyclotomic_poly >>> from sympy.polys.numberfields.modules import PowerBasis, ModuleHomomorphism >>> T = Poly(cyclotomic_poly(5)) >>> A = PowerBasis(T) >>> B = A.submodule_from_gens([2*A(j) for j in range(4)]) >>> phi = ModuleHomomorphism(A, B, lambda x: 6*x) >>> print(phi.matrix()) # doctest: +SKIP DomainMatrix([[3, 0, 0, 0], [0, 3, 0, 0], [0, 0, 3, 0], [0, 0, 0, 3]], (4, 4), ZZ) """ self.domain = domain self.codomain = codomain self.mapping = mapping def matrix(self, modulus=None): r""" Compute the matrix of this homomorphism. Parameters ========== modulus : int, optional A positive prime number $p$ if the matrix should be reduced mod $p$. Returns ======= :py:class:`~.DomainMatrix` The matrix is over :ref:`ZZ`, or else over :ref:`GF(p)` if a modulus was given. """ basis = self.domain.basis_elements() cols = [self.codomain.represent(self.mapping(elt)) for elt in basis] if not cols: return DomainMatrix.zeros((self.codomain.n, 0), ZZ).to_dense() M = cols[0].hstack(*cols[1:]) if modulus: M = M.convert_to(FF(modulus)) return M def kernel(self, modulus=None): r""" Compute a Submodule representing the kernel of this homomorphism. Parameters ========== modulus : int, optional A positive prime number $p$ if the kernel should be computed mod $p$. Returns ======= :py:class:`~.Submodule` This submodule's generators span the kernel of this homomorphism over :ref:`ZZ`, or else over :ref:`GF(p)` if a modulus was given. """ M = self.matrix(modulus=modulus) if modulus is None: M = M.convert_to(QQ) # Note: Even when working over a finite field, what we want here is # the pullback into the integers, so in this case the conversion to ZZ # below is appropriate. When working over ZZ, the kernel should be a # ZZ-submodule, so, while the conversion to QQ above was required in # order for the nullspace calculation to work, conversion back to ZZ # afterward should always work. # TODO: # Watch <https://github.com/sympy/sympy/issues/21834>, which calls # for fraction-free algorithms. If this is implemented, we can skip # the conversion to `QQ` above. K = M.nullspace().convert_to(ZZ).transpose() return self.domain.submodule_from_matrix(K) class ModuleEndomorphism(ModuleHomomorphism): r"""A homomorphism from one module to itself.""" def __init__(self, domain, mapping): r""" Parameters ========== domain : :py:class:`~.Module` The common domain and codomain of the mapping. mapping : callable An arbitrary callable is accepted, but should be chosen so as to represent an actual module endomorphism. In particular, should accept and return elements of *domain*. """ super().__init__(domain, domain, mapping) class InnerEndomorphism(ModuleEndomorphism): r""" An inner endomorphism on a module, i.e. the endomorphism corresponding to multiplication by a fixed element. """ def __init__(self, domain, multiplier): r""" Parameters ========== domain : :py:class:`~.Module` The domain and codomain of the endomorphism. multiplier : :py:class:`~.ModuleElement` The element $a$ defining the mapping as $x \mapsto a x$. """ super().__init__(domain, lambda x: multiplier * x) self.multiplier = multiplier class EndomorphismRing: r"""The ring of endomorphisms on a module.""" def __init__(self, domain): """ Parameters ========== domain : :py:class:`~.Module` The domain and codomain of the endomorphisms. """ self.domain = domain def inner_endomorphism(self, multiplier): r""" Form an inner endomorphism belonging to this endomorphism ring. Parameters ========== multiplier : :py:class:`~.ModuleElement` Element $a$ defining the inner endomorphism $x \mapsto a x$. Returns ======= :py:class:`~.InnerEndomorphism` """ return InnerEndomorphism(self.domain, multiplier) def represent(self, element): r""" Represent an element of this endomorphism ring, as a single column vector. Explanation =========== Let $M$ be a module, and $E$ its ring of endomorphisms. Let $N$ be another module, and consider a homomorphism $\varphi: N \rightarrow E$. In the event that $\varphi$ is to be represented by a matrix $A$, each column of $A$ must represent an element of $E$. This is possible when the elements of $E$ are themselves representable as matrices, by stacking the columns of such a matrix into a single column. This method supports calculating such matrices $A$, by representing an element of this endomorphism ring first as a matrix, and then stacking that matrix's columns into a single column. Examples ======== Note that in these examples we print matrix transposes, to make their columns easier to inspect. >>> from sympy import Poly, cyclotomic_poly >>> from sympy.polys.numberfields.modules import PowerBasis >>> from sympy.polys.numberfields.modules import ModuleHomomorphism >>> T = Poly(cyclotomic_poly(5)) >>> M = PowerBasis(T) >>> E = M.endomorphism_ring() Let $\zeta$ be a primitive 5th root of unity, a generator of our field, and consider the inner endomorphism $\tau$ on the ring of integers, induced by $\zeta$: >>> zeta = M(1) >>> tau = E.inner_endomorphism(zeta) >>> tau.matrix().transpose() # doctest: +SKIP DomainMatrix( [[0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], [-1, -1, -1, -1]], (4, 4), ZZ) The matrix representation of $\tau$ is as expected. The first column shows that multiplying by $\zeta$ carries $1$ to $\zeta$, the second column that it carries $\zeta$ to $\zeta^2$, and so forth. The ``represent`` method of the endomorphism ring ``E`` stacks these into a single column: >>> E.represent(tau).transpose() # doctest: +SKIP DomainMatrix( [[0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, -1, -1, -1, -1]], (1, 16), ZZ) This is useful when we want to consider a homomorphism $\varphi$ having ``E`` as codomain: >>> phi = ModuleHomomorphism(M, E, lambda x: E.inner_endomorphism(x)) and we want to compute the matrix of such a homomorphism: >>> phi.matrix().transpose() # doctest: +SKIP DomainMatrix( [[1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], [0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, -1, -1, -1, -1], [0, 0, 1, 0, 0, 0, 0, 1, -1, -1, -1, -1, 1, 0, 0, 0], [0, 0, 0, 1, -1, -1, -1, -1, 1, 0, 0, 0, 0, 1, 0, 0]], (4, 16), ZZ) Note that the stacked matrix of $\tau$ occurs as the second column in this example. This is because $\zeta$ is the second basis element of ``M``, and $\varphi(\zeta) = \tau$. Parameters ========== element : :py:class:`~.ModuleEndomorphism` belonging to this ring. Returns ======= :py:class:`~.DomainMatrix` Column vector equalling the vertical stacking of all the columns of the matrix that represents the given *element* as a mapping. """ if isinstance(element, ModuleEndomorphism) and element.domain == self.domain: M = element.matrix() # Transform the matrix into a single column, which should reproduce # the original columns, one after another. m, n = M.shape if n == 0: return M return M[:, 0].vstack(*[M[:, j] for j in range(1, n)]) raise NotImplementedError def find_min_poly(alpha, domain, x=None, powers=None): r""" Find a polynomial of least degree (not necessarily irreducible) satisfied by an element of a finitely-generated ring with unity. Examples ======== For the $n$th cyclotomic field, $n$ an odd prime, consider the quadratic equation whose roots are the two periods of length $(n-1)/2$. Article 356 of Gauss tells us that we should get $x^2 + x - (n-1)/4$ or $x^2 + x + (n+1)/4$ according to whether $n$ is 1 or 3 mod 4, respectively. >>> from sympy import Poly, cyclotomic_poly, primitive_root, QQ >>> from sympy.abc import x >>> from sympy.polys.numberfields.modules import PowerBasis, find_min_poly >>> n = 13 >>> g = primitive_root(n) >>> C = PowerBasis(Poly(cyclotomic_poly(n, x))) >>> ee = [g**(2*k+1) % n for k in range((n-1)//2)] >>> eta = sum(C(e) for e in ee) >>> print(find_min_poly(eta, QQ, x=x).as_expr()) x**2 + x - 3 >>> n = 19 >>> g = primitive_root(n) >>> C = PowerBasis(Poly(cyclotomic_poly(n, x))) >>> ee = [g**(2*k+2) % n for k in range((n-1)//2)] >>> eta = sum(C(e) for e in ee) >>> print(find_min_poly(eta, QQ, x=x).as_expr()) x**2 + x + 5 Parameters ========== alpha : :py:class:`~.ModuleElement` The element whose min poly is to be found, and whose module has multiplication and starts with unity. domain : :py:class:`~.Domain` The desired domain of the polynomial. x : :py:class:`~.Symbol`, optional The desired variable for the polynomial. powers : list, optional If desired, pass an empty list. The powers of *alpha* (as :py:class:`~.ModuleElement` instances) from the zeroth up to the degree of the min poly will be recorded here, as we compute them. Returns ======= :py:class:`~.Poly`, ``None`` The minimal polynomial for alpha, or ``None`` if no polynomial could be found over the desired domain. Raises ====== MissingUnityError If the module to which alpha belongs does not start with unity. ClosureFailure If the module to which alpha belongs is not closed under multiplication. """ R = alpha.module if not R.starts_with_unity(): raise MissingUnityError("alpha must belong to finitely generated ring with unity.") if powers is None: powers = [] one = R(0) powers.append(one) powers_matrix = one.column(domain=domain) ak = alpha m = None for k in range(1, R.n + 1): powers.append(ak) ak_col = ak.column(domain=domain) try: X = powers_matrix._solve(ak_col)[0] except DMBadInputError: # This means alpha^k still isn't in the domain-span of the lower powers. powers_matrix = powers_matrix.hstack(ak_col) ak *= alpha else: # alpha^k is in the domain-span of the lower powers, so we have found a # minimal-degree poly for alpha. coeffs = [1] + [-c for c in reversed(X.to_list_flat())] x = x or Dummy('x') if domain.is_FF: m = Poly(coeffs, x, modulus=domain.mod) else: m = Poly(coeffs, x, domain=domain) break return m
6005024471be6e5935aca9b7027ae48227a53c08a10a21a3b5d6573f23a9e1a2
'''Functions returning normal forms of matrices''' from collections import defaultdict from .domainmatrix import DomainMatrix from .exceptions import DMDomainError, DMShapeError from sympy.ntheory.modular import symmetric_residue from sympy.polys.domains import QQ, ZZ # TODO (future work): # There are faster algorithms for Smith and Hermite normal forms, which # we should implement. See e.g. the Kannan-Bachem algorithm: # <https://www.researchgate.net/publication/220617516_Polynomial_Algorithms_for_Computing_the_Smith_and_Hermite_Normal_Forms_of_an_Integer_Matrix> def smith_normal_form(m): ''' Return the Smith Normal Form of a matrix `m` over the ring `domain`. This will only work if the ring is a principal ideal domain. Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices import DomainMatrix >>> from sympy.polys.matrices.normalforms import smith_normal_form >>> m = DomainMatrix([[ZZ(12), ZZ(6), ZZ(4)], ... [ZZ(3), ZZ(9), ZZ(6)], ... [ZZ(2), ZZ(16), ZZ(14)]], (3, 3), ZZ) >>> print(smith_normal_form(m).to_Matrix()) Matrix([[1, 0, 0], [0, 10, 0], [0, 0, -30]]) ''' invs = invariant_factors(m) smf = DomainMatrix.diag(invs, m.domain, m.shape) return smf def add_columns(m, i, j, a, b, c, d): # replace m[:, i] by a*m[:, i] + b*m[:, j] # and m[:, j] by c*m[:, i] + d*m[:, j] for k in range(len(m)): e = m[k][i] m[k][i] = a*e + b*m[k][j] m[k][j] = c*e + d*m[k][j] def invariant_factors(m): ''' Return the tuple of abelian invariants for a matrix `m` (as in the Smith-Normal form) References ========== [1] https://en.wikipedia.org/wiki/Smith_normal_form#Algorithm [2] http://sierra.nmsu.edu/morandi/notes/SmithNormalForm.pdf ''' domain = m.domain if not domain.is_PID: msg = "The matrix entries must be over a principal ideal domain" raise ValueError(msg) if 0 in m.shape: return () rows, cols = shape = m.shape m = list(m.to_dense().rep) def add_rows(m, i, j, a, b, c, d): # replace m[i, :] by a*m[i, :] + b*m[j, :] # and m[j, :] by c*m[i, :] + d*m[j, :] for k in range(cols): e = m[i][k] m[i][k] = a*e + b*m[j][k] m[j][k] = c*e + d*m[j][k] def clear_column(m): # make m[1:, 0] zero by row and column operations if m[0][0] == 0: return m # pragma: nocover pivot = m[0][0] for j in range(1, rows): if m[j][0] == 0: continue d, r = domain.div(m[j][0], pivot) if r == 0: add_rows(m, 0, j, 1, 0, -d, 1) else: a, b, g = domain.gcdex(pivot, m[j][0]) d_0 = domain.div(m[j][0], g)[0] d_j = domain.div(pivot, g)[0] add_rows(m, 0, j, a, b, d_0, -d_j) pivot = g return m def clear_row(m): # make m[0, 1:] zero by row and column operations if m[0][0] == 0: return m # pragma: nocover pivot = m[0][0] for j in range(1, cols): if m[0][j] == 0: continue d, r = domain.div(m[0][j], pivot) if r == 0: add_columns(m, 0, j, 1, 0, -d, 1) else: a, b, g = domain.gcdex(pivot, m[0][j]) d_0 = domain.div(m[0][j], g)[0] d_j = domain.div(pivot, g)[0] add_columns(m, 0, j, a, b, d_0, -d_j) pivot = g return m # permute the rows and columns until m[0,0] is non-zero if possible ind = [i for i in range(rows) if m[i][0] != 0] if ind and ind[0] != 0: m[0], m[ind[0]] = m[ind[0]], m[0] else: ind = [j for j in range(cols) if m[0][j] != 0] if ind and ind[0] != 0: for row in m: row[0], row[ind[0]] = row[ind[0]], row[0] # make the first row and column except m[0,0] zero while (any(m[0][i] != 0 for i in range(1,cols)) or any(m[i][0] != 0 for i in range(1,rows))): m = clear_column(m) m = clear_row(m) if 1 in shape: invs = () else: lower_right = DomainMatrix([r[1:] for r in m[1:]], (rows-1, cols-1), domain) invs = invariant_factors(lower_right) if m[0][0]: result = [m[0][0]] result.extend(invs) # in case m[0] doesn't divide the invariants of the rest of the matrix for i in range(len(result)-1): if result[i] and domain.div(result[i+1], result[i])[1] != 0: g = domain.gcd(result[i+1], result[i]) result[i+1] = domain.div(result[i], g)[0]*result[i+1] result[i] = g else: break else: result = invs + (m[0][0],) return tuple(result) def _gcdex(a, b): r""" This supports the functions that compute Hermite Normal Form. Explanation =========== Let x, y be the coefficients returned by the extended Euclidean Algorithm, so that x*a + y*b = g. In the algorithms for computing HNF, it is critical that x, y not only satisfy the condition of being small in magnitude -- namely that |x| <= |b|/g, |y| <- |a|/g -- but also that y == 0 when a | b. """ x, y, g = ZZ.gcdex(a, b) if a != 0 and b % a == 0: y = 0 x = -1 if a < 0 else 1 return x, y, g def _hermite_normal_form(A): r""" Compute the Hermite Normal Form of DomainMatrix *A* over :ref:`ZZ`. Parameters ========== A : :py:class:`~.DomainMatrix` over domain :ref:`ZZ`. Returns ======= :py:class:`~.DomainMatrix` The HNF of matrix *A*. Raises ====== DMDomainError If the domain of the matrix is not :ref:`ZZ`. References ========== .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.* (See Algorithm 2.4.5.) """ if not A.domain.is_ZZ: raise DMDomainError('Matrix must be over domain ZZ.') # We work one row at a time, starting from the bottom row, and working our # way up. m, n = A.shape A = A.to_dense().rep.copy() # Our goal is to put pivot entries in the rightmost columns. # Invariant: Before processing each row, k should be the index of the # leftmost column in which we have so far put a pivot. k = n for i in range(m - 1, -1, -1): if k == 0: # This case can arise when n < m and we've already found n pivots. # We don't need to consider any more rows, because this is already # the maximum possible number of pivots. break k -= 1 # k now points to the column in which we want to put a pivot. # We want zeros in all entries to the left of the pivot column. for j in range(k - 1, -1, -1): if A[i][j] != 0: # Replace cols j, k by lin combs of these cols such that, in row i, # col j has 0, while col k has the gcd of their row i entries. Note # that this ensures a nonzero entry in col k. u, v, d = _gcdex(A[i][k], A[i][j]) r, s = A[i][k] // d, A[i][j] // d add_columns(A, k, j, u, v, -s, r) b = A[i][k] # Do not want the pivot entry to be negative. if b < 0: add_columns(A, k, k, -1, 0, -1, 0) b = -b # The pivot entry will be 0 iff the row was 0 from the pivot col all the # way to the left. In this case, we are still working on the same pivot # col for the next row. Therefore: if b == 0: k += 1 # If the pivot entry is nonzero, then we want to reduce all entries to its # right in the sense of the division algorithm, i.e. make them all remainders # w.r.t. the pivot as divisor. else: for j in range(k + 1, n): q = A[i][j] // b add_columns(A, j, k, 1, -q, 0, 1) # Finally, the HNF consists of those columns of A in which we succeeded in making # a nonzero pivot. return DomainMatrix.from_rep(A)[:, k:] def _hermite_normal_form_modulo_D(A, D): r""" Perform the mod *D* Hermite Normal Form reduction algorithm on :py:class:`~.DomainMatrix` *A*. Explanation =========== If *A* is an $m \times n$ matrix of rank $m$, having Hermite Normal Form $W$, and if *D* is any positive integer known in advance to be a multiple of $\det(W)$, then the HNF of *A* can be computed by an algorithm that works mod *D* in order to prevent coefficient explosion. Parameters ========== A : :py:class:`~.DomainMatrix` over :ref:`ZZ` $m \times n$ matrix, having rank $m$. D : :ref:`ZZ` Positive integer, known to be a multiple of the determinant of the HNF of *A*. Returns ======= :py:class:`~.DomainMatrix` The HNF of matrix *A*. Raises ====== DMDomainError If the domain of the matrix is not :ref:`ZZ`, or if *D* is given but is not in :ref:`ZZ`. DMShapeError If the matrix has more rows than columns. References ========== .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.* (See Algorithm 2.4.8.) """ if not A.domain.is_ZZ: raise DMDomainError('Matrix must be over domain ZZ.') if not ZZ.of_type(D) or D < 1: raise DMDomainError('Modulus D must be positive element of domain ZZ.') def add_columns_mod_R(m, R, i, j, a, b, c, d): # replace m[:, i] by (a*m[:, i] + b*m[:, j]) % R # and m[:, j] by (c*m[:, i] + d*m[:, j]) % R for k in range(len(m)): e = m[k][i] m[k][i] = symmetric_residue((a * e + b * m[k][j]) % R, R) m[k][j] = symmetric_residue((c * e + d * m[k][j]) % R, R) W = defaultdict(dict) m, n = A.shape if n < m: raise DMShapeError('Matrix must have at least as many columns as rows.') A = A.to_dense().rep.copy() k = n R = D for i in range(m - 1, -1, -1): k -= 1 for j in range(k - 1, -1, -1): if A[i][j] != 0: u, v, d = _gcdex(A[i][k], A[i][j]) r, s = A[i][k] // d, A[i][j] // d add_columns_mod_R(A, R, k, j, u, v, -s, r) b = A[i][k] if b == 0: A[i][k] = b = R u, v, d = _gcdex(b, R) for ii in range(m): W[ii][i] = u*A[ii][k] % R if W[i][i] == 0: W[i][i] = R for j in range(i + 1, m): q = W[i][j] // W[i][i] add_columns(W, j, i, 1, -q, 0, 1) R //= d return DomainMatrix(W, (m, m), ZZ).to_dense() def hermite_normal_form(A, *, D=None, check_rank=False): r""" Compute the Hermite Normal Form of :py:class:`~.DomainMatrix` *A* over :ref:`ZZ`. Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices import DomainMatrix >>> from sympy.polys.matrices.normalforms import hermite_normal_form >>> m = DomainMatrix([[ZZ(12), ZZ(6), ZZ(4)], ... [ZZ(3), ZZ(9), ZZ(6)], ... [ZZ(2), ZZ(16), ZZ(14)]], (3, 3), ZZ) >>> print(hermite_normal_form(m).to_Matrix()) Matrix([[10, 0, 2], [0, 15, 3], [0, 0, 2]]) Parameters ========== A : $m \times n$ ``DomainMatrix`` over :ref:`ZZ`. D : :ref:`ZZ`, optional Let $W$ be the HNF of *A*. If known in advance, a positive integer *D* being any multiple of $\det(W)$ may be provided. In this case, if *A* also has rank $m$, then we may use an alternative algorithm that works mod *D* in order to prevent coefficient explosion. check_rank : boolean, optional (default=False) The basic assumption is that, if you pass a value for *D*, then you already believe that *A* has rank $m$, so we do not waste time checking it for you. If you do want this to be checked (and the ordinary, non-modulo *D* algorithm to be used if the check fails), then set *check_rank* to ``True``. Returns ======= :py:class:`~.DomainMatrix` The HNF of matrix *A*. Raises ====== DMDomainError If the domain of the matrix is not :ref:`ZZ`, or if *D* is given but is not in :ref:`ZZ`. DMShapeError If the mod *D* algorithm is used but the matrix has more rows than columns. References ========== .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.* (See Algorithms 2.4.5 and 2.4.8.) """ if not A.domain.is_ZZ: raise DMDomainError('Matrix must be over domain ZZ.') if D is not None and (not check_rank or A.convert_to(QQ).rank() == A.shape[0]): return _hermite_normal_form_modulo_D(A, D) else: return _hermite_normal_form(A)
1d59e181b5d2708190f5aacea1fe1378cb08abb124f0e281d5885ba870656d5a
from sympy import QQ, ZZ from sympy.abc import x, theta from sympy.core.mul import prod from sympy.ntheory import factorint from sympy.ntheory.residue_ntheory import n_order from sympy.polys import Poly, cyclotomic_poly from sympy.polys.matrices import DomainMatrix from sympy.polys.numberfields.basis import round_two from sympy.polys.numberfields.exceptions import StructureError from sympy.polys.numberfields.modules import PowerBasis, to_col from sympy.polys.numberfields.primes import ( prime_decomp, _two_elt_rep, _check_formal_conditions_for_maximal_order, ) from sympy.testing.pytest import raises def test_check_formal_conditions_for_maximal_order(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ)) C = B.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ)) D = A.submodule_from_matrix(DomainMatrix.eye(4, ZZ)[:, :-1]) # Is a direct submodule of a power basis, but lacks 1 as first generator: raises(StructureError, lambda: _check_formal_conditions_for_maximal_order(B)) # Is not a direct submodule of a power basis: raises(StructureError, lambda: _check_formal_conditions_for_maximal_order(C)) # Is direct submod of pow basis, and starts with 1, but not sq/max rank/HNF: raises(StructureError, lambda: _check_formal_conditions_for_maximal_order(D)) def test_two_elt_rep(): ell = 7 T = Poly(cyclotomic_poly(ell)) ZK, dK = round_two(T) for p in [29, 13, 11, 5]: P = prime_decomp(p, T) for Pi in P: # We have Pi in two-element representation, and, because we are # looking at a cyclotomic field, this was computed by the "easy" # method that just factors T mod p. We will now convert this to # a set of Z-generators, then convert that back into a two-element # rep. The latter need not be identical to the two-elt rep we # already have, but it must have the same HNF. H = p*ZK + Pi.alpha*ZK gens = H.basis_element_pullbacks() # Note: we could supply f = Pi.f, but prefer to test behavior without it. b = _two_elt_rep(gens, ZK, p) if b != Pi.alpha: H2 = p*ZK + b*ZK assert H2 == H def test_valuation_at_prime_ideal(): p = 7 T = Poly(cyclotomic_poly(p)) ZK, dK = round_two(T) P = prime_decomp(p, T, dK=dK, ZK=ZK) assert len(P) == 1 P0 = P[0] v = P0.valuation(p*ZK) assert v == P0.e # Test easy 0 case: assert P0.valuation(5*ZK) == 0 def test_decomp_1(): # All prime decompositions in cyclotomic fields are in the "easy case," # since the index is unity. # Here we check the ramified prime. T = Poly(cyclotomic_poly(7)) raises(ValueError, lambda: prime_decomp(7)) P = prime_decomp(7, T) assert len(P) == 1 P0 = P[0] assert P0.e == 6 assert P0.f == 1 # Test powers: assert P0**0 == P0.ZK assert P0**1 == P0 assert P0**6 == 7 * P0.ZK def test_decomp_2(): # More easy cyclotomic cases, but here we check unramified primes. ell = 7 T = Poly(cyclotomic_poly(ell)) for p in [29, 13, 11, 5]: f_exp = n_order(p, ell) g_exp = (ell - 1) // f_exp P = prime_decomp(p, T) assert len(P) == g_exp for Pi in P: assert Pi.e == 1 assert Pi.f == f_exp def test_decomp_3(): T = Poly(x ** 2 - 35) rad = {} ZK, dK = round_two(T, radicals=rad) # 35 is 3 mod 4, so field disc is 4*5*7, and theory says each of the # rational primes 2, 5, 7 should be the square of a prime ideal. for p in [2, 5, 7]: P = prime_decomp(p, T, dK=dK, ZK=ZK, radical=rad.get(p)) assert len(P) == 1 assert P[0].e == 2 assert P[0]**2 == p*ZK def test_decomp_4(): T = Poly(x ** 2 - 21) rad = {} ZK, dK = round_two(T, radicals=rad) # 21 is 1 mod 4, so field disc is 3*7, and theory says the # rational primes 3, 7 should be the square of a prime ideal. for p in [3, 7]: P = prime_decomp(p, T, dK=dK, ZK=ZK, radical=rad.get(p)) assert len(P) == 1 assert P[0].e == 2 assert P[0]**2 == p*ZK def test_decomp_5(): # Here is our first test of the "hard case" of prime decomposition. # We work in a quadratic extension Q(sqrt(d)) where d is 1 mod 4, and # we consider the factorization of the rational prime 2, which divides # the index. # Theory says the form of p's factorization depends on the residue of # d mod 8, so we consider both cases, d = 1 mod 8 and d = 5 mod 8. for d in [-7, -3]: T = Poly(x ** 2 - d) rad = {} ZK, dK = round_two(T, radicals=rad) p = 2 P = prime_decomp(p, T, dK=dK, ZK=ZK, radical=rad.get(p)) if d % 8 == 1: assert len(P) == 2 assert all(P[i].e == 1 and P[i].f == 1 for i in range(2)) assert prod(Pi**Pi.e for Pi in P) == p * ZK else: assert d % 8 == 5 assert len(P) == 1 assert P[0].e == 1 assert P[0].f == 2 assert P[0].as_submodule() == p * ZK def test_decomp_6(): # Another case where 2 divides the index. This is Dedekind's example of # an essential discriminant divisor. (See Cohen, Excercise 6.10.) T = Poly(x ** 3 + x ** 2 - 2 * x + 8) rad = {} ZK, dK = round_two(T, radicals=rad) p = 2 P = prime_decomp(p, T, dK=dK, ZK=ZK, radical=rad.get(p)) assert len(P) == 3 assert all(Pi.e == Pi.f == 1 for Pi in P) assert prod(Pi**Pi.e for Pi in P) == p*ZK def test_decomp_7(): # Try working through an AlgebraicField T = Poly(x ** 3 + x ** 2 - 2 * x + 8) K = QQ.alg_field_from_poly(T) p = 2 P = K.primes_above(p) ZK = K.maximal_order() assert len(P) == 3 assert all(Pi.e == Pi.f == 1 for Pi in P) assert prod(Pi**Pi.e for Pi in P) == p*ZK def test_decomp_8(): # This time we consider various cubics, and try factoring all primes # dividing the index. cases = ( x ** 3 + 3 * x ** 2 - 4 * x + 4, x ** 3 + 3 * x ** 2 + 3 * x - 3, x ** 3 + 5 * x ** 2 - x + 3, x ** 3 + 5 * x ** 2 - 5 * x - 5, x ** 3 + 3 * x ** 2 + 5, x ** 3 + 6 * x ** 2 + 3 * x - 1, x ** 3 + 6 * x ** 2 + 4, x ** 3 + 7 * x ** 2 + 7 * x - 7, x ** 3 + 7 * x ** 2 - x + 5, x ** 3 + 7 * x ** 2 - 5 * x + 5, x ** 3 + 4 * x ** 2 - 3 * x + 7, x ** 3 + 8 * x ** 2 + 5 * x - 1, x ** 3 + 8 * x ** 2 - 2 * x + 6, x ** 3 + 6 * x ** 2 - 3 * x + 8, x ** 3 + 9 * x ** 2 + 6 * x - 8, x ** 3 + 15 * x ** 2 - 9 * x + 13, ) def display(T, p, radical, P, I, J): """Useful for inspection, when running test manually.""" print('=' * 20) print(T, p, radical) for Pi in P: print(f' ({Pi!r})') print("I: ", I) print("J: ", J) print(f'Equal: {I == J}') inspect = False for g in cases: T = Poly(g) rad = {} ZK, dK = round_two(T, radicals=rad) dT = T.discriminant() f_squared = dT // dK F = factorint(f_squared) for p in F: radical = rad.get(p) P = prime_decomp(p, T, dK=dK, ZK=ZK, radical=radical) I = prod(Pi**Pi.e for Pi in P) J = p * ZK if inspect: display(T, p, radical, P, I, J) assert I == J def test_PrimeIdeal_eq(): # `==` should fail on objects of different types, so even a completely # inert PrimeIdeal should test unequal to the rational prime it divides. T = Poly(cyclotomic_poly(7)) P0 = prime_decomp(5, T)[0] assert P0.f == 6 assert P0.as_submodule() == 5 * P0.ZK assert P0 != 5 def test_PrimeIdeal_add(): T = Poly(cyclotomic_poly(7)) P0 = prime_decomp(7, T)[0] # Adding ideals computes their GCD, so adding the ramified prime dividing # 7 to 7 itself should reproduce this prime (as a submodule). assert P0 + 7 * P0.ZK == P0.as_submodule() def test_str(): # Without alias: k = QQ.alg_field_from_poly(Poly(x**2 + 7)) frp = k.primes_above(2)[0] assert str(frp) == '(2, 3*_x/2 + 1/2)' frp = k.primes_above(3)[0] assert str(frp) == '(3)' # With alias: k = QQ.alg_field_from_poly(Poly(x ** 2 + 7), alias='alpha') frp = k.primes_above(2)[0] assert str(frp) == '(2, 3*alpha/2 + 1/2)' frp = k.primes_above(3)[0] assert str(frp) == '(3)' def test_repr(): T = Poly(x**2 + 7) ZK, dK = round_two(T) P = prime_decomp(2, T, dK=dK, ZK=ZK) assert repr(P[0]) == '[ (2, (3*x + 1)/2) e=1, f=1 ]' assert P[0].repr(field_gen=theta) == '[ (2, (3*theta + 1)/2) e=1, f=1 ]' assert P[0].repr(field_gen=theta, just_gens=True) == '(2, (3*theta + 1)/2)' def test_PrimeIdeal_reduce(): k = QQ.alg_field_from_poly(Poly(x ** 3 + x ** 2 - 2 * x + 8)) Zk = k.maximal_order() P = k.primes_above(2) frp = P[2] # reduce_element a = Zk.parent(to_col([23, 20, 11]), denom=6) a_bar_expected = Zk.parent(to_col([11, 5, 2]), denom=6) a_bar = frp.reduce_element(a) assert a_bar == a_bar_expected # reduce_ANP a = k([QQ(11, 6), QQ(20, 6), QQ(23, 6)]) a_bar_expected = k([QQ(2, 6), QQ(5, 6), QQ(11, 6)]) a_bar = frp.reduce_ANP(a) assert a_bar == a_bar_expected # reduce_alg_num a = k.to_alg_num(a) a_bar_expected = k.to_alg_num(a_bar_expected) a_bar = frp.reduce_alg_num(a) assert a_bar == a_bar_expected def test_issue_23402(): k = QQ.alg_field_from_poly(Poly(x ** 3 + x ** 2 - 2 * x + 8)) P = k.primes_above(3) assert P[0].alpha.equiv(0)
194e35eba8ff84c941db6b96c7122357f38df11b32be968decbcb778af3f9bc6
from sympy.abc import x, zeta from sympy.polys import Poly, cyclotomic_poly from sympy.polys.domains import FF, QQ, ZZ from sympy.polys.matrices import DomainMatrix, DM from sympy.polys.numberfields.exceptions import ( ClosureFailure, MissingUnityError, StructureError ) from sympy.polys.numberfields.modules import ( Module, ModuleElement, ModuleEndomorphism, PowerBasis, PowerBasisElement, find_min_poly, is_sq_maxrank_HNF, make_mod_elt, to_col, ) from sympy.polys.numberfields.utilities import is_int from sympy.polys.polyerrors import UnificationFailed from sympy.testing.pytest import raises def test_to_col(): c = [1, 2, 3, 4] m = to_col(c) assert m.domain.is_ZZ assert m.shape == (4, 1) assert m.flat() == c def test_Module_NotImplemented(): M = Module() raises(NotImplementedError, lambda: M.n) raises(NotImplementedError, lambda: M.mult_tab()) raises(NotImplementedError, lambda: M.represent(None)) raises(NotImplementedError, lambda: M.starts_with_unity()) raises(NotImplementedError, lambda: M.element_from_rational(QQ(2, 3))) def test_Module_ancestors(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ)) C = B.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ)) D = B.submodule_from_matrix(5 * DomainMatrix.eye(4, ZZ)) assert C.ancestors(include_self=True) == [A, B, C] assert D.ancestors(include_self=True) == [A, B, D] assert C.power_basis_ancestor() == A assert C.nearest_common_ancestor(D) == B M = Module() assert M.power_basis_ancestor() is None def test_Module_compat_col(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) col = to_col([1, 2, 3, 4]) row = col.transpose() assert A.is_compat_col(col) is True assert A.is_compat_col(row) is False assert A.is_compat_col(1) is False assert A.is_compat_col(DomainMatrix.eye(3, ZZ)[:, 0]) is False assert A.is_compat_col(DomainMatrix.eye(4, QQ)[:, 0]) is False assert A.is_compat_col(DomainMatrix.eye(4, ZZ)[:, 0]) is True def test_Module_call(): T = Poly(cyclotomic_poly(5, x)) B = PowerBasis(T) assert B(0).col.flat() == [1, 0, 0, 0] assert B(1).col.flat() == [0, 1, 0, 0] col = DomainMatrix.eye(4, ZZ)[:, 2] assert B(col).col == col raises(ValueError, lambda: B(-1)) def test_Module_starts_with_unity(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ)) assert A.starts_with_unity() is True assert B.starts_with_unity() is False def test_Module_basis_elements(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ)) basis = B.basis_elements() bp = B.basis_element_pullbacks() for i, (e, p) in enumerate(zip(basis, bp)): c = [0] * 4 assert e.module == B assert p.module == A c[i] = 1 assert e == B(to_col(c)) c[i] = 2 assert p == A(to_col(c)) def test_Module_zero(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ)) assert A.zero().col.flat() == [0, 0, 0, 0] assert A.zero().module == A assert B.zero().col.flat() == [0, 0, 0, 0] assert B.zero().module == B def test_Module_one(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ)) assert A.one().col.flat() == [1, 0, 0, 0] assert A.one().module == A assert B.one().col.flat() == [1, 0, 0, 0] assert B.one().module == A def test_Module_element_from_rational(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ)) rA = A.element_from_rational(QQ(22, 7)) rB = B.element_from_rational(QQ(22, 7)) assert rA.coeffs == [22, 0, 0, 0] assert rA.denom == 7 assert rA.module == A assert rB.coeffs == [22, 0, 0, 0] assert rB.denom == 7 assert rB.module == A def test_Module_submodule_from_gens(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) gens = [2*A(0), 2*A(1), 6*A(0), 6*A(1)] B = A.submodule_from_gens(gens) # Because the 3rd and 4th generators do not add anything new, we expect # the cols of the matrix of B to just reproduce the first two gens: M = gens[0].column().hstack(gens[1].column()) assert B.matrix == M # At least one generator must be provided: raises(ValueError, lambda: A.submodule_from_gens([])) # All generators must belong to A: raises(ValueError, lambda: A.submodule_from_gens([3*A(0), B(0)])) def test_Module_submodule_from_matrix(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ)) e = B(to_col([1, 2, 3, 4])) f = e.to_parent() assert f.col.flat() == [2, 4, 6, 8] # Matrix must be over ZZ: raises(ValueError, lambda: A.submodule_from_matrix(DomainMatrix.eye(4, QQ))) # Number of rows of matrix must equal number of generators of module A: raises(ValueError, lambda: A.submodule_from_matrix(2 * DomainMatrix.eye(5, ZZ))) def test_Module_whole_submodule(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) B = A.whole_submodule() e = B(to_col([1, 2, 3, 4])) f = e.to_parent() assert f.col.flat() == [1, 2, 3, 4] e0, e1, e2, e3 = B(0), B(1), B(2), B(3) assert e2 * e3 == e0 assert e3 ** 2 == e1 def test_PowerBasis_repr(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) assert repr(A) == 'PowerBasis(x**4 + x**3 + x**2 + x + 1)' def test_PowerBasis_eq(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) B = PowerBasis(T) assert A == B def test_PowerBasis_mult_tab(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) M = A.mult_tab() exp = {0: {0: [1, 0, 0, 0], 1: [0, 1, 0, 0], 2: [0, 0, 1, 0], 3: [0, 0, 0, 1]}, 1: {1: [0, 0, 1, 0], 2: [0, 0, 0, 1], 3: [-1, -1, -1, -1]}, 2: {2: [-1, -1, -1, -1], 3: [1, 0, 0, 0]}, 3: {3: [0, 1, 0, 0]}} # We get the table we expect: assert M == exp # And all entries are of expected type: assert all(is_int(c) for u in M for v in M[u] for c in M[u][v]) def test_PowerBasis_represent(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) col = to_col([1, 2, 3, 4]) a = A(col) assert A.represent(a) == col b = A(col, denom=2) raises(ClosureFailure, lambda: A.represent(b)) def test_PowerBasis_element_from_poly(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) f = Poly(1 + 2*x) g = Poly(x**4) h = Poly(0, x) assert A.element_from_poly(f).coeffs == [1, 2, 0, 0] assert A.element_from_poly(g).coeffs == [-1, -1, -1, -1] assert A.element_from_poly(h).coeffs == [0, 0, 0, 0] def test_PowerBasis_element__conversions(): k = QQ.cyclotomic_field(5) L = QQ.cyclotomic_field(7) B = PowerBasis(k) # ANP --> PowerBasisElement a = k([QQ(1, 2), QQ(1, 3), 5, 7]) e = B.element_from_ANP(a) assert e.coeffs == [42, 30, 2, 3] assert e.denom == 6 # PowerBasisElement --> ANP assert e.to_ANP() == a # Cannot convert ANP from different field d = L([QQ(1, 2), QQ(1, 3), 5, 7]) raises(UnificationFailed, lambda: B.element_from_ANP(d)) # AlgebraicNumber --> PowerBasisElement alpha = k.to_alg_num(a) eps = B.element_from_alg_num(alpha) assert eps.coeffs == [42, 30, 2, 3] assert eps.denom == 6 # PowerBasisElement --> AlgebraicNumber assert eps.to_alg_num() == alpha # Cannot convert AlgebraicNumber from different field delta = L.to_alg_num(d) raises(UnificationFailed, lambda: B.element_from_alg_num(delta)) # When we don't know the field: C = PowerBasis(k.ext.minpoly) # Can convert from AlgebraicNumber: eps = C.element_from_alg_num(alpha) assert eps.coeffs == [42, 30, 2, 3] assert eps.denom == 6 # But can't convert back: raises(StructureError, lambda: eps.to_alg_num()) def test_Submodule_repr(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ), denom=3) assert repr(B) == 'Submodule[[2, 0, 0, 0], [0, 2, 0, 0], [0, 0, 2, 0], [0, 0, 0, 2]]/3' def test_Submodule_reduced(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ)) C = A.submodule_from_matrix(6 * DomainMatrix.eye(4, ZZ), denom=3) D = C.reduced() assert D.denom == 1 and D == C == B def test_Submodule_discard_before(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ)) B.compute_mult_tab() C = B.discard_before(2) assert C.parent == B.parent assert B.is_sq_maxrank_HNF() and not C.is_sq_maxrank_HNF() assert C.matrix == B.matrix[:, 2:] assert C.mult_tab() == {0: {0: [-2, -2], 1: [0, 0]}, 1: {1: [0, 0]}} def test_Submodule_QQ_matrix(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ)) C = A.submodule_from_matrix(6 * DomainMatrix.eye(4, ZZ), denom=3) assert C.QQ_matrix == B.QQ_matrix def test_Submodule_represent(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ)) C = B.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ)) a0 = A(to_col([6, 12, 18, 24])) a1 = A(to_col([2, 4, 6, 8])) a2 = A(to_col([1, 3, 5, 7])) b1 = B.represent(a1) assert b1.flat() == [1, 2, 3, 4] c0 = C.represent(a0) assert c0.flat() == [1, 2, 3, 4] Y = A.submodule_from_matrix(DomainMatrix([ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], ], (3, 4), ZZ).transpose()) U = Poly(cyclotomic_poly(7, x)) Z = PowerBasis(U) z0 = Z(to_col([1, 2, 3, 4, 5, 6])) raises(ClosureFailure, lambda: Y.represent(A(3))) raises(ClosureFailure, lambda: B.represent(a2)) raises(ClosureFailure, lambda: B.represent(z0)) def test_Submodule_is_compat_submodule(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ)) C = A.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ)) D = C.submodule_from_matrix(5 * DomainMatrix.eye(4, ZZ)) assert B.is_compat_submodule(C) is True assert B.is_compat_submodule(A) is False assert B.is_compat_submodule(D) is False def test_Submodule_eq(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ)) C = A.submodule_from_matrix(6 * DomainMatrix.eye(4, ZZ), denom=3) assert C == B def test_Submodule_add(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) B = A.submodule_from_matrix(DomainMatrix([ [4, 0, 0, 0], [0, 4, 0, 0], ], (2, 4), ZZ).transpose(), denom=6) C = A.submodule_from_matrix(DomainMatrix([ [0, 10, 0, 0], [0, 0, 7, 0], ], (2, 4), ZZ).transpose(), denom=15) D = A.submodule_from_matrix(DomainMatrix([ [20, 0, 0, 0], [ 0, 20, 0, 0], [ 0, 0, 14, 0], ], (3, 4), ZZ).transpose(), denom=30) assert B + C == D U = Poly(cyclotomic_poly(7, x)) Z = PowerBasis(U) Y = Z.submodule_from_gens([Z(0), Z(1)]) raises(TypeError, lambda: B + Y) def test_Submodule_mul(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) C = A.submodule_from_matrix(DomainMatrix([ [0, 10, 0, 0], [0, 0, 7, 0], ], (2, 4), ZZ).transpose(), denom=15) C1 = A.submodule_from_matrix(DomainMatrix([ [0, 20, 0, 0], [0, 0, 14, 0], ], (2, 4), ZZ).transpose(), denom=3) C2 = A.submodule_from_matrix(DomainMatrix([ [0, 0, 10, 0], [0, 0, 0, 7], ], (2, 4), ZZ).transpose(), denom=15) C3_unred = A.submodule_from_matrix(DomainMatrix([ [0, 0, 100, 0], [0, 0, 0, 70], [0, 0, 0, 70], [-49, -49, -49, -49] ], (4, 4), ZZ).transpose(), denom=225) C3 = A.submodule_from_matrix(DomainMatrix([ [4900, 4900, 0, 0], [4410, 4410, 10, 0], [2107, 2107, 7, 7] ], (3, 4), ZZ).transpose(), denom=225) assert C * 1 == C assert C ** 1 == C assert C * 10 == C1 assert C * A(1) == C2 assert C.mul(C, hnf=False) == C3_unred assert C * C == C3 assert C ** 2 == C3 def test_Submodule_reduce_element(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) B = A.whole_submodule() b = B(to_col([90, 84, 80, 75]), denom=120) C = B.submodule_from_matrix(DomainMatrix.eye(4, ZZ), denom=2) b_bar_expected = B(to_col([30, 24, 20, 15]), denom=120) b_bar = C.reduce_element(b) assert b_bar == b_bar_expected C = B.submodule_from_matrix(DomainMatrix.eye(4, ZZ), denom=4) b_bar_expected = B(to_col([0, 24, 20, 15]), denom=120) b_bar = C.reduce_element(b) assert b_bar == b_bar_expected C = B.submodule_from_matrix(DomainMatrix.eye(4, ZZ), denom=8) b_bar_expected = B(to_col([0, 9, 5, 0]), denom=120) b_bar = C.reduce_element(b) assert b_bar == b_bar_expected a = A(to_col([1, 2, 3, 4])) raises(NotImplementedError, lambda: C.reduce_element(a)) C = B.submodule_from_matrix(DomainMatrix([ [5, 4, 3, 2], [0, 8, 7, 6], [0, 0,11,12], [0, 0, 0, 1] ], (4, 4), ZZ).transpose()) raises(StructureError, lambda: C.reduce_element(b)) def test_is_HNF(): M = DM([ [3, 2, 1], [0, 2, 1], [0, 0, 1] ], ZZ) M1 = DM([ [3, 2, 1], [0, -2, 1], [0, 0, 1] ], ZZ) M2 = DM([ [3, 2, 3], [0, 2, 1], [0, 0, 1] ], ZZ) assert is_sq_maxrank_HNF(M) is True assert is_sq_maxrank_HNF(M1) is False assert is_sq_maxrank_HNF(M2) is False def test_make_mod_elt(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ)) col = to_col([1, 2, 3, 4]) eA = make_mod_elt(A, col) eB = make_mod_elt(B, col) assert isinstance(eA, PowerBasisElement) assert not isinstance(eB, PowerBasisElement) def test_ModuleElement_repr(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) e = A(to_col([1, 2, 3, 4]), denom=2) assert repr(e) == '[1, 2, 3, 4]/2' def test_ModuleElement_reduced(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) e = A(to_col([2, 4, 6, 8]), denom=2) f = e.reduced() assert f.denom == 1 and f == e def test_ModuleElement_reduced_mod_p(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) e = A(to_col([20, 40, 60, 80])) f = e.reduced_mod_p(7) assert f.coeffs == [-1, -2, -3, 3] def test_ModuleElement_from_int_list(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) c = [1, 2, 3, 4] assert ModuleElement.from_int_list(A, c).coeffs == c def test_ModuleElement_len(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) e = A(0) assert len(e) == 4 def test_ModuleElement_column(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) e = A(0) col1 = e.column() assert col1 == e.col and col1 is not e.col col2 = e.column(domain=FF(5)) assert col2.domain.is_FF def test_ModuleElement_QQ_col(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) e = A(to_col([1, 2, 3, 4]), denom=1) f = A(to_col([3, 6, 9, 12]), denom=3) assert e.QQ_col == f.QQ_col def test_ModuleElement_to_ancestors(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ)) C = B.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ)) D = C.submodule_from_matrix(5 * DomainMatrix.eye(4, ZZ)) eD = D(0) eC = eD.to_parent() eB = eD.to_ancestor(B) eA = eD.over_power_basis() assert eC.module is C and eC.coeffs == [5, 0, 0, 0] assert eB.module is B and eB.coeffs == [15, 0, 0, 0] assert eA.module is A and eA.coeffs == [30, 0, 0, 0] a = A(0) raises(ValueError, lambda: a.to_parent()) def test_ModuleElement_compatibility(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ)) C = B.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ)) D = B.submodule_from_matrix(5 * DomainMatrix.eye(4, ZZ)) assert C(0).is_compat(C(1)) is True assert C(0).is_compat(D(0)) is False u, v = C(0).unify(D(0)) assert u.module is B and v.module is B assert C(C.represent(u)) == C(0) and D(D.represent(v)) == D(0) u, v = C(0).unify(C(1)) assert u == C(0) and v == C(1) U = Poly(cyclotomic_poly(7, x)) Z = PowerBasis(U) raises(UnificationFailed, lambda: C(0).unify(Z(1))) def test_ModuleElement_eq(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) e = A(to_col([1, 2, 3, 4]), denom=1) f = A(to_col([3, 6, 9, 12]), denom=3) assert e == f U = Poly(cyclotomic_poly(7, x)) Z = PowerBasis(U) assert e != Z(0) assert e != 3.14 def test_ModuleElement_equiv(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) e = A(to_col([1, 2, 3, 4]), denom=1) f = A(to_col([3, 6, 9, 12]), denom=3) assert e.equiv(f) C = A.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ)) g = C(to_col([1, 2, 3, 4]), denom=1) h = A(to_col([3, 6, 9, 12]), denom=1) assert g.equiv(h) assert C(to_col([5, 0, 0, 0]), denom=7).equiv(QQ(15, 7)) U = Poly(cyclotomic_poly(7, x)) Z = PowerBasis(U) raises(UnificationFailed, lambda: e.equiv(Z(0))) assert e.equiv(3.14) is False def test_ModuleElement_add(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) C = A.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ)) e = A(to_col([1, 2, 3, 4]), denom=6) f = A(to_col([5, 6, 7, 8]), denom=10) g = C(to_col([1, 1, 1, 1]), denom=2) assert e + f == A(to_col([10, 14, 18, 22]), denom=15) assert e - f == A(to_col([-5, -4, -3, -2]), denom=15) assert e + g == A(to_col([10, 11, 12, 13]), denom=6) assert e + QQ(7, 10) == A(to_col([26, 10, 15, 20]), denom=30) assert g + QQ(7, 10) == A(to_col([22, 15, 15, 15]), denom=10) U = Poly(cyclotomic_poly(7, x)) Z = PowerBasis(U) raises(TypeError, lambda: e + Z(0)) raises(TypeError, lambda: e + 3.14) def test_ModuleElement_mul(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) C = A.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ)) e = A(to_col([0, 2, 0, 0]), denom=3) f = A(to_col([0, 0, 0, 7]), denom=5) g = C(to_col([0, 0, 0, 1]), denom=2) h = A(to_col([0, 0, 3, 1]), denom=7) assert e * f == A(to_col([-14, -14, -14, -14]), denom=15) assert e * g == A(to_col([-1, -1, -1, -1])) assert e * h == A(to_col([-2, -2, -2, 4]), denom=21) assert e * QQ(6, 5) == A(to_col([0, 4, 0, 0]), denom=5) assert (g * QQ(10, 21)).equiv(A(to_col([0, 0, 0, 5]), denom=7)) assert e // QQ(6, 5) == A(to_col([0, 5, 0, 0]), denom=9) U = Poly(cyclotomic_poly(7, x)) Z = PowerBasis(U) raises(TypeError, lambda: e * Z(0)) raises(TypeError, lambda: e * 3.14) raises(TypeError, lambda: e // 3.14) raises(ZeroDivisionError, lambda: e // 0) def test_ModuleElement_div(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) C = A.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ)) e = A(to_col([0, 2, 0, 0]), denom=3) f = A(to_col([0, 0, 0, 7]), denom=5) g = C(to_col([1, 1, 1, 1])) assert e // f == 10*A(3)//21 assert e // g == -2*A(2)//9 assert 3 // g == -A(1) def test_ModuleElement_pow(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) C = A.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ)) e = A(to_col([0, 2, 0, 0]), denom=3) g = C(to_col([0, 0, 0, 1]), denom=2) assert e ** 3 == A(to_col([0, 0, 0, 8]), denom=27) assert g ** 2 == C(to_col([0, 3, 0, 0]), denom=4) assert e ** 0 == A(to_col([1, 0, 0, 0])) assert g ** 0 == A(to_col([1, 0, 0, 0])) assert e ** 1 == e assert g ** 1 == g def test_ModuleElement_mod(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) e = A(to_col([1, 15, 8, 0]), denom=2) assert e % 7 == A(to_col([1, 1, 8, 0]), denom=2) assert e % QQ(1, 2) == A.zero() assert e % QQ(1, 3) == A(to_col([1, 1, 0, 0]), denom=6) B = A.submodule_from_gens([A(0), 5*A(1), 3*A(2), A(3)]) assert e % B == A(to_col([1, 5, 2, 0]), denom=2) C = B.whole_submodule() raises(TypeError, lambda: e % C) def test_PowerBasisElement_polys(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) e = A(to_col([1, 15, 8, 0]), denom=2) assert e.numerator(x=zeta) == Poly(8 * zeta ** 2 + 15 * zeta + 1, domain=ZZ) assert e.poly(x=zeta) == Poly(4 * zeta ** 2 + QQ(15, 2) * zeta + QQ(1, 2), domain=QQ) def test_PowerBasisElement_norm(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) lam = A(to_col([1, -1, 0, 0])) assert lam.norm() == 5 def test_PowerBasisElement_inverse(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) e = A(to_col([1, 1, 1, 1])) assert 2 // e == -2*A(1) assert e ** -3 == -A(3) def test_ModuleHomomorphism_matrix(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) phi = ModuleEndomorphism(A, lambda a: a ** 2) M = phi.matrix() assert M == DomainMatrix([ [1, 0, -1, 0], [0, 0, -1, 1], [0, 1, -1, 0], [0, 0, -1, 0] ], (4, 4), ZZ) def test_ModuleHomomorphism_kernel(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) phi = ModuleEndomorphism(A, lambda a: a ** 5) N = phi.kernel() assert N.n == 3 def test_EndomorphismRing_represent(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) R = A.endomorphism_ring() phi = R.inner_endomorphism(A(1)) col = R.represent(phi) assert col.transpose() == DomainMatrix([ [0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, -1, -1, -1, -1] ], (1, 16), ZZ) B = A.submodule_from_matrix(DomainMatrix.zeros((4, 0), ZZ)) S = B.endomorphism_ring() psi = S.inner_endomorphism(A(1)) col = S.represent(psi) assert col == DomainMatrix([], (0, 0), ZZ) raises(NotImplementedError, lambda: R.represent(3.14)) def test_find_min_poly(): T = Poly(cyclotomic_poly(5, x)) A = PowerBasis(T) powers = [] m = find_min_poly(A(1), QQ, x=x, powers=powers) assert m == Poly(T, domain=QQ) assert len(powers) == 5 # powers list need not be passed m = find_min_poly(A(1), QQ, x=x) assert m == Poly(T, domain=QQ) B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ)) raises(MissingUnityError, lambda: find_min_poly(B(1), QQ))
ff80a6dc42711e1dd3130176efcb81ed6419c1e15616cc778f4cdcd806458032
from sympy.testing.pytest import raises from sympy.core.symbol import Symbol from sympy.polys.matrices.normalforms import ( invariant_factors, smith_normal_form, hermite_normal_form, _hermite_normal_form, _hermite_normal_form_modulo_D) from sympy.polys.domains import ZZ, QQ from sympy.polys.matrices import DomainMatrix, DM from sympy.polys.matrices.exceptions import DMDomainError, DMShapeError def test_smith_normal(): m = DM([[12, 6, 4, 8], [3, 9, 6, 12], [2, 16, 14, 28], [20, 10, 10, 20]], ZZ) smf = DM([[1, 0, 0, 0], [0, 10, 0, 0], [0, 0, -30, 0], [0, 0, 0, 0]], ZZ) assert smith_normal_form(m).to_dense() == smf x = Symbol('x') m = DM([[x-1, 1, -1], [ 0, x, -1], [ 0, -1, x]], QQ[x]) dx = m.domain.gens[0] assert invariant_factors(m) == (1, dx-1, dx**2-1) zr = DomainMatrix([], (0, 2), ZZ) zc = DomainMatrix([[], []], (2, 0), ZZ) assert smith_normal_form(zr).to_dense() == zr assert smith_normal_form(zc).to_dense() == zc assert smith_normal_form(DM([[2, 4]], ZZ)).to_dense() == DM([[2, 0]], ZZ) assert smith_normal_form(DM([[0, -2]], ZZ)).to_dense() == DM([[-2, 0]], ZZ) assert smith_normal_form(DM([[0], [-2]], ZZ)).to_dense() == DM([[-2], [0]], ZZ) m = DM([[3, 0, 0, 0], [0, 0, 0, 0], [0, 0, 2, 0]], ZZ) snf = DM([[1, 0, 0, 0], [0, 6, 0, 0], [0, 0, 0, 0]], ZZ) assert smith_normal_form(m).to_dense() == snf raises(ValueError, lambda: smith_normal_form(DM([[1]], ZZ[x]))) def test_hermite_normal(): m = DM([[2, 7, 17, 29, 41], [3, 11, 19, 31, 43], [5, 13, 23, 37, 47]], ZZ) hnf = DM([[1, 0, 0], [0, 2, 1], [0, 0, 1]], ZZ) assert hermite_normal_form(m) == hnf assert hermite_normal_form(m, D=ZZ(2)) == hnf assert hermite_normal_form(m, D=ZZ(2), check_rank=True) == hnf m = m.transpose() hnf = DM([[37, 0, 19], [222, -6, 113], [48, 0, 25], [0, 2, 1], [0, 0, 1]], ZZ) assert hermite_normal_form(m) == hnf raises(DMShapeError, lambda: _hermite_normal_form_modulo_D(m, ZZ(96))) raises(DMDomainError, lambda: _hermite_normal_form_modulo_D(m, QQ(96))) m = DM([[8, 28, 68, 116, 164], [3, 11, 19, 31, 43], [5, 13, 23, 37, 47]], ZZ) hnf = DM([[4, 0, 0], [0, 2, 1], [0, 0, 1]], ZZ) assert hermite_normal_form(m) == hnf assert hermite_normal_form(m, D=ZZ(8)) == hnf assert hermite_normal_form(m, D=ZZ(8), check_rank=True) == hnf m = DM([[10, 8, 6, 30, 2], [45, 36, 27, 18, 9], [5, 4, 3, 2, 1]], ZZ) hnf = DM([[26, 2], [0, 9], [0, 1]], ZZ) assert hermite_normal_form(m) == hnf m = DM([[2, 7], [0, 0], [0, 0]], ZZ) hnf = DM([[1], [0], [0]], ZZ) assert hermite_normal_form(m) == hnf m = DM([[-2, 1], [0, 1]], ZZ) hnf = DM([[2, 1], [0, 1]], ZZ) assert hermite_normal_form(m) == hnf m = DomainMatrix([[QQ(1)]], (1, 1), QQ) raises(DMDomainError, lambda: hermite_normal_form(m)) raises(DMDomainError, lambda: _hermite_normal_form(m)) raises(DMDomainError, lambda: _hermite_normal_form_modulo_D(m, ZZ(1)))
95c4fcc3b9a7e94119f13fb17c0e13a86e0cb7b271634d281e1396ec9b4741f6
from sympy.core.singleton import S from sympy.core.symbol import symbols from sympy.parsing.ast_parser import parse_expr from sympy.testing.pytest import raises from sympy.core.sympify import SympifyError import warnings def test_parse_expr(): a, b = symbols('a, b') # tests issue_16393 assert parse_expr('a + b', {}) == a + b raises(SympifyError, lambda: parse_expr('a + ', {})) # tests Transform.visit_Constant assert parse_expr('1 + 2', {}) == S(3) assert parse_expr('1 + 2.0', {}) == S(3.0) # tests Transform.visit_Name assert parse_expr('Rational(1, 2)', {}) == S(1)/2 assert parse_expr('a', {'a': a}) == a # tests issue_23092 with warnings.catch_warnings(): warnings.simplefilter('error') assert parse_expr('6 * 7', {}) == S(42)
67393297d360f766286a87317ee118668ca92fe4c139150bbae66e3402357441
# -*- coding: utf-8 -*- import sys import builtins import types from sympy.assumptions import Q from sympy.core import Symbol, Function, Float, Rational, Integer, I, Mul, Pow, Eq from sympy.functions import exp, factorial, factorial2, sin, Min, Max from sympy.logic import And from sympy.series import Limit from sympy.testing.pytest import raises, skip from sympy.parsing.sympy_parser import ( parse_expr, standard_transformations, rationalize, TokenError, split_symbols, implicit_multiplication, convert_equals_signs, convert_xor, function_exponentiation, lambda_notation, auto_symbol, repeated_decimals, implicit_multiplication_application, auto_number, factorial_notation, implicit_application, _transformation, T ) def test_sympy_parser(): x = Symbol('x') inputs = { '2*x': 2 * x, '3.00': Float(3), '22/7': Rational(22, 7), '2+3j': 2 + 3*I, 'exp(x)': exp(x), 'x!': factorial(x), 'x!!': factorial2(x), '(x + 1)! - 1': factorial(x + 1) - 1, '3.[3]': Rational(10, 3), '.0[3]': Rational(1, 30), '3.2[3]': Rational(97, 30), '1.3[12]': Rational(433, 330), '1 + 3.[3]': Rational(13, 3), '1 + .0[3]': Rational(31, 30), '1 + 3.2[3]': Rational(127, 30), '.[0011]': Rational(1, 909), '0.1[00102] + 1': Rational(366697, 333330), '1.[0191]': Rational(10190, 9999), '10!': 3628800, '-(2)': -Integer(2), '[-1, -2, 3]': [Integer(-1), Integer(-2), Integer(3)], 'Symbol("x").free_symbols': x.free_symbols, "S('S(3).n(n=3)')": 3.00, 'factorint(12, visual=True)': Mul( Pow(2, 2, evaluate=False), Pow(3, 1, evaluate=False), evaluate=False), 'Limit(sin(x), x, 0, dir="-")': Limit(sin(x), x, 0, dir='-'), 'Q.even(x)': Q.even(x), } for text, result in inputs.items(): assert parse_expr(text) == result raises(TypeError, lambda: parse_expr('x', standard_transformations)) raises(TypeError, lambda: parse_expr('x', transformations=lambda x,y: 1)) raises(TypeError, lambda: parse_expr('x', transformations=(lambda x,y: 1,))) raises(TypeError, lambda: parse_expr('x', transformations=((),))) raises(TypeError, lambda: parse_expr('x', {}, [], [])) raises(TypeError, lambda: parse_expr('x', [], [], {})) raises(TypeError, lambda: parse_expr('x', [], [], {})) def test_rationalize(): inputs = { '0.123': Rational(123, 1000) } transformations = standard_transformations + (rationalize,) for text, result in inputs.items(): assert parse_expr(text, transformations=transformations) == result def test_factorial_fail(): inputs = ['x!!!', 'x!!!!', '(!)'] for text in inputs: try: parse_expr(text) assert False except TokenError: assert True def test_repeated_fail(): inputs = ['1[1]', '.1e1[1]', '0x1[1]', '1.1j[1]', '1.1[1 + 1]', '0.1[[1]]', '0x1.1[1]'] # All are valid Python, so only raise TypeError for invalid indexing for text in inputs: raises(TypeError, lambda: parse_expr(text)) inputs = ['0.1[', '0.1[1', '0.1[]'] for text in inputs: raises((TokenError, SyntaxError), lambda: parse_expr(text)) def test_repeated_dot_only(): assert parse_expr('.[1]') == Rational(1, 9) assert parse_expr('1 + .[1]') == Rational(10, 9) def test_local_dict(): local_dict = { 'my_function': lambda x: x + 2 } inputs = { 'my_function(2)': Integer(4) } for text, result in inputs.items(): assert parse_expr(text, local_dict=local_dict) == result def test_local_dict_split_implmult(): t = standard_transformations + (split_symbols, implicit_multiplication,) w = Symbol('w', real=True) y = Symbol('y') assert parse_expr('yx', local_dict={'x':w}, transformations=t) == y*w def test_local_dict_symbol_to_fcn(): x = Symbol('x') d = {'foo': Function('bar')} assert parse_expr('foo(x)', local_dict=d) == d['foo'](x) d = {'foo': Symbol('baz')} raises(TypeError, lambda: parse_expr('foo(x)', local_dict=d)) def test_global_dict(): global_dict = { 'Symbol': Symbol } inputs = { 'Q & S': And(Symbol('Q'), Symbol('S')) } for text, result in inputs.items(): assert parse_expr(text, global_dict=global_dict) == result def test_no_globals(): # Replicate creating the default global_dict: default_globals = {} exec('from sympy import *', default_globals) builtins_dict = vars(builtins) for name, obj in builtins_dict.items(): if isinstance(obj, types.BuiltinFunctionType): default_globals[name] = obj default_globals['max'] = Max default_globals['min'] = Min # Need to include Symbol or parse_expr will not work: default_globals.pop('Symbol') global_dict = {'Symbol':Symbol} for name in default_globals: obj = parse_expr(name, global_dict=global_dict) assert obj == Symbol(name) def test_issue_2515(): raises(TokenError, lambda: parse_expr('(()')) raises(TokenError, lambda: parse_expr('"""')) def test_issue_7663(): x = Symbol('x') e = '2*(x+1)' assert parse_expr(e, evaluate=0) == parse_expr(e, evaluate=False) assert parse_expr(e, evaluate=0).equals(2*(x+1)) def test_recursive_evaluate_false_10560(): inputs = { '4*-3' : '4*-3', '-4*3' : '(-4)*3', "-2*x*y": '(-2)*x*y', "x*-4*x": "x*(-4)*x" } for text, result in inputs.items(): assert parse_expr(text, evaluate=False) == parse_expr(result, evaluate=False) def test_function_evaluate_false(): inputs = [ 'Abs(0)', 'im(0)', 're(0)', 'sign(0)', 'arg(0)', 'conjugate(0)', 'acos(0)', 'acot(0)', 'acsc(0)', 'asec(0)', 'asin(0)', 'atan(0)', 'acosh(0)', 'acoth(0)', 'acsch(0)', 'asech(0)', 'asinh(0)', 'atanh(0)', 'cos(0)', 'cot(0)', 'csc(0)', 'sec(0)', 'sin(0)', 'tan(0)', 'cosh(0)', 'coth(0)', 'csch(0)', 'sech(0)', 'sinh(0)', 'tanh(0)', 'exp(0)', 'log(0)', 'sqrt(0)', ] for case in inputs: expr = parse_expr(case, evaluate=False) assert case == str(expr) != str(expr.doit()) assert str(parse_expr('ln(0)', evaluate=False)) == 'log(0)' assert str(parse_expr('cbrt(0)', evaluate=False)) == '0**(1/3)' def test_issue_10773(): inputs = { '-10/5': '(-10)/5', '-10/-5' : '(-10)/(-5)', } for text, result in inputs.items(): assert parse_expr(text, evaluate=False) == parse_expr(result, evaluate=False) def test_split_symbols(): transformations = standard_transformations + \ (split_symbols, implicit_multiplication,) x = Symbol('x') y = Symbol('y') xy = Symbol('xy') assert parse_expr("xy") == xy assert parse_expr("xy", transformations=transformations) == x*y def test_split_symbols_function(): transformations = standard_transformations + \ (split_symbols, implicit_multiplication,) x = Symbol('x') y = Symbol('y') a = Symbol('a') f = Function('f') assert parse_expr("ay(x+1)", transformations=transformations) == a*y*(x+1) assert parse_expr("af(x+1)", transformations=transformations, local_dict={'f':f}) == a*f(x+1) def test_functional_exponent(): t = standard_transformations + (convert_xor, function_exponentiation) x = Symbol('x') y = Symbol('y') a = Symbol('a') yfcn = Function('y') assert parse_expr("sin^2(x)", transformations=t) == (sin(x))**2 assert parse_expr("sin^y(x)", transformations=t) == (sin(x))**y assert parse_expr("exp^y(x)", transformations=t) == (exp(x))**y assert parse_expr("E^y(x)", transformations=t) == exp(yfcn(x)) assert parse_expr("a^y(x)", transformations=t) == a**(yfcn(x)) def test_match_parentheses_implicit_multiplication(): transformations = standard_transformations + \ (implicit_multiplication,) raises(TokenError, lambda: parse_expr('(1,2),(3,4]',transformations=transformations)) def test_convert_equals_signs(): transformations = standard_transformations + \ (convert_equals_signs, ) x = Symbol('x') y = Symbol('y') assert parse_expr("1*2=x", transformations=transformations) == Eq(2, x) assert parse_expr("y = x", transformations=transformations) == Eq(y, x) assert parse_expr("(2*y = x) = False", transformations=transformations) == Eq(Eq(2*y, x), False) def test_parse_function_issue_3539(): x = Symbol('x') f = Function('f') assert parse_expr('f(x)') == f(x) def test_split_symbols_numeric(): transformations = ( standard_transformations + (implicit_multiplication_application,)) n = Symbol('n') expr1 = parse_expr('2**n * 3**n') expr2 = parse_expr('2**n3**n', transformations=transformations) assert expr1 == expr2 == 2**n*3**n expr1 = parse_expr('n12n34', transformations=transformations) assert expr1 == n*12*n*34 def test_unicode_names(): assert parse_expr('α') == Symbol('α') def test_python3_features(): # Make sure the tokenizer can handle Python 3-only features if sys.version_info < (3, 8): skip("test_python3_features requires Python 3.8 or newer") assert parse_expr("123_456") == 123456 assert parse_expr("1.2[3_4]") == parse_expr("1.2[34]") == Rational(611, 495) assert parse_expr("1.2[012_012]") == parse_expr("1.2[012012]") == Rational(400, 333) assert parse_expr('.[3_4]') == parse_expr('.[34]') == Rational(34, 99) assert parse_expr('.1[3_4]') == parse_expr('.1[34]') == Rational(133, 990) assert parse_expr('123_123.123_123[3_4]') == parse_expr('123123.123123[34]') == Rational(12189189189211, 99000000) def test_issue_19501(): x = Symbol('x') eq = parse_expr('E**x(1+x)', local_dict={'x': x}, transformations=( standard_transformations + (implicit_multiplication_application,))) assert eq.free_symbols == {x} def test_parsing_definitions(): from sympy.abc import x assert len(_transformation) == 12 # if this changes, extend below assert _transformation[0] == lambda_notation assert _transformation[1] == auto_symbol assert _transformation[2] == repeated_decimals assert _transformation[3] == auto_number assert _transformation[4] == factorial_notation assert _transformation[5] == implicit_multiplication_application assert _transformation[6] == convert_xor assert _transformation[7] == implicit_application assert _transformation[8] == implicit_multiplication assert _transformation[9] == convert_equals_signs assert _transformation[10] == function_exponentiation assert _transformation[11] == rationalize assert T[:5] == T[0,1,2,3,4] == standard_transformations t = _transformation assert T[-1, 0] == (t[len(t) - 1], t[0]) assert T[:5, 8] == standard_transformations + (t[8],) assert parse_expr('0.3x^2', transformations='all') == 3*x**2/10 assert parse_expr('sin 3x', transformations='implicit') == sin(3*x) def test_builtins(): cases = [ ('abs(x)', 'Abs(x)'), ('max(x, y)', 'Max(x, y)'), ('min(x, y)', 'Min(x, y)'), ('pow(x, y)', 'Pow(x, y)'), ] for built_in_func_call, sympy_func_call in cases: assert parse_expr(built_in_func_call) == parse_expr(sympy_func_call) assert str(parse_expr('pow(38, -1, 97)')) == '23' def test_issue_22822(): raises(ValueError, lambda: parse_expr('x', {'': 1})) data = {'some_parameter': None} assert parse_expr('some_parameter is None', data) is True
e758c86d42a9a38ca4b04117df6537cf4322d80a7b9759ccdf62b2a1b2d071b1
from sympy.testing.pytest import raises, XFAIL from sympy.external import import_module from sympy.concrete.products import Product from sympy.concrete.summations import Sum from sympy.core.add import Add from sympy.core.function import (Derivative, Function) from sympy.core.mul import Mul from sympy.core.numbers import (E, oo) from sympy.core.power import Pow from sympy.core.relational import (GreaterThan, LessThan, StrictGreaterThan, StrictLessThan, Unequality) from sympy.core.symbol import Symbol from sympy.functions.combinatorial.factorials import (binomial, factorial) from sympy.functions.elementary.complexes import (Abs, conjugate) from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.integers import (ceiling, floor) from sympy.functions.elementary.miscellaneous import (root, sqrt) from sympy.functions.elementary.trigonometric import (asin, cos, csc, sec, sin, tan) from sympy.integrals.integrals import Integral from sympy.series.limits import Limit from sympy.core.relational import Eq, Ne, Lt, Le, Gt, Ge from sympy.physics.quantum.state import Bra, Ket from sympy.abc import x, y, z, a, b, c, t, k, n antlr4 = import_module("antlr4") # disable tests if antlr4-python*-runtime is not present if not antlr4: disabled = True theta = Symbol('theta') f = Function('f') # shorthand definitions def _Add(a, b): return Add(a, b, evaluate=False) def _Mul(a, b): return Mul(a, b, evaluate=False) def _Pow(a, b): return Pow(a, b, evaluate=False) def _Sqrt(a): return sqrt(a, evaluate=False) def _Conjugate(a): return conjugate(a, evaluate=False) def _Abs(a): return Abs(a, evaluate=False) def _factorial(a): return factorial(a, evaluate=False) def _exp(a): return exp(a, evaluate=False) def _log(a, b): return log(a, b, evaluate=False) def _binomial(n, k): return binomial(n, k, evaluate=False) def test_import(): from sympy.parsing.latex._build_latex_antlr import ( build_parser, check_antlr_version, dir_latex_antlr ) # XXX: It would be better to come up with a test for these... del build_parser, check_antlr_version, dir_latex_antlr # These LaTeX strings should parse to the corresponding SymPy expression GOOD_PAIRS = [ (r"0", 0), (r"1", 1), (r"-3.14", -3.14), (r"(-7.13)(1.5)", _Mul(-7.13, 1.5)), (r"x", x), (r"2x", 2*x), (r"x^2", x**2), (r"x^\frac{1}{2}", _Pow(x, _Pow(2, -1))), (r"x^{3 + 1}", x**_Add(3, 1)), (r"-c", -c), (r"a \cdot b", a * b), (r"a / b", a / b), (r"a \div b", a / b), (r"a + b", a + b), (r"a + b - a", _Add(a+b, -a)), (r"a^2 + b^2 = c^2", Eq(a**2 + b**2, c**2)), (r"(x + y) z", _Mul(_Add(x, y), z)), (r"\left(x + y\right) z", _Mul(_Add(x, y), z)), (r"\left( x + y\right ) z", _Mul(_Add(x, y), z)), (r"\left( x + y\right ) z", _Mul(_Add(x, y), z)), (r"\left[x + y\right] z", _Mul(_Add(x, y), z)), (r"\left\{x + y\right\} z", _Mul(_Add(x, y), z)), (r"1+1", _Add(1, 1)), (r"0+1", _Add(0, 1)), (r"1*2", _Mul(1, 2)), (r"0*1", _Mul(0, 1)), (r"1 \times 2 ", _Mul(1, 2)), (r"x = y", Eq(x, y)), (r"x \neq y", Ne(x, y)), (r"x < y", Lt(x, y)), (r"x > y", Gt(x, y)), (r"x \leq y", Le(x, y)), (r"x \geq y", Ge(x, y)), (r"x \le y", Le(x, y)), (r"x \ge y", Ge(x, y)), (r"\lfloor x \rfloor", floor(x)), (r"\lceil x \rceil", ceiling(x)), (r"\langle x |", Bra('x')), (r"| x \rangle", Ket('x')), (r"\sin \theta", sin(theta)), (r"\sin(\theta)", sin(theta)), (r"\sin^{-1} a", asin(a)), (r"\sin a \cos b", _Mul(sin(a), cos(b))), (r"\sin \cos \theta", sin(cos(theta))), (r"\sin(\cos \theta)", sin(cos(theta))), (r"\frac{a}{b}", a / b), (r"\dfrac{a}{b}", a / b), (r"\tfrac{a}{b}", a / b), (r"\frac{a + b}{c}", _Mul(a + b, _Pow(c, -1))), (r"\frac{7}{3}", _Mul(7, _Pow(3, -1))), (r"(\csc x)(\sec y)", csc(x)*sec(y)), (r"\lim_{x \to 3} a", Limit(a, x, 3)), (r"\lim_{x \rightarrow 3} a", Limit(a, x, 3)), (r"\lim_{x \Rightarrow 3} a", Limit(a, x, 3)), (r"\lim_{x \longrightarrow 3} a", Limit(a, x, 3)), (r"\lim_{x \Longrightarrow 3} a", Limit(a, x, 3)), (r"\lim_{x \to 3^{+}} a", Limit(a, x, 3, dir='+')), (r"\lim_{x \to 3^{-}} a", Limit(a, x, 3, dir='-')), (r"\infty", oo), (r"\lim_{x \to \infty} \frac{1}{x}", Limit(_Pow(x, -1), x, oo)), (r"\frac{d}{dx} x", Derivative(x, x)), (r"\frac{d}{dt} x", Derivative(x, t)), (r"f(x)", f(x)), (r"f(x, y)", f(x, y)), (r"f(x, y, z)", f(x, y, z)), (r"\frac{d f(x)}{dx}", Derivative(f(x), x)), (r"\frac{d\theta(x)}{dx}", Derivative(Function('theta')(x), x)), (r"x \neq y", Unequality(x, y)), (r"|x|", _Abs(x)), (r"||x||", _Abs(Abs(x))), (r"|x||y|", _Abs(x)*_Abs(y)), (r"||x||y||", _Abs(_Abs(x)*_Abs(y))), (r"\pi^{|xy|}", Symbol('pi')**_Abs(x*y)), (r"\int x dx", Integral(x, x)), (r"\int x d\theta", Integral(x, theta)), (r"\int (x^2 - y)dx", Integral(x**2 - y, x)), (r"\int x + a dx", Integral(_Add(x, a), x)), (r"\int da", Integral(1, a)), (r"\int_0^7 dx", Integral(1, (x, 0, 7))), (r"\int\limits_{0}^{1} x dx", Integral(x, (x, 0, 1))), (r"\int_a^b x dx", Integral(x, (x, a, b))), (r"\int^b_a x dx", Integral(x, (x, a, b))), (r"\int_{a}^b x dx", Integral(x, (x, a, b))), (r"\int^{b}_a x dx", Integral(x, (x, a, b))), (r"\int_{a}^{b} x dx", Integral(x, (x, a, b))), (r"\int^{b}_{a} x dx", Integral(x, (x, a, b))), (r"\int_{f(a)}^{f(b)} f(z) dz", Integral(f(z), (z, f(a), f(b)))), (r"\int (x+a)", Integral(_Add(x, a), x)), (r"\int a + b + c dx", Integral(_Add(_Add(a, b), c), x)), (r"\int \frac{dz}{z}", Integral(Pow(z, -1), z)), (r"\int \frac{3 dz}{z}", Integral(3*Pow(z, -1), z)), (r"\int \frac{1}{x} dx", Integral(Pow(x, -1), x)), (r"\int \frac{1}{a} + \frac{1}{b} dx", Integral(_Add(_Pow(a, -1), Pow(b, -1)), x)), (r"\int \frac{3 \cdot d\theta}{\theta}", Integral(3*_Pow(theta, -1), theta)), (r"\int \frac{1}{x} + 1 dx", Integral(_Add(_Pow(x, -1), 1), x)), (r"x_0", Symbol('x_{0}')), (r"x_{1}", Symbol('x_{1}')), (r"x_a", Symbol('x_{a}')), (r"x_{b}", Symbol('x_{b}')), (r"h_\theta", Symbol('h_{theta}')), (r"h_{\theta}", Symbol('h_{theta}')), (r"h_{\theta}(x_0, x_1)", Function('h_{theta}')(Symbol('x_{0}'), Symbol('x_{1}'))), (r"x!", _factorial(x)), (r"100!", _factorial(100)), (r"\theta!", _factorial(theta)), (r"(x + 1)!", _factorial(_Add(x, 1))), (r"(x!)!", _factorial(_factorial(x))), (r"x!!!", _factorial(_factorial(_factorial(x)))), (r"5!7!", _Mul(_factorial(5), _factorial(7))), (r"\sqrt{x}", sqrt(x)), (r"\sqrt{x + b}", sqrt(_Add(x, b))), (r"\sqrt[3]{\sin x}", root(sin(x), 3)), (r"\sqrt[y]{\sin x}", root(sin(x), y)), (r"\sqrt[\theta]{\sin x}", root(sin(x), theta)), (r"\sqrt{\frac{12}{6}}", _Sqrt(_Mul(12, _Pow(6, -1)))), (r"\overline{z}", _Conjugate(z)), (r"\overline{\overline{z}}", _Conjugate(_Conjugate(z))), (r"\overline{x + y}", _Conjugate(_Add(x, y))), (r"\overline{x} + \overline{y}", _Conjugate(x) + _Conjugate(y)), (r"x < y", StrictLessThan(x, y)), (r"x \leq y", LessThan(x, y)), (r"x > y", StrictGreaterThan(x, y)), (r"x \geq y", GreaterThan(x, y)), (r"\mathit{x}", Symbol('x')), (r"\mathit{test}", Symbol('test')), (r"\mathit{TEST}", Symbol('TEST')), (r"\mathit{HELLO world}", Symbol('HELLO world')), (r"\sum_{k = 1}^{3} c", Sum(c, (k, 1, 3))), (r"\sum_{k = 1}^3 c", Sum(c, (k, 1, 3))), (r"\sum^{3}_{k = 1} c", Sum(c, (k, 1, 3))), (r"\sum^3_{k = 1} c", Sum(c, (k, 1, 3))), (r"\sum_{k = 1}^{10} k^2", Sum(k**2, (k, 1, 10))), (r"\sum_{n = 0}^{\infty} \frac{1}{n!}", Sum(_Pow(_factorial(n), -1), (n, 0, oo))), (r"\prod_{a = b}^{c} x", Product(x, (a, b, c))), (r"\prod_{a = b}^c x", Product(x, (a, b, c))), (r"\prod^{c}_{a = b} x", Product(x, (a, b, c))), (r"\prod^c_{a = b} x", Product(x, (a, b, c))), (r"\exp x", _exp(x)), (r"\exp(x)", _exp(x)), (r"\ln x", _log(x, E)), (r"\ln xy", _log(x*y, E)), (r"\log x", _log(x, 10)), (r"\log xy", _log(x*y, 10)), (r"\log_{2} x", _log(x, 2)), (r"\log_{a} x", _log(x, a)), (r"\log_{11} x", _log(x, 11)), (r"\log_{a^2} x", _log(x, _Pow(a, 2))), (r"[x]", x), (r"[a + b]", _Add(a, b)), (r"\frac{d}{dx} [ \tan x ]", Derivative(tan(x), x)), (r"\binom{n}{k}", _binomial(n, k)), (r"\tbinom{n}{k}", _binomial(n, k)), (r"\dbinom{n}{k}", _binomial(n, k)), (r"\binom{n}{0}", _binomial(n, 0)), (r"x^\binom{n}{k}", _Pow(x, _binomial(n, k))), (r"a \, b", _Mul(a, b)), (r"a \thinspace b", _Mul(a, b)), (r"a \: b", _Mul(a, b)), (r"a \medspace b", _Mul(a, b)), (r"a \; b", _Mul(a, b)), (r"a \thickspace b", _Mul(a, b)), (r"a \quad b", _Mul(a, b)), (r"a \qquad b", _Mul(a, b)), (r"a \! b", _Mul(a, b)), (r"a \negthinspace b", _Mul(a, b)), (r"a \negmedspace b", _Mul(a, b)), (r"a \negthickspace b", _Mul(a, b)), (r"\int x \, dx", Integral(x, x)), (r"\log_2 x", _log(x, 2)), (r"\log_a x", _log(x, a)), (r"5^0 - 4^0", _Add(_Pow(5, 0), _Mul(-1, _Pow(4, 0)))), ] def test_parseable(): from sympy.parsing.latex import parse_latex for latex_str, sympy_expr in GOOD_PAIRS: assert parse_latex(latex_str) == sympy_expr, latex_str # These bad LaTeX strings should raise a LaTeXParsingError when parsed BAD_STRINGS = [ r"(", r")", r"\frac{d}{dx}", r"(\frac{d}{dx})", r"\sqrt{}", r"\sqrt", r"\overline{}", r"\overline", r"{", r"}", r"\mathit{x + y}", r"\mathit{21}", r"\frac{2}{}", r"\frac{}{2}", r"\int", r"!", r"!0", r"_", r"^", r"|", r"||x|", r"()", r"((((((((((((((((()))))))))))))))))", r"-", r"\frac{d}{dx} + \frac{d}{dt}", r"f(x,,y)", r"f(x,y,", r"\sin^x", r"\cos^2", r"@", r"#", r"$", r"%", r"&", r"*", r"" "\\", r"~", r"\frac{(2 + x}{1 - x)}", ] def test_not_parseable(): from sympy.parsing.latex import parse_latex, LaTeXParsingError for latex_str in BAD_STRINGS: with raises(LaTeXParsingError): parse_latex(latex_str) # At time of migration from latex2sympy, should fail but doesn't FAILING_BAD_STRINGS = [ r"\cos 1 \cos", r"f(,", r"f()", r"a \div \div b", r"a \cdot \cdot b", r"a // b", r"a +", r"1.1.1", r"1 +", r"a / b /", ] @XFAIL def test_failing_not_parseable(): from sympy.parsing.latex import parse_latex, LaTeXParsingError for latex_str in FAILING_BAD_STRINGS: with raises(LaTeXParsingError): parse_latex(latex_str)
3fd815ba1cfe80492f6386a64130120a3d97d2d2b994b926245af30e66dc677d
from sympy import sin, Function, symbols, Dummy, Lambda, cos from sympy.parsing.mathematica import parse_mathematica, MathematicaParser from sympy.core.sympify import sympify from sympy.abc import n, w, x, y, z from sympy.testing.pytest import raises def test_mathematica(): d = { '- 6x': '-6*x', 'Sin[x]^2': 'sin(x)**2', '2(x-1)': '2*(x-1)', '3y+8': '3*y+8', 'ArcSin[2x+9(4-x)^2]/x': 'asin(2*x+9*(4-x)**2)/x', 'x+y': 'x+y', '355/113': '355/113', '2.718281828': '2.718281828', 'Sin[12]': 'sin(12)', 'Exp[Log[4]]': 'exp(log(4))', '(x+1)(x+3)': '(x+1)*(x+3)', 'Cos[ArcCos[3.6]]': 'cos(acos(3.6))', 'Cos[x]==Sin[y]': 'Eq(cos(x), sin(y))', '2*Sin[x+y]': '2*sin(x+y)', 'Sin[x]+Cos[y]': 'sin(x)+cos(y)', 'Sin[Cos[x]]': 'sin(cos(x))', '2*Sqrt[x+y]': '2*sqrt(x+y)', # Test case from the issue 4259 '+Sqrt[2]': 'sqrt(2)', '-Sqrt[2]': '-sqrt(2)', '-1/Sqrt[2]': '-1/sqrt(2)', '-(1/Sqrt[3])': '-(1/sqrt(3))', '1/(2*Sqrt[5])': '1/(2*sqrt(5))', 'Mod[5,3]': 'Mod(5,3)', '-Mod[5,3]': '-Mod(5,3)', '(x+1)y': '(x+1)*y', 'x(y+1)': 'x*(y+1)', 'Sin[x]Cos[y]': 'sin(x)*cos(y)', 'Sin[x]^2Cos[y]^2': 'sin(x)**2*cos(y)**2', 'Cos[x]^2(1 - Cos[y]^2)': 'cos(x)**2*(1-cos(y)**2)', 'x y': 'x*y', 'x y': 'x*y', '2 x': '2*x', 'x 8': 'x*8', '2 8': '2*8', '4.x': '4.*x', '4. 3': '4.*3', '4. 3.': '4.*3.', '1 2 3': '1*2*3', ' - 2 * Sqrt[ 2 3 * ( 1 + 5 ) ] ': '-2*sqrt(2*3*(1+5))', 'Log[2,4]': 'log(4,2)', 'Log[Log[2,4],4]': 'log(4,log(4,2))', 'Exp[Sqrt[2]^2Log[2, 8]]': 'exp(sqrt(2)**2*log(8,2))', 'ArcSin[Cos[0]]': 'asin(cos(0))', 'Log2[16]': 'log(16,2)', 'Max[1,-2,3,-4]': 'Max(1,-2,3,-4)', 'Min[1,-2,3]': 'Min(1,-2,3)', 'Exp[I Pi/2]': 'exp(I*pi/2)', 'ArcTan[x,y]': 'atan2(y,x)', 'Pochhammer[x,y]': 'rf(x,y)', 'ExpIntegralEi[x]': 'Ei(x)', 'SinIntegral[x]': 'Si(x)', 'CosIntegral[x]': 'Ci(x)', 'AiryAi[x]': 'airyai(x)', 'AiryAiPrime[5]': 'airyaiprime(5)', 'AiryBi[x]': 'airybi(x)', 'AiryBiPrime[7]': 'airybiprime(7)', 'LogIntegral[4]': ' li(4)', 'PrimePi[7]': 'primepi(7)', 'Prime[5]': 'prime(5)', 'PrimeQ[5]': 'isprime(5)' } for e in d: assert parse_mathematica(e) == sympify(d[e]) # The parsed form of this expression should not evaluate the Lambda object: assert parse_mathematica("Sin[#]^2 + Cos[#]^2 &[x]") == sin(x)**2 + cos(x)**2 d1, d2, d3 = symbols("d1:4", cls=Dummy) assert parse_mathematica("Sin[#] + Cos[#3] &").dummy_eq(Lambda((d1, d2, d3), sin(d1) + cos(d3))) assert parse_mathematica("Sin[#^2] &").dummy_eq(Lambda(d1, sin(d1**2))) assert parse_mathematica("Function[x, x^3]") == Lambda(x, x**3) assert parse_mathematica("Function[{x, y}, x^2 + y^2]") == Lambda((x, y), x**2 + y**2) def test_parser_mathematica_tokenizer(): parser = MathematicaParser() chain = lambda expr: parser._from_tokens_to_fullformlist(parser._from_mathematica_to_tokens(expr)) # Basic patterns assert chain("x") == "x" assert chain("42") == "42" assert chain(".2") == ".2" assert chain("+x") == "x" assert chain("-1") == "-1" assert chain("- 3") == "-3" assert chain("+Sin[x]") == ["Sin", "x"] assert chain("-Sin[x]") == ["Times", "-1", ["Sin", "x"]] assert chain("x(a+1)") == ["Times", "x", ["Plus", "a", "1"]] assert chain("(x)") == "x" assert chain("(+x)") == "x" assert chain("-a") == ["Times", "-1", "a"] assert chain("(-x)") == ["Times", "-1", "x"] assert chain("(x + y)") == ["Plus", "x", "y"] assert chain("3 + 4") == ["Plus", "3", "4"] assert chain("a - 3") == ["Plus", "a", "-3"] assert chain("a - b") == ["Plus", "a", ["Times", "-1", "b"]] assert chain("7 * 8") == ["Times", "7", "8"] assert chain("a + b*c") == ["Plus", "a", ["Times", "b", "c"]] assert chain("a + b* c* d + 2 * e") == ["Plus", "a", ["Times", "b", "c", "d"], ["Times", "2", "e"]] assert chain("a / b") == ["Times", "a", ["Power", "b", "-1"]] # Missing asterisk (*) patterns: assert chain("x y") == ["Times", "x", "y"] assert chain("3 4") == ["Times", "3", "4"] assert chain("a[b] c") == ["Times", ["a", "b"], "c"] assert chain("(x) (y)") == ["Times", "x", "y"] assert chain("3 (a)") == ["Times", "3", "a"] assert chain("(a) b") == ["Times", "a", "b"] assert chain("4.2") == "4.2" assert chain("4 2") == ["Times", "4", "2"] assert chain("4 2") == ["Times", "4", "2"] assert chain("3 . 4") == ["Dot", "3", "4"] assert chain("4. 2") == ["Times", "4.", "2"] assert chain("x.y") == ["Dot", "x", "y"] assert chain("4.y") == ["Times", "4.", "y"] assert chain("4 .y") == ["Dot", "4", "y"] assert chain("x.4") == ["Times", "x", ".4"] assert chain("x0.3") == ["Times", "x0", ".3"] assert chain("x. 4") == ["Dot", "x", "4"] # Comments assert chain("a (* +b *) + c") == ["Plus", "a", "c"] assert chain("a (* + b *) + (**)c (* +d *) + e") == ["Plus", "a", "c", "e"] assert chain("""a + (* + b *) c + (* d *) e """) == ["Plus", "a", "c", "e"] # Operators couples + and -, * and / are mutually associative: # (i.e. expression gets flattened when mixing these operators) assert chain("a*b/c") == ["Times", "a", "b", ["Power", "c", "-1"]] assert chain("a/b*c") == ["Times", "a", ["Power", "b", "-1"], "c"] assert chain("a+b-c") == ["Plus", "a", "b", ["Times", "-1", "c"]] assert chain("a-b+c") == ["Plus", "a", ["Times", "-1", "b"], "c"] assert chain("-a + b -c ") == ["Plus", ["Times", "-1", "a"], "b", ["Times", "-1", "c"]] assert chain("a/b/c*d") == ["Times", "a", ["Power", "b", "-1"], ["Power", "c", "-1"], "d"] assert chain("a/b/c") == ["Times", "a", ["Power", "b", "-1"], ["Power", "c", "-1"]] assert chain("a-b-c") == ["Plus", "a", ["Times", "-1", "b"], ["Times", "-1", "c"]] assert chain("1/a") == ["Times", "1", ["Power", "a", "-1"]] assert chain("1/a/b") == ["Times", "1", ["Power", "a", "-1"], ["Power", "b", "-1"]] assert chain("-1/a*b") == ["Times", "-1", ["Power", "a", "-1"], "b"] # Enclosures of various kinds, i.e. ( ) [ ] [[ ]] { } assert chain("(a + b) + c") == ["Plus", ["Plus", "a", "b"], "c"] assert chain(" a + (b + c) + d ") == ["Plus", "a", ["Plus", "b", "c"], "d"] assert chain("a * (b + c)") == ["Times", "a", ["Plus", "b", "c"]] assert chain("a b (c d)") == ["Times", "a", "b", ["Times", "c", "d"]] assert chain("{a, b, 2, c}") == ["List", "a", "b", "2", "c"] assert chain("{a, {b, c}}") == ["List", "a", ["List", "b", "c"]] assert chain("{{a}}") == ["List", ["List", "a"]] assert chain("a[b, c]") == ["a", "b", "c"] assert chain("a[[b, c]]") == ["Part", "a", "b", "c"] assert chain("a[b[c]]") == ["a", ["b", "c"]] assert chain("a[[b, c[[d, {e,f}]]]]") == ["Part", "a", "b", ["Part", "c", "d", ["List", "e", "f"]]] assert chain("a[b[[c,d]]]") == ["a", ["Part", "b", "c", "d"]] assert chain("a[[b[c]]]") == ["Part", "a", ["b", "c"]] assert chain("a[[b[[c]]]]") == ["Part", "a", ["Part", "b", "c"]] assert chain("a[[b[c[[d]]]]]") == ["Part", "a", ["b", ["Part", "c", "d"]]] assert chain("a[b[[c[d]]]]") == ["a", ["Part", "b", ["c", "d"]]] assert chain("x[[a+1, b+2, c+3]]") == ["Part", "x", ["Plus", "a", "1"], ["Plus", "b", "2"], ["Plus", "c", "3"]] assert chain("x[a+1, b+2, c+3]") == ["x", ["Plus", "a", "1"], ["Plus", "b", "2"], ["Plus", "c", "3"]] assert chain("{a+1, b+2, c+3}") == ["List", ["Plus", "a", "1"], ["Plus", "b", "2"], ["Plus", "c", "3"]] # Flat operator: assert chain("a*b*c*d*e") == ["Times", "a", "b", "c", "d", "e"] assert chain("a +b + c+ d+e") == ["Plus", "a", "b", "c", "d", "e"] # Right priority operator: assert chain("a^b") == ["Power", "a", "b"] assert chain("a^b^c") == ["Power", "a", ["Power", "b", "c"]] assert chain("a^b^c^d") == ["Power", "a", ["Power", "b", ["Power", "c", "d"]]] # Left priority operator: assert chain("a/.b") == ["ReplaceAll", "a", "b"] assert chain("a/.b/.c/.d") == ["ReplaceAll", ["ReplaceAll", ["ReplaceAll", "a", "b"], "c"], "d"] assert chain("a//b") == ["a", "b"] assert chain("a//b//c") == [["a", "b"], "c"] assert chain("a//b//c//d") == [[["a", "b"], "c"], "d"] # Compound expressions assert chain("a;b") == ["CompoundExpression", "a", "b"] assert chain("a;") == ["CompoundExpression", "a", "Null"] assert chain("a;b;") == ["CompoundExpression", "a", "b", "Null"] assert chain("a[b;c]") == ["a", ["CompoundExpression", "b", "c"]] assert chain("a[b,c;d,e]") == ["a", "b", ["CompoundExpression", "c", "d"], "e"] assert chain("a[b,c;,d]") == ["a", "b", ["CompoundExpression", "c", "Null"], "d"] # New lines assert chain("a\nb\n") == ["CompoundExpression", "a", "b"] assert chain("a\n\nb\n (c \nd) \n") == ["CompoundExpression", "a", "b", ["Times", "c", "d"]] assert chain("\na; b\nc") == ["CompoundExpression", "a", "b", "c"] assert chain("a + \nb\n") == ["Plus", "a", "b"] assert chain("a\nb; c; d\n e; (f \n g); h + \n i") == ["CompoundExpression", "a", "b", "c", "d", "e", ["Times", "f", "g"], ["Plus", "h", "i"]] assert chain("\n{\na\nb; c; d\n e (f \n g); h + \n i\n\n}\n") == ["List", ["CompoundExpression", ["Times", "a", "b"], "c", ["Times", "d", "e", ["Times", "f", "g"]], ["Plus", "h", "i"]]] # Patterns assert chain("y_") == ["Pattern", "y", ["Blank"]] assert chain("y_.") == ["Optional", ["Pattern", "y", ["Blank"]]] assert chain("y__") == ["Pattern", "y", ["BlankSequence"]] assert chain("y___") == ["Pattern", "y", ["BlankNullSequence"]] assert chain("a[b_.,c_]") == ["a", ["Optional", ["Pattern", "b", ["Blank"]]], ["Pattern", "c", ["Blank"]]] assert chain("b_. c") == ["Times", ["Optional", ["Pattern", "b", ["Blank"]]], "c"] # Slots for lambda functions assert chain("#") == ["Slot", "1"] assert chain("#3") == ["Slot", "3"] assert chain("#n") == ["Slot", "n"] assert chain("##") == ["SlotSequence", "1"] assert chain("##a") == ["SlotSequence", "a"] # Lambda functions assert chain("x&") == ["Function", "x"] assert chain("#&") == ["Function", ["Slot", "1"]] assert chain("#+3&") == ["Function", ["Plus", ["Slot", "1"], "3"]] assert chain("#1 + #2&") == ["Function", ["Plus", ["Slot", "1"], ["Slot", "2"]]] assert chain("# + #&") == ["Function", ["Plus", ["Slot", "1"], ["Slot", "1"]]] assert chain("#&[x]") == [["Function", ["Slot", "1"]], "x"] assert chain("#1 + #2 & [x, y]") == [["Function", ["Plus", ["Slot", "1"], ["Slot", "2"]]], "x", "y"] assert chain("#1^2#2^3&") == ["Function", ["Times", ["Power", ["Slot", "1"], "2"], ["Power", ["Slot", "2"], "3"]]] # Strings inside Mathematica expressions: assert chain('"abc"') == ["_Str", "abc"] assert chain('"a\\"b"') == ["_Str", 'a"b'] # This expression does not make sense mathematically, it's just testing the parser: assert chain('x + "abc" ^ 3') == ["Plus", "x", ["Power", ["_Str", "abc"], "3"]] assert chain('"a (* b *) c"') == ["_Str", "a (* b *) c"] assert chain('"a" (* b *) ') == ["_Str", "a"] assert chain('"a [ b] "') == ["_Str", "a [ b] "] raises(SyntaxError, lambda: chain('"')) raises(SyntaxError, lambda: chain('"\\"')) raises(SyntaxError, lambda: chain('"abc')) raises(SyntaxError, lambda: chain('"abc\\"def')) # Invalid expressions: raises(SyntaxError, lambda: chain("(,")) raises(SyntaxError, lambda: chain("()")) raises(SyntaxError, lambda: chain("a (* b")) def test_parser_mathematica_exp_alt(): parser = MathematicaParser() convert_chain2 = lambda expr: parser._from_fullformlist_to_fullformsympy(parser._from_fullform_to_fullformlist(expr)) convert_chain3 = lambda expr: parser._from_fullformsympy_to_sympy(convert_chain2(expr)) Sin, Times, Plus, Power = symbols("Sin Times Plus Power", cls=Function) full_form1 = "Sin[Times[x, y]]" full_form2 = "Plus[Times[x, y], z]" full_form3 = "Sin[Times[x, Plus[y, z], Power[w, n]]]]" assert parser._from_fullform_to_fullformlist(full_form1) == ["Sin", ["Times", "x", "y"]] assert parser._from_fullform_to_fullformlist(full_form2) == ["Plus", ["Times", "x", "y"], "z"] assert parser._from_fullform_to_fullformlist(full_form3) == ["Sin", ["Times", "x", ["Plus", "y", "z"], ["Power", "w", "n"]]] assert convert_chain2(full_form1) == Sin(Times(x, y)) assert convert_chain2(full_form2) == Plus(Times(x, y), z) assert convert_chain2(full_form3) == Sin(Times(x, Plus(y, z), Power(w, n))) assert convert_chain3(full_form1) == sin(x*y) assert convert_chain3(full_form2) == x*y + z assert convert_chain3(full_form3) == sin(x*(y + z)*w**n)
6caaabfa4fc4bc61aef626be0d7610f45eabbe1f7a79f2463e04bfc2a395b7f0
# Ported from latex2sympy by @augustt198 # https://github.com/augustt198/latex2sympy # See license in LICENSE.txt import sympy from sympy.external import import_module from sympy.printing.str import StrPrinter from sympy.physics.quantum.state import Bra, Ket from .errors import LaTeXParsingError LaTeXParser = LaTeXLexer = MathErrorListener = None try: LaTeXParser = import_module('sympy.parsing.latex._antlr.latexparser', import_kwargs={'fromlist': ['LaTeXParser']}).LaTeXParser LaTeXLexer = import_module('sympy.parsing.latex._antlr.latexlexer', import_kwargs={'fromlist': ['LaTeXLexer']}).LaTeXLexer except Exception: pass ErrorListener = import_module('antlr4.error.ErrorListener', warn_not_installed=True, import_kwargs={'fromlist': ['ErrorListener']} ) if ErrorListener: class MathErrorListener(ErrorListener.ErrorListener): # type: ignore def __init__(self, src): super(ErrorListener.ErrorListener, self).__init__() self.src = src def syntaxError(self, recog, symbol, line, col, msg, e): fmt = "%s\n%s\n%s" marker = "~" * col + "^" if msg.startswith("missing"): err = fmt % (msg, self.src, marker) elif msg.startswith("no viable"): err = fmt % ("I expected something else here", self.src, marker) elif msg.startswith("mismatched"): names = LaTeXParser.literalNames expected = [ names[i] for i in e.getExpectedTokens() if i < len(names) ] if len(expected) < 10: expected = " ".join(expected) err = (fmt % ("I expected one of these: " + expected, self.src, marker)) else: err = (fmt % ("I expected something else here", self.src, marker)) else: err = fmt % ("I don't understand this", self.src, marker) raise LaTeXParsingError(err) def parse_latex(sympy): antlr4 = import_module('antlr4', warn_not_installed=True) if None in [antlr4, MathErrorListener]: raise ImportError("LaTeX parsing requires the antlr4 Python package," " provided by pip (antlr4-python2-runtime or" " antlr4-python3-runtime) or" " conda (antlr-python-runtime)") matherror = MathErrorListener(sympy) stream = antlr4.InputStream(sympy) lex = LaTeXLexer(stream) lex.removeErrorListeners() lex.addErrorListener(matherror) tokens = antlr4.CommonTokenStream(lex) parser = LaTeXParser(tokens) # remove default console error listener parser.removeErrorListeners() parser.addErrorListener(matherror) relation = parser.math().relation() expr = convert_relation(relation) return expr def convert_relation(rel): if rel.expr(): return convert_expr(rel.expr()) lh = convert_relation(rel.relation(0)) rh = convert_relation(rel.relation(1)) if rel.LT(): return sympy.StrictLessThan(lh, rh) elif rel.LTE(): return sympy.LessThan(lh, rh) elif rel.GT(): return sympy.StrictGreaterThan(lh, rh) elif rel.GTE(): return sympy.GreaterThan(lh, rh) elif rel.EQUAL(): return sympy.Eq(lh, rh) elif rel.NEQ(): return sympy.Ne(lh, rh) def convert_expr(expr): return convert_add(expr.additive()) def convert_add(add): if add.ADD(): lh = convert_add(add.additive(0)) rh = convert_add(add.additive(1)) return sympy.Add(lh, rh, evaluate=False) elif add.SUB(): lh = convert_add(add.additive(0)) rh = convert_add(add.additive(1)) return sympy.Add(lh, sympy.Mul(-1, rh, evaluate=False), evaluate=False) else: return convert_mp(add.mp()) def convert_mp(mp): if hasattr(mp, 'mp'): mp_left = mp.mp(0) mp_right = mp.mp(1) else: mp_left = mp.mp_nofunc(0) mp_right = mp.mp_nofunc(1) if mp.MUL() or mp.CMD_TIMES() or mp.CMD_CDOT(): lh = convert_mp(mp_left) rh = convert_mp(mp_right) return sympy.Mul(lh, rh, evaluate=False) elif mp.DIV() or mp.CMD_DIV() or mp.COLON(): lh = convert_mp(mp_left) rh = convert_mp(mp_right) return sympy.Mul(lh, sympy.Pow(rh, -1, evaluate=False), evaluate=False) else: if hasattr(mp, 'unary'): return convert_unary(mp.unary()) else: return convert_unary(mp.unary_nofunc()) def convert_unary(unary): if hasattr(unary, 'unary'): nested_unary = unary.unary() else: nested_unary = unary.unary_nofunc() if hasattr(unary, 'postfix_nofunc'): first = unary.postfix() tail = unary.postfix_nofunc() postfix = [first] + tail else: postfix = unary.postfix() if unary.ADD(): return convert_unary(nested_unary) elif unary.SUB(): numabs = convert_unary(nested_unary) # Use Integer(-n) instead of Mul(-1, n) return -numabs elif postfix: return convert_postfix_list(postfix) def convert_postfix_list(arr, i=0): if i >= len(arr): raise LaTeXParsingError("Index out of bounds") res = convert_postfix(arr[i]) if isinstance(res, sympy.Expr): if i == len(arr) - 1: return res # nothing to multiply by else: if i > 0: left = convert_postfix(arr[i - 1]) right = convert_postfix(arr[i + 1]) if isinstance(left, sympy.Expr) and isinstance( right, sympy.Expr): left_syms = convert_postfix(arr[i - 1]).atoms(sympy.Symbol) right_syms = convert_postfix(arr[i + 1]).atoms( sympy.Symbol) # if the left and right sides contain no variables and the # symbol in between is 'x', treat as multiplication. if not (left_syms or right_syms) and str(res) == 'x': return convert_postfix_list(arr, i + 1) # multiply by next return sympy.Mul( res, convert_postfix_list(arr, i + 1), evaluate=False) else: # must be derivative wrt = res[0] if i == len(arr) - 1: raise LaTeXParsingError("Expected expression for derivative") else: expr = convert_postfix_list(arr, i + 1) return sympy.Derivative(expr, wrt) def do_subs(expr, at): if at.expr(): at_expr = convert_expr(at.expr()) syms = at_expr.atoms(sympy.Symbol) if len(syms) == 0: return expr elif len(syms) > 0: sym = next(iter(syms)) return expr.subs(sym, at_expr) elif at.equality(): lh = convert_expr(at.equality().expr(0)) rh = convert_expr(at.equality().expr(1)) return expr.subs(lh, rh) def convert_postfix(postfix): if hasattr(postfix, 'exp'): exp_nested = postfix.exp() else: exp_nested = postfix.exp_nofunc() exp = convert_exp(exp_nested) for op in postfix.postfix_op(): if op.BANG(): if isinstance(exp, list): raise LaTeXParsingError("Cannot apply postfix to derivative") exp = sympy.factorial(exp, evaluate=False) elif op.eval_at(): ev = op.eval_at() at_b = None at_a = None if ev.eval_at_sup(): at_b = do_subs(exp, ev.eval_at_sup()) if ev.eval_at_sub(): at_a = do_subs(exp, ev.eval_at_sub()) if at_b is not None and at_a is not None: exp = sympy.Add(at_b, -1 * at_a, evaluate=False) elif at_b is not None: exp = at_b elif at_a is not None: exp = at_a return exp def convert_exp(exp): if hasattr(exp, 'exp'): exp_nested = exp.exp() else: exp_nested = exp.exp_nofunc() if exp_nested: base = convert_exp(exp_nested) if isinstance(base, list): raise LaTeXParsingError("Cannot raise derivative to power") if exp.atom(): exponent = convert_atom(exp.atom()) elif exp.expr(): exponent = convert_expr(exp.expr()) return sympy.Pow(base, exponent, evaluate=False) else: if hasattr(exp, 'comp'): return convert_comp(exp.comp()) else: return convert_comp(exp.comp_nofunc()) def convert_comp(comp): if comp.group(): return convert_expr(comp.group().expr()) elif comp.abs_group(): return sympy.Abs(convert_expr(comp.abs_group().expr()), evaluate=False) elif comp.atom(): return convert_atom(comp.atom()) elif comp.floor(): return convert_floor(comp.floor()) elif comp.ceil(): return convert_ceil(comp.ceil()) elif comp.func(): return convert_func(comp.func()) def convert_atom(atom): if atom.LETTER(): subscriptName = '' if atom.subexpr(): subscript = None if atom.subexpr().expr(): # subscript is expr subscript = convert_expr(atom.subexpr().expr()) else: # subscript is atom subscript = convert_atom(atom.subexpr().atom()) subscriptName = '_{' + StrPrinter().doprint(subscript) + '}' return sympy.Symbol(atom.LETTER().getText() + subscriptName) elif atom.SYMBOL(): s = atom.SYMBOL().getText()[1:] if s == "infty": return sympy.oo else: if atom.subexpr(): subscript = None if atom.subexpr().expr(): # subscript is expr subscript = convert_expr(atom.subexpr().expr()) else: # subscript is atom subscript = convert_atom(atom.subexpr().atom()) subscriptName = StrPrinter().doprint(subscript) s += '_{' + subscriptName + '}' return sympy.Symbol(s) elif atom.NUMBER(): s = atom.NUMBER().getText().replace(",", "") return sympy.Number(s) elif atom.DIFFERENTIAL(): var = get_differential_var(atom.DIFFERENTIAL()) return sympy.Symbol('d' + var.name) elif atom.mathit(): text = rule2text(atom.mathit().mathit_text()) return sympy.Symbol(text) elif atom.frac(): return convert_frac(atom.frac()) elif atom.binom(): return convert_binom(atom.binom()) elif atom.bra(): val = convert_expr(atom.bra().expr()) return Bra(val) elif atom.ket(): val = convert_expr(atom.ket().expr()) return Ket(val) def rule2text(ctx): stream = ctx.start.getInputStream() # starting index of starting token startIdx = ctx.start.start # stopping index of stopping token stopIdx = ctx.stop.stop return stream.getText(startIdx, stopIdx) def convert_frac(frac): diff_op = False partial_op = False lower_itv = frac.lower.getSourceInterval() lower_itv_len = lower_itv[1] - lower_itv[0] + 1 if (frac.lower.start == frac.lower.stop and frac.lower.start.type == LaTeXLexer.DIFFERENTIAL): wrt = get_differential_var_str(frac.lower.start.text) diff_op = True elif (lower_itv_len == 2 and frac.lower.start.type == LaTeXLexer.SYMBOL and frac.lower.start.text == '\\partial' and (frac.lower.stop.type == LaTeXLexer.LETTER or frac.lower.stop.type == LaTeXLexer.SYMBOL)): partial_op = True wrt = frac.lower.stop.text if frac.lower.stop.type == LaTeXLexer.SYMBOL: wrt = wrt[1:] if diff_op or partial_op: wrt = sympy.Symbol(wrt) if (diff_op and frac.upper.start == frac.upper.stop and frac.upper.start.type == LaTeXLexer.LETTER and frac.upper.start.text == 'd'): return [wrt] elif (partial_op and frac.upper.start == frac.upper.stop and frac.upper.start.type == LaTeXLexer.SYMBOL and frac.upper.start.text == '\\partial'): return [wrt] upper_text = rule2text(frac.upper) expr_top = None if diff_op and upper_text.startswith('d'): expr_top = parse_latex(upper_text[1:]) elif partial_op and frac.upper.start.text == '\\partial': expr_top = parse_latex(upper_text[len('\\partial'):]) if expr_top: return sympy.Derivative(expr_top, wrt) expr_top = convert_expr(frac.upper) expr_bot = convert_expr(frac.lower) inverse_denom = sympy.Pow(expr_bot, -1, evaluate=False) if expr_top == 1: return inverse_denom else: return sympy.Mul(expr_top, inverse_denom, evaluate=False) def convert_binom(binom): expr_n = convert_expr(binom.n) expr_k = convert_expr(binom.k) return sympy.binomial(expr_n, expr_k, evaluate=False) def convert_floor(floor): val = convert_expr(floor.val) return sympy.floor(val, evaluate=False) def convert_ceil(ceil): val = convert_expr(ceil.val) return sympy.ceiling(val, evaluate=False) def convert_func(func): if func.func_normal(): if func.L_PAREN(): # function called with parenthesis arg = convert_func_arg(func.func_arg()) else: arg = convert_func_arg(func.func_arg_noparens()) name = func.func_normal().start.text[1:] # change arc<trig> -> a<trig> if name in [ "arcsin", "arccos", "arctan", "arccsc", "arcsec", "arccot" ]: name = "a" + name[3:] expr = getattr(sympy.functions, name)(arg, evaluate=False) if name in ["arsinh", "arcosh", "artanh"]: name = "a" + name[2:] expr = getattr(sympy.functions, name)(arg, evaluate=False) if name == "exp": expr = sympy.exp(arg, evaluate=False) if (name == "log" or name == "ln"): if func.subexpr(): if func.subexpr().expr(): base = convert_expr(func.subexpr().expr()) else: base = convert_atom(func.subexpr().atom()) elif name == "log": base = 10 elif name == "ln": base = sympy.E expr = sympy.log(arg, base, evaluate=False) func_pow = None should_pow = True if func.supexpr(): if func.supexpr().expr(): func_pow = convert_expr(func.supexpr().expr()) else: func_pow = convert_atom(func.supexpr().atom()) if name in [ "sin", "cos", "tan", "csc", "sec", "cot", "sinh", "cosh", "tanh" ]: if func_pow == -1: name = "a" + name should_pow = False expr = getattr(sympy.functions, name)(arg, evaluate=False) if func_pow and should_pow: expr = sympy.Pow(expr, func_pow, evaluate=False) return expr elif func.LETTER() or func.SYMBOL(): if func.LETTER(): fname = func.LETTER().getText() elif func.SYMBOL(): fname = func.SYMBOL().getText()[1:] fname = str(fname) # can't be unicode if func.subexpr(): subscript = None if func.subexpr().expr(): # subscript is expr subscript = convert_expr(func.subexpr().expr()) else: # subscript is atom subscript = convert_atom(func.subexpr().atom()) subscriptName = StrPrinter().doprint(subscript) fname += '_{' + subscriptName + '}' input_args = func.args() output_args = [] while input_args.args(): # handle multiple arguments to function output_args.append(convert_expr(input_args.expr())) input_args = input_args.args() output_args.append(convert_expr(input_args.expr())) return sympy.Function(fname)(*output_args) elif func.FUNC_INT(): return handle_integral(func) elif func.FUNC_SQRT(): expr = convert_expr(func.base) if func.root: r = convert_expr(func.root) return sympy.root(expr, r, evaluate=False) else: return sympy.sqrt(expr, evaluate=False) elif func.FUNC_OVERLINE(): expr = convert_expr(func.base) return sympy.conjugate(expr, evaluate=False) elif func.FUNC_SUM(): return handle_sum_or_prod(func, "summation") elif func.FUNC_PROD(): return handle_sum_or_prod(func, "product") elif func.FUNC_LIM(): return handle_limit(func) def convert_func_arg(arg): if hasattr(arg, 'expr'): return convert_expr(arg.expr()) else: return convert_mp(arg.mp_nofunc()) def handle_integral(func): if func.additive(): integrand = convert_add(func.additive()) elif func.frac(): integrand = convert_frac(func.frac()) else: integrand = 1 int_var = None if func.DIFFERENTIAL(): int_var = get_differential_var(func.DIFFERENTIAL()) else: for sym in integrand.atoms(sympy.Symbol): s = str(sym) if len(s) > 1 and s[0] == 'd': if s[1] == '\\': int_var = sympy.Symbol(s[2:]) else: int_var = sympy.Symbol(s[1:]) int_sym = sym if int_var: integrand = integrand.subs(int_sym, 1) else: # Assume dx by default int_var = sympy.Symbol('x') if func.subexpr(): if func.subexpr().atom(): lower = convert_atom(func.subexpr().atom()) else: lower = convert_expr(func.subexpr().expr()) if func.supexpr().atom(): upper = convert_atom(func.supexpr().atom()) else: upper = convert_expr(func.supexpr().expr()) return sympy.Integral(integrand, (int_var, lower, upper)) else: return sympy.Integral(integrand, int_var) def handle_sum_or_prod(func, name): val = convert_mp(func.mp()) iter_var = convert_expr(func.subeq().equality().expr(0)) start = convert_expr(func.subeq().equality().expr(1)) if func.supexpr().expr(): # ^{expr} end = convert_expr(func.supexpr().expr()) else: # ^atom end = convert_atom(func.supexpr().atom()) if name == "summation": return sympy.Sum(val, (iter_var, start, end)) elif name == "product": return sympy.Product(val, (iter_var, start, end)) def handle_limit(func): sub = func.limit_sub() if sub.LETTER(): var = sympy.Symbol(sub.LETTER().getText()) elif sub.SYMBOL(): var = sympy.Symbol(sub.SYMBOL().getText()[1:]) else: var = sympy.Symbol('x') if sub.SUB(): direction = "-" else: direction = "+" approaching = convert_expr(sub.expr()) content = convert_mp(func.mp()) return sympy.Limit(content, var, approaching, direction) def get_differential_var(d): text = get_differential_var_str(d.getText()) return sympy.Symbol(text) def get_differential_var_str(text): for i in range(1, len(text)): c = text[i] if not (c == " " or c == "\r" or c == "\n" or c == "\t"): idx = i break text = text[idx:] if text[0] == "\\": text = text[1:] return text
7fb2474bd313054eea41b8445da3a7f441833964af5b78a4fb53ef7236b9f38d
# encoding: utf-8 # *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND *** # # Generated from ../LaTeX.g4, derived from latex2sympy # latex2sympy is licensed under the MIT license # https://github.com/augustt198/latex2sympy/blob/master/LICENSE.txt # # Generated with antlr4 # antlr4 is licensed under the BSD-3-Clause License # https://github.com/antlr/antlr4/blob/master/LICENSE.txt from __future__ import print_function from antlr4 import * from io import StringIO import sys def serializedATN(): with StringIO() as buf: buf.write(u"\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2") buf.write(u"Z\u03a9\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4") buf.write(u"\7\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\4\r") buf.write(u"\t\r\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22\t\22") buf.write(u"\4\23\t\23\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\4") buf.write(u"\30\t\30\4\31\t\31\4\32\t\32\4\33\t\33\4\34\t\34\4\35") buf.write(u"\t\35\4\36\t\36\4\37\t\37\4 \t \4!\t!\4\"\t\"\4#\t#\4") buf.write(u"$\t$\4%\t%\4&\t&\4\'\t\'\4(\t(\4)\t)\4*\t*\4+\t+\4,\t") buf.write(u",\4-\t-\4.\t.\4/\t/\4\60\t\60\4\61\t\61\4\62\t\62\4\63") buf.write(u"\t\63\4\64\t\64\4\65\t\65\4\66\t\66\4\67\t\67\48\t8\4") buf.write(u"9\t9\4:\t:\4;\t;\4<\t<\4=\t=\4>\t>\4?\t?\4@\t@\4A\tA") buf.write(u"\4B\tB\4C\tC\4D\tD\4E\tE\4F\tF\4G\tG\4H\tH\4I\tI\4J\t") buf.write(u"J\4K\tK\4L\tL\4M\tM\4N\tN\4O\tO\4P\tP\4Q\tQ\4R\tR\4S") buf.write(u"\tS\4T\tT\4U\tU\4V\tV\4W\tW\4X\tX\4Y\tY\4Z\tZ\4[\t[\3") buf.write(u"\2\3\2\3\3\6\3\u00bb\n\3\r\3\16\3\u00bc\3\3\3\3\3\4\3") buf.write(u"\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\5\4\u00cd") buf.write(u"\n\4\3\4\3\4\3\5\3\5\3\5\3\5\3\5\3\5\3\5\3\5\3\5\3\5") buf.write(u"\3\5\5\5\u00dc\n\5\3\5\3\5\3\6\3\6\3\6\3\6\3\6\3\6\3") buf.write(u"\6\3\6\3\6\3\6\3\6\3\6\3\6\5\6\u00ed\n\6\3\6\3\6\3\7") buf.write(u"\3\7\3\7\3\7\3\7\3\7\3\7\3\7\3\b\3\b\3\b\3\b\3\b\3\b") buf.write(u"\3\b\3\b\3\b\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t") buf.write(u"\3\t\3\t\3\t\3\t\3\t\5\t\u0111\n\t\3\t\3\t\3\n\3\n\3") buf.write(u"\n\3\n\3\n\3\n\3\n\3\n\3\n\3\n\3\n\3\n\3\n\3\n\3\n\3") buf.write(u"\13\3\13\3\13\3\13\3\13\3\13\3\13\3\13\3\13\3\13\3\13") buf.write(u"\3\13\3\13\3\13\3\13\3\13\3\13\3\f\3\f\3\f\3\f\3\f\3") buf.write(u"\f\3\f\3\f\3\r\3\r\3\r\3\r\3\r\3\r\3\r\3\r\3\r\3\16\3") buf.write(u"\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16") buf.write(u"\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3") buf.write(u"\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16") buf.write(u"\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3") buf.write(u"\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\5\16\u0179\n\16") buf.write(u"\3\16\3\16\3\17\3\17\3\20\3\20\3\21\3\21\3\22\3\22\3") buf.write(u"\23\3\23\3\24\3\24\3\25\3\25\3\26\3\26\3\27\3\27\3\27") buf.write(u"\3\30\3\30\3\30\3\31\3\31\3\32\3\32\3\33\3\33\3\34\3") buf.write(u"\34\3\34\3\34\3\34\3\34\3\34\3\34\3\35\3\35\3\35\3\35") buf.write(u"\3\35\3\35\3\35\3\36\3\36\3\36\3\36\3\36\3\36\3\36\3") buf.write(u"\36\3\37\3\37\3\37\3\37\3\37\3\37\3\37\3\37\3 \3 \3 ") buf.write(u"\3 \3 \3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3") buf.write(u"!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!") buf.write(u"\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3") buf.write(u"!\3!\3!\3!\3!\5!\u01f4\n!\3\"\3\"\3\"\3\"\3\"\3\"\3\"") buf.write(u"\3\"\3\"\3\"\3\"\3\"\3\"\3\"\3\"\5\"\u0205\n\"\3#\3#") buf.write(u"\3#\3#\3#\3$\3$\3$\3$\3$\3$\3%\3%\3%\3%\3%\3&\3&\3&\3") buf.write(u"&\3&\3\'\3\'\3\'\3\'\3(\3(\3(\3(\3(\3)\3)\3)\3)\3)\3") buf.write(u"*\3*\3*\3*\3*\3+\3+\3+\3+\3+\3,\3,\3,\3,\3,\3-\3-\3-") buf.write(u"\3-\3-\3.\3.\3.\3.\3.\3.\3.\3.\3/\3/\3/\3/\3/\3/\3/\3") buf.write(u"/\3\60\3\60\3\60\3\60\3\60\3\60\3\60\3\60\3\61\3\61\3") buf.write(u"\61\3\61\3\61\3\61\3\61\3\61\3\62\3\62\3\62\3\62\3\62") buf.write(u"\3\62\3\62\3\62\3\63\3\63\3\63\3\63\3\63\3\63\3\63\3") buf.write(u"\63\3\64\3\64\3\64\3\64\3\64\3\64\3\65\3\65\3\65\3\65") buf.write(u"\3\65\3\65\3\66\3\66\3\66\3\66\3\66\3\66\3\67\3\67\3") buf.write(u"\67\3\67\3\67\3\67\3\67\3\67\38\38\38\38\38\38\38\38") buf.write(u"\39\39\39\39\39\39\39\39\3:\3:\3:\3:\3:\3:\3:\3:\3;\3") buf.write(u";\3;\3;\3;\3;\3;\3;\3<\3<\3<\3<\3<\3<\3<\3=\3=\3=\3=") buf.write(u"\3=\3=\3=\3>\3>\3>\3>\3>\3>\3?\3?\3?\3?\3?\3?\3?\3?\3") buf.write(u"?\3?\3@\3@\3@\3@\3@\3@\3@\3A\3A\3A\3A\3A\3A\3B\3B\3B") buf.write(u"\3B\3B\3C\3C\3C\3C\3C\3C\3C\3C\3C\3C\3C\3C\3C\3C\3C\3") buf.write(u"C\3C\5C\u02e9\nC\3D\3D\3D\3D\3D\3D\3D\3E\3E\3E\3E\3E") buf.write(u"\3E\3E\3E\3F\3F\3F\3F\3F\3F\3F\3F\3G\3G\3G\3G\3G\3G\3") buf.write(u"G\3G\3H\3H\3I\3I\3J\3J\3K\3K\3L\3L\7L\u0314\nL\fL\16") buf.write(u"L\u0317\13L\3L\3L\3L\6L\u031c\nL\rL\16L\u031d\5L\u0320") buf.write(u"\nL\3M\3M\3N\3N\3O\6O\u0327\nO\rO\16O\u0328\3O\3O\3O") buf.write(u"\3O\3O\7O\u0330\nO\fO\16O\u0333\13O\3O\7O\u0336\nO\f") buf.write(u"O\16O\u0339\13O\3O\3O\3O\3O\3O\7O\u0340\nO\fO\16O\u0343") buf.write(u"\13O\3O\3O\6O\u0347\nO\rO\16O\u0348\5O\u034b\nO\3P\3") buf.write(u"P\7P\u034f\nP\fP\16P\u0352\13P\5P\u0354\nP\3P\3P\3P\7") buf.write(u"P\u0359\nP\fP\16P\u035c\13P\3P\5P\u035f\nP\5P\u0361\n") buf.write(u"P\3Q\3Q\3Q\3Q\3Q\3R\3R\3S\3S\3S\3S\3S\3S\3S\3S\3S\5S") buf.write(u"\u0373\nS\3T\3T\3T\3T\3T\3T\3U\3U\3U\3U\3U\3U\3U\3U\3") buf.write(u"U\3U\3V\3V\3W\3W\3W\3W\3W\3W\3W\3W\3W\5W\u0390\nW\3X") buf.write(u"\3X\3X\3X\3X\3X\3Y\3Y\3Y\3Y\3Y\3Y\3Y\3Y\3Y\3Y\3Z\3Z\3") buf.write(u"[\3[\6[\u03a6\n[\r[\16[\u03a7\5\u0315\u0350\u035a\2\\") buf.write(u"\3\3\5\4\7\5\t\6\13\7\r\b\17\t\21\n\23\13\25\f\27\r\31") buf.write(u"\16\33\17\35\20\37\21!\22#\23%\24\'\25)\26+\27-\30/\31") buf.write(u"\61\32\63\33\65\34\67\359\36;\37= ?!A\"C#E$G%I&K\'M(") buf.write(u"O)Q*S+U,W-Y.[/]\60_\61a\62c\63e\64g\65i\66k\67m8o9q:") buf.write(u"s;u<w=y>{?}@\177A\u0081B\u0083C\u0085D\u0087E\u0089F") buf.write(u"\u008bG\u008dH\u008fI\u0091J\u0093K\u0095\2\u0097L\u0099") buf.write(u"M\u009b\2\u009dN\u009fO\u00a1P\u00a3Q\u00a5R\u00a7S\u00a9") buf.write(u"T\u00abU\u00adV\u00afW\u00b1X\u00b3Y\u00b5Z\3\2\5\5\2") buf.write(u"\13\f\17\17\"\"\4\2C\\c|\3\2\62;\2\u03d3\2\3\3\2\2\2") buf.write(u"\2\5\3\2\2\2\2\7\3\2\2\2\2\t\3\2\2\2\2\13\3\2\2\2\2\r") buf.write(u"\3\2\2\2\2\17\3\2\2\2\2\21\3\2\2\2\2\23\3\2\2\2\2\25") buf.write(u"\3\2\2\2\2\27\3\2\2\2\2\31\3\2\2\2\2\33\3\2\2\2\2\35") buf.write(u"\3\2\2\2\2\37\3\2\2\2\2!\3\2\2\2\2#\3\2\2\2\2%\3\2\2") buf.write(u"\2\2\'\3\2\2\2\2)\3\2\2\2\2+\3\2\2\2\2-\3\2\2\2\2/\3") buf.write(u"\2\2\2\2\61\3\2\2\2\2\63\3\2\2\2\2\65\3\2\2\2\2\67\3") buf.write(u"\2\2\2\29\3\2\2\2\2;\3\2\2\2\2=\3\2\2\2\2?\3\2\2\2\2") buf.write(u"A\3\2\2\2\2C\3\2\2\2\2E\3\2\2\2\2G\3\2\2\2\2I\3\2\2\2") buf.write(u"\2K\3\2\2\2\2M\3\2\2\2\2O\3\2\2\2\2Q\3\2\2\2\2S\3\2\2") buf.write(u"\2\2U\3\2\2\2\2W\3\2\2\2\2Y\3\2\2\2\2[\3\2\2\2\2]\3\2") buf.write(u"\2\2\2_\3\2\2\2\2a\3\2\2\2\2c\3\2\2\2\2e\3\2\2\2\2g\3") buf.write(u"\2\2\2\2i\3\2\2\2\2k\3\2\2\2\2m\3\2\2\2\2o\3\2\2\2\2") buf.write(u"q\3\2\2\2\2s\3\2\2\2\2u\3\2\2\2\2w\3\2\2\2\2y\3\2\2\2") buf.write(u"\2{\3\2\2\2\2}\3\2\2\2\2\177\3\2\2\2\2\u0081\3\2\2\2") buf.write(u"\2\u0083\3\2\2\2\2\u0085\3\2\2\2\2\u0087\3\2\2\2\2\u0089") buf.write(u"\3\2\2\2\2\u008b\3\2\2\2\2\u008d\3\2\2\2\2\u008f\3\2") buf.write(u"\2\2\2\u0091\3\2\2\2\2\u0093\3\2\2\2\2\u0097\3\2\2\2") buf.write(u"\2\u0099\3\2\2\2\2\u009d\3\2\2\2\2\u009f\3\2\2\2\2\u00a1") buf.write(u"\3\2\2\2\2\u00a3\3\2\2\2\2\u00a5\3\2\2\2\2\u00a7\3\2") buf.write(u"\2\2\2\u00a9\3\2\2\2\2\u00ab\3\2\2\2\2\u00ad\3\2\2\2") buf.write(u"\2\u00af\3\2\2\2\2\u00b1\3\2\2\2\2\u00b3\3\2\2\2\2\u00b5") buf.write(u"\3\2\2\2\3\u00b7\3\2\2\2\5\u00ba\3\2\2\2\7\u00cc\3\2") buf.write(u"\2\2\t\u00db\3\2\2\2\13\u00ec\3\2\2\2\r\u00f0\3\2\2\2") buf.write(u"\17\u00f8\3\2\2\2\21\u0110\3\2\2\2\23\u0114\3\2\2\2\25") buf.write(u"\u0123\3\2\2\2\27\u0134\3\2\2\2\31\u013c\3\2\2\2\33\u0178") buf.write(u"\3\2\2\2\35\u017c\3\2\2\2\37\u017e\3\2\2\2!\u0180\3\2") buf.write(u"\2\2#\u0182\3\2\2\2%\u0184\3\2\2\2\'\u0186\3\2\2\2)\u0188") buf.write(u"\3\2\2\2+\u018a\3\2\2\2-\u018c\3\2\2\2/\u018f\3\2\2\2") buf.write(u"\61\u0192\3\2\2\2\63\u0194\3\2\2\2\65\u0196\3\2\2\2\67") buf.write(u"\u0198\3\2\2\29\u01a0\3\2\2\2;\u01a7\3\2\2\2=\u01af\3") buf.write(u"\2\2\2?\u01b7\3\2\2\2A\u01f3\3\2\2\2C\u0204\3\2\2\2E") buf.write(u"\u0206\3\2\2\2G\u020b\3\2\2\2I\u0211\3\2\2\2K\u0216\3") buf.write(u"\2\2\2M\u021b\3\2\2\2O\u021f\3\2\2\2Q\u0224\3\2\2\2S") buf.write(u"\u0229\3\2\2\2U\u022e\3\2\2\2W\u0233\3\2\2\2Y\u0238\3") buf.write(u"\2\2\2[\u023d\3\2\2\2]\u0245\3\2\2\2_\u024d\3\2\2\2a") buf.write(u"\u0255\3\2\2\2c\u025d\3\2\2\2e\u0265\3\2\2\2g\u026d\3") buf.write(u"\2\2\2i\u0273\3\2\2\2k\u0279\3\2\2\2m\u027f\3\2\2\2o") buf.write(u"\u0287\3\2\2\2q\u028f\3\2\2\2s\u0297\3\2\2\2u\u029f\3") buf.write(u"\2\2\2w\u02a7\3\2\2\2y\u02ae\3\2\2\2{\u02b5\3\2\2\2}") buf.write(u"\u02bb\3\2\2\2\177\u02c5\3\2\2\2\u0081\u02cc\3\2\2\2") buf.write(u"\u0083\u02d2\3\2\2\2\u0085\u02e8\3\2\2\2\u0087\u02ea") buf.write(u"\3\2\2\2\u0089\u02f1\3\2\2\2\u008b\u02f9\3\2\2\2\u008d") buf.write(u"\u0301\3\2\2\2\u008f\u0309\3\2\2\2\u0091\u030b\3\2\2") buf.write(u"\2\u0093\u030d\3\2\2\2\u0095\u030f\3\2\2\2\u0097\u0311") buf.write(u"\3\2\2\2\u0099\u0321\3\2\2\2\u009b\u0323\3\2\2\2\u009d") buf.write(u"\u034a\3\2\2\2\u009f\u0360\3\2\2\2\u00a1\u0362\3\2\2") buf.write(u"\2\u00a3\u0367\3\2\2\2\u00a5\u0372\3\2\2\2\u00a7\u0374") buf.write(u"\3\2\2\2\u00a9\u037a\3\2\2\2\u00ab\u0384\3\2\2\2\u00ad") buf.write(u"\u038f\3\2\2\2\u00af\u0391\3\2\2\2\u00b1\u0397\3\2\2") buf.write(u"\2\u00b3\u03a1\3\2\2\2\u00b5\u03a3\3\2\2\2\u00b7\u00b8") buf.write(u"\7.\2\2\u00b8\4\3\2\2\2\u00b9\u00bb\t\2\2\2\u00ba\u00b9") buf.write(u"\3\2\2\2\u00bb\u00bc\3\2\2\2\u00bc\u00ba\3\2\2\2\u00bc") buf.write(u"\u00bd\3\2\2\2\u00bd\u00be\3\2\2\2\u00be\u00bf\b\3\2") buf.write(u"\2\u00bf\6\3\2\2\2\u00c0\u00c1\7^\2\2\u00c1\u00cd\7.") buf.write(u"\2\2\u00c2\u00c3\7^\2\2\u00c3\u00c4\7v\2\2\u00c4\u00c5") buf.write(u"\7j\2\2\u00c5\u00c6\7k\2\2\u00c6\u00c7\7p\2\2\u00c7\u00c8") buf.write(u"\7u\2\2\u00c8\u00c9\7r\2\2\u00c9\u00ca\7c\2\2\u00ca\u00cb") buf.write(u"\7e\2\2\u00cb\u00cd\7g\2\2\u00cc\u00c0\3\2\2\2\u00cc") buf.write(u"\u00c2\3\2\2\2\u00cd\u00ce\3\2\2\2\u00ce\u00cf\b\4\2") buf.write(u"\2\u00cf\b\3\2\2\2\u00d0\u00d1\7^\2\2\u00d1\u00dc\7<") buf.write(u"\2\2\u00d2\u00d3\7^\2\2\u00d3\u00d4\7o\2\2\u00d4\u00d5") buf.write(u"\7g\2\2\u00d5\u00d6\7f\2\2\u00d6\u00d7\7u\2\2\u00d7\u00d8") buf.write(u"\7r\2\2\u00d8\u00d9\7c\2\2\u00d9\u00da\7e\2\2\u00da\u00dc") buf.write(u"\7g\2\2\u00db\u00d0\3\2\2\2\u00db\u00d2\3\2\2\2\u00dc") buf.write(u"\u00dd\3\2\2\2\u00dd\u00de\b\5\2\2\u00de\n\3\2\2\2\u00df") buf.write(u"\u00e0\7^\2\2\u00e0\u00ed\7=\2\2\u00e1\u00e2\7^\2\2\u00e2") buf.write(u"\u00e3\7v\2\2\u00e3\u00e4\7j\2\2\u00e4\u00e5\7k\2\2\u00e5") buf.write(u"\u00e6\7e\2\2\u00e6\u00e7\7m\2\2\u00e7\u00e8\7u\2\2\u00e8") buf.write(u"\u00e9\7r\2\2\u00e9\u00ea\7c\2\2\u00ea\u00eb\7e\2\2\u00eb") buf.write(u"\u00ed\7g\2\2\u00ec\u00df\3\2\2\2\u00ec\u00e1\3\2\2\2") buf.write(u"\u00ed\u00ee\3\2\2\2\u00ee\u00ef\b\6\2\2\u00ef\f\3\2") buf.write(u"\2\2\u00f0\u00f1\7^\2\2\u00f1\u00f2\7s\2\2\u00f2\u00f3") buf.write(u"\7w\2\2\u00f3\u00f4\7c\2\2\u00f4\u00f5\7f\2\2\u00f5\u00f6") buf.write(u"\3\2\2\2\u00f6\u00f7\b\7\2\2\u00f7\16\3\2\2\2\u00f8\u00f9") buf.write(u"\7^\2\2\u00f9\u00fa\7s\2\2\u00fa\u00fb\7s\2\2\u00fb\u00fc") buf.write(u"\7w\2\2\u00fc\u00fd\7c\2\2\u00fd\u00fe\7f\2\2\u00fe\u00ff") buf.write(u"\3\2\2\2\u00ff\u0100\b\b\2\2\u0100\20\3\2\2\2\u0101\u0102") buf.write(u"\7^\2\2\u0102\u0111\7#\2\2\u0103\u0104\7^\2\2\u0104\u0105") buf.write(u"\7p\2\2\u0105\u0106\7g\2\2\u0106\u0107\7i\2\2\u0107\u0108") buf.write(u"\7v\2\2\u0108\u0109\7j\2\2\u0109\u010a\7k\2\2\u010a\u010b") buf.write(u"\7p\2\2\u010b\u010c\7u\2\2\u010c\u010d\7r\2\2\u010d\u010e") buf.write(u"\7c\2\2\u010e\u010f\7e\2\2\u010f\u0111\7g\2\2\u0110\u0101") buf.write(u"\3\2\2\2\u0110\u0103\3\2\2\2\u0111\u0112\3\2\2\2\u0112") buf.write(u"\u0113\b\t\2\2\u0113\22\3\2\2\2\u0114\u0115\7^\2\2\u0115") buf.write(u"\u0116\7p\2\2\u0116\u0117\7g\2\2\u0117\u0118\7i\2\2\u0118") buf.write(u"\u0119\7o\2\2\u0119\u011a\7g\2\2\u011a\u011b\7f\2\2\u011b") buf.write(u"\u011c\7u\2\2\u011c\u011d\7r\2\2\u011d\u011e\7c\2\2\u011e") buf.write(u"\u011f\7e\2\2\u011f\u0120\7g\2\2\u0120\u0121\3\2\2\2") buf.write(u"\u0121\u0122\b\n\2\2\u0122\24\3\2\2\2\u0123\u0124\7^") buf.write(u"\2\2\u0124\u0125\7p\2\2\u0125\u0126\7g\2\2\u0126\u0127") buf.write(u"\7i\2\2\u0127\u0128\7v\2\2\u0128\u0129\7j\2\2\u0129\u012a") buf.write(u"\7k\2\2\u012a\u012b\7e\2\2\u012b\u012c\7m\2\2\u012c\u012d") buf.write(u"\7u\2\2\u012d\u012e\7r\2\2\u012e\u012f\7c\2\2\u012f\u0130") buf.write(u"\7e\2\2\u0130\u0131\7g\2\2\u0131\u0132\3\2\2\2\u0132") buf.write(u"\u0133\b\13\2\2\u0133\26\3\2\2\2\u0134\u0135\7^\2\2\u0135") buf.write(u"\u0136\7n\2\2\u0136\u0137\7g\2\2\u0137\u0138\7h\2\2\u0138") buf.write(u"\u0139\7v\2\2\u0139\u013a\3\2\2\2\u013a\u013b\b\f\2\2") buf.write(u"\u013b\30\3\2\2\2\u013c\u013d\7^\2\2\u013d\u013e\7t\2") buf.write(u"\2\u013e\u013f\7k\2\2\u013f\u0140\7i\2\2\u0140\u0141") buf.write(u"\7j\2\2\u0141\u0142\7v\2\2\u0142\u0143\3\2\2\2\u0143") buf.write(u"\u0144\b\r\2\2\u0144\32\3\2\2\2\u0145\u0146\7^\2\2\u0146") buf.write(u"\u0147\7x\2\2\u0147\u0148\7t\2\2\u0148\u0149\7w\2\2\u0149") buf.write(u"\u014a\7n\2\2\u014a\u0179\7g\2\2\u014b\u014c\7^\2\2\u014c") buf.write(u"\u014d\7x\2\2\u014d\u014e\7e\2\2\u014e\u014f\7g\2\2\u014f") buf.write(u"\u0150\7p\2\2\u0150\u0151\7v\2\2\u0151\u0152\7g\2\2\u0152") buf.write(u"\u0179\7t\2\2\u0153\u0154\7^\2\2\u0154\u0155\7x\2\2\u0155") buf.write(u"\u0156\7d\2\2\u0156\u0157\7q\2\2\u0157\u0179\7z\2\2\u0158") buf.write(u"\u0159\7^\2\2\u0159\u015a\7x\2\2\u015a\u015b\7u\2\2\u015b") buf.write(u"\u015c\7m\2\2\u015c\u015d\7k\2\2\u015d\u0179\7r\2\2\u015e") buf.write(u"\u015f\7^\2\2\u015f\u0160\7x\2\2\u0160\u0161\7u\2\2\u0161") buf.write(u"\u0162\7r\2\2\u0162\u0163\7c\2\2\u0163\u0164\7e\2\2\u0164") buf.write(u"\u0179\7g\2\2\u0165\u0166\7^\2\2\u0166\u0167\7j\2\2\u0167") buf.write(u"\u0168\7h\2\2\u0168\u0169\7k\2\2\u0169\u0179\7n\2\2\u016a") buf.write(u"\u016b\7^\2\2\u016b\u0179\7,\2\2\u016c\u016d\7^\2\2\u016d") buf.write(u"\u0179\7/\2\2\u016e\u016f\7^\2\2\u016f\u0179\7\60\2\2") buf.write(u"\u0170\u0171\7^\2\2\u0171\u0179\7\61\2\2\u0172\u0173") buf.write(u"\7^\2\2\u0173\u0179\7$\2\2\u0174\u0175\7^\2\2\u0175\u0179") buf.write(u"\7*\2\2\u0176\u0177\7^\2\2\u0177\u0179\7?\2\2\u0178\u0145") buf.write(u"\3\2\2\2\u0178\u014b\3\2\2\2\u0178\u0153\3\2\2\2\u0178") buf.write(u"\u0158\3\2\2\2\u0178\u015e\3\2\2\2\u0178\u0165\3\2\2") buf.write(u"\2\u0178\u016a\3\2\2\2\u0178\u016c\3\2\2\2\u0178\u016e") buf.write(u"\3\2\2\2\u0178\u0170\3\2\2\2\u0178\u0172\3\2\2\2\u0178") buf.write(u"\u0174\3\2\2\2\u0178\u0176\3\2\2\2\u0179\u017a\3\2\2") buf.write(u"\2\u017a\u017b\b\16\2\2\u017b\34\3\2\2\2\u017c\u017d") buf.write(u"\7-\2\2\u017d\36\3\2\2\2\u017e\u017f\7/\2\2\u017f \3") buf.write(u"\2\2\2\u0180\u0181\7,\2\2\u0181\"\3\2\2\2\u0182\u0183") buf.write(u"\7\61\2\2\u0183$\3\2\2\2\u0184\u0185\7*\2\2\u0185&\3") buf.write(u"\2\2\2\u0186\u0187\7+\2\2\u0187(\3\2\2\2\u0188\u0189") buf.write(u"\7}\2\2\u0189*\3\2\2\2\u018a\u018b\7\177\2\2\u018b,\3") buf.write(u"\2\2\2\u018c\u018d\7^\2\2\u018d\u018e\7}\2\2\u018e.\3") buf.write(u"\2\2\2\u018f\u0190\7^\2\2\u0190\u0191\7\177\2\2\u0191") buf.write(u"\60\3\2\2\2\u0192\u0193\7]\2\2\u0193\62\3\2\2\2\u0194") buf.write(u"\u0195\7_\2\2\u0195\64\3\2\2\2\u0196\u0197\7~\2\2\u0197") buf.write(u"\66\3\2\2\2\u0198\u0199\7^\2\2\u0199\u019a\7t\2\2\u019a") buf.write(u"\u019b\7k\2\2\u019b\u019c\7i\2\2\u019c\u019d\7j\2\2\u019d") buf.write(u"\u019e\7v\2\2\u019e\u019f\7~\2\2\u019f8\3\2\2\2\u01a0") buf.write(u"\u01a1\7^\2\2\u01a1\u01a2\7n\2\2\u01a2\u01a3\7g\2\2\u01a3") buf.write(u"\u01a4\7h\2\2\u01a4\u01a5\7v\2\2\u01a5\u01a6\7~\2\2\u01a6") buf.write(u":\3\2\2\2\u01a7\u01a8\7^\2\2\u01a8\u01a9\7n\2\2\u01a9") buf.write(u"\u01aa\7c\2\2\u01aa\u01ab\7p\2\2\u01ab\u01ac\7i\2\2\u01ac") buf.write(u"\u01ad\7n\2\2\u01ad\u01ae\7g\2\2\u01ae<\3\2\2\2\u01af") buf.write(u"\u01b0\7^\2\2\u01b0\u01b1\7t\2\2\u01b1\u01b2\7c\2\2\u01b2") buf.write(u"\u01b3\7p\2\2\u01b3\u01b4\7i\2\2\u01b4\u01b5\7n\2\2\u01b5") buf.write(u"\u01b6\7g\2\2\u01b6>\3\2\2\2\u01b7\u01b8\7^\2\2\u01b8") buf.write(u"\u01b9\7n\2\2\u01b9\u01ba\7k\2\2\u01ba\u01bb\7o\2\2\u01bb") buf.write(u"@\3\2\2\2\u01bc\u01bd\7^\2\2\u01bd\u01be\7v\2\2\u01be") buf.write(u"\u01f4\7q\2\2\u01bf\u01c0\7^\2\2\u01c0\u01c1\7t\2\2\u01c1") buf.write(u"\u01c2\7k\2\2\u01c2\u01c3\7i\2\2\u01c3\u01c4\7j\2\2\u01c4") buf.write(u"\u01c5\7v\2\2\u01c5\u01c6\7c\2\2\u01c6\u01c7\7t\2\2\u01c7") buf.write(u"\u01c8\7t\2\2\u01c8\u01c9\7q\2\2\u01c9\u01f4\7y\2\2\u01ca") buf.write(u"\u01cb\7^\2\2\u01cb\u01cc\7T\2\2\u01cc\u01cd\7k\2\2\u01cd") buf.write(u"\u01ce\7i\2\2\u01ce\u01cf\7j\2\2\u01cf\u01d0\7v\2\2\u01d0") buf.write(u"\u01d1\7c\2\2\u01d1\u01d2\7t\2\2\u01d2\u01d3\7t\2\2\u01d3") buf.write(u"\u01d4\7q\2\2\u01d4\u01f4\7y\2\2\u01d5\u01d6\7^\2\2\u01d6") buf.write(u"\u01d7\7n\2\2\u01d7\u01d8\7q\2\2\u01d8\u01d9\7p\2\2\u01d9") buf.write(u"\u01da\7i\2\2\u01da\u01db\7t\2\2\u01db\u01dc\7k\2\2\u01dc") buf.write(u"\u01dd\7i\2\2\u01dd\u01de\7j\2\2\u01de\u01df\7v\2\2\u01df") buf.write(u"\u01e0\7c\2\2\u01e0\u01e1\7t\2\2\u01e1\u01e2\7t\2\2\u01e2") buf.write(u"\u01e3\7q\2\2\u01e3\u01f4\7y\2\2\u01e4\u01e5\7^\2\2\u01e5") buf.write(u"\u01e6\7N\2\2\u01e6\u01e7\7q\2\2\u01e7\u01e8\7p\2\2\u01e8") buf.write(u"\u01e9\7i\2\2\u01e9\u01ea\7t\2\2\u01ea\u01eb\7k\2\2\u01eb") buf.write(u"\u01ec\7i\2\2\u01ec\u01ed\7j\2\2\u01ed\u01ee\7v\2\2\u01ee") buf.write(u"\u01ef\7c\2\2\u01ef\u01f0\7t\2\2\u01f0\u01f1\7t\2\2\u01f1") buf.write(u"\u01f2\7q\2\2\u01f2\u01f4\7y\2\2\u01f3\u01bc\3\2\2\2") buf.write(u"\u01f3\u01bf\3\2\2\2\u01f3\u01ca\3\2\2\2\u01f3\u01d5") buf.write(u"\3\2\2\2\u01f3\u01e4\3\2\2\2\u01f4B\3\2\2\2\u01f5\u01f6") buf.write(u"\7^\2\2\u01f6\u01f7\7k\2\2\u01f7\u01f8\7p\2\2\u01f8\u0205") buf.write(u"\7v\2\2\u01f9\u01fa\7^\2\2\u01fa\u01fb\7k\2\2\u01fb\u01fc") buf.write(u"\7p\2\2\u01fc\u01fd\7v\2\2\u01fd\u01fe\7^\2\2\u01fe\u01ff") buf.write(u"\7n\2\2\u01ff\u0200\7k\2\2\u0200\u0201\7o\2\2\u0201\u0202") buf.write(u"\7k\2\2\u0202\u0203\7v\2\2\u0203\u0205\7u\2\2\u0204\u01f5") buf.write(u"\3\2\2\2\u0204\u01f9\3\2\2\2\u0205D\3\2\2\2\u0206\u0207") buf.write(u"\7^\2\2\u0207\u0208\7u\2\2\u0208\u0209\7w\2\2\u0209\u020a") buf.write(u"\7o\2\2\u020aF\3\2\2\2\u020b\u020c\7^\2\2\u020c\u020d") buf.write(u"\7r\2\2\u020d\u020e\7t\2\2\u020e\u020f\7q\2\2\u020f\u0210") buf.write(u"\7f\2\2\u0210H\3\2\2\2\u0211\u0212\7^\2\2\u0212\u0213") buf.write(u"\7g\2\2\u0213\u0214\7z\2\2\u0214\u0215\7r\2\2\u0215J") buf.write(u"\3\2\2\2\u0216\u0217\7^\2\2\u0217\u0218\7n\2\2\u0218") buf.write(u"\u0219\7q\2\2\u0219\u021a\7i\2\2\u021aL\3\2\2\2\u021b") buf.write(u"\u021c\7^\2\2\u021c\u021d\7n\2\2\u021d\u021e\7p\2\2\u021e") buf.write(u"N\3\2\2\2\u021f\u0220\7^\2\2\u0220\u0221\7u\2\2\u0221") buf.write(u"\u0222\7k\2\2\u0222\u0223\7p\2\2\u0223P\3\2\2\2\u0224") buf.write(u"\u0225\7^\2\2\u0225\u0226\7e\2\2\u0226\u0227\7q\2\2\u0227") buf.write(u"\u0228\7u\2\2\u0228R\3\2\2\2\u0229\u022a\7^\2\2\u022a") buf.write(u"\u022b\7v\2\2\u022b\u022c\7c\2\2\u022c\u022d\7p\2\2\u022d") buf.write(u"T\3\2\2\2\u022e\u022f\7^\2\2\u022f\u0230\7e\2\2\u0230") buf.write(u"\u0231\7u\2\2\u0231\u0232\7e\2\2\u0232V\3\2\2\2\u0233") buf.write(u"\u0234\7^\2\2\u0234\u0235\7u\2\2\u0235\u0236\7g\2\2\u0236") buf.write(u"\u0237\7e\2\2\u0237X\3\2\2\2\u0238\u0239\7^\2\2\u0239") buf.write(u"\u023a\7e\2\2\u023a\u023b\7q\2\2\u023b\u023c\7v\2\2\u023c") buf.write(u"Z\3\2\2\2\u023d\u023e\7^\2\2\u023e\u023f\7c\2\2\u023f") buf.write(u"\u0240\7t\2\2\u0240\u0241\7e\2\2\u0241\u0242\7u\2\2\u0242") buf.write(u"\u0243\7k\2\2\u0243\u0244\7p\2\2\u0244\\\3\2\2\2\u0245") buf.write(u"\u0246\7^\2\2\u0246\u0247\7c\2\2\u0247\u0248\7t\2\2\u0248") buf.write(u"\u0249\7e\2\2\u0249\u024a\7e\2\2\u024a\u024b\7q\2\2\u024b") buf.write(u"\u024c\7u\2\2\u024c^\3\2\2\2\u024d\u024e\7^\2\2\u024e") buf.write(u"\u024f\7c\2\2\u024f\u0250\7t\2\2\u0250\u0251\7e\2\2\u0251") buf.write(u"\u0252\7v\2\2\u0252\u0253\7c\2\2\u0253\u0254\7p\2\2\u0254") buf.write(u"`\3\2\2\2\u0255\u0256\7^\2\2\u0256\u0257\7c\2\2\u0257") buf.write(u"\u0258\7t\2\2\u0258\u0259\7e\2\2\u0259\u025a\7e\2\2\u025a") buf.write(u"\u025b\7u\2\2\u025b\u025c\7e\2\2\u025cb\3\2\2\2\u025d") buf.write(u"\u025e\7^\2\2\u025e\u025f\7c\2\2\u025f\u0260\7t\2\2\u0260") buf.write(u"\u0261\7e\2\2\u0261\u0262\7u\2\2\u0262\u0263\7g\2\2\u0263") buf.write(u"\u0264\7e\2\2\u0264d\3\2\2\2\u0265\u0266\7^\2\2\u0266") buf.write(u"\u0267\7c\2\2\u0267\u0268\7t\2\2\u0268\u0269\7e\2\2\u0269") buf.write(u"\u026a\7e\2\2\u026a\u026b\7q\2\2\u026b\u026c\7v\2\2\u026c") buf.write(u"f\3\2\2\2\u026d\u026e\7^\2\2\u026e\u026f\7u\2\2\u026f") buf.write(u"\u0270\7k\2\2\u0270\u0271\7p\2\2\u0271\u0272\7j\2\2\u0272") buf.write(u"h\3\2\2\2\u0273\u0274\7^\2\2\u0274\u0275\7e\2\2\u0275") buf.write(u"\u0276\7q\2\2\u0276\u0277\7u\2\2\u0277\u0278\7j\2\2\u0278") buf.write(u"j\3\2\2\2\u0279\u027a\7^\2\2\u027a\u027b\7v\2\2\u027b") buf.write(u"\u027c\7c\2\2\u027c\u027d\7p\2\2\u027d\u027e\7j\2\2\u027e") buf.write(u"l\3\2\2\2\u027f\u0280\7^\2\2\u0280\u0281\7c\2\2\u0281") buf.write(u"\u0282\7t\2\2\u0282\u0283\7u\2\2\u0283\u0284\7k\2\2\u0284") buf.write(u"\u0285\7p\2\2\u0285\u0286\7j\2\2\u0286n\3\2\2\2\u0287") buf.write(u"\u0288\7^\2\2\u0288\u0289\7c\2\2\u0289\u028a\7t\2\2\u028a") buf.write(u"\u028b\7e\2\2\u028b\u028c\7q\2\2\u028c\u028d\7u\2\2\u028d") buf.write(u"\u028e\7j\2\2\u028ep\3\2\2\2\u028f\u0290\7^\2\2\u0290") buf.write(u"\u0291\7c\2\2\u0291\u0292\7t\2\2\u0292\u0293\7v\2\2\u0293") buf.write(u"\u0294\7c\2\2\u0294\u0295\7p\2\2\u0295\u0296\7j\2\2\u0296") buf.write(u"r\3\2\2\2\u0297\u0298\7^\2\2\u0298\u0299\7n\2\2\u0299") buf.write(u"\u029a\7h\2\2\u029a\u029b\7n\2\2\u029b\u029c\7q\2\2\u029c") buf.write(u"\u029d\7q\2\2\u029d\u029e\7t\2\2\u029et\3\2\2\2\u029f") buf.write(u"\u02a0\7^\2\2\u02a0\u02a1\7t\2\2\u02a1\u02a2\7h\2\2\u02a2") buf.write(u"\u02a3\7n\2\2\u02a3\u02a4\7q\2\2\u02a4\u02a5\7q\2\2\u02a5") buf.write(u"\u02a6\7t\2\2\u02a6v\3\2\2\2\u02a7\u02a8\7^\2\2\u02a8") buf.write(u"\u02a9\7n\2\2\u02a9\u02aa\7e\2\2\u02aa\u02ab\7g\2\2\u02ab") buf.write(u"\u02ac\7k\2\2\u02ac\u02ad\7n\2\2\u02adx\3\2\2\2\u02ae") buf.write(u"\u02af\7^\2\2\u02af\u02b0\7t\2\2\u02b0\u02b1\7e\2\2\u02b1") buf.write(u"\u02b2\7g\2\2\u02b2\u02b3\7k\2\2\u02b3\u02b4\7n\2\2\u02b4") buf.write(u"z\3\2\2\2\u02b5\u02b6\7^\2\2\u02b6\u02b7\7u\2\2\u02b7") buf.write(u"\u02b8\7s\2\2\u02b8\u02b9\7t\2\2\u02b9\u02ba\7v\2\2\u02ba") buf.write(u"|\3\2\2\2\u02bb\u02bc\7^\2\2\u02bc\u02bd\7q\2\2\u02bd") buf.write(u"\u02be\7x\2\2\u02be\u02bf\7g\2\2\u02bf\u02c0\7t\2\2\u02c0") buf.write(u"\u02c1\7n\2\2\u02c1\u02c2\7k\2\2\u02c2\u02c3\7p\2\2\u02c3") buf.write(u"\u02c4\7g\2\2\u02c4~\3\2\2\2\u02c5\u02c6\7^\2\2\u02c6") buf.write(u"\u02c7\7v\2\2\u02c7\u02c8\7k\2\2\u02c8\u02c9\7o\2\2\u02c9") buf.write(u"\u02ca\7g\2\2\u02ca\u02cb\7u\2\2\u02cb\u0080\3\2\2\2") buf.write(u"\u02cc\u02cd\7^\2\2\u02cd\u02ce\7e\2\2\u02ce\u02cf\7") buf.write(u"f\2\2\u02cf\u02d0\7q\2\2\u02d0\u02d1\7v\2\2\u02d1\u0082") buf.write(u"\3\2\2\2\u02d2\u02d3\7^\2\2\u02d3\u02d4\7f\2\2\u02d4") buf.write(u"\u02d5\7k\2\2\u02d5\u02d6\7x\2\2\u02d6\u0084\3\2\2\2") buf.write(u"\u02d7\u02d8\7^\2\2\u02d8\u02d9\7h\2\2\u02d9\u02da\7") buf.write(u"t\2\2\u02da\u02db\7c\2\2\u02db\u02e9\7e\2\2\u02dc\u02dd") buf.write(u"\7^\2\2\u02dd\u02de\7f\2\2\u02de\u02df\7h\2\2\u02df\u02e0") buf.write(u"\7t\2\2\u02e0\u02e1\7c\2\2\u02e1\u02e9\7e\2\2\u02e2\u02e3") buf.write(u"\7^\2\2\u02e3\u02e4\7v\2\2\u02e4\u02e5\7h\2\2\u02e5\u02e6") buf.write(u"\7t\2\2\u02e6\u02e7\7c\2\2\u02e7\u02e9\7e\2\2\u02e8\u02d7") buf.write(u"\3\2\2\2\u02e8\u02dc\3\2\2\2\u02e8\u02e2\3\2\2\2\u02e9") buf.write(u"\u0086\3\2\2\2\u02ea\u02eb\7^\2\2\u02eb\u02ec\7d\2\2") buf.write(u"\u02ec\u02ed\7k\2\2\u02ed\u02ee\7p\2\2\u02ee\u02ef\7") buf.write(u"q\2\2\u02ef\u02f0\7o\2\2\u02f0\u0088\3\2\2\2\u02f1\u02f2") buf.write(u"\7^\2\2\u02f2\u02f3\7f\2\2\u02f3\u02f4\7d\2\2\u02f4\u02f5") buf.write(u"\7k\2\2\u02f5\u02f6\7p\2\2\u02f6\u02f7\7q\2\2\u02f7\u02f8") buf.write(u"\7o\2\2\u02f8\u008a\3\2\2\2\u02f9\u02fa\7^\2\2\u02fa") buf.write(u"\u02fb\7v\2\2\u02fb\u02fc\7d\2\2\u02fc\u02fd\7k\2\2\u02fd") buf.write(u"\u02fe\7p\2\2\u02fe\u02ff\7q\2\2\u02ff\u0300\7o\2\2\u0300") buf.write(u"\u008c\3\2\2\2\u0301\u0302\7^\2\2\u0302\u0303\7o\2\2") buf.write(u"\u0303\u0304\7c\2\2\u0304\u0305\7v\2\2\u0305\u0306\7") buf.write(u"j\2\2\u0306\u0307\7k\2\2\u0307\u0308\7v\2\2\u0308\u008e") buf.write(u"\3\2\2\2\u0309\u030a\7a\2\2\u030a\u0090\3\2\2\2\u030b") buf.write(u"\u030c\7`\2\2\u030c\u0092\3\2\2\2\u030d\u030e\7<\2\2") buf.write(u"\u030e\u0094\3\2\2\2\u030f\u0310\t\2\2\2\u0310\u0096") buf.write(u"\3\2\2\2\u0311\u0315\7f\2\2\u0312\u0314\5\u0095K\2\u0313") buf.write(u"\u0312\3\2\2\2\u0314\u0317\3\2\2\2\u0315\u0316\3\2\2") buf.write(u"\2\u0315\u0313\3\2\2\2\u0316\u031f\3\2\2\2\u0317\u0315") buf.write(u"\3\2\2\2\u0318\u0320\t\3\2\2\u0319\u031b\7^\2\2\u031a") buf.write(u"\u031c\t\3\2\2\u031b\u031a\3\2\2\2\u031c\u031d\3\2\2") buf.write(u"\2\u031d\u031b\3\2\2\2\u031d\u031e\3\2\2\2\u031e\u0320") buf.write(u"\3\2\2\2\u031f\u0318\3\2\2\2\u031f\u0319\3\2\2\2\u0320") buf.write(u"\u0098\3\2\2\2\u0321\u0322\t\3\2\2\u0322\u009a\3\2\2") buf.write(u"\2\u0323\u0324\t\4\2\2\u0324\u009c\3\2\2\2\u0325\u0327") buf.write(u"\5\u009bN\2\u0326\u0325\3\2\2\2\u0327\u0328\3\2\2\2\u0328") buf.write(u"\u0326\3\2\2\2\u0328\u0329\3\2\2\2\u0329\u0331\3\2\2") buf.write(u"\2\u032a\u032b\7.\2\2\u032b\u032c\5\u009bN\2\u032c\u032d") buf.write(u"\5\u009bN\2\u032d\u032e\5\u009bN\2\u032e\u0330\3\2\2") buf.write(u"\2\u032f\u032a\3\2\2\2\u0330\u0333\3\2\2\2\u0331\u032f") buf.write(u"\3\2\2\2\u0331\u0332\3\2\2\2\u0332\u034b\3\2\2\2\u0333") buf.write(u"\u0331\3\2\2\2\u0334\u0336\5\u009bN\2\u0335\u0334\3\2") buf.write(u"\2\2\u0336\u0339\3\2\2\2\u0337\u0335\3\2\2\2\u0337\u0338") buf.write(u"\3\2\2\2\u0338\u0341\3\2\2\2\u0339\u0337\3\2\2\2\u033a") buf.write(u"\u033b\7.\2\2\u033b\u033c\5\u009bN\2\u033c\u033d\5\u009b") buf.write(u"N\2\u033d\u033e\5\u009bN\2\u033e\u0340\3\2\2\2\u033f") buf.write(u"\u033a\3\2\2\2\u0340\u0343\3\2\2\2\u0341\u033f\3\2\2") buf.write(u"\2\u0341\u0342\3\2\2\2\u0342\u0344\3\2\2\2\u0343\u0341") buf.write(u"\3\2\2\2\u0344\u0346\7\60\2\2\u0345\u0347\5\u009bN\2") buf.write(u"\u0346\u0345\3\2\2\2\u0347\u0348\3\2\2\2\u0348\u0346") buf.write(u"\3\2\2\2\u0348\u0349\3\2\2\2\u0349\u034b\3\2\2\2\u034a") buf.write(u"\u0326\3\2\2\2\u034a\u0337\3\2\2\2\u034b\u009e\3\2\2") buf.write(u"\2\u034c\u0350\7(\2\2\u034d\u034f\5\u0095K\2\u034e\u034d") buf.write(u"\3\2\2\2\u034f\u0352\3\2\2\2\u0350\u0351\3\2\2\2\u0350") buf.write(u"\u034e\3\2\2\2\u0351\u0354\3\2\2\2\u0352\u0350\3\2\2") buf.write(u"\2\u0353\u034c\3\2\2\2\u0353\u0354\3\2\2\2\u0354\u0355") buf.write(u"\3\2\2\2\u0355\u0361\7?\2\2\u0356\u035e\7?\2\2\u0357") buf.write(u"\u0359\5\u0095K\2\u0358\u0357\3\2\2\2\u0359\u035c\3\2") buf.write(u"\2\2\u035a\u035b\3\2\2\2\u035a\u0358\3\2\2\2\u035b\u035d") buf.write(u"\3\2\2\2\u035c\u035a\3\2\2\2\u035d\u035f\7(\2\2\u035e") buf.write(u"\u035a\3\2\2\2\u035e\u035f\3\2\2\2\u035f\u0361\3\2\2") buf.write(u"\2\u0360\u0353\3\2\2\2\u0360\u0356\3\2\2\2\u0361\u00a0") buf.write(u"\3\2\2\2\u0362\u0363\7^\2\2\u0363\u0364\7p\2\2\u0364") buf.write(u"\u0365\7g\2\2\u0365\u0366\7s\2\2\u0366\u00a2\3\2\2\2") buf.write(u"\u0367\u0368\7>\2\2\u0368\u00a4\3\2\2\2\u0369\u036a\7") buf.write(u"^\2\2\u036a\u036b\7n\2\2\u036b\u036c\7g\2\2\u036c\u0373") buf.write(u"\7s\2\2\u036d\u036e\7^\2\2\u036e\u036f\7n\2\2\u036f\u0373") buf.write(u"\7g\2\2\u0370\u0373\5\u00a7T\2\u0371\u0373\5\u00a9U\2") buf.write(u"\u0372\u0369\3\2\2\2\u0372\u036d\3\2\2\2\u0372\u0370") buf.write(u"\3\2\2\2\u0372\u0371\3\2\2\2\u0373\u00a6\3\2\2\2\u0374") buf.write(u"\u0375\7^\2\2\u0375\u0376\7n\2\2\u0376\u0377\7g\2\2\u0377") buf.write(u"\u0378\7s\2\2\u0378\u0379\7s\2\2\u0379\u00a8\3\2\2\2") buf.write(u"\u037a\u037b\7^\2\2\u037b\u037c\7n\2\2\u037c\u037d\7") buf.write(u"g\2\2\u037d\u037e\7s\2\2\u037e\u037f\7u\2\2\u037f\u0380") buf.write(u"\7n\2\2\u0380\u0381\7c\2\2\u0381\u0382\7p\2\2\u0382\u0383") buf.write(u"\7v\2\2\u0383\u00aa\3\2\2\2\u0384\u0385\7@\2\2\u0385") buf.write(u"\u00ac\3\2\2\2\u0386\u0387\7^\2\2\u0387\u0388\7i\2\2") buf.write(u"\u0388\u0389\7g\2\2\u0389\u0390\7s\2\2\u038a\u038b\7") buf.write(u"^\2\2\u038b\u038c\7i\2\2\u038c\u0390\7g\2\2\u038d\u0390") buf.write(u"\5\u00afX\2\u038e\u0390\5\u00b1Y\2\u038f\u0386\3\2\2") buf.write(u"\2\u038f\u038a\3\2\2\2\u038f\u038d\3\2\2\2\u038f\u038e") buf.write(u"\3\2\2\2\u0390\u00ae\3\2\2\2\u0391\u0392\7^\2\2\u0392") buf.write(u"\u0393\7i\2\2\u0393\u0394\7g\2\2\u0394\u0395\7s\2\2\u0395") buf.write(u"\u0396\7s\2\2\u0396\u00b0\3\2\2\2\u0397\u0398\7^\2\2") buf.write(u"\u0398\u0399\7i\2\2\u0399\u039a\7g\2\2\u039a\u039b\7") buf.write(u"s\2\2\u039b\u039c\7u\2\2\u039c\u039d\7n\2\2\u039d\u039e") buf.write(u"\7c\2\2\u039e\u039f\7p\2\2\u039f\u03a0\7v\2\2\u03a0\u00b2") buf.write(u"\3\2\2\2\u03a1\u03a2\7#\2\2\u03a2\u00b4\3\2\2\2\u03a3") buf.write(u"\u03a5\7^\2\2\u03a4\u03a6\t\3\2\2\u03a5\u03a4\3\2\2\2") buf.write(u"\u03a6\u03a7\3\2\2\2\u03a7\u03a5\3\2\2\2\u03a7\u03a8") buf.write(u"\3\2\2\2\u03a8\u00b6\3\2\2\2\35\2\u00bc\u00cc\u00db\u00ec") buf.write(u"\u0110\u0178\u01f3\u0204\u02e8\u0315\u031d\u031f\u0328") buf.write(u"\u0331\u0337\u0341\u0348\u034a\u0350\u0353\u035a\u035e") buf.write(u"\u0360\u0372\u038f\u03a7\3\b\2\2") return buf.getvalue() class LaTeXLexer(Lexer): atn = ATNDeserializer().deserialize(serializedATN()) decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ] T__0 = 1 WS = 2 THINSPACE = 3 MEDSPACE = 4 THICKSPACE = 5 QUAD = 6 QQUAD = 7 NEGTHINSPACE = 8 NEGMEDSPACE = 9 NEGTHICKSPACE = 10 CMD_LEFT = 11 CMD_RIGHT = 12 IGNORE = 13 ADD = 14 SUB = 15 MUL = 16 DIV = 17 L_PAREN = 18 R_PAREN = 19 L_BRACE = 20 R_BRACE = 21 L_BRACE_LITERAL = 22 R_BRACE_LITERAL = 23 L_BRACKET = 24 R_BRACKET = 25 BAR = 26 R_BAR = 27 L_BAR = 28 L_ANGLE = 29 R_ANGLE = 30 FUNC_LIM = 31 LIM_APPROACH_SYM = 32 FUNC_INT = 33 FUNC_SUM = 34 FUNC_PROD = 35 FUNC_EXP = 36 FUNC_LOG = 37 FUNC_LN = 38 FUNC_SIN = 39 FUNC_COS = 40 FUNC_TAN = 41 FUNC_CSC = 42 FUNC_SEC = 43 FUNC_COT = 44 FUNC_ARCSIN = 45 FUNC_ARCCOS = 46 FUNC_ARCTAN = 47 FUNC_ARCCSC = 48 FUNC_ARCSEC = 49 FUNC_ARCCOT = 50 FUNC_SINH = 51 FUNC_COSH = 52 FUNC_TANH = 53 FUNC_ARSINH = 54 FUNC_ARCOSH = 55 FUNC_ARTANH = 56 L_FLOOR = 57 R_FLOOR = 58 L_CEIL = 59 R_CEIL = 60 FUNC_SQRT = 61 FUNC_OVERLINE = 62 CMD_TIMES = 63 CMD_CDOT = 64 CMD_DIV = 65 CMD_FRAC = 66 CMD_BINOM = 67 CMD_DBINOM = 68 CMD_TBINOM = 69 CMD_MATHIT = 70 UNDERSCORE = 71 CARET = 72 COLON = 73 DIFFERENTIAL = 74 LETTER = 75 NUMBER = 76 EQUAL = 77 NEQ = 78 LT = 79 LTE = 80 LTE_Q = 81 LTE_S = 82 GT = 83 GTE = 84 GTE_Q = 85 GTE_S = 86 BANG = 87 SYMBOL = 88 channelNames = [ u"DEFAULT_TOKEN_CHANNEL", u"HIDDEN" ] modeNames = [ u"DEFAULT_MODE" ] literalNames = [ u"<INVALID>", u"','", u"'\\quad'", u"'\\qquad'", u"'\\negmedspace'", u"'\\negthickspace'", u"'\\left'", u"'\\right'", u"'+'", u"'-'", u"'*'", u"'/'", u"'('", u"')'", u"'{'", u"'}'", u"'\\{'", u"'\\}'", u"'['", u"']'", u"'|'", u"'\\right|'", u"'\\left|'", u"'\\langle'", u"'\\rangle'", u"'\\lim'", u"'\\sum'", u"'\\prod'", u"'\\exp'", u"'\\log'", u"'\\ln'", u"'\\sin'", u"'\\cos'", u"'\\tan'", u"'\\csc'", u"'\\sec'", u"'\\cot'", u"'\\arcsin'", u"'\\arccos'", u"'\\arctan'", u"'\\arccsc'", u"'\\arcsec'", u"'\\arccot'", u"'\\sinh'", u"'\\cosh'", u"'\\tanh'", u"'\\arsinh'", u"'\\arcosh'", u"'\\artanh'", u"'\\lfloor'", u"'\\rfloor'", u"'\\lceil'", u"'\\rceil'", u"'\\sqrt'", u"'\\overline'", u"'\\times'", u"'\\cdot'", u"'\\div'", u"'\\binom'", u"'\\dbinom'", u"'\\tbinom'", u"'\\mathit'", u"'_'", u"'^'", u"':'", u"'\\neq'", u"'<'", u"'\\leqq'", u"'\\leqslant'", u"'>'", u"'\\geqq'", u"'\\geqslant'", u"'!'" ] symbolicNames = [ u"<INVALID>", u"WS", u"THINSPACE", u"MEDSPACE", u"THICKSPACE", u"QUAD", u"QQUAD", u"NEGTHINSPACE", u"NEGMEDSPACE", u"NEGTHICKSPACE", u"CMD_LEFT", u"CMD_RIGHT", u"IGNORE", u"ADD", u"SUB", u"MUL", u"DIV", u"L_PAREN", u"R_PAREN", u"L_BRACE", u"R_BRACE", u"L_BRACE_LITERAL", u"R_BRACE_LITERAL", u"L_BRACKET", u"R_BRACKET", u"BAR", u"R_BAR", u"L_BAR", u"L_ANGLE", u"R_ANGLE", u"FUNC_LIM", u"LIM_APPROACH_SYM", u"FUNC_INT", u"FUNC_SUM", u"FUNC_PROD", u"FUNC_EXP", u"FUNC_LOG", u"FUNC_LN", u"FUNC_SIN", u"FUNC_COS", u"FUNC_TAN", u"FUNC_CSC", u"FUNC_SEC", u"FUNC_COT", u"FUNC_ARCSIN", u"FUNC_ARCCOS", u"FUNC_ARCTAN", u"FUNC_ARCCSC", u"FUNC_ARCSEC", u"FUNC_ARCCOT", u"FUNC_SINH", u"FUNC_COSH", u"FUNC_TANH", u"FUNC_ARSINH", u"FUNC_ARCOSH", u"FUNC_ARTANH", u"L_FLOOR", u"R_FLOOR", u"L_CEIL", u"R_CEIL", u"FUNC_SQRT", u"FUNC_OVERLINE", u"CMD_TIMES", u"CMD_CDOT", u"CMD_DIV", u"CMD_FRAC", u"CMD_BINOM", u"CMD_DBINOM", u"CMD_TBINOM", u"CMD_MATHIT", u"UNDERSCORE", u"CARET", u"COLON", u"DIFFERENTIAL", u"LETTER", u"NUMBER", u"EQUAL", u"NEQ", u"LT", u"LTE", u"LTE_Q", u"LTE_S", u"GT", u"GTE", u"GTE_Q", u"GTE_S", u"BANG", u"SYMBOL" ] ruleNames = [ u"T__0", u"WS", u"THINSPACE", u"MEDSPACE", u"THICKSPACE", u"QUAD", u"QQUAD", u"NEGTHINSPACE", u"NEGMEDSPACE", u"NEGTHICKSPACE", u"CMD_LEFT", u"CMD_RIGHT", u"IGNORE", u"ADD", u"SUB", u"MUL", u"DIV", u"L_PAREN", u"R_PAREN", u"L_BRACE", u"R_BRACE", u"L_BRACE_LITERAL", u"R_BRACE_LITERAL", u"L_BRACKET", u"R_BRACKET", u"BAR", u"R_BAR", u"L_BAR", u"L_ANGLE", u"R_ANGLE", u"FUNC_LIM", u"LIM_APPROACH_SYM", u"FUNC_INT", u"FUNC_SUM", u"FUNC_PROD", u"FUNC_EXP", u"FUNC_LOG", u"FUNC_LN", u"FUNC_SIN", u"FUNC_COS", u"FUNC_TAN", u"FUNC_CSC", u"FUNC_SEC", u"FUNC_COT", u"FUNC_ARCSIN", u"FUNC_ARCCOS", u"FUNC_ARCTAN", u"FUNC_ARCCSC", u"FUNC_ARCSEC", u"FUNC_ARCCOT", u"FUNC_SINH", u"FUNC_COSH", u"FUNC_TANH", u"FUNC_ARSINH", u"FUNC_ARCOSH", u"FUNC_ARTANH", u"L_FLOOR", u"R_FLOOR", u"L_CEIL", u"R_CEIL", u"FUNC_SQRT", u"FUNC_OVERLINE", u"CMD_TIMES", u"CMD_CDOT", u"CMD_DIV", u"CMD_FRAC", u"CMD_BINOM", u"CMD_DBINOM", u"CMD_TBINOM", u"CMD_MATHIT", u"UNDERSCORE", u"CARET", u"COLON", u"WS_CHAR", u"DIFFERENTIAL", u"LETTER", u"DIGIT", u"NUMBER", u"EQUAL", u"NEQ", u"LT", u"LTE", u"LTE_Q", u"LTE_S", u"GT", u"GTE", u"GTE_Q", u"GTE_S", u"BANG", u"SYMBOL" ] grammarFileName = u"LaTeX.g4" def __init__(self, input=None, output=sys.stdout): super(LaTeXLexer, self).__init__(input, output=output) self.checkVersion("4.7.2") self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache()) self._actions = None self._predicates = None
3204246433c066e93a8f44602dcfd35a928be890ecdddbe4171cd5861e4a4860
# encoding: utf-8 # *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND *** # # Generated from ../LaTeX.g4, derived from latex2sympy # latex2sympy is licensed under the MIT license # https://github.com/augustt198/latex2sympy/blob/master/LICENSE.txt # # Generated with antlr4 # antlr4 is licensed under the BSD-3-Clause License # https://github.com/antlr/antlr4/blob/master/LICENSE.txt from __future__ import print_function from antlr4 import * from io import StringIO import sys def serializedATN(): with StringIO() as buf: buf.write(u"\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\3") buf.write(u"Z\u01d3\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t") buf.write(u"\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\4\r\t\r") buf.write(u"\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22\t\22\4") buf.write(u"\23\t\23\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\4\30") buf.write(u"\t\30\4\31\t\31\4\32\t\32\4\33\t\33\4\34\t\34\4\35\t") buf.write(u"\35\4\36\t\36\4\37\t\37\4 \t \4!\t!\4\"\t\"\4#\t#\4$") buf.write(u"\t$\4%\t%\4&\t&\4\'\t\'\4(\t(\4)\t)\3\2\3\2\3\3\3\3\3") buf.write(u"\3\3\3\3\3\3\3\7\3[\n\3\f\3\16\3^\13\3\3\4\3\4\3\4\3") buf.write(u"\4\3\5\3\5\3\6\3\6\3\6\3\6\3\6\3\6\7\6l\n\6\f\6\16\6") buf.write(u"o\13\6\3\7\3\7\3\7\3\7\3\7\3\7\7\7w\n\7\f\7\16\7z\13") buf.write(u"\7\3\b\3\b\3\b\3\b\3\b\3\b\7\b\u0082\n\b\f\b\16\b\u0085") buf.write(u"\13\b\3\t\3\t\3\t\6\t\u008a\n\t\r\t\16\t\u008b\5\t\u008e") buf.write(u"\n\t\3\n\3\n\3\n\3\n\7\n\u0094\n\n\f\n\16\n\u0097\13") buf.write(u"\n\5\n\u0099\n\n\3\13\3\13\7\13\u009d\n\13\f\13\16\13") buf.write(u"\u00a0\13\13\3\f\3\f\7\f\u00a4\n\f\f\f\16\f\u00a7\13") buf.write(u"\f\3\r\3\r\5\r\u00ab\n\r\3\16\3\16\3\16\3\16\3\16\3\16") buf.write(u"\5\16\u00b3\n\16\3\17\3\17\3\17\3\17\5\17\u00b9\n\17") buf.write(u"\3\17\3\17\3\20\3\20\3\20\3\20\5\20\u00c1\n\20\3\20\3") buf.write(u"\20\3\21\3\21\3\21\3\21\3\21\3\21\3\21\3\21\3\21\3\21") buf.write(u"\5\21\u00cf\n\21\3\21\5\21\u00d2\n\21\7\21\u00d4\n\21") buf.write(u"\f\21\16\21\u00d7\13\21\3\22\3\22\3\22\3\22\3\22\3\22") buf.write(u"\3\22\3\22\3\22\3\22\5\22\u00e3\n\22\3\22\5\22\u00e6") buf.write(u"\n\22\7\22\u00e8\n\22\f\22\16\22\u00eb\13\22\3\23\3\23") buf.write(u"\3\23\3\23\3\23\3\23\5\23\u00f3\n\23\3\24\3\24\3\24\3") buf.write(u"\24\3\24\5\24\u00fa\n\24\3\25\3\25\3\25\3\25\3\25\3\25") buf.write(u"\3\25\3\25\3\25\3\25\3\25\3\25\3\25\3\25\3\25\3\25\5") buf.write(u"\25\u010c\n\25\3\26\3\26\3\26\3\26\3\27\3\27\5\27\u0114") buf.write(u"\n\27\3\27\3\27\3\27\3\27\3\27\3\27\3\27\5\27\u011d\n") buf.write(u"\27\3\30\3\30\3\30\3\30\3\31\3\31\3\31\3\31\3\32\3\32") buf.write(u"\3\32\3\32\3\32\3\33\7\33\u012d\n\33\f\33\16\33\u0130") buf.write(u"\13\33\3\34\3\34\3\34\3\34\3\34\3\34\3\34\3\34\3\35\3") buf.write(u"\35\3\35\3\35\3\35\3\35\3\35\3\35\3\36\3\36\3\36\3\36") buf.write(u"\3\37\3\37\3\37\3\37\3 \3 \3!\3!\5!\u014e\n!\3!\5!\u0151") buf.write(u"\n!\3!\5!\u0154\n!\3!\5!\u0157\n!\5!\u0159\n!\3!\3!\3") buf.write(u"!\3!\3!\5!\u0160\n!\3!\3!\5!\u0164\n!\3!\3!\3!\3!\3!") buf.write(u"\3!\3!\3!\3!\3!\3!\5!\u0171\n!\3!\5!\u0174\n!\3!\3!\3") buf.write(u"!\5!\u0179\n!\3!\3!\3!\3!\3!\5!\u0180\n!\3!\3!\3!\3!") buf.write(u"\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\5!\u0192\n!\3!\3") buf.write(u"!\3!\3!\3!\3!\5!\u019a\n!\3\"\3\"\3\"\3\"\3\"\5\"\u01a1") buf.write(u"\n\"\3#\3#\3#\3#\3#\3#\3#\3#\3#\5#\u01ac\n#\3#\3#\3$") buf.write(u"\3$\3$\3$\3$\5$\u01b5\n$\3%\3%\3&\3&\3&\3&\3&\3&\5&\u01bf") buf.write(u"\n&\3\'\3\'\3\'\3\'\3\'\3\'\5\'\u01c7\n\'\3(\3(\3(\3") buf.write(u"(\3(\3)\3)\3)\3)\3)\3)\2\b\4\n\f\16 \"*\2\4\6\b\n\f\16") buf.write(u"\20\22\24\26\30\32\34\36 \"$&(*,.\60\62\64\668:<>@BD") buf.write(u"FHJLNP\2\13\4\2ORUV\3\2\20\21\5\2\22\23ACKK\4\2MMZZ\3") buf.write(u"\2\34\35\4\2\34\34\36\36\3\2EG\3\2&:\3\2$%\2\u01ed\2") buf.write(u"R\3\2\2\2\4T\3\2\2\2\6_\3\2\2\2\bc\3\2\2\2\ne\3\2\2\2") buf.write(u"\fp\3\2\2\2\16{\3\2\2\2\20\u008d\3\2\2\2\22\u0098\3\2") buf.write(u"\2\2\24\u009a\3\2\2\2\26\u00a1\3\2\2\2\30\u00aa\3\2\2") buf.write(u"\2\32\u00ac\3\2\2\2\34\u00b4\3\2\2\2\36\u00bc\3\2\2\2") buf.write(u" \u00c4\3\2\2\2\"\u00d8\3\2\2\2$\u00f2\3\2\2\2&\u00f9") buf.write(u"\3\2\2\2(\u010b\3\2\2\2*\u010d\3\2\2\2,\u011c\3\2\2\2") buf.write(u".\u011e\3\2\2\2\60\u0122\3\2\2\2\62\u0126\3\2\2\2\64") buf.write(u"\u012e\3\2\2\2\66\u0131\3\2\2\28\u0139\3\2\2\2:\u0141") buf.write(u"\3\2\2\2<\u0145\3\2\2\2>\u0149\3\2\2\2@\u0199\3\2\2\2") buf.write(u"B\u01a0\3\2\2\2D\u01a2\3\2\2\2F\u01b4\3\2\2\2H\u01b6") buf.write(u"\3\2\2\2J\u01b8\3\2\2\2L\u01c0\3\2\2\2N\u01c8\3\2\2\2") buf.write(u"P\u01cd\3\2\2\2RS\5\4\3\2S\3\3\2\2\2TU\b\3\1\2UV\5\b") buf.write(u"\5\2V\\\3\2\2\2WX\f\4\2\2XY\t\2\2\2Y[\5\4\3\5ZW\3\2\2") buf.write(u"\2[^\3\2\2\2\\Z\3\2\2\2\\]\3\2\2\2]\5\3\2\2\2^\\\3\2") buf.write(u"\2\2_`\5\b\5\2`a\7O\2\2ab\5\b\5\2b\7\3\2\2\2cd\5\n\6") buf.write(u"\2d\t\3\2\2\2ef\b\6\1\2fg\5\f\7\2gm\3\2\2\2hi\f\4\2\2") buf.write(u"ij\t\3\2\2jl\5\n\6\5kh\3\2\2\2lo\3\2\2\2mk\3\2\2\2mn") buf.write(u"\3\2\2\2n\13\3\2\2\2om\3\2\2\2pq\b\7\1\2qr\5\20\t\2r") buf.write(u"x\3\2\2\2st\f\4\2\2tu\t\4\2\2uw\5\f\7\5vs\3\2\2\2wz\3") buf.write(u"\2\2\2xv\3\2\2\2xy\3\2\2\2y\r\3\2\2\2zx\3\2\2\2{|\b\b") buf.write(u"\1\2|}\5\22\n\2}\u0083\3\2\2\2~\177\f\4\2\2\177\u0080") buf.write(u"\t\4\2\2\u0080\u0082\5\16\b\5\u0081~\3\2\2\2\u0082\u0085") buf.write(u"\3\2\2\2\u0083\u0081\3\2\2\2\u0083\u0084\3\2\2\2\u0084") buf.write(u"\17\3\2\2\2\u0085\u0083\3\2\2\2\u0086\u0087\t\3\2\2\u0087") buf.write(u"\u008e\5\20\t\2\u0088\u008a\5\24\13\2\u0089\u0088\3\2") buf.write(u"\2\2\u008a\u008b\3\2\2\2\u008b\u0089\3\2\2\2\u008b\u008c") buf.write(u"\3\2\2\2\u008c\u008e\3\2\2\2\u008d\u0086\3\2\2\2\u008d") buf.write(u"\u0089\3\2\2\2\u008e\21\3\2\2\2\u008f\u0090\t\3\2\2\u0090") buf.write(u"\u0099\5\22\n\2\u0091\u0095\5\24\13\2\u0092\u0094\5\26") buf.write(u"\f\2\u0093\u0092\3\2\2\2\u0094\u0097\3\2\2\2\u0095\u0093") buf.write(u"\3\2\2\2\u0095\u0096\3\2\2\2\u0096\u0099\3\2\2\2\u0097") buf.write(u"\u0095\3\2\2\2\u0098\u008f\3\2\2\2\u0098\u0091\3\2\2") buf.write(u"\2\u0099\23\3\2\2\2\u009a\u009e\5 \21\2\u009b\u009d\5") buf.write(u"\30\r\2\u009c\u009b\3\2\2\2\u009d\u00a0\3\2\2\2\u009e") buf.write(u"\u009c\3\2\2\2\u009e\u009f\3\2\2\2\u009f\25\3\2\2\2\u00a0") buf.write(u"\u009e\3\2\2\2\u00a1\u00a5\5\"\22\2\u00a2\u00a4\5\30") buf.write(u"\r\2\u00a3\u00a2\3\2\2\2\u00a4\u00a7\3\2\2\2\u00a5\u00a3") buf.write(u"\3\2\2\2\u00a5\u00a6\3\2\2\2\u00a6\27\3\2\2\2\u00a7\u00a5") buf.write(u"\3\2\2\2\u00a8\u00ab\7Y\2\2\u00a9\u00ab\5\32\16\2\u00aa") buf.write(u"\u00a8\3\2\2\2\u00aa\u00a9\3\2\2\2\u00ab\31\3\2\2\2\u00ac") buf.write(u"\u00b2\7\34\2\2\u00ad\u00b3\5\36\20\2\u00ae\u00b3\5\34") buf.write(u"\17\2\u00af\u00b0\5\36\20\2\u00b0\u00b1\5\34\17\2\u00b1") buf.write(u"\u00b3\3\2\2\2\u00b2\u00ad\3\2\2\2\u00b2\u00ae\3\2\2") buf.write(u"\2\u00b2\u00af\3\2\2\2\u00b3\33\3\2\2\2\u00b4\u00b5\7") buf.write(u"I\2\2\u00b5\u00b8\7\26\2\2\u00b6\u00b9\5\b\5\2\u00b7") buf.write(u"\u00b9\5\6\4\2\u00b8\u00b6\3\2\2\2\u00b8\u00b7\3\2\2") buf.write(u"\2\u00b9\u00ba\3\2\2\2\u00ba\u00bb\7\27\2\2\u00bb\35") buf.write(u"\3\2\2\2\u00bc\u00bd\7J\2\2\u00bd\u00c0\7\26\2\2\u00be") buf.write(u"\u00c1\5\b\5\2\u00bf\u00c1\5\6\4\2\u00c0\u00be\3\2\2") buf.write(u"\2\u00c0\u00bf\3\2\2\2\u00c1\u00c2\3\2\2\2\u00c2\u00c3") buf.write(u"\7\27\2\2\u00c3\37\3\2\2\2\u00c4\u00c5\b\21\1\2\u00c5") buf.write(u"\u00c6\5$\23\2\u00c6\u00d5\3\2\2\2\u00c7\u00c8\f\4\2") buf.write(u"\2\u00c8\u00ce\7J\2\2\u00c9\u00cf\5,\27\2\u00ca\u00cb") buf.write(u"\7\26\2\2\u00cb\u00cc\5\b\5\2\u00cc\u00cd\7\27\2\2\u00cd") buf.write(u"\u00cf\3\2\2\2\u00ce\u00c9\3\2\2\2\u00ce\u00ca\3\2\2") buf.write(u"\2\u00cf\u00d1\3\2\2\2\u00d0\u00d2\5J&\2\u00d1\u00d0") buf.write(u"\3\2\2\2\u00d1\u00d2\3\2\2\2\u00d2\u00d4\3\2\2\2\u00d3") buf.write(u"\u00c7\3\2\2\2\u00d4\u00d7\3\2\2\2\u00d5\u00d3\3\2\2") buf.write(u"\2\u00d5\u00d6\3\2\2\2\u00d6!\3\2\2\2\u00d7\u00d5\3\2") buf.write(u"\2\2\u00d8\u00d9\b\22\1\2\u00d9\u00da\5&\24\2\u00da\u00e9") buf.write(u"\3\2\2\2\u00db\u00dc\f\4\2\2\u00dc\u00e2\7J\2\2\u00dd") buf.write(u"\u00e3\5,\27\2\u00de\u00df\7\26\2\2\u00df\u00e0\5\b\5") buf.write(u"\2\u00e0\u00e1\7\27\2\2\u00e1\u00e3\3\2\2\2\u00e2\u00dd") buf.write(u"\3\2\2\2\u00e2\u00de\3\2\2\2\u00e3\u00e5\3\2\2\2\u00e4") buf.write(u"\u00e6\5J&\2\u00e5\u00e4\3\2\2\2\u00e5\u00e6\3\2\2\2") buf.write(u"\u00e6\u00e8\3\2\2\2\u00e7\u00db\3\2\2\2\u00e8\u00eb") buf.write(u"\3\2\2\2\u00e9\u00e7\3\2\2\2\u00e9\u00ea\3\2\2\2\u00ea") buf.write(u"#\3\2\2\2\u00eb\u00e9\3\2\2\2\u00ec\u00f3\5(\25\2\u00ed") buf.write(u"\u00f3\5*\26\2\u00ee\u00f3\5@!\2\u00ef\u00f3\5,\27\2") buf.write(u"\u00f0\u00f3\5:\36\2\u00f1\u00f3\5<\37\2\u00f2\u00ec") buf.write(u"\3\2\2\2\u00f2\u00ed\3\2\2\2\u00f2\u00ee\3\2\2\2\u00f2") buf.write(u"\u00ef\3\2\2\2\u00f2\u00f0\3\2\2\2\u00f2\u00f1\3\2\2") buf.write(u"\2\u00f3%\3\2\2\2\u00f4\u00fa\5(\25\2\u00f5\u00fa\5*") buf.write(u"\26\2\u00f6\u00fa\5,\27\2\u00f7\u00fa\5:\36\2\u00f8\u00fa") buf.write(u"\5<\37\2\u00f9\u00f4\3\2\2\2\u00f9\u00f5\3\2\2\2\u00f9") buf.write(u"\u00f6\3\2\2\2\u00f9\u00f7\3\2\2\2\u00f9\u00f8\3\2\2") buf.write(u"\2\u00fa\'\3\2\2\2\u00fb\u00fc\7\24\2\2\u00fc\u00fd\5") buf.write(u"\b\5\2\u00fd\u00fe\7\25\2\2\u00fe\u010c\3\2\2\2\u00ff") buf.write(u"\u0100\7\32\2\2\u0100\u0101\5\b\5\2\u0101\u0102\7\33") buf.write(u"\2\2\u0102\u010c\3\2\2\2\u0103\u0104\7\26\2\2\u0104\u0105") buf.write(u"\5\b\5\2\u0105\u0106\7\27\2\2\u0106\u010c\3\2\2\2\u0107") buf.write(u"\u0108\7\30\2\2\u0108\u0109\5\b\5\2\u0109\u010a\7\31") buf.write(u"\2\2\u010a\u010c\3\2\2\2\u010b\u00fb\3\2\2\2\u010b\u00ff") buf.write(u"\3\2\2\2\u010b\u0103\3\2\2\2\u010b\u0107\3\2\2\2\u010c") buf.write(u")\3\2\2\2\u010d\u010e\7\34\2\2\u010e\u010f\5\b\5\2\u010f") buf.write(u"\u0110\7\34\2\2\u0110+\3\2\2\2\u0111\u0113\t\5\2\2\u0112") buf.write(u"\u0114\5J&\2\u0113\u0112\3\2\2\2\u0113\u0114\3\2\2\2") buf.write(u"\u0114\u011d\3\2\2\2\u0115\u011d\7N\2\2\u0116\u011d\7") buf.write(u"L\2\2\u0117\u011d\5\62\32\2\u0118\u011d\5\66\34\2\u0119") buf.write(u"\u011d\58\35\2\u011a\u011d\5.\30\2\u011b\u011d\5\60\31") buf.write(u"\2\u011c\u0111\3\2\2\2\u011c\u0115\3\2\2\2\u011c\u0116") buf.write(u"\3\2\2\2\u011c\u0117\3\2\2\2\u011c\u0118\3\2\2\2\u011c") buf.write(u"\u0119\3\2\2\2\u011c\u011a\3\2\2\2\u011c\u011b\3\2\2") buf.write(u"\2\u011d-\3\2\2\2\u011e\u011f\7\37\2\2\u011f\u0120\5") buf.write(u"\b\5\2\u0120\u0121\t\6\2\2\u0121/\3\2\2\2\u0122\u0123") buf.write(u"\t\7\2\2\u0123\u0124\5\b\5\2\u0124\u0125\7 \2\2\u0125") buf.write(u"\61\3\2\2\2\u0126\u0127\7H\2\2\u0127\u0128\7\26\2\2\u0128") buf.write(u"\u0129\5\64\33\2\u0129\u012a\7\27\2\2\u012a\63\3\2\2") buf.write(u"\2\u012b\u012d\7M\2\2\u012c\u012b\3\2\2\2\u012d\u0130") buf.write(u"\3\2\2\2\u012e\u012c\3\2\2\2\u012e\u012f\3\2\2\2\u012f") buf.write(u"\65\3\2\2\2\u0130\u012e\3\2\2\2\u0131\u0132\7D\2\2\u0132") buf.write(u"\u0133\7\26\2\2\u0133\u0134\5\b\5\2\u0134\u0135\7\27") buf.write(u"\2\2\u0135\u0136\7\26\2\2\u0136\u0137\5\b\5\2\u0137\u0138") buf.write(u"\7\27\2\2\u0138\67\3\2\2\2\u0139\u013a\t\b\2\2\u013a") buf.write(u"\u013b\7\26\2\2\u013b\u013c\5\b\5\2\u013c\u013d\7\27") buf.write(u"\2\2\u013d\u013e\7\26\2\2\u013e\u013f\5\b\5\2\u013f\u0140") buf.write(u"\7\27\2\2\u01409\3\2\2\2\u0141\u0142\7;\2\2\u0142\u0143") buf.write(u"\5\b\5\2\u0143\u0144\7<\2\2\u0144;\3\2\2\2\u0145\u0146") buf.write(u"\7=\2\2\u0146\u0147\5\b\5\2\u0147\u0148\7>\2\2\u0148") buf.write(u"=\3\2\2\2\u0149\u014a\t\t\2\2\u014a?\3\2\2\2\u014b\u0158") buf.write(u"\5> \2\u014c\u014e\5J&\2\u014d\u014c\3\2\2\2\u014d\u014e") buf.write(u"\3\2\2\2\u014e\u0150\3\2\2\2\u014f\u0151\5L\'\2\u0150") buf.write(u"\u014f\3\2\2\2\u0150\u0151\3\2\2\2\u0151\u0159\3\2\2") buf.write(u"\2\u0152\u0154\5L\'\2\u0153\u0152\3\2\2\2\u0153\u0154") buf.write(u"\3\2\2\2\u0154\u0156\3\2\2\2\u0155\u0157\5J&\2\u0156") buf.write(u"\u0155\3\2\2\2\u0156\u0157\3\2\2\2\u0157\u0159\3\2\2") buf.write(u"\2\u0158\u014d\3\2\2\2\u0158\u0153\3\2\2\2\u0159\u015f") buf.write(u"\3\2\2\2\u015a\u015b\7\24\2\2\u015b\u015c\5F$\2\u015c") buf.write(u"\u015d\7\25\2\2\u015d\u0160\3\2\2\2\u015e\u0160\5H%\2") buf.write(u"\u015f\u015a\3\2\2\2\u015f\u015e\3\2\2\2\u0160\u019a") buf.write(u"\3\2\2\2\u0161\u0163\t\5\2\2\u0162\u0164\5J&\2\u0163") buf.write(u"\u0162\3\2\2\2\u0163\u0164\3\2\2\2\u0164\u0165\3\2\2") buf.write(u"\2\u0165\u0166\7\24\2\2\u0166\u0167\5B\"\2\u0167\u0168") buf.write(u"\7\25\2\2\u0168\u019a\3\2\2\2\u0169\u0170\7#\2\2\u016a") buf.write(u"\u016b\5J&\2\u016b\u016c\5L\'\2\u016c\u0171\3\2\2\2\u016d") buf.write(u"\u016e\5L\'\2\u016e\u016f\5J&\2\u016f\u0171\3\2\2\2\u0170") buf.write(u"\u016a\3\2\2\2\u0170\u016d\3\2\2\2\u0170\u0171\3\2\2") buf.write(u"\2\u0171\u0178\3\2\2\2\u0172\u0174\5\n\6\2\u0173\u0172") buf.write(u"\3\2\2\2\u0173\u0174\3\2\2\2\u0174\u0175\3\2\2\2\u0175") buf.write(u"\u0179\7L\2\2\u0176\u0179\5\66\34\2\u0177\u0179\5\n\6") buf.write(u"\2\u0178\u0173\3\2\2\2\u0178\u0176\3\2\2\2\u0178\u0177") buf.write(u"\3\2\2\2\u0179\u019a\3\2\2\2\u017a\u017f\7?\2\2\u017b") buf.write(u"\u017c\7\32\2\2\u017c\u017d\5\b\5\2\u017d\u017e\7\33") buf.write(u"\2\2\u017e\u0180\3\2\2\2\u017f\u017b\3\2\2\2\u017f\u0180") buf.write(u"\3\2\2\2\u0180\u0181\3\2\2\2\u0181\u0182\7\26\2\2\u0182") buf.write(u"\u0183\5\b\5\2\u0183\u0184\7\27\2\2\u0184\u019a\3\2\2") buf.write(u"\2\u0185\u0186\7@\2\2\u0186\u0187\7\26\2\2\u0187\u0188") buf.write(u"\5\b\5\2\u0188\u0189\7\27\2\2\u0189\u019a\3\2\2\2\u018a") buf.write(u"\u0191\t\n\2\2\u018b\u018c\5N(\2\u018c\u018d\5L\'\2\u018d") buf.write(u"\u0192\3\2\2\2\u018e\u018f\5L\'\2\u018f\u0190\5N(\2\u0190") buf.write(u"\u0192\3\2\2\2\u0191\u018b\3\2\2\2\u0191\u018e\3\2\2") buf.write(u"\2\u0192\u0193\3\2\2\2\u0193\u0194\5\f\7\2\u0194\u019a") buf.write(u"\3\2\2\2\u0195\u0196\7!\2\2\u0196\u0197\5D#\2\u0197\u0198") buf.write(u"\5\f\7\2\u0198\u019a\3\2\2\2\u0199\u014b\3\2\2\2\u0199") buf.write(u"\u0161\3\2\2\2\u0199\u0169\3\2\2\2\u0199\u017a\3\2\2") buf.write(u"\2\u0199\u0185\3\2\2\2\u0199\u018a\3\2\2\2\u0199\u0195") buf.write(u"\3\2\2\2\u019aA\3\2\2\2\u019b\u019c\5\b\5\2\u019c\u019d") buf.write(u"\7\3\2\2\u019d\u019e\5B\"\2\u019e\u01a1\3\2\2\2\u019f") buf.write(u"\u01a1\5\b\5\2\u01a0\u019b\3\2\2\2\u01a0\u019f\3\2\2") buf.write(u"\2\u01a1C\3\2\2\2\u01a2\u01a3\7I\2\2\u01a3\u01a4\7\26") buf.write(u"\2\2\u01a4\u01a5\t\5\2\2\u01a5\u01a6\7\"\2\2\u01a6\u01ab") buf.write(u"\5\b\5\2\u01a7\u01a8\7J\2\2\u01a8\u01a9\7\26\2\2\u01a9") buf.write(u"\u01aa\t\3\2\2\u01aa\u01ac\7\27\2\2\u01ab\u01a7\3\2\2") buf.write(u"\2\u01ab\u01ac\3\2\2\2\u01ac\u01ad\3\2\2\2\u01ad\u01ae") buf.write(u"\7\27\2\2\u01aeE\3\2\2\2\u01af\u01b5\5\b\5\2\u01b0\u01b1") buf.write(u"\5\b\5\2\u01b1\u01b2\7\3\2\2\u01b2\u01b3\5F$\2\u01b3") buf.write(u"\u01b5\3\2\2\2\u01b4\u01af\3\2\2\2\u01b4\u01b0\3\2\2") buf.write(u"\2\u01b5G\3\2\2\2\u01b6\u01b7\5\16\b\2\u01b7I\3\2\2\2") buf.write(u"\u01b8\u01be\7I\2\2\u01b9\u01bf\5,\27\2\u01ba\u01bb\7") buf.write(u"\26\2\2\u01bb\u01bc\5\b\5\2\u01bc\u01bd\7\27\2\2\u01bd") buf.write(u"\u01bf\3\2\2\2\u01be\u01b9\3\2\2\2\u01be\u01ba\3\2\2") buf.write(u"\2\u01bfK\3\2\2\2\u01c0\u01c6\7J\2\2\u01c1\u01c7\5,\27") buf.write(u"\2\u01c2\u01c3\7\26\2\2\u01c3\u01c4\5\b\5\2\u01c4\u01c5") buf.write(u"\7\27\2\2\u01c5\u01c7\3\2\2\2\u01c6\u01c1\3\2\2\2\u01c6") buf.write(u"\u01c2\3\2\2\2\u01c7M\3\2\2\2\u01c8\u01c9\7I\2\2\u01c9") buf.write(u"\u01ca\7\26\2\2\u01ca\u01cb\5\6\4\2\u01cb\u01cc\7\27") buf.write(u"\2\2\u01ccO\3\2\2\2\u01cd\u01ce\7I\2\2\u01ce\u01cf\7") buf.write(u"\26\2\2\u01cf\u01d0\5\6\4\2\u01d0\u01d1\7\27\2\2\u01d1") buf.write(u"Q\3\2\2\2.\\mx\u0083\u008b\u008d\u0095\u0098\u009e\u00a5") buf.write(u"\u00aa\u00b2\u00b8\u00c0\u00ce\u00d1\u00d5\u00e2\u00e5") buf.write(u"\u00e9\u00f2\u00f9\u010b\u0113\u011c\u012e\u014d\u0150") buf.write(u"\u0153\u0156\u0158\u015f\u0163\u0170\u0173\u0178\u017f") buf.write(u"\u0191\u0199\u01a0\u01ab\u01b4\u01be\u01c6") return buf.getvalue() class LaTeXParser ( Parser ): grammarFileName = "LaTeX.g4" atn = ATNDeserializer().deserialize(serializedATN()) decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ] sharedContextCache = PredictionContextCache() literalNames = [ u"<INVALID>", u"','", u"<INVALID>", u"<INVALID>", u"<INVALID>", u"<INVALID>", u"'\\quad'", u"'\\qquad'", u"<INVALID>", u"'\\negmedspace'", u"'\\negthickspace'", u"'\\left'", u"'\\right'", u"<INVALID>", u"'+'", u"'-'", u"'*'", u"'/'", u"'('", u"')'", u"'{'", u"'}'", u"'\\{'", u"'\\}'", u"'['", u"']'", u"'|'", u"'\\right|'", u"'\\left|'", u"'\\langle'", u"'\\rangle'", u"'\\lim'", u"<INVALID>", u"<INVALID>", u"'\\sum'", u"'\\prod'", u"'\\exp'", u"'\\log'", u"'\\ln'", u"'\\sin'", u"'\\cos'", u"'\\tan'", u"'\\csc'", u"'\\sec'", u"'\\cot'", u"'\\arcsin'", u"'\\arccos'", u"'\\arctan'", u"'\\arccsc'", u"'\\arcsec'", u"'\\arccot'", u"'\\sinh'", u"'\\cosh'", u"'\\tanh'", u"'\\arsinh'", u"'\\arcosh'", u"'\\artanh'", u"'\\lfloor'", u"'\\rfloor'", u"'\\lceil'", u"'\\rceil'", u"'\\sqrt'", u"'\\overline'", u"'\\times'", u"'\\cdot'", u"'\\div'", u"<INVALID>", u"'\\binom'", u"'\\dbinom'", u"'\\tbinom'", u"'\\mathit'", u"'_'", u"'^'", u"':'", u"<INVALID>", u"<INVALID>", u"<INVALID>", u"<INVALID>", u"'\\neq'", u"'<'", u"<INVALID>", u"'\\leqq'", u"'\\leqslant'", u"'>'", u"<INVALID>", u"'\\geqq'", u"'\\geqslant'", u"'!'" ] symbolicNames = [ u"<INVALID>", u"<INVALID>", u"WS", u"THINSPACE", u"MEDSPACE", u"THICKSPACE", u"QUAD", u"QQUAD", u"NEGTHINSPACE", u"NEGMEDSPACE", u"NEGTHICKSPACE", u"CMD_LEFT", u"CMD_RIGHT", u"IGNORE", u"ADD", u"SUB", u"MUL", u"DIV", u"L_PAREN", u"R_PAREN", u"L_BRACE", u"R_BRACE", u"L_BRACE_LITERAL", u"R_BRACE_LITERAL", u"L_BRACKET", u"R_BRACKET", u"BAR", u"R_BAR", u"L_BAR", u"L_ANGLE", u"R_ANGLE", u"FUNC_LIM", u"LIM_APPROACH_SYM", u"FUNC_INT", u"FUNC_SUM", u"FUNC_PROD", u"FUNC_EXP", u"FUNC_LOG", u"FUNC_LN", u"FUNC_SIN", u"FUNC_COS", u"FUNC_TAN", u"FUNC_CSC", u"FUNC_SEC", u"FUNC_COT", u"FUNC_ARCSIN", u"FUNC_ARCCOS", u"FUNC_ARCTAN", u"FUNC_ARCCSC", u"FUNC_ARCSEC", u"FUNC_ARCCOT", u"FUNC_SINH", u"FUNC_COSH", u"FUNC_TANH", u"FUNC_ARSINH", u"FUNC_ARCOSH", u"FUNC_ARTANH", u"L_FLOOR", u"R_FLOOR", u"L_CEIL", u"R_CEIL", u"FUNC_SQRT", u"FUNC_OVERLINE", u"CMD_TIMES", u"CMD_CDOT", u"CMD_DIV", u"CMD_FRAC", u"CMD_BINOM", u"CMD_DBINOM", u"CMD_TBINOM", u"CMD_MATHIT", u"UNDERSCORE", u"CARET", u"COLON", u"DIFFERENTIAL", u"LETTER", u"NUMBER", u"EQUAL", u"NEQ", u"LT", u"LTE", u"LTE_Q", u"LTE_S", u"GT", u"GTE", u"GTE_Q", u"GTE_S", u"BANG", u"SYMBOL" ] RULE_math = 0 RULE_relation = 1 RULE_equality = 2 RULE_expr = 3 RULE_additive = 4 RULE_mp = 5 RULE_mp_nofunc = 6 RULE_unary = 7 RULE_unary_nofunc = 8 RULE_postfix = 9 RULE_postfix_nofunc = 10 RULE_postfix_op = 11 RULE_eval_at = 12 RULE_eval_at_sub = 13 RULE_eval_at_sup = 14 RULE_exp = 15 RULE_exp_nofunc = 16 RULE_comp = 17 RULE_comp_nofunc = 18 RULE_group = 19 RULE_abs_group = 20 RULE_atom = 21 RULE_bra = 22 RULE_ket = 23 RULE_mathit = 24 RULE_mathit_text = 25 RULE_frac = 26 RULE_binom = 27 RULE_floor = 28 RULE_ceil = 29 RULE_func_normal = 30 RULE_func = 31 RULE_args = 32 RULE_limit_sub = 33 RULE_func_arg = 34 RULE_func_arg_noparens = 35 RULE_subexpr = 36 RULE_supexpr = 37 RULE_subeq = 38 RULE_supeq = 39 ruleNames = [ u"math", u"relation", u"equality", u"expr", u"additive", u"mp", u"mp_nofunc", u"unary", u"unary_nofunc", u"postfix", u"postfix_nofunc", u"postfix_op", u"eval_at", u"eval_at_sub", u"eval_at_sup", u"exp", u"exp_nofunc", u"comp", u"comp_nofunc", u"group", u"abs_group", u"atom", u"bra", u"ket", u"mathit", u"mathit_text", u"frac", u"binom", u"floor", u"ceil", u"func_normal", u"func", u"args", u"limit_sub", u"func_arg", u"func_arg_noparens", u"subexpr", u"supexpr", u"subeq", u"supeq" ] EOF = Token.EOF T__0=1 WS=2 THINSPACE=3 MEDSPACE=4 THICKSPACE=5 QUAD=6 QQUAD=7 NEGTHINSPACE=8 NEGMEDSPACE=9 NEGTHICKSPACE=10 CMD_LEFT=11 CMD_RIGHT=12 IGNORE=13 ADD=14 SUB=15 MUL=16 DIV=17 L_PAREN=18 R_PAREN=19 L_BRACE=20 R_BRACE=21 L_BRACE_LITERAL=22 R_BRACE_LITERAL=23 L_BRACKET=24 R_BRACKET=25 BAR=26 R_BAR=27 L_BAR=28 L_ANGLE=29 R_ANGLE=30 FUNC_LIM=31 LIM_APPROACH_SYM=32 FUNC_INT=33 FUNC_SUM=34 FUNC_PROD=35 FUNC_EXP=36 FUNC_LOG=37 FUNC_LN=38 FUNC_SIN=39 FUNC_COS=40 FUNC_TAN=41 FUNC_CSC=42 FUNC_SEC=43 FUNC_COT=44 FUNC_ARCSIN=45 FUNC_ARCCOS=46 FUNC_ARCTAN=47 FUNC_ARCCSC=48 FUNC_ARCSEC=49 FUNC_ARCCOT=50 FUNC_SINH=51 FUNC_COSH=52 FUNC_TANH=53 FUNC_ARSINH=54 FUNC_ARCOSH=55 FUNC_ARTANH=56 L_FLOOR=57 R_FLOOR=58 L_CEIL=59 R_CEIL=60 FUNC_SQRT=61 FUNC_OVERLINE=62 CMD_TIMES=63 CMD_CDOT=64 CMD_DIV=65 CMD_FRAC=66 CMD_BINOM=67 CMD_DBINOM=68 CMD_TBINOM=69 CMD_MATHIT=70 UNDERSCORE=71 CARET=72 COLON=73 DIFFERENTIAL=74 LETTER=75 NUMBER=76 EQUAL=77 NEQ=78 LT=79 LTE=80 LTE_Q=81 LTE_S=82 GT=83 GTE=84 GTE_Q=85 GTE_S=86 BANG=87 SYMBOL=88 def __init__(self, input, output=sys.stdout): super(LaTeXParser, self).__init__(input, output=output) self.checkVersion("4.7.2") self._interp = ParserATNSimulator(self, self.atn, self.decisionsToDFA, self.sharedContextCache) self._predicates = None class MathContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.MathContext, self).__init__(parent, invokingState) self.parser = parser def relation(self): return self.getTypedRuleContext(LaTeXParser.RelationContext,0) def getRuleIndex(self): return LaTeXParser.RULE_math def math(self): localctx = LaTeXParser.MathContext(self, self._ctx, self.state) self.enterRule(localctx, 0, self.RULE_math) try: self.enterOuterAlt(localctx, 1) self.state = 80 self.relation(0) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class RelationContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.RelationContext, self).__init__(parent, invokingState) self.parser = parser def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def relation(self, i=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.RelationContext) else: return self.getTypedRuleContext(LaTeXParser.RelationContext,i) def EQUAL(self): return self.getToken(LaTeXParser.EQUAL, 0) def LT(self): return self.getToken(LaTeXParser.LT, 0) def LTE(self): return self.getToken(LaTeXParser.LTE, 0) def GT(self): return self.getToken(LaTeXParser.GT, 0) def GTE(self): return self.getToken(LaTeXParser.GTE, 0) def NEQ(self): return self.getToken(LaTeXParser.NEQ, 0) def getRuleIndex(self): return LaTeXParser.RULE_relation def relation(self, _p=0): _parentctx = self._ctx _parentState = self.state localctx = LaTeXParser.RelationContext(self, self._ctx, _parentState) _prevctx = localctx _startState = 2 self.enterRecursionRule(localctx, 2, self.RULE_relation, _p) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 83 self.expr() self._ctx.stop = self._input.LT(-1) self.state = 90 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,0,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: if self._parseListeners is not None: self.triggerExitRuleEvent() _prevctx = localctx localctx = LaTeXParser.RelationContext(self, _parentctx, _parentState) self.pushNewRecursionContext(localctx, _startState, self.RULE_relation) self.state = 85 if not self.precpred(self._ctx, 2): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 2)") self.state = 86 _la = self._input.LA(1) if not(((((_la - 77)) & ~0x3f) == 0 and ((1 << (_la - 77)) & ((1 << (LaTeXParser.EQUAL - 77)) | (1 << (LaTeXParser.NEQ - 77)) | (1 << (LaTeXParser.LT - 77)) | (1 << (LaTeXParser.LTE - 77)) | (1 << (LaTeXParser.GT - 77)) | (1 << (LaTeXParser.GTE - 77)))) != 0)): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 87 self.relation(3) self.state = 92 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,0,self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.unrollRecursionContexts(_parentctx) return localctx class EqualityContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.EqualityContext, self).__init__(parent, invokingState) self.parser = parser def expr(self, i=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.ExprContext) else: return self.getTypedRuleContext(LaTeXParser.ExprContext,i) def EQUAL(self): return self.getToken(LaTeXParser.EQUAL, 0) def getRuleIndex(self): return LaTeXParser.RULE_equality def equality(self): localctx = LaTeXParser.EqualityContext(self, self._ctx, self.state) self.enterRule(localctx, 4, self.RULE_equality) try: self.enterOuterAlt(localctx, 1) self.state = 93 self.expr() self.state = 94 self.match(LaTeXParser.EQUAL) self.state = 95 self.expr() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ExprContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.ExprContext, self).__init__(parent, invokingState) self.parser = parser def additive(self): return self.getTypedRuleContext(LaTeXParser.AdditiveContext,0) def getRuleIndex(self): return LaTeXParser.RULE_expr def expr(self): localctx = LaTeXParser.ExprContext(self, self._ctx, self.state) self.enterRule(localctx, 6, self.RULE_expr) try: self.enterOuterAlt(localctx, 1) self.state = 97 self.additive(0) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class AdditiveContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.AdditiveContext, self).__init__(parent, invokingState) self.parser = parser def mp(self): return self.getTypedRuleContext(LaTeXParser.MpContext,0) def additive(self, i=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.AdditiveContext) else: return self.getTypedRuleContext(LaTeXParser.AdditiveContext,i) def ADD(self): return self.getToken(LaTeXParser.ADD, 0) def SUB(self): return self.getToken(LaTeXParser.SUB, 0) def getRuleIndex(self): return LaTeXParser.RULE_additive def additive(self, _p=0): _parentctx = self._ctx _parentState = self.state localctx = LaTeXParser.AdditiveContext(self, self._ctx, _parentState) _prevctx = localctx _startState = 8 self.enterRecursionRule(localctx, 8, self.RULE_additive, _p) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 100 self.mp(0) self._ctx.stop = self._input.LT(-1) self.state = 107 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,1,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: if self._parseListeners is not None: self.triggerExitRuleEvent() _prevctx = localctx localctx = LaTeXParser.AdditiveContext(self, _parentctx, _parentState) self.pushNewRecursionContext(localctx, _startState, self.RULE_additive) self.state = 102 if not self.precpred(self._ctx, 2): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 2)") self.state = 103 _la = self._input.LA(1) if not(_la==LaTeXParser.ADD or _la==LaTeXParser.SUB): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 104 self.additive(3) self.state = 109 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,1,self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.unrollRecursionContexts(_parentctx) return localctx class MpContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.MpContext, self).__init__(parent, invokingState) self.parser = parser def unary(self): return self.getTypedRuleContext(LaTeXParser.UnaryContext,0) def mp(self, i=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.MpContext) else: return self.getTypedRuleContext(LaTeXParser.MpContext,i) def MUL(self): return self.getToken(LaTeXParser.MUL, 0) def CMD_TIMES(self): return self.getToken(LaTeXParser.CMD_TIMES, 0) def CMD_CDOT(self): return self.getToken(LaTeXParser.CMD_CDOT, 0) def DIV(self): return self.getToken(LaTeXParser.DIV, 0) def CMD_DIV(self): return self.getToken(LaTeXParser.CMD_DIV, 0) def COLON(self): return self.getToken(LaTeXParser.COLON, 0) def getRuleIndex(self): return LaTeXParser.RULE_mp def mp(self, _p=0): _parentctx = self._ctx _parentState = self.state localctx = LaTeXParser.MpContext(self, self._ctx, _parentState) _prevctx = localctx _startState = 10 self.enterRecursionRule(localctx, 10, self.RULE_mp, _p) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 111 self.unary() self._ctx.stop = self._input.LT(-1) self.state = 118 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,2,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: if self._parseListeners is not None: self.triggerExitRuleEvent() _prevctx = localctx localctx = LaTeXParser.MpContext(self, _parentctx, _parentState) self.pushNewRecursionContext(localctx, _startState, self.RULE_mp) self.state = 113 if not self.precpred(self._ctx, 2): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 2)") self.state = 114 _la = self._input.LA(1) if not(((((_la - 16)) & ~0x3f) == 0 and ((1 << (_la - 16)) & ((1 << (LaTeXParser.MUL - 16)) | (1 << (LaTeXParser.DIV - 16)) | (1 << (LaTeXParser.CMD_TIMES - 16)) | (1 << (LaTeXParser.CMD_CDOT - 16)) | (1 << (LaTeXParser.CMD_DIV - 16)) | (1 << (LaTeXParser.COLON - 16)))) != 0)): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 115 self.mp(3) self.state = 120 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,2,self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.unrollRecursionContexts(_parentctx) return localctx class Mp_nofuncContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Mp_nofuncContext, self).__init__(parent, invokingState) self.parser = parser def unary_nofunc(self): return self.getTypedRuleContext(LaTeXParser.Unary_nofuncContext,0) def mp_nofunc(self, i=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.Mp_nofuncContext) else: return self.getTypedRuleContext(LaTeXParser.Mp_nofuncContext,i) def MUL(self): return self.getToken(LaTeXParser.MUL, 0) def CMD_TIMES(self): return self.getToken(LaTeXParser.CMD_TIMES, 0) def CMD_CDOT(self): return self.getToken(LaTeXParser.CMD_CDOT, 0) def DIV(self): return self.getToken(LaTeXParser.DIV, 0) def CMD_DIV(self): return self.getToken(LaTeXParser.CMD_DIV, 0) def COLON(self): return self.getToken(LaTeXParser.COLON, 0) def getRuleIndex(self): return LaTeXParser.RULE_mp_nofunc def mp_nofunc(self, _p=0): _parentctx = self._ctx _parentState = self.state localctx = LaTeXParser.Mp_nofuncContext(self, self._ctx, _parentState) _prevctx = localctx _startState = 12 self.enterRecursionRule(localctx, 12, self.RULE_mp_nofunc, _p) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 122 self.unary_nofunc() self._ctx.stop = self._input.LT(-1) self.state = 129 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,3,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: if self._parseListeners is not None: self.triggerExitRuleEvent() _prevctx = localctx localctx = LaTeXParser.Mp_nofuncContext(self, _parentctx, _parentState) self.pushNewRecursionContext(localctx, _startState, self.RULE_mp_nofunc) self.state = 124 if not self.precpred(self._ctx, 2): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 2)") self.state = 125 _la = self._input.LA(1) if not(((((_la - 16)) & ~0x3f) == 0 and ((1 << (_la - 16)) & ((1 << (LaTeXParser.MUL - 16)) | (1 << (LaTeXParser.DIV - 16)) | (1 << (LaTeXParser.CMD_TIMES - 16)) | (1 << (LaTeXParser.CMD_CDOT - 16)) | (1 << (LaTeXParser.CMD_DIV - 16)) | (1 << (LaTeXParser.COLON - 16)))) != 0)): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 126 self.mp_nofunc(3) self.state = 131 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,3,self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.unrollRecursionContexts(_parentctx) return localctx class UnaryContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.UnaryContext, self).__init__(parent, invokingState) self.parser = parser def unary(self): return self.getTypedRuleContext(LaTeXParser.UnaryContext,0) def ADD(self): return self.getToken(LaTeXParser.ADD, 0) def SUB(self): return self.getToken(LaTeXParser.SUB, 0) def postfix(self, i=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.PostfixContext) else: return self.getTypedRuleContext(LaTeXParser.PostfixContext,i) def getRuleIndex(self): return LaTeXParser.RULE_unary def unary(self): localctx = LaTeXParser.UnaryContext(self, self._ctx, self.state) self.enterRule(localctx, 14, self.RULE_unary) self._la = 0 # Token type try: self.state = 139 self._errHandler.sync(self) token = self._input.LA(1) if token in [LaTeXParser.ADD, LaTeXParser.SUB]: self.enterOuterAlt(localctx, 1) self.state = 132 _la = self._input.LA(1) if not(_la==LaTeXParser.ADD or _la==LaTeXParser.SUB): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 133 self.unary() pass elif token in [LaTeXParser.L_PAREN, LaTeXParser.L_BRACE, LaTeXParser.L_BRACE_LITERAL, LaTeXParser.L_BRACKET, LaTeXParser.BAR, LaTeXParser.L_BAR, LaTeXParser.L_ANGLE, LaTeXParser.FUNC_LIM, LaTeXParser.FUNC_INT, LaTeXParser.FUNC_SUM, LaTeXParser.FUNC_PROD, LaTeXParser.FUNC_EXP, LaTeXParser.FUNC_LOG, LaTeXParser.FUNC_LN, LaTeXParser.FUNC_SIN, LaTeXParser.FUNC_COS, LaTeXParser.FUNC_TAN, LaTeXParser.FUNC_CSC, LaTeXParser.FUNC_SEC, LaTeXParser.FUNC_COT, LaTeXParser.FUNC_ARCSIN, LaTeXParser.FUNC_ARCCOS, LaTeXParser.FUNC_ARCTAN, LaTeXParser.FUNC_ARCCSC, LaTeXParser.FUNC_ARCSEC, LaTeXParser.FUNC_ARCCOT, LaTeXParser.FUNC_SINH, LaTeXParser.FUNC_COSH, LaTeXParser.FUNC_TANH, LaTeXParser.FUNC_ARSINH, LaTeXParser.FUNC_ARCOSH, LaTeXParser.FUNC_ARTANH, LaTeXParser.L_FLOOR, LaTeXParser.L_CEIL, LaTeXParser.FUNC_SQRT, LaTeXParser.FUNC_OVERLINE, LaTeXParser.CMD_FRAC, LaTeXParser.CMD_BINOM, LaTeXParser.CMD_DBINOM, LaTeXParser.CMD_TBINOM, LaTeXParser.CMD_MATHIT, LaTeXParser.DIFFERENTIAL, LaTeXParser.LETTER, LaTeXParser.NUMBER, LaTeXParser.SYMBOL]: self.enterOuterAlt(localctx, 2) self.state = 135 self._errHandler.sync(self) _alt = 1 while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt == 1: self.state = 134 self.postfix() else: raise NoViableAltException(self) self.state = 137 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,4,self._ctx) pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Unary_nofuncContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Unary_nofuncContext, self).__init__(parent, invokingState) self.parser = parser def unary_nofunc(self): return self.getTypedRuleContext(LaTeXParser.Unary_nofuncContext,0) def ADD(self): return self.getToken(LaTeXParser.ADD, 0) def SUB(self): return self.getToken(LaTeXParser.SUB, 0) def postfix(self): return self.getTypedRuleContext(LaTeXParser.PostfixContext,0) def postfix_nofunc(self, i=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.Postfix_nofuncContext) else: return self.getTypedRuleContext(LaTeXParser.Postfix_nofuncContext,i) def getRuleIndex(self): return LaTeXParser.RULE_unary_nofunc def unary_nofunc(self): localctx = LaTeXParser.Unary_nofuncContext(self, self._ctx, self.state) self.enterRule(localctx, 16, self.RULE_unary_nofunc) self._la = 0 # Token type try: self.state = 150 self._errHandler.sync(self) token = self._input.LA(1) if token in [LaTeXParser.ADD, LaTeXParser.SUB]: self.enterOuterAlt(localctx, 1) self.state = 141 _la = self._input.LA(1) if not(_la==LaTeXParser.ADD or _la==LaTeXParser.SUB): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 142 self.unary_nofunc() pass elif token in [LaTeXParser.L_PAREN, LaTeXParser.L_BRACE, LaTeXParser.L_BRACE_LITERAL, LaTeXParser.L_BRACKET, LaTeXParser.BAR, LaTeXParser.L_BAR, LaTeXParser.L_ANGLE, LaTeXParser.FUNC_LIM, LaTeXParser.FUNC_INT, LaTeXParser.FUNC_SUM, LaTeXParser.FUNC_PROD, LaTeXParser.FUNC_EXP, LaTeXParser.FUNC_LOG, LaTeXParser.FUNC_LN, LaTeXParser.FUNC_SIN, LaTeXParser.FUNC_COS, LaTeXParser.FUNC_TAN, LaTeXParser.FUNC_CSC, LaTeXParser.FUNC_SEC, LaTeXParser.FUNC_COT, LaTeXParser.FUNC_ARCSIN, LaTeXParser.FUNC_ARCCOS, LaTeXParser.FUNC_ARCTAN, LaTeXParser.FUNC_ARCCSC, LaTeXParser.FUNC_ARCSEC, LaTeXParser.FUNC_ARCCOT, LaTeXParser.FUNC_SINH, LaTeXParser.FUNC_COSH, LaTeXParser.FUNC_TANH, LaTeXParser.FUNC_ARSINH, LaTeXParser.FUNC_ARCOSH, LaTeXParser.FUNC_ARTANH, LaTeXParser.L_FLOOR, LaTeXParser.L_CEIL, LaTeXParser.FUNC_SQRT, LaTeXParser.FUNC_OVERLINE, LaTeXParser.CMD_FRAC, LaTeXParser.CMD_BINOM, LaTeXParser.CMD_DBINOM, LaTeXParser.CMD_TBINOM, LaTeXParser.CMD_MATHIT, LaTeXParser.DIFFERENTIAL, LaTeXParser.LETTER, LaTeXParser.NUMBER, LaTeXParser.SYMBOL]: self.enterOuterAlt(localctx, 2) self.state = 143 self.postfix() self.state = 147 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,6,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: self.state = 144 self.postfix_nofunc() self.state = 149 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,6,self._ctx) pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class PostfixContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.PostfixContext, self).__init__(parent, invokingState) self.parser = parser def exp(self): return self.getTypedRuleContext(LaTeXParser.ExpContext,0) def postfix_op(self, i=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.Postfix_opContext) else: return self.getTypedRuleContext(LaTeXParser.Postfix_opContext,i) def getRuleIndex(self): return LaTeXParser.RULE_postfix def postfix(self): localctx = LaTeXParser.PostfixContext(self, self._ctx, self.state) self.enterRule(localctx, 18, self.RULE_postfix) try: self.enterOuterAlt(localctx, 1) self.state = 152 self.exp(0) self.state = 156 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,8,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: self.state = 153 self.postfix_op() self.state = 158 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,8,self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Postfix_nofuncContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Postfix_nofuncContext, self).__init__(parent, invokingState) self.parser = parser def exp_nofunc(self): return self.getTypedRuleContext(LaTeXParser.Exp_nofuncContext,0) def postfix_op(self, i=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.Postfix_opContext) else: return self.getTypedRuleContext(LaTeXParser.Postfix_opContext,i) def getRuleIndex(self): return LaTeXParser.RULE_postfix_nofunc def postfix_nofunc(self): localctx = LaTeXParser.Postfix_nofuncContext(self, self._ctx, self.state) self.enterRule(localctx, 20, self.RULE_postfix_nofunc) try: self.enterOuterAlt(localctx, 1) self.state = 159 self.exp_nofunc(0) self.state = 163 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,9,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: self.state = 160 self.postfix_op() self.state = 165 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,9,self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Postfix_opContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Postfix_opContext, self).__init__(parent, invokingState) self.parser = parser def BANG(self): return self.getToken(LaTeXParser.BANG, 0) def eval_at(self): return self.getTypedRuleContext(LaTeXParser.Eval_atContext,0) def getRuleIndex(self): return LaTeXParser.RULE_postfix_op def postfix_op(self): localctx = LaTeXParser.Postfix_opContext(self, self._ctx, self.state) self.enterRule(localctx, 22, self.RULE_postfix_op) try: self.state = 168 self._errHandler.sync(self) token = self._input.LA(1) if token in [LaTeXParser.BANG]: self.enterOuterAlt(localctx, 1) self.state = 166 self.match(LaTeXParser.BANG) pass elif token in [LaTeXParser.BAR]: self.enterOuterAlt(localctx, 2) self.state = 167 self.eval_at() pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Eval_atContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Eval_atContext, self).__init__(parent, invokingState) self.parser = parser def BAR(self): return self.getToken(LaTeXParser.BAR, 0) def eval_at_sup(self): return self.getTypedRuleContext(LaTeXParser.Eval_at_supContext,0) def eval_at_sub(self): return self.getTypedRuleContext(LaTeXParser.Eval_at_subContext,0) def getRuleIndex(self): return LaTeXParser.RULE_eval_at def eval_at(self): localctx = LaTeXParser.Eval_atContext(self, self._ctx, self.state) self.enterRule(localctx, 24, self.RULE_eval_at) try: self.enterOuterAlt(localctx, 1) self.state = 170 self.match(LaTeXParser.BAR) self.state = 176 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,11,self._ctx) if la_ == 1: self.state = 171 self.eval_at_sup() pass elif la_ == 2: self.state = 172 self.eval_at_sub() pass elif la_ == 3: self.state = 173 self.eval_at_sup() self.state = 174 self.eval_at_sub() pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Eval_at_subContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Eval_at_subContext, self).__init__(parent, invokingState) self.parser = parser def UNDERSCORE(self): return self.getToken(LaTeXParser.UNDERSCORE, 0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def equality(self): return self.getTypedRuleContext(LaTeXParser.EqualityContext,0) def getRuleIndex(self): return LaTeXParser.RULE_eval_at_sub def eval_at_sub(self): localctx = LaTeXParser.Eval_at_subContext(self, self._ctx, self.state) self.enterRule(localctx, 26, self.RULE_eval_at_sub) try: self.enterOuterAlt(localctx, 1) self.state = 178 self.match(LaTeXParser.UNDERSCORE) self.state = 179 self.match(LaTeXParser.L_BRACE) self.state = 182 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,12,self._ctx) if la_ == 1: self.state = 180 self.expr() pass elif la_ == 2: self.state = 181 self.equality() pass self.state = 184 self.match(LaTeXParser.R_BRACE) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Eval_at_supContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Eval_at_supContext, self).__init__(parent, invokingState) self.parser = parser def CARET(self): return self.getToken(LaTeXParser.CARET, 0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def equality(self): return self.getTypedRuleContext(LaTeXParser.EqualityContext,0) def getRuleIndex(self): return LaTeXParser.RULE_eval_at_sup def eval_at_sup(self): localctx = LaTeXParser.Eval_at_supContext(self, self._ctx, self.state) self.enterRule(localctx, 28, self.RULE_eval_at_sup) try: self.enterOuterAlt(localctx, 1) self.state = 186 self.match(LaTeXParser.CARET) self.state = 187 self.match(LaTeXParser.L_BRACE) self.state = 190 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,13,self._ctx) if la_ == 1: self.state = 188 self.expr() pass elif la_ == 2: self.state = 189 self.equality() pass self.state = 192 self.match(LaTeXParser.R_BRACE) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ExpContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.ExpContext, self).__init__(parent, invokingState) self.parser = parser def comp(self): return self.getTypedRuleContext(LaTeXParser.CompContext,0) def exp(self): return self.getTypedRuleContext(LaTeXParser.ExpContext,0) def CARET(self): return self.getToken(LaTeXParser.CARET, 0) def atom(self): return self.getTypedRuleContext(LaTeXParser.AtomContext,0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def subexpr(self): return self.getTypedRuleContext(LaTeXParser.SubexprContext,0) def getRuleIndex(self): return LaTeXParser.RULE_exp def exp(self, _p=0): _parentctx = self._ctx _parentState = self.state localctx = LaTeXParser.ExpContext(self, self._ctx, _parentState) _prevctx = localctx _startState = 30 self.enterRecursionRule(localctx, 30, self.RULE_exp, _p) try: self.enterOuterAlt(localctx, 1) self.state = 195 self.comp() self._ctx.stop = self._input.LT(-1) self.state = 211 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,16,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: if self._parseListeners is not None: self.triggerExitRuleEvent() _prevctx = localctx localctx = LaTeXParser.ExpContext(self, _parentctx, _parentState) self.pushNewRecursionContext(localctx, _startState, self.RULE_exp) self.state = 197 if not self.precpred(self._ctx, 2): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 2)") self.state = 198 self.match(LaTeXParser.CARET) self.state = 204 self._errHandler.sync(self) token = self._input.LA(1) if token in [LaTeXParser.BAR, LaTeXParser.L_BAR, LaTeXParser.L_ANGLE, LaTeXParser.CMD_FRAC, LaTeXParser.CMD_BINOM, LaTeXParser.CMD_DBINOM, LaTeXParser.CMD_TBINOM, LaTeXParser.CMD_MATHIT, LaTeXParser.DIFFERENTIAL, LaTeXParser.LETTER, LaTeXParser.NUMBER, LaTeXParser.SYMBOL]: self.state = 199 self.atom() pass elif token in [LaTeXParser.L_BRACE]: self.state = 200 self.match(LaTeXParser.L_BRACE) self.state = 201 self.expr() self.state = 202 self.match(LaTeXParser.R_BRACE) pass else: raise NoViableAltException(self) self.state = 207 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,15,self._ctx) if la_ == 1: self.state = 206 self.subexpr() self.state = 213 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,16,self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.unrollRecursionContexts(_parentctx) return localctx class Exp_nofuncContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Exp_nofuncContext, self).__init__(parent, invokingState) self.parser = parser def comp_nofunc(self): return self.getTypedRuleContext(LaTeXParser.Comp_nofuncContext,0) def exp_nofunc(self): return self.getTypedRuleContext(LaTeXParser.Exp_nofuncContext,0) def CARET(self): return self.getToken(LaTeXParser.CARET, 0) def atom(self): return self.getTypedRuleContext(LaTeXParser.AtomContext,0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def subexpr(self): return self.getTypedRuleContext(LaTeXParser.SubexprContext,0) def getRuleIndex(self): return LaTeXParser.RULE_exp_nofunc def exp_nofunc(self, _p=0): _parentctx = self._ctx _parentState = self.state localctx = LaTeXParser.Exp_nofuncContext(self, self._ctx, _parentState) _prevctx = localctx _startState = 32 self.enterRecursionRule(localctx, 32, self.RULE_exp_nofunc, _p) try: self.enterOuterAlt(localctx, 1) self.state = 215 self.comp_nofunc() self._ctx.stop = self._input.LT(-1) self.state = 231 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,19,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: if self._parseListeners is not None: self.triggerExitRuleEvent() _prevctx = localctx localctx = LaTeXParser.Exp_nofuncContext(self, _parentctx, _parentState) self.pushNewRecursionContext(localctx, _startState, self.RULE_exp_nofunc) self.state = 217 if not self.precpred(self._ctx, 2): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 2)") self.state = 218 self.match(LaTeXParser.CARET) self.state = 224 self._errHandler.sync(self) token = self._input.LA(1) if token in [LaTeXParser.BAR, LaTeXParser.L_BAR, LaTeXParser.L_ANGLE, LaTeXParser.CMD_FRAC, LaTeXParser.CMD_BINOM, LaTeXParser.CMD_DBINOM, LaTeXParser.CMD_TBINOM, LaTeXParser.CMD_MATHIT, LaTeXParser.DIFFERENTIAL, LaTeXParser.LETTER, LaTeXParser.NUMBER, LaTeXParser.SYMBOL]: self.state = 219 self.atom() pass elif token in [LaTeXParser.L_BRACE]: self.state = 220 self.match(LaTeXParser.L_BRACE) self.state = 221 self.expr() self.state = 222 self.match(LaTeXParser.R_BRACE) pass else: raise NoViableAltException(self) self.state = 227 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,18,self._ctx) if la_ == 1: self.state = 226 self.subexpr() self.state = 233 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,19,self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.unrollRecursionContexts(_parentctx) return localctx class CompContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.CompContext, self).__init__(parent, invokingState) self.parser = parser def group(self): return self.getTypedRuleContext(LaTeXParser.GroupContext,0) def abs_group(self): return self.getTypedRuleContext(LaTeXParser.Abs_groupContext,0) def func(self): return self.getTypedRuleContext(LaTeXParser.FuncContext,0) def atom(self): return self.getTypedRuleContext(LaTeXParser.AtomContext,0) def floor(self): return self.getTypedRuleContext(LaTeXParser.FloorContext,0) def ceil(self): return self.getTypedRuleContext(LaTeXParser.CeilContext,0) def getRuleIndex(self): return LaTeXParser.RULE_comp def comp(self): localctx = LaTeXParser.CompContext(self, self._ctx, self.state) self.enterRule(localctx, 34, self.RULE_comp) try: self.state = 240 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,20,self._ctx) if la_ == 1: self.enterOuterAlt(localctx, 1) self.state = 234 self.group() pass elif la_ == 2: self.enterOuterAlt(localctx, 2) self.state = 235 self.abs_group() pass elif la_ == 3: self.enterOuterAlt(localctx, 3) self.state = 236 self.func() pass elif la_ == 4: self.enterOuterAlt(localctx, 4) self.state = 237 self.atom() pass elif la_ == 5: self.enterOuterAlt(localctx, 5) self.state = 238 self.floor() pass elif la_ == 6: self.enterOuterAlt(localctx, 6) self.state = 239 self.ceil() pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Comp_nofuncContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Comp_nofuncContext, self).__init__(parent, invokingState) self.parser = parser def group(self): return self.getTypedRuleContext(LaTeXParser.GroupContext,0) def abs_group(self): return self.getTypedRuleContext(LaTeXParser.Abs_groupContext,0) def atom(self): return self.getTypedRuleContext(LaTeXParser.AtomContext,0) def floor(self): return self.getTypedRuleContext(LaTeXParser.FloorContext,0) def ceil(self): return self.getTypedRuleContext(LaTeXParser.CeilContext,0) def getRuleIndex(self): return LaTeXParser.RULE_comp_nofunc def comp_nofunc(self): localctx = LaTeXParser.Comp_nofuncContext(self, self._ctx, self.state) self.enterRule(localctx, 36, self.RULE_comp_nofunc) try: self.state = 247 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,21,self._ctx) if la_ == 1: self.enterOuterAlt(localctx, 1) self.state = 242 self.group() pass elif la_ == 2: self.enterOuterAlt(localctx, 2) self.state = 243 self.abs_group() pass elif la_ == 3: self.enterOuterAlt(localctx, 3) self.state = 244 self.atom() pass elif la_ == 4: self.enterOuterAlt(localctx, 4) self.state = 245 self.floor() pass elif la_ == 5: self.enterOuterAlt(localctx, 5) self.state = 246 self.ceil() pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class GroupContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.GroupContext, self).__init__(parent, invokingState) self.parser = parser def L_PAREN(self): return self.getToken(LaTeXParser.L_PAREN, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def R_PAREN(self): return self.getToken(LaTeXParser.R_PAREN, 0) def L_BRACKET(self): return self.getToken(LaTeXParser.L_BRACKET, 0) def R_BRACKET(self): return self.getToken(LaTeXParser.R_BRACKET, 0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def L_BRACE_LITERAL(self): return self.getToken(LaTeXParser.L_BRACE_LITERAL, 0) def R_BRACE_LITERAL(self): return self.getToken(LaTeXParser.R_BRACE_LITERAL, 0) def getRuleIndex(self): return LaTeXParser.RULE_group def group(self): localctx = LaTeXParser.GroupContext(self, self._ctx, self.state) self.enterRule(localctx, 38, self.RULE_group) try: self.state = 265 self._errHandler.sync(self) token = self._input.LA(1) if token in [LaTeXParser.L_PAREN]: self.enterOuterAlt(localctx, 1) self.state = 249 self.match(LaTeXParser.L_PAREN) self.state = 250 self.expr() self.state = 251 self.match(LaTeXParser.R_PAREN) pass elif token in [LaTeXParser.L_BRACKET]: self.enterOuterAlt(localctx, 2) self.state = 253 self.match(LaTeXParser.L_BRACKET) self.state = 254 self.expr() self.state = 255 self.match(LaTeXParser.R_BRACKET) pass elif token in [LaTeXParser.L_BRACE]: self.enterOuterAlt(localctx, 3) self.state = 257 self.match(LaTeXParser.L_BRACE) self.state = 258 self.expr() self.state = 259 self.match(LaTeXParser.R_BRACE) pass elif token in [LaTeXParser.L_BRACE_LITERAL]: self.enterOuterAlt(localctx, 4) self.state = 261 self.match(LaTeXParser.L_BRACE_LITERAL) self.state = 262 self.expr() self.state = 263 self.match(LaTeXParser.R_BRACE_LITERAL) pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Abs_groupContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Abs_groupContext, self).__init__(parent, invokingState) self.parser = parser def BAR(self, i=None): if i is None: return self.getTokens(LaTeXParser.BAR) else: return self.getToken(LaTeXParser.BAR, i) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def getRuleIndex(self): return LaTeXParser.RULE_abs_group def abs_group(self): localctx = LaTeXParser.Abs_groupContext(self, self._ctx, self.state) self.enterRule(localctx, 40, self.RULE_abs_group) try: self.enterOuterAlt(localctx, 1) self.state = 267 self.match(LaTeXParser.BAR) self.state = 268 self.expr() self.state = 269 self.match(LaTeXParser.BAR) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class AtomContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.AtomContext, self).__init__(parent, invokingState) self.parser = parser def LETTER(self): return self.getToken(LaTeXParser.LETTER, 0) def SYMBOL(self): return self.getToken(LaTeXParser.SYMBOL, 0) def subexpr(self): return self.getTypedRuleContext(LaTeXParser.SubexprContext,0) def NUMBER(self): return self.getToken(LaTeXParser.NUMBER, 0) def DIFFERENTIAL(self): return self.getToken(LaTeXParser.DIFFERENTIAL, 0) def mathit(self): return self.getTypedRuleContext(LaTeXParser.MathitContext,0) def frac(self): return self.getTypedRuleContext(LaTeXParser.FracContext,0) def binom(self): return self.getTypedRuleContext(LaTeXParser.BinomContext,0) def bra(self): return self.getTypedRuleContext(LaTeXParser.BraContext,0) def ket(self): return self.getTypedRuleContext(LaTeXParser.KetContext,0) def getRuleIndex(self): return LaTeXParser.RULE_atom def atom(self): localctx = LaTeXParser.AtomContext(self, self._ctx, self.state) self.enterRule(localctx, 42, self.RULE_atom) self._la = 0 # Token type try: self.state = 282 self._errHandler.sync(self) token = self._input.LA(1) if token in [LaTeXParser.LETTER, LaTeXParser.SYMBOL]: self.enterOuterAlt(localctx, 1) self.state = 271 _la = self._input.LA(1) if not(_la==LaTeXParser.LETTER or _la==LaTeXParser.SYMBOL): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 273 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,23,self._ctx) if la_ == 1: self.state = 272 self.subexpr() pass elif token in [LaTeXParser.NUMBER]: self.enterOuterAlt(localctx, 2) self.state = 275 self.match(LaTeXParser.NUMBER) pass elif token in [LaTeXParser.DIFFERENTIAL]: self.enterOuterAlt(localctx, 3) self.state = 276 self.match(LaTeXParser.DIFFERENTIAL) pass elif token in [LaTeXParser.CMD_MATHIT]: self.enterOuterAlt(localctx, 4) self.state = 277 self.mathit() pass elif token in [LaTeXParser.CMD_FRAC]: self.enterOuterAlt(localctx, 5) self.state = 278 self.frac() pass elif token in [LaTeXParser.CMD_BINOM, LaTeXParser.CMD_DBINOM, LaTeXParser.CMD_TBINOM]: self.enterOuterAlt(localctx, 6) self.state = 279 self.binom() pass elif token in [LaTeXParser.L_ANGLE]: self.enterOuterAlt(localctx, 7) self.state = 280 self.bra() pass elif token in [LaTeXParser.BAR, LaTeXParser.L_BAR]: self.enterOuterAlt(localctx, 8) self.state = 281 self.ket() pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class BraContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.BraContext, self).__init__(parent, invokingState) self.parser = parser def L_ANGLE(self): return self.getToken(LaTeXParser.L_ANGLE, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def R_BAR(self): return self.getToken(LaTeXParser.R_BAR, 0) def BAR(self): return self.getToken(LaTeXParser.BAR, 0) def getRuleIndex(self): return LaTeXParser.RULE_bra def bra(self): localctx = LaTeXParser.BraContext(self, self._ctx, self.state) self.enterRule(localctx, 44, self.RULE_bra) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 284 self.match(LaTeXParser.L_ANGLE) self.state = 285 self.expr() self.state = 286 _la = self._input.LA(1) if not(_la==LaTeXParser.BAR or _la==LaTeXParser.R_BAR): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class KetContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.KetContext, self).__init__(parent, invokingState) self.parser = parser def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def R_ANGLE(self): return self.getToken(LaTeXParser.R_ANGLE, 0) def L_BAR(self): return self.getToken(LaTeXParser.L_BAR, 0) def BAR(self): return self.getToken(LaTeXParser.BAR, 0) def getRuleIndex(self): return LaTeXParser.RULE_ket def ket(self): localctx = LaTeXParser.KetContext(self, self._ctx, self.state) self.enterRule(localctx, 46, self.RULE_ket) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 288 _la = self._input.LA(1) if not(_la==LaTeXParser.BAR or _la==LaTeXParser.L_BAR): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 289 self.expr() self.state = 290 self.match(LaTeXParser.R_ANGLE) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class MathitContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.MathitContext, self).__init__(parent, invokingState) self.parser = parser def CMD_MATHIT(self): return self.getToken(LaTeXParser.CMD_MATHIT, 0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def mathit_text(self): return self.getTypedRuleContext(LaTeXParser.Mathit_textContext,0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def getRuleIndex(self): return LaTeXParser.RULE_mathit def mathit(self): localctx = LaTeXParser.MathitContext(self, self._ctx, self.state) self.enterRule(localctx, 48, self.RULE_mathit) try: self.enterOuterAlt(localctx, 1) self.state = 292 self.match(LaTeXParser.CMD_MATHIT) self.state = 293 self.match(LaTeXParser.L_BRACE) self.state = 294 self.mathit_text() self.state = 295 self.match(LaTeXParser.R_BRACE) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Mathit_textContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Mathit_textContext, self).__init__(parent, invokingState) self.parser = parser def LETTER(self, i=None): if i is None: return self.getTokens(LaTeXParser.LETTER) else: return self.getToken(LaTeXParser.LETTER, i) def getRuleIndex(self): return LaTeXParser.RULE_mathit_text def mathit_text(self): localctx = LaTeXParser.Mathit_textContext(self, self._ctx, self.state) self.enterRule(localctx, 50, self.RULE_mathit_text) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 300 self._errHandler.sync(self) _la = self._input.LA(1) while _la==LaTeXParser.LETTER: self.state = 297 self.match(LaTeXParser.LETTER) self.state = 302 self._errHandler.sync(self) _la = self._input.LA(1) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class FracContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.FracContext, self).__init__(parent, invokingState) self.parser = parser self.upper = None # ExprContext self.lower = None # ExprContext def CMD_FRAC(self): return self.getToken(LaTeXParser.CMD_FRAC, 0) def L_BRACE(self, i=None): if i is None: return self.getTokens(LaTeXParser.L_BRACE) else: return self.getToken(LaTeXParser.L_BRACE, i) def R_BRACE(self, i=None): if i is None: return self.getTokens(LaTeXParser.R_BRACE) else: return self.getToken(LaTeXParser.R_BRACE, i) def expr(self, i=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.ExprContext) else: return self.getTypedRuleContext(LaTeXParser.ExprContext,i) def getRuleIndex(self): return LaTeXParser.RULE_frac def frac(self): localctx = LaTeXParser.FracContext(self, self._ctx, self.state) self.enterRule(localctx, 52, self.RULE_frac) try: self.enterOuterAlt(localctx, 1) self.state = 303 self.match(LaTeXParser.CMD_FRAC) self.state = 304 self.match(LaTeXParser.L_BRACE) self.state = 305 localctx.upper = self.expr() self.state = 306 self.match(LaTeXParser.R_BRACE) self.state = 307 self.match(LaTeXParser.L_BRACE) self.state = 308 localctx.lower = self.expr() self.state = 309 self.match(LaTeXParser.R_BRACE) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class BinomContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.BinomContext, self).__init__(parent, invokingState) self.parser = parser self.n = None # ExprContext self.k = None # ExprContext def L_BRACE(self, i=None): if i is None: return self.getTokens(LaTeXParser.L_BRACE) else: return self.getToken(LaTeXParser.L_BRACE, i) def R_BRACE(self, i=None): if i is None: return self.getTokens(LaTeXParser.R_BRACE) else: return self.getToken(LaTeXParser.R_BRACE, i) def CMD_BINOM(self): return self.getToken(LaTeXParser.CMD_BINOM, 0) def CMD_DBINOM(self): return self.getToken(LaTeXParser.CMD_DBINOM, 0) def CMD_TBINOM(self): return self.getToken(LaTeXParser.CMD_TBINOM, 0) def expr(self, i=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.ExprContext) else: return self.getTypedRuleContext(LaTeXParser.ExprContext,i) def getRuleIndex(self): return LaTeXParser.RULE_binom def binom(self): localctx = LaTeXParser.BinomContext(self, self._ctx, self.state) self.enterRule(localctx, 54, self.RULE_binom) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 311 _la = self._input.LA(1) if not(((((_la - 67)) & ~0x3f) == 0 and ((1 << (_la - 67)) & ((1 << (LaTeXParser.CMD_BINOM - 67)) | (1 << (LaTeXParser.CMD_DBINOM - 67)) | (1 << (LaTeXParser.CMD_TBINOM - 67)))) != 0)): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 312 self.match(LaTeXParser.L_BRACE) self.state = 313 localctx.n = self.expr() self.state = 314 self.match(LaTeXParser.R_BRACE) self.state = 315 self.match(LaTeXParser.L_BRACE) self.state = 316 localctx.k = self.expr() self.state = 317 self.match(LaTeXParser.R_BRACE) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class FloorContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.FloorContext, self).__init__(parent, invokingState) self.parser = parser self.val = None # ExprContext def L_FLOOR(self): return self.getToken(LaTeXParser.L_FLOOR, 0) def R_FLOOR(self): return self.getToken(LaTeXParser.R_FLOOR, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def getRuleIndex(self): return LaTeXParser.RULE_floor def floor(self): localctx = LaTeXParser.FloorContext(self, self._ctx, self.state) self.enterRule(localctx, 56, self.RULE_floor) try: self.enterOuterAlt(localctx, 1) self.state = 319 self.match(LaTeXParser.L_FLOOR) self.state = 320 localctx.val = self.expr() self.state = 321 self.match(LaTeXParser.R_FLOOR) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class CeilContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.CeilContext, self).__init__(parent, invokingState) self.parser = parser self.val = None # ExprContext def L_CEIL(self): return self.getToken(LaTeXParser.L_CEIL, 0) def R_CEIL(self): return self.getToken(LaTeXParser.R_CEIL, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def getRuleIndex(self): return LaTeXParser.RULE_ceil def ceil(self): localctx = LaTeXParser.CeilContext(self, self._ctx, self.state) self.enterRule(localctx, 58, self.RULE_ceil) try: self.enterOuterAlt(localctx, 1) self.state = 323 self.match(LaTeXParser.L_CEIL) self.state = 324 localctx.val = self.expr() self.state = 325 self.match(LaTeXParser.R_CEIL) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Func_normalContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Func_normalContext, self).__init__(parent, invokingState) self.parser = parser def FUNC_EXP(self): return self.getToken(LaTeXParser.FUNC_EXP, 0) def FUNC_LOG(self): return self.getToken(LaTeXParser.FUNC_LOG, 0) def FUNC_LN(self): return self.getToken(LaTeXParser.FUNC_LN, 0) def FUNC_SIN(self): return self.getToken(LaTeXParser.FUNC_SIN, 0) def FUNC_COS(self): return self.getToken(LaTeXParser.FUNC_COS, 0) def FUNC_TAN(self): return self.getToken(LaTeXParser.FUNC_TAN, 0) def FUNC_CSC(self): return self.getToken(LaTeXParser.FUNC_CSC, 0) def FUNC_SEC(self): return self.getToken(LaTeXParser.FUNC_SEC, 0) def FUNC_COT(self): return self.getToken(LaTeXParser.FUNC_COT, 0) def FUNC_ARCSIN(self): return self.getToken(LaTeXParser.FUNC_ARCSIN, 0) def FUNC_ARCCOS(self): return self.getToken(LaTeXParser.FUNC_ARCCOS, 0) def FUNC_ARCTAN(self): return self.getToken(LaTeXParser.FUNC_ARCTAN, 0) def FUNC_ARCCSC(self): return self.getToken(LaTeXParser.FUNC_ARCCSC, 0) def FUNC_ARCSEC(self): return self.getToken(LaTeXParser.FUNC_ARCSEC, 0) def FUNC_ARCCOT(self): return self.getToken(LaTeXParser.FUNC_ARCCOT, 0) def FUNC_SINH(self): return self.getToken(LaTeXParser.FUNC_SINH, 0) def FUNC_COSH(self): return self.getToken(LaTeXParser.FUNC_COSH, 0) def FUNC_TANH(self): return self.getToken(LaTeXParser.FUNC_TANH, 0) def FUNC_ARSINH(self): return self.getToken(LaTeXParser.FUNC_ARSINH, 0) def FUNC_ARCOSH(self): return self.getToken(LaTeXParser.FUNC_ARCOSH, 0) def FUNC_ARTANH(self): return self.getToken(LaTeXParser.FUNC_ARTANH, 0) def getRuleIndex(self): return LaTeXParser.RULE_func_normal def func_normal(self): localctx = LaTeXParser.Func_normalContext(self, self._ctx, self.state) self.enterRule(localctx, 60, self.RULE_func_normal) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 327 _la = self._input.LA(1) if not((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << LaTeXParser.FUNC_EXP) | (1 << LaTeXParser.FUNC_LOG) | (1 << LaTeXParser.FUNC_LN) | (1 << LaTeXParser.FUNC_SIN) | (1 << LaTeXParser.FUNC_COS) | (1 << LaTeXParser.FUNC_TAN) | (1 << LaTeXParser.FUNC_CSC) | (1 << LaTeXParser.FUNC_SEC) | (1 << LaTeXParser.FUNC_COT) | (1 << LaTeXParser.FUNC_ARCSIN) | (1 << LaTeXParser.FUNC_ARCCOS) | (1 << LaTeXParser.FUNC_ARCTAN) | (1 << LaTeXParser.FUNC_ARCCSC) | (1 << LaTeXParser.FUNC_ARCSEC) | (1 << LaTeXParser.FUNC_ARCCOT) | (1 << LaTeXParser.FUNC_SINH) | (1 << LaTeXParser.FUNC_COSH) | (1 << LaTeXParser.FUNC_TANH) | (1 << LaTeXParser.FUNC_ARSINH) | (1 << LaTeXParser.FUNC_ARCOSH) | (1 << LaTeXParser.FUNC_ARTANH))) != 0)): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class FuncContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.FuncContext, self).__init__(parent, invokingState) self.parser = parser self.root = None # ExprContext self.base = None # ExprContext def func_normal(self): return self.getTypedRuleContext(LaTeXParser.Func_normalContext,0) def L_PAREN(self): return self.getToken(LaTeXParser.L_PAREN, 0) def func_arg(self): return self.getTypedRuleContext(LaTeXParser.Func_argContext,0) def R_PAREN(self): return self.getToken(LaTeXParser.R_PAREN, 0) def func_arg_noparens(self): return self.getTypedRuleContext(LaTeXParser.Func_arg_noparensContext,0) def subexpr(self): return self.getTypedRuleContext(LaTeXParser.SubexprContext,0) def supexpr(self): return self.getTypedRuleContext(LaTeXParser.SupexprContext,0) def args(self): return self.getTypedRuleContext(LaTeXParser.ArgsContext,0) def LETTER(self): return self.getToken(LaTeXParser.LETTER, 0) def SYMBOL(self): return self.getToken(LaTeXParser.SYMBOL, 0) def FUNC_INT(self): return self.getToken(LaTeXParser.FUNC_INT, 0) def DIFFERENTIAL(self): return self.getToken(LaTeXParser.DIFFERENTIAL, 0) def frac(self): return self.getTypedRuleContext(LaTeXParser.FracContext,0) def additive(self): return self.getTypedRuleContext(LaTeXParser.AdditiveContext,0) def FUNC_SQRT(self): return self.getToken(LaTeXParser.FUNC_SQRT, 0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def expr(self, i=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.ExprContext) else: return self.getTypedRuleContext(LaTeXParser.ExprContext,i) def L_BRACKET(self): return self.getToken(LaTeXParser.L_BRACKET, 0) def R_BRACKET(self): return self.getToken(LaTeXParser.R_BRACKET, 0) def FUNC_OVERLINE(self): return self.getToken(LaTeXParser.FUNC_OVERLINE, 0) def mp(self): return self.getTypedRuleContext(LaTeXParser.MpContext,0) def FUNC_SUM(self): return self.getToken(LaTeXParser.FUNC_SUM, 0) def FUNC_PROD(self): return self.getToken(LaTeXParser.FUNC_PROD, 0) def subeq(self): return self.getTypedRuleContext(LaTeXParser.SubeqContext,0) def FUNC_LIM(self): return self.getToken(LaTeXParser.FUNC_LIM, 0) def limit_sub(self): return self.getTypedRuleContext(LaTeXParser.Limit_subContext,0) def getRuleIndex(self): return LaTeXParser.RULE_func def func(self): localctx = LaTeXParser.FuncContext(self, self._ctx, self.state) self.enterRule(localctx, 62, self.RULE_func) self._la = 0 # Token type try: self.state = 407 self._errHandler.sync(self) token = self._input.LA(1) if token in [LaTeXParser.FUNC_EXP, LaTeXParser.FUNC_LOG, LaTeXParser.FUNC_LN, LaTeXParser.FUNC_SIN, LaTeXParser.FUNC_COS, LaTeXParser.FUNC_TAN, LaTeXParser.FUNC_CSC, LaTeXParser.FUNC_SEC, LaTeXParser.FUNC_COT, LaTeXParser.FUNC_ARCSIN, LaTeXParser.FUNC_ARCCOS, LaTeXParser.FUNC_ARCTAN, LaTeXParser.FUNC_ARCCSC, LaTeXParser.FUNC_ARCSEC, LaTeXParser.FUNC_ARCCOT, LaTeXParser.FUNC_SINH, LaTeXParser.FUNC_COSH, LaTeXParser.FUNC_TANH, LaTeXParser.FUNC_ARSINH, LaTeXParser.FUNC_ARCOSH, LaTeXParser.FUNC_ARTANH]: self.enterOuterAlt(localctx, 1) self.state = 329 self.func_normal() self.state = 342 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,30,self._ctx) if la_ == 1: self.state = 331 self._errHandler.sync(self) _la = self._input.LA(1) if _la==LaTeXParser.UNDERSCORE: self.state = 330 self.subexpr() self.state = 334 self._errHandler.sync(self) _la = self._input.LA(1) if _la==LaTeXParser.CARET: self.state = 333 self.supexpr() pass elif la_ == 2: self.state = 337 self._errHandler.sync(self) _la = self._input.LA(1) if _la==LaTeXParser.CARET: self.state = 336 self.supexpr() self.state = 340 self._errHandler.sync(self) _la = self._input.LA(1) if _la==LaTeXParser.UNDERSCORE: self.state = 339 self.subexpr() pass self.state = 349 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,31,self._ctx) if la_ == 1: self.state = 344 self.match(LaTeXParser.L_PAREN) self.state = 345 self.func_arg() self.state = 346 self.match(LaTeXParser.R_PAREN) pass elif la_ == 2: self.state = 348 self.func_arg_noparens() pass pass elif token in [LaTeXParser.LETTER, LaTeXParser.SYMBOL]: self.enterOuterAlt(localctx, 2) self.state = 351 _la = self._input.LA(1) if not(_la==LaTeXParser.LETTER or _la==LaTeXParser.SYMBOL): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 353 self._errHandler.sync(self) _la = self._input.LA(1) if _la==LaTeXParser.UNDERSCORE: self.state = 352 self.subexpr() self.state = 355 self.match(LaTeXParser.L_PAREN) self.state = 356 self.args() self.state = 357 self.match(LaTeXParser.R_PAREN) pass elif token in [LaTeXParser.FUNC_INT]: self.enterOuterAlt(localctx, 3) self.state = 359 self.match(LaTeXParser.FUNC_INT) self.state = 366 self._errHandler.sync(self) token = self._input.LA(1) if token in [LaTeXParser.UNDERSCORE]: self.state = 360 self.subexpr() self.state = 361 self.supexpr() pass elif token in [LaTeXParser.CARET]: self.state = 363 self.supexpr() self.state = 364 self.subexpr() pass elif token in [LaTeXParser.ADD, LaTeXParser.SUB, LaTeXParser.L_PAREN, LaTeXParser.L_BRACE, LaTeXParser.L_BRACE_LITERAL, LaTeXParser.L_BRACKET, LaTeXParser.BAR, LaTeXParser.L_BAR, LaTeXParser.L_ANGLE, LaTeXParser.FUNC_LIM, LaTeXParser.FUNC_INT, LaTeXParser.FUNC_SUM, LaTeXParser.FUNC_PROD, LaTeXParser.FUNC_EXP, LaTeXParser.FUNC_LOG, LaTeXParser.FUNC_LN, LaTeXParser.FUNC_SIN, LaTeXParser.FUNC_COS, LaTeXParser.FUNC_TAN, LaTeXParser.FUNC_CSC, LaTeXParser.FUNC_SEC, LaTeXParser.FUNC_COT, LaTeXParser.FUNC_ARCSIN, LaTeXParser.FUNC_ARCCOS, LaTeXParser.FUNC_ARCTAN, LaTeXParser.FUNC_ARCCSC, LaTeXParser.FUNC_ARCSEC, LaTeXParser.FUNC_ARCCOT, LaTeXParser.FUNC_SINH, LaTeXParser.FUNC_COSH, LaTeXParser.FUNC_TANH, LaTeXParser.FUNC_ARSINH, LaTeXParser.FUNC_ARCOSH, LaTeXParser.FUNC_ARTANH, LaTeXParser.L_FLOOR, LaTeXParser.L_CEIL, LaTeXParser.FUNC_SQRT, LaTeXParser.FUNC_OVERLINE, LaTeXParser.CMD_FRAC, LaTeXParser.CMD_BINOM, LaTeXParser.CMD_DBINOM, LaTeXParser.CMD_TBINOM, LaTeXParser.CMD_MATHIT, LaTeXParser.DIFFERENTIAL, LaTeXParser.LETTER, LaTeXParser.NUMBER, LaTeXParser.SYMBOL]: pass else: pass self.state = 374 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,35,self._ctx) if la_ == 1: self.state = 369 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,34,self._ctx) if la_ == 1: self.state = 368 self.additive(0) self.state = 371 self.match(LaTeXParser.DIFFERENTIAL) pass elif la_ == 2: self.state = 372 self.frac() pass elif la_ == 3: self.state = 373 self.additive(0) pass pass elif token in [LaTeXParser.FUNC_SQRT]: self.enterOuterAlt(localctx, 4) self.state = 376 self.match(LaTeXParser.FUNC_SQRT) self.state = 381 self._errHandler.sync(self) _la = self._input.LA(1) if _la==LaTeXParser.L_BRACKET: self.state = 377 self.match(LaTeXParser.L_BRACKET) self.state = 378 localctx.root = self.expr() self.state = 379 self.match(LaTeXParser.R_BRACKET) self.state = 383 self.match(LaTeXParser.L_BRACE) self.state = 384 localctx.base = self.expr() self.state = 385 self.match(LaTeXParser.R_BRACE) pass elif token in [LaTeXParser.FUNC_OVERLINE]: self.enterOuterAlt(localctx, 5) self.state = 387 self.match(LaTeXParser.FUNC_OVERLINE) self.state = 388 self.match(LaTeXParser.L_BRACE) self.state = 389 localctx.base = self.expr() self.state = 390 self.match(LaTeXParser.R_BRACE) pass elif token in [LaTeXParser.FUNC_SUM, LaTeXParser.FUNC_PROD]: self.enterOuterAlt(localctx, 6) self.state = 392 _la = self._input.LA(1) if not(_la==LaTeXParser.FUNC_SUM or _la==LaTeXParser.FUNC_PROD): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 399 self._errHandler.sync(self) token = self._input.LA(1) if token in [LaTeXParser.UNDERSCORE]: self.state = 393 self.subeq() self.state = 394 self.supexpr() pass elif token in [LaTeXParser.CARET]: self.state = 396 self.supexpr() self.state = 397 self.subeq() pass else: raise NoViableAltException(self) self.state = 401 self.mp(0) pass elif token in [LaTeXParser.FUNC_LIM]: self.enterOuterAlt(localctx, 7) self.state = 403 self.match(LaTeXParser.FUNC_LIM) self.state = 404 self.limit_sub() self.state = 405 self.mp(0) pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ArgsContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.ArgsContext, self).__init__(parent, invokingState) self.parser = parser def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def args(self): return self.getTypedRuleContext(LaTeXParser.ArgsContext,0) def getRuleIndex(self): return LaTeXParser.RULE_args def args(self): localctx = LaTeXParser.ArgsContext(self, self._ctx, self.state) self.enterRule(localctx, 64, self.RULE_args) try: self.state = 414 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,39,self._ctx) if la_ == 1: self.enterOuterAlt(localctx, 1) self.state = 409 self.expr() self.state = 410 self.match(LaTeXParser.T__0) self.state = 411 self.args() pass elif la_ == 2: self.enterOuterAlt(localctx, 2) self.state = 413 self.expr() pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Limit_subContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Limit_subContext, self).__init__(parent, invokingState) self.parser = parser def UNDERSCORE(self): return self.getToken(LaTeXParser.UNDERSCORE, 0) def L_BRACE(self, i=None): if i is None: return self.getTokens(LaTeXParser.L_BRACE) else: return self.getToken(LaTeXParser.L_BRACE, i) def LIM_APPROACH_SYM(self): return self.getToken(LaTeXParser.LIM_APPROACH_SYM, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def R_BRACE(self, i=None): if i is None: return self.getTokens(LaTeXParser.R_BRACE) else: return self.getToken(LaTeXParser.R_BRACE, i) def LETTER(self): return self.getToken(LaTeXParser.LETTER, 0) def SYMBOL(self): return self.getToken(LaTeXParser.SYMBOL, 0) def CARET(self): return self.getToken(LaTeXParser.CARET, 0) def ADD(self): return self.getToken(LaTeXParser.ADD, 0) def SUB(self): return self.getToken(LaTeXParser.SUB, 0) def getRuleIndex(self): return LaTeXParser.RULE_limit_sub def limit_sub(self): localctx = LaTeXParser.Limit_subContext(self, self._ctx, self.state) self.enterRule(localctx, 66, self.RULE_limit_sub) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 416 self.match(LaTeXParser.UNDERSCORE) self.state = 417 self.match(LaTeXParser.L_BRACE) self.state = 418 _la = self._input.LA(1) if not(_la==LaTeXParser.LETTER or _la==LaTeXParser.SYMBOL): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 419 self.match(LaTeXParser.LIM_APPROACH_SYM) self.state = 420 self.expr() self.state = 425 self._errHandler.sync(self) _la = self._input.LA(1) if _la==LaTeXParser.CARET: self.state = 421 self.match(LaTeXParser.CARET) self.state = 422 self.match(LaTeXParser.L_BRACE) self.state = 423 _la = self._input.LA(1) if not(_la==LaTeXParser.ADD or _la==LaTeXParser.SUB): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 424 self.match(LaTeXParser.R_BRACE) self.state = 427 self.match(LaTeXParser.R_BRACE) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Func_argContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Func_argContext, self).__init__(parent, invokingState) self.parser = parser def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def func_arg(self): return self.getTypedRuleContext(LaTeXParser.Func_argContext,0) def getRuleIndex(self): return LaTeXParser.RULE_func_arg def func_arg(self): localctx = LaTeXParser.Func_argContext(self, self._ctx, self.state) self.enterRule(localctx, 68, self.RULE_func_arg) try: self.state = 434 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,41,self._ctx) if la_ == 1: self.enterOuterAlt(localctx, 1) self.state = 429 self.expr() pass elif la_ == 2: self.enterOuterAlt(localctx, 2) self.state = 430 self.expr() self.state = 431 self.match(LaTeXParser.T__0) self.state = 432 self.func_arg() pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Func_arg_noparensContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Func_arg_noparensContext, self).__init__(parent, invokingState) self.parser = parser def mp_nofunc(self): return self.getTypedRuleContext(LaTeXParser.Mp_nofuncContext,0) def getRuleIndex(self): return LaTeXParser.RULE_func_arg_noparens def func_arg_noparens(self): localctx = LaTeXParser.Func_arg_noparensContext(self, self._ctx, self.state) self.enterRule(localctx, 70, self.RULE_func_arg_noparens) try: self.enterOuterAlt(localctx, 1) self.state = 436 self.mp_nofunc(0) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class SubexprContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.SubexprContext, self).__init__(parent, invokingState) self.parser = parser def UNDERSCORE(self): return self.getToken(LaTeXParser.UNDERSCORE, 0) def atom(self): return self.getTypedRuleContext(LaTeXParser.AtomContext,0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def getRuleIndex(self): return LaTeXParser.RULE_subexpr def subexpr(self): localctx = LaTeXParser.SubexprContext(self, self._ctx, self.state) self.enterRule(localctx, 72, self.RULE_subexpr) try: self.enterOuterAlt(localctx, 1) self.state = 438 self.match(LaTeXParser.UNDERSCORE) self.state = 444 self._errHandler.sync(self) token = self._input.LA(1) if token in [LaTeXParser.BAR, LaTeXParser.L_BAR, LaTeXParser.L_ANGLE, LaTeXParser.CMD_FRAC, LaTeXParser.CMD_BINOM, LaTeXParser.CMD_DBINOM, LaTeXParser.CMD_TBINOM, LaTeXParser.CMD_MATHIT, LaTeXParser.DIFFERENTIAL, LaTeXParser.LETTER, LaTeXParser.NUMBER, LaTeXParser.SYMBOL]: self.state = 439 self.atom() pass elif token in [LaTeXParser.L_BRACE]: self.state = 440 self.match(LaTeXParser.L_BRACE) self.state = 441 self.expr() self.state = 442 self.match(LaTeXParser.R_BRACE) pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class SupexprContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.SupexprContext, self).__init__(parent, invokingState) self.parser = parser def CARET(self): return self.getToken(LaTeXParser.CARET, 0) def atom(self): return self.getTypedRuleContext(LaTeXParser.AtomContext,0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def getRuleIndex(self): return LaTeXParser.RULE_supexpr def supexpr(self): localctx = LaTeXParser.SupexprContext(self, self._ctx, self.state) self.enterRule(localctx, 74, self.RULE_supexpr) try: self.enterOuterAlt(localctx, 1) self.state = 446 self.match(LaTeXParser.CARET) self.state = 452 self._errHandler.sync(self) token = self._input.LA(1) if token in [LaTeXParser.BAR, LaTeXParser.L_BAR, LaTeXParser.L_ANGLE, LaTeXParser.CMD_FRAC, LaTeXParser.CMD_BINOM, LaTeXParser.CMD_DBINOM, LaTeXParser.CMD_TBINOM, LaTeXParser.CMD_MATHIT, LaTeXParser.DIFFERENTIAL, LaTeXParser.LETTER, LaTeXParser.NUMBER, LaTeXParser.SYMBOL]: self.state = 447 self.atom() pass elif token in [LaTeXParser.L_BRACE]: self.state = 448 self.match(LaTeXParser.L_BRACE) self.state = 449 self.expr() self.state = 450 self.match(LaTeXParser.R_BRACE) pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class SubeqContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.SubeqContext, self).__init__(parent, invokingState) self.parser = parser def UNDERSCORE(self): return self.getToken(LaTeXParser.UNDERSCORE, 0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def equality(self): return self.getTypedRuleContext(LaTeXParser.EqualityContext,0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def getRuleIndex(self): return LaTeXParser.RULE_subeq def subeq(self): localctx = LaTeXParser.SubeqContext(self, self._ctx, self.state) self.enterRule(localctx, 76, self.RULE_subeq) try: self.enterOuterAlt(localctx, 1) self.state = 454 self.match(LaTeXParser.UNDERSCORE) self.state = 455 self.match(LaTeXParser.L_BRACE) self.state = 456 self.equality() self.state = 457 self.match(LaTeXParser.R_BRACE) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class SupeqContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.SupeqContext, self).__init__(parent, invokingState) self.parser = parser def UNDERSCORE(self): return self.getToken(LaTeXParser.UNDERSCORE, 0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def equality(self): return self.getTypedRuleContext(LaTeXParser.EqualityContext,0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def getRuleIndex(self): return LaTeXParser.RULE_supeq def supeq(self): localctx = LaTeXParser.SupeqContext(self, self._ctx, self.state) self.enterRule(localctx, 78, self.RULE_supeq) try: self.enterOuterAlt(localctx, 1) self.state = 459 self.match(LaTeXParser.UNDERSCORE) self.state = 460 self.match(LaTeXParser.L_BRACE) self.state = 461 self.equality() self.state = 462 self.match(LaTeXParser.R_BRACE) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx def sempred(self, localctx, ruleIndex, predIndex): if self._predicates == None: self._predicates = dict() self._predicates[1] = self.relation_sempred self._predicates[4] = self.additive_sempred self._predicates[5] = self.mp_sempred self._predicates[6] = self.mp_nofunc_sempred self._predicates[15] = self.exp_sempred self._predicates[16] = self.exp_nofunc_sempred pred = self._predicates.get(ruleIndex, None) if pred is None: raise Exception("No predicate with index:" + str(ruleIndex)) else: return pred(localctx, predIndex) def relation_sempred(self, localctx, predIndex): if predIndex == 0: return self.precpred(self._ctx, 2) def additive_sempred(self, localctx, predIndex): if predIndex == 1: return self.precpred(self._ctx, 2) def mp_sempred(self, localctx, predIndex): if predIndex == 2: return self.precpred(self._ctx, 2) def mp_nofunc_sempred(self, localctx, predIndex): if predIndex == 3: return self.precpred(self._ctx, 2) def exp_sempred(self, localctx, predIndex): if predIndex == 4: return self.precpred(self._ctx, 2) def exp_nofunc_sempred(self, localctx, predIndex): if predIndex == 5: return self.precpred(self._ctx, 2)
250bc57e9e77316f1c261c4493236fb0c9a1843ec5567700923b86317bb91689
from sympy.testing.pytest import warns_deprecated_sympy from sympy.core.symbol import Symbol from sympy.polys.polytools import Poly from sympy.matrices import Matrix from sympy.matrices.normalforms import ( invariant_factors, smith_normal_form, hermite_normal_form, ) from sympy.polys.domains import ZZ, QQ from sympy.core.numbers import Integer def test_smith_normal(): m = Matrix([[12,6,4,8],[3,9,6,12],[2,16,14,28],[20,10,10,20]]) smf = Matrix([[1, 0, 0, 0], [0, 10, 0, 0], [0, 0, -30, 0], [0, 0, 0, 0]]) assert smith_normal_form(m) == smf x = Symbol('x') with warns_deprecated_sympy(): m = Matrix([[Poly(x-1), Poly(1, x),Poly(-1,x)], [0, Poly(x), Poly(-1,x)], [Poly(0,x),Poly(-1,x),Poly(x)]]) invs = 1, x - 1, x**2 - 1 assert invariant_factors(m, domain=QQ[x]) == invs m = Matrix([[2, 4]]) smf = Matrix([[2, 0]]) assert smith_normal_form(m) == smf def test_smith_normal_deprecated(): from sympy.polys.solvers import RawMatrix as Matrix with warns_deprecated_sympy(): m = Matrix([[12, 6, 4,8],[3,9,6,12],[2,16,14,28],[20,10,10,20]]) setattr(m, 'ring', ZZ) with warns_deprecated_sympy(): smf = Matrix([[1, 0, 0, 0], [0, 10, 0, 0], [0, 0, -30, 0], [0, 0, 0, 0]]) assert smith_normal_form(m) == smf x = Symbol('x') with warns_deprecated_sympy(): m = Matrix([[Poly(x-1), Poly(1, x),Poly(-1,x)], [0, Poly(x), Poly(-1,x)], [Poly(0,x),Poly(-1,x),Poly(x)]]) setattr(m, 'ring', QQ[x]) invs = (Poly(1, x, domain='QQ'), Poly(x - 1, domain='QQ'), Poly(x**2 - 1, domain='QQ')) assert invariant_factors(m) == invs with warns_deprecated_sympy(): m = Matrix([[2, 4]]) setattr(m, 'ring', ZZ) with warns_deprecated_sympy(): smf = Matrix([[2, 0]]) assert smith_normal_form(m) == smf def test_hermite_normal(): m = Matrix([[2, 7, 17, 29, 41], [3, 11, 19, 31, 43], [5, 13, 23, 37, 47]]) hnf = Matrix([[1, 0, 0], [0, 2, 1], [0, 0, 1]]) assert hermite_normal_form(m) == hnf tr_hnf = Matrix([[37, 0, 19], [222, -6, 113], [48, 0, 25], [0, 2, 1], [0, 0, 1]]) assert hermite_normal_form(m.transpose()) == tr_hnf m = Matrix([[8, 28, 68, 116, 164], [3, 11, 19, 31, 43], [5, 13, 23, 37, 47]]) hnf = Matrix([[4, 0, 0], [0, 2, 1], [0, 0, 1]]) assert hermite_normal_form(m) == hnf assert hermite_normal_form(m, D=8) == hnf assert hermite_normal_form(m, D=ZZ(8)) == hnf assert hermite_normal_form(m, D=Integer(8)) == hnf m = Matrix([[10, 8, 6, 30, 2], [45, 36, 27, 18, 9], [5, 4, 3, 2, 1]]) hnf = Matrix([[26, 2], [0, 9], [0, 1]]) assert hermite_normal_form(m) == hnf m = Matrix([[2, 7], [0, 0], [0, 0]]) hnf = Matrix([[1], [0], [0]]) assert hermite_normal_form(m) == hnf def test_issue_23410(): A = Matrix([[1, 12], [0, 8], [0, 5]]) H = Matrix([[1, 0], [0, 8], [0, 5]]) assert hermite_normal_form(A) == H
c2d7564ec662096b089e0ef618b0849dd3c5802d011a42ca37c39f0eb521e284
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 cls._evaluate(obj) return obj @classmethod def _evaluate(cls, expr): return canonicalize(expr) @property def shape(self): matrices = [arg for arg in self.args if arg.is_Matrix] return (matrices[0].rows, matrices[-1].cols) 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 expand(self, **kwargs): expanded = super(MatMul, self).expand(**kwargs) return self._evaluate(expanded) 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 i in range(1, len(args)): A = new_args[-1] B = args[i] if isinstance(B, Inverse) and isinstance(B.arg, MatMul): Bargs = B.arg.args l = len(Bargs) if list(Bargs) == new_args[-l:]: new_args = new_args[:-l] + [Identity(B.shape[0])] continue if isinstance(A, Inverse) and isinstance(A.arg, MatMul): Aargs = A.arg.args l = len(Aargs) if list(Aargs) == args[i:i+l]: identity = Identity(A.shape[0]) new_args[-1] = identity for j in range(i, i+l): args[j] = identity continue 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
1bf9da82f09a494cf0df9209113ad4d2cf6644493e776511c72938f34b753e81
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: obj = cls._evaluate(obj) return obj @classmethod def _evaluate(cls, expr): args = expr.args if not any(isinstance(i, MatrixExpr) for i in args): return Add(*args, evaluate=True) return canonicalize(expr) @property def shape(self): return self.args[0].shape def could_extract_minus_sign(self): return _could_extract_minus_sign(self) def expand(self, **kwargs): expanded = super(MatAdd, self).expand(**kwargs) return self._evaluate(expanded) def _entry(self, i, j, **kwargs): return Add(*[arg._entry(i, j, **kwargs) for arg in self.args]) def _eval_transpose(self): return MatAdd(*[transpose(arg) for arg in self.args]).doit() def _eval_adjoint(self): return MatAdd(*[adjoint(arg) for arg in self.args]).doit() def _eval_trace(self): from .trace import trace return Add(*[trace(arg) for arg in self.args]).doit() def doit(self, **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)))
cdc5c4f8a67becac19bcc83b9252da8e930e0765b64eb9f0f5cd2e6ef52df615
from sympy.concrete.summations import Sum from sympy.core.exprtools import gcd_terms from sympy.core.function import (diff, expand) from sympy.core.relational import Eq from sympy.core.symbol import (Dummy, Symbol, Str) from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.matrices.dense import zeros from sympy.polys.polytools import factor from sympy.core import (S, symbols, Add, Mul, SympifyError, Rational, Function) from sympy.functions import sin, cos, tan, sqrt, cbrt, exp from sympy.simplify import simplify from sympy.matrices import (ImmutableMatrix, Inverse, MatAdd, MatMul, MatPow, Matrix, MatrixExpr, MatrixSymbol, 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_matexpr_properties(): assert A.shape == (n, m) assert (A*B).shape == (n, l) raises(ShapeError, lambda: B*A) assert A[0, 1].indices == (0, 1) assert A[0, 0].symbol == A assert A[0, 0].symbol.name == 'A' def test_matexpr(): assert (x*A).shape == A.shape assert (x*A).__class__ == MatMul assert 2*A - A - A == ZeroMatrix(*A.shape) assert (A*B).shape == (n, l) def test_matexpr_subs(): A = MatrixSymbol('A', n, m) B = MatrixSymbol('B', m, l) C = MatrixSymbol('C', m, l) assert A.subs(n, m).shape == (m, m) assert (A*B).subs(B, C) == A*C assert (A*B).subs(l, n).is_square W = MatrixSymbol("W", 3, 3) X = MatrixSymbol("X", 2, 2) Y = MatrixSymbol("Y", 1, 2) Z = MatrixSymbol("Z", n, 2) # no restrictions on Symbol replacement assert X.subs(X, Y) == Y # it might be better to just change the name y = Str('y') assert X.subs(Str("X"), y).args == (y, 2, 2) # it's ok to introduce a wider matrix assert X[1, 1].subs(X, W) == W[1, 1] # but for a given MatrixExpression, only change # name if indexing on the new shape is valid. # Here, X is 2,2; Y is 1,2 and Y[1, 1] is out # of range so an error is raised raises(IndexError, lambda: X[1, 1].subs(X, Y)) # here, [0, 1] is in range so the subs succeeds assert X[0, 1].subs(X, Y) == Y[0, 1] # and here the size of n will accept any index # in the first position assert W[2, 1].subs(W, Z) == Z[2, 1] # but not in the second position raises(IndexError, lambda: W[2, 2].subs(W, Z)) # any matrix should raise if invalid raises(IndexError, lambda: W[2, 2].subs(W, zeros(2))) A = SparseMatrix([[1, 2], [3, 4]]) B = Matrix([[1, 2], [3, 4]]) C, D = MatrixSymbol('C', 2, 2), MatrixSymbol('D', 2, 2) assert (C*D).subs({C: A, D: B}) == MatMul(A, B) def test_addition(): A = MatrixSymbol('A', n, m) B = MatrixSymbol('B', n, m) assert isinstance(A + B, MatAdd) assert (A + B).shape == A.shape assert isinstance(A - A + 2*B, MatMul) raises(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_matexpr_indexing(): A = MatrixSymbol('A', n, m) A[1, 2] A[l, k] A[l + 1, k + 1] A = MatrixSymbol('A', 2, 1) for i in range(-2, 2): for j in range(-1, 1): A[i, j] def test_single_indexing(): A = MatrixSymbol('A', 2, 3) assert A[1] == A[0, 1] assert A[int(1)] == A[0, 1] assert A[3] == A[1, 0] assert list(A[:2, :2]) == [A[0, 0], A[0, 1], A[1, 0], A[1, 1]] raises(IndexError, lambda: A[6]) raises(IndexError, lambda: A[n]) B = MatrixSymbol('B', n, m) raises(IndexError, lambda: B[1]) B = MatrixSymbol('B', n, 3) assert B[3] == B[1, 0] def test_MatrixElement_commutative(): assert A[0, 1]*A[1, 0] == A[1, 0]*A[0, 1] def test_MatrixSymbol_determinant(): A = MatrixSymbol('A', 4, 4) assert A.as_explicit().det() == A[0, 0]*A[1, 1]*A[2, 2]*A[3, 3] - \ A[0, 0]*A[1, 1]*A[2, 3]*A[3, 2] - A[0, 0]*A[1, 2]*A[2, 1]*A[3, 3] + \ A[0, 0]*A[1, 2]*A[2, 3]*A[3, 1] + A[0, 0]*A[1, 3]*A[2, 1]*A[3, 2] - \ A[0, 0]*A[1, 3]*A[2, 2]*A[3, 1] - A[0, 1]*A[1, 0]*A[2, 2]*A[3, 3] + \ A[0, 1]*A[1, 0]*A[2, 3]*A[3, 2] + A[0, 1]*A[1, 2]*A[2, 0]*A[3, 3] - \ A[0, 1]*A[1, 2]*A[2, 3]*A[3, 0] - A[0, 1]*A[1, 3]*A[2, 0]*A[3, 2] + \ A[0, 1]*A[1, 3]*A[2, 2]*A[3, 0] + A[0, 2]*A[1, 0]*A[2, 1]*A[3, 3] - \ A[0, 2]*A[1, 0]*A[2, 3]*A[3, 1] - A[0, 2]*A[1, 1]*A[2, 0]*A[3, 3] + \ A[0, 2]*A[1, 1]*A[2, 3]*A[3, 0] + A[0, 2]*A[1, 3]*A[2, 0]*A[3, 1] - \ A[0, 2]*A[1, 3]*A[2, 1]*A[3, 0] - A[0, 3]*A[1, 0]*A[2, 1]*A[3, 2] + \ A[0, 3]*A[1, 0]*A[2, 2]*A[3, 1] + A[0, 3]*A[1, 1]*A[2, 0]*A[3, 2] - \ A[0, 3]*A[1, 1]*A[2, 2]*A[3, 0] - A[0, 3]*A[1, 2]*A[2, 0]*A[3, 1] + \ A[0, 3]*A[1, 2]*A[2, 1]*A[3, 0] B = MatrixSymbol('B', 4, 4) assert Determinant(A + B).doit() == det(A + B) == (A + B).det() def test_MatrixElement_diff(): assert (A[3, 0]*A[0, 0]).diff(A[0, 0]) == A[3, 0] def test_MatrixElement_doit(): u = MatrixSymbol('u', 2, 1) v = ImmutableMatrix([3, 5]) assert u[0, 0].subs(u, v).doit() == v[0, 0] def test_identity_powers(): M = Identity(n) assert MatPow(M, 3).doit() == M**3 assert M**n == M assert MatPow(M, 0).doit() == M**2 assert M**-2 == M assert MatPow(M, -2).doit() == M**0 N = Identity(3) assert MatPow(N, 2).doit() == N**n assert MatPow(N, 3).doit() == N assert MatPow(N, -2).doit() == N**4 assert MatPow(N, 2).doit() == N**0 def test_Zero_power(): z1 = ZeroMatrix(n, n) assert z1**4 == z1 raises(ValueError, lambda:z1**-2) assert z1**0 == Identity(n) assert MatPow(z1, 2).doit() == z1**2 raises(ValueError, lambda:MatPow(z1, -2).doit()) z2 = ZeroMatrix(3, 3) assert MatPow(z2, 4).doit() == z2**4 raises(ValueError, lambda:z2**-3) assert z2**3 == MatPow(z2, 3).doit() assert z2**0 == Identity(3) raises(ValueError, lambda:MatPow(z2, -1).doit()) def test_matrixelement_diff(): dexpr = diff((D*w)[k,0], w[p,0]) assert w[k, p].diff(w[k, p]) == 1 assert w[k, p].diff(w[0, 0]) == KroneckerDelta(0, k, (0, n-1))*KroneckerDelta(0, p, (0, 0)) _i_1 = Dummy("_i_1") assert dexpr.dummy_eq(Sum(KroneckerDelta(_i_1, p, (0, n-1))*D[k, _i_1], (_i_1, 0, n - 1))) assert dexpr.doit() == D[k, p] def test_MatrixElement_with_values(): x, y, z, w = symbols("x y z w") M = Matrix([[x, y], [z, w]]) i, j = symbols("i, j") Mij = M[i, j] assert isinstance(Mij, MatrixElement) Ms = SparseMatrix([[2, 3], [4, 5]]) msij = Ms[i, j] assert isinstance(msij, MatrixElement) for oi, oj in [(0, 0), (0, 1), (1, 0), (1, 1)]: assert Mij.subs({i: oi, j: oj}) == M[oi, oj] assert msij.subs({i: oi, j: oj}) == Ms[oi, oj] A = MatrixSymbol("A", 2, 2) assert A[0, 0].subs(A, M) == x assert A[i, j].subs(A, M) == M[i, j] assert M[i, j].subs(M, A) == A[i, j] assert isinstance(M[3*i - 2, j], MatrixElement) assert M[3*i - 2, j].subs({i: 1, j: 0}) == M[1, 0] assert isinstance(M[i, 0], MatrixElement) assert M[i, 0].subs(i, 0) == M[0, 0] assert M[0, i].subs(i, 1) == M[0, 1] assert M[i, j].diff(x) == Matrix([[1, 0], [0, 0]])[i, j] raises(ValueError, lambda: M[i, 2]) raises(ValueError, lambda: M[i, -1]) raises(ValueError, lambda: M[2, i]) raises(ValueError, lambda: M[-1, i]) def test_inv(): B = MatrixSymbol('B', 3, 3) assert B.inv() == B**-1 # https://github.com/sympy/sympy/issues/19162 X = MatrixSymbol('X', 1, 1).as_explicit() assert X.inv() == Matrix([[1/X[0, 0]]]) X = MatrixSymbol('X', 2, 2).as_explicit() detX = X[0, 0]*X[1, 1] - X[0, 1]*X[1, 0] invX = Matrix([[ X[1, 1], -X[0, 1]], [-X[1, 0], X[0, 0]]]) / detX assert X.inv() == invX @XFAIL def test_factor_expand(): A = MatrixSymbol("A", n, n) B = MatrixSymbol("B", n, n) expr1 = (A + B)*(C + D) expr2 = A*C + B*C + A*D + B*D assert expr1 != expr2 assert expand(expr1) == expr2 assert factor(expr2) == expr1 expr = B**(-1)*(A**(-1)*B**(-1) - A**(-1)*C*B**(-1))**(-1)*A**(-1) I = Identity(n) # Ideally we get the first, but we at least don't want a wrong answer assert factor(expr) in [I - C, B**-1*(A**-1*(I - C)*B**-1)**-1*A**-1] def test_issue_2749(): A = MatrixSymbol("A", 5, 2) assert (A.T * A).I.as_explicit() == Matrix([[(A.T * A).I[0, 0], (A.T * A).I[0, 1]], \ [(A.T * A).I[1, 0], (A.T * A).I[1, 1]]]) def test_issue_2750(): x = MatrixSymbol('x', 1, 1) assert (x.T*x).as_explicit()**-1 == Matrix([[x[0, 0]**(-2)]]) def test_issue_7842(): A = MatrixSymbol('A', 3, 1) B = MatrixSymbol('B', 2, 1) assert Eq(A, B) == False assert Eq(A[1,0], B[1, 0]).func is Eq A = ZeroMatrix(2, 3) B = ZeroMatrix(2, 3) assert Eq(A, B) == True def test_issue_21195(): t = symbols('t') x = Function('x')(t) dx = x.diff(t) exp1 = cos(x) + cos(x)*dx exp2 = sin(x) + tan(x)*(dx.diff(t)) exp3 = sin(x)*sin(t)*(dx.diff(t)).diff(t) A = Matrix([[exp1], [exp2], [exp3]]) B = Matrix([[exp1.diff(x)], [exp2.diff(x)], [exp3.diff(x)]]) assert A.diff(x) == B def test_MatMul_postprocessor(): z = zeros(2) z1 = ZeroMatrix(2, 2) assert Mul(0, z) == Mul(z, 0) in [z, z1] M = Matrix([[1, 2], [3, 4]]) Mx = Matrix([[x, 2*x], [3*x, 4*x]]) assert Mul(x, M) == Mul(M, x) == Mx A = MatrixSymbol("A", 2, 2) assert Mul(A, M) == MatMul(A, M) assert Mul(M, A) == MatMul(M, A) # Scalars should be absorbed into constant matrices a = Mul(x, M, A) b = Mul(M, x, A) c = Mul(M, A, x) assert a == b == c == MatMul(Mx, A) a = Mul(x, A, M) b = Mul(A, x, M) c = Mul(A, M, x) assert a == b == c == MatMul(A, Mx) assert Mul(M, M) == M**2 assert Mul(A, M, M) == MatMul(A, M**2) assert Mul(M, M, A) == MatMul(M**2, A) assert Mul(M, A, M) == MatMul(M, A, M) assert Mul(A, x, M, M, x) == MatMul(A, Mx**2) @XFAIL def test_MatAdd_postprocessor_xfail(): # This is difficult to get working because of the way that Add processes # its args. z = zeros(2) assert Add(z, S.NaN) == Add(S.NaN, z) def test_MatAdd_postprocessor(): # Some of these are nonsensical, but we do not raise errors for Add # because that breaks algorithms that want to replace matrices with dummy # symbols. z = zeros(2) assert Add(0, z) == Add(z, 0) == z a = Add(S.Infinity, z) assert a == Add(z, S.Infinity) assert isinstance(a, Add) assert a.args == (S.Infinity, z) a = Add(S.ComplexInfinity, z) assert a == Add(z, S.ComplexInfinity) assert isinstance(a, Add) assert a.args == (S.ComplexInfinity, z) a = Add(z, S.NaN) # assert a == Add(S.NaN, z) # See the XFAIL above assert isinstance(a, Add) assert a.args == (S.NaN, z) M = Matrix([[1, 2], [3, 4]]) a = Add(x, M) assert a == Add(M, x) assert isinstance(a, Add) assert a.args == (x, M) A = MatrixSymbol("A", 2, 2) assert Add(A, M) == Add(M, A) == A + M # Scalars should be absorbed into constant matrices (producing an error) a = Add(x, M, A) assert a == Add(M, x, A) == Add(M, A, x) == Add(x, A, M) == Add(A, x, M) == Add(A, M, x) assert isinstance(a, Add) assert a.args == (x, A + M) assert Add(M, M) == 2*M assert Add(M, A, M) == Add(M, M, A) == Add(A, M, M) == A + 2*M a = Add(A, x, M, M, x) assert isinstance(a, Add) assert a.args == (2*x, A + 2*M) def test_simplify_matrix_expressions(): # Various simplification functions assert type(gcd_terms(C*D + D*C)) == MatAdd a = gcd_terms(2*C*D + 4*D*C) assert type(a) == MatAdd assert a.args == (2*C*D, 4*D*C) def test_exp(): A = MatrixSymbol('A', 2, 2) B = MatrixSymbol('B', 2, 2) expr1 = exp(A)*exp(B) expr2 = exp(B)*exp(A) assert expr1 != expr2 assert expr1 - expr2 != 0 assert not isinstance(expr1, exp) assert not isinstance(expr2, exp) def test_invalid_args(): raises(SympifyError, lambda: MatrixSymbol(1, 2, 'A')) def test_matrixsymbol_from_symbol(): # The label should be preserved during doit and subs A_label = Symbol('A', complex=True) A = MatrixSymbol(A_label, 2, 2) A_1 = A.doit() A_2 = A.subs(2, 3) assert A_1.args == A.args assert A_2.args[0] == A.args[0] def test_as_explicit(): Z = MatrixSymbol('Z', 2, 3) assert Z.as_explicit() == ImmutableMatrix([ [Z[0, 0], Z[0, 1], Z[0, 2]], [Z[1, 0], Z[1, 1], Z[1, 2]], ]) raises(ValueError, lambda: A.as_explicit()) def test_MatrixSet(): M = MatrixSet(2, 2, set=S.Reals) assert M.shape == (2, 2) assert M.set == S.Reals X = Matrix([[1, 2], [3, 4]]) assert X in M X = ZeroMatrix(2, 2) assert X in M raises(TypeError, lambda: A in M) raises(TypeError, lambda: 1 in M) M = MatrixSet(n, m, set=S.Reals) assert A in M raises(TypeError, lambda: C in M) raises(TypeError, lambda: X in M) M = MatrixSet(2, 2, set={1, 2, 3}) X = Matrix([[1, 2], [3, 4]]) Y = Matrix([[1, 2]]) assert (X in M) == S.false assert (Y in M) == S.false raises(ValueError, lambda: MatrixSet(2, -2, S.Reals)) raises(ValueError, lambda: MatrixSet(2.4, -1, S.Reals)) raises(TypeError, lambda: MatrixSet(2, 2, (1, 2, 3))) def test_matrixsymbol_solving(): A = MatrixSymbol('A', 2, 2) B = MatrixSymbol('B', 2, 2) Z = ZeroMatrix(2, 2) assert -(-A + B) - A + B == Z assert (-(-A + B) - A + B).simplify() == Z assert (-(-A + B) - A + B).expand() == Z assert (-(-A + B) - A + B - Z).simplify() == Z assert (-(-A + B) - A + B - Z).expand() == Z assert (A*(A + B) + B*(A.T + B.T)).expand() == A**2 + A*B + B*A.T + B*B.T
d02d0043201cc51055f616a0c0ece9188a76dd8401db2c51d85795abbb4c818f
#!/usr/bin/env python """Distutils based setup script for SymPy. This uses Distutils (https://python.org/sigs/distutils-sig/) the standard python mechanism for installing packages. Optionally, you can use Setuptools (https://setuptools.readthedocs.io/en/latest/) to automatically handle dependencies. For the easiest installation just type the command (you'll probably need root privileges for that): python setup.py install This will install the library in the default location. For instructions on how to customize the install procedure read the output of: python setup.py --help install In addition, there are some other commands: python setup.py clean -> will clean all trash (*.pyc and stuff) python setup.py test -> will run the complete test suite python setup.py bench -> will run the complete benchmark suite python setup.py audit -> will run pyflakes checker on source code To get a full list of available commands, read the output of: python setup.py --help-commands Or, if all else fails, feel free to write to the sympy list at [email protected] and ask for help. """ import sys import os import shutil import glob import subprocess from distutils.command.sdist import sdist min_mpmath_version = '0.19' # This directory dir_setup = os.path.dirname(os.path.realpath(__file__)) extra_kwargs = {} try: from setuptools import setup, Command extra_kwargs['zip_safe'] = False extra_kwargs['entry_points'] = { 'console_scripts': [ 'isympy = isympy:main', ] } except ImportError: from distutils.core import setup, Command extra_kwargs['scripts'] = ['bin/isympy'] # handle mpmath deps in the hard way: from sympy.external.importtools import version_tuple try: import mpmath if version_tuple(mpmath.__version__) < version_tuple(min_mpmath_version): raise ImportError except ImportError: print("Please install the mpmath package with a version >= %s" % min_mpmath_version) sys.exit(-1) if sys.version_info < (3, 8): print("SymPy requires Python 3.8 or newer. Python %d.%d detected" % sys.version_info[:2]) sys.exit(-1) # Check that this list is uptodate against the result of the command: # python bin/generate_module_list.py modules = [ 'sympy.algebras', 'sympy.assumptions', 'sympy.assumptions.handlers', 'sympy.assumptions.predicates', 'sympy.assumptions.relation', 'sympy.benchmarks', 'sympy.calculus', 'sympy.categories', 'sympy.codegen', 'sympy.combinatorics', 'sympy.concrete', 'sympy.core', 'sympy.core.benchmarks', 'sympy.crypto', 'sympy.diffgeom', 'sympy.discrete', 'sympy.external', 'sympy.functions', 'sympy.functions.combinatorial', 'sympy.functions.elementary', 'sympy.functions.elementary.benchmarks', 'sympy.functions.special', 'sympy.functions.special.benchmarks', 'sympy.geometry', 'sympy.holonomic', 'sympy.integrals', 'sympy.integrals.benchmarks', 'sympy.integrals.rubi', 'sympy.integrals.rubi.parsetools', 'sympy.integrals.rubi.rubi_tests', 'sympy.integrals.rubi.rules', 'sympy.interactive', 'sympy.liealgebras', 'sympy.logic', 'sympy.logic.algorithms', 'sympy.logic.utilities', 'sympy.matrices', 'sympy.matrices.benchmarks', 'sympy.matrices.expressions', 'sympy.multipledispatch', 'sympy.ntheory', 'sympy.parsing', 'sympy.parsing.autolev', 'sympy.parsing.autolev._antlr', 'sympy.parsing.c', 'sympy.parsing.fortran', 'sympy.parsing.latex', 'sympy.parsing.latex._antlr', 'sympy.physics', 'sympy.physics.continuum_mechanics', 'sympy.physics.control', 'sympy.physics.hep', 'sympy.physics.mechanics', 'sympy.physics.optics', 'sympy.physics.quantum', 'sympy.physics.units', 'sympy.physics.units.definitions', 'sympy.physics.units.systems', 'sympy.physics.vector', 'sympy.plotting', 'sympy.plotting.intervalmath', 'sympy.plotting.pygletplot', 'sympy.polys', 'sympy.polys.agca', 'sympy.polys.benchmarks', 'sympy.polys.domains', 'sympy.polys.matrices', 'sympy.polys.numberfields', 'sympy.printing', 'sympy.printing.pretty', 'sympy.sandbox', 'sympy.series', 'sympy.series.benchmarks', 'sympy.sets', 'sympy.sets.handlers', 'sympy.simplify', 'sympy.solvers', 'sympy.solvers.benchmarks', 'sympy.solvers.diophantine', 'sympy.solvers.ode', 'sympy.stats', 'sympy.stats.sampling', 'sympy.strategies', 'sympy.strategies.branch', 'sympy.tensor', 'sympy.tensor.array', 'sympy.tensor.array.expressions', 'sympy.testing', 'sympy.unify', 'sympy.utilities', 'sympy.utilities._compilation', 'sympy.utilities.mathml', 'sympy.vector', ] class audit(Command): """Audits SymPy's source code for following issues: - Names which are used but not defined or used before they are defined. - Names which are redefined without having been used. """ description = "Audit SymPy source with PyFlakes" user_options = [] def initialize_options(self): self.all = None def finalize_options(self): pass def run(self): try: import pyflakes.scripts.pyflakes as flakes except ImportError: print("In order to run the audit, you need to have PyFlakes installed.") sys.exit(-1) dirs = (os.path.join(*d) for d in (m.split('.') for m in modules)) warns = 0 for dir in dirs: for filename in os.listdir(dir): if filename.endswith('.py') and filename != '__init__.py': warns += flakes.checkPath(os.path.join(dir, filename)) if warns > 0: print("Audit finished with total %d warnings" % warns) class clean(Command): """Cleans *.pyc and debian trashs, so you should get the same copy as is in the VCS. """ description = "remove build files" user_options = [("all", "a", "the same")] def initialize_options(self): self.all = None def finalize_options(self): pass def run(self): curr_dir = os.getcwd() for root, dirs, files in os.walk(dir_setup): for file in files: if file.endswith('.pyc') and os.path.isfile: os.remove(os.path.join(root, file)) os.chdir(dir_setup) names = ["python-build-stamp-2.4", "MANIFEST", "build", "dist", "doc/_build", "sample.tex"] for f in names: if os.path.isfile(f): os.remove(f) elif os.path.isdir(f): shutil.rmtree(f) for name in glob.glob(os.path.join(dir_setup, "doc", "src", "modules", "physics", "vector", "*.pdf")): if os.path.isfile(name): os.remove(name) os.chdir(curr_dir) class test_sympy(Command): """Runs all tests under the sympy/ folder """ description = "run all tests and doctests; also see bin/test and bin/doctest" user_options = [] # distutils complains if this is not here. def __init__(self, *args): self.args = args[0] # so we can pass it to other classes Command.__init__(self, *args) def initialize_options(self): # distutils wants this pass def finalize_options(self): # this too pass def run(self): from sympy.testing import runtests runtests.run_all_tests() class run_benchmarks(Command): """Runs all SymPy benchmarks""" description = "run all benchmarks" user_options = [] # distutils complains if this is not here. def __init__(self, *args): self.args = args[0] # so we can pass it to other classes Command.__init__(self, *args) def initialize_options(self): # distutils wants this pass def finalize_options(self): # this too pass # we use py.test like architecture: # # o collector -- collects benchmarks # o runner -- executes benchmarks # o presenter -- displays benchmarks results # # this is done in sympy.utilities.benchmarking on top of py.test def run(self): from sympy.utilities import benchmarking benchmarking.main(['sympy']) class antlr(Command): """Generate code with antlr4""" description = "generate parser code from antlr grammars" user_options = [] # distutils complains if this is not here. def __init__(self, *args): self.args = args[0] # so we can pass it to other classes Command.__init__(self, *args) def initialize_options(self): # distutils wants this pass def finalize_options(self): # this too pass def run(self): from sympy.parsing.latex._build_latex_antlr import build_parser as build_latex_parser if not build_latex_parser(): sys.exit(-1) from sympy.parsing.autolev._build_autolev_antlr import build_parser as build_autolev_parser if not build_autolev_parser(): sys.exit(-1) class sdist_sympy(sdist): def run(self): # Fetch git commit hash and write down to commit_hash.txt before # shipped in tarball. commit_hash = None commit_hash_filepath = 'doc/commit_hash.txt' try: commit_hash = \ subprocess.check_output(['git', 'rev-parse', 'HEAD']) commit_hash = commit_hash.decode('ascii') commit_hash = commit_hash.rstrip() print('Commit hash found : {}.'.format(commit_hash)) print('Writing it to {}.'.format(commit_hash_filepath)) except: pass if commit_hash: with open(commit_hash_filepath, 'w') as f: f.write(commit_hash) super(sdist_sympy, self).run() try: os.remove(commit_hash_filepath) print( 'Successfully removed temporary file {}.' .format(commit_hash_filepath)) except OSError as e: print("Error deleting %s - %s." % (e.filename, e.strerror)) # Check that this list is uptodate against the result of the command: # python bin/generate_test_list.py tests = [ 'sympy.algebras.tests', 'sympy.assumptions.tests', 'sympy.calculus.tests', 'sympy.categories.tests', 'sympy.codegen.tests', 'sympy.combinatorics.tests', 'sympy.concrete.tests', 'sympy.core.tests', 'sympy.crypto.tests', 'sympy.diffgeom.tests', 'sympy.discrete.tests', 'sympy.external.tests', 'sympy.functions.combinatorial.tests', 'sympy.functions.elementary.tests', 'sympy.functions.special.tests', 'sympy.geometry.tests', 'sympy.holonomic.tests', 'sympy.integrals.rubi.parsetools.tests', 'sympy.integrals.rubi.rubi_tests.tests', 'sympy.integrals.rubi.tests', 'sympy.integrals.tests', 'sympy.interactive.tests', 'sympy.liealgebras.tests', 'sympy.logic.tests', 'sympy.matrices.expressions.tests', 'sympy.matrices.tests', 'sympy.multipledispatch.tests', 'sympy.ntheory.tests', 'sympy.parsing.tests', 'sympy.physics.continuum_mechanics.tests', 'sympy.physics.control.tests', 'sympy.physics.hep.tests', 'sympy.physics.mechanics.tests', 'sympy.physics.optics.tests', 'sympy.physics.quantum.tests', 'sympy.physics.tests', 'sympy.physics.units.tests', 'sympy.physics.vector.tests', 'sympy.plotting.intervalmath.tests', 'sympy.plotting.pygletplot.tests', 'sympy.plotting.tests', 'sympy.polys.agca.tests', 'sympy.polys.domains.tests', 'sympy.polys.matrices.tests', 'sympy.polys.numberfields.tests', 'sympy.polys.tests', 'sympy.printing.pretty.tests', 'sympy.printing.tests', 'sympy.sandbox.tests', 'sympy.series.tests', 'sympy.sets.tests', 'sympy.simplify.tests', 'sympy.solvers.diophantine.tests', 'sympy.solvers.ode.tests', 'sympy.solvers.tests', 'sympy.stats.sampling.tests', 'sympy.stats.tests', 'sympy.strategies.branch.tests', 'sympy.strategies.tests', 'sympy.tensor.array.expressions.tests', 'sympy.tensor.array.tests', 'sympy.tensor.tests', 'sympy.testing.tests', 'sympy.unify.tests', 'sympy.utilities._compilation.tests', 'sympy.utilities.tests', 'sympy.vector.tests', ] with open(os.path.join(dir_setup, 'sympy', 'release.py')) as f: # Defines __version__ exec(f.read()) if __name__ == '__main__': setup(name='sympy', version=__version__, description='Computer algebra system (CAS) in Python', author='SymPy development team', author_email='[email protected]', license='BSD', keywords="Math CAS", url='https://sympy.org', project_urls={ 'Source': 'https://github.com/sympy/sympy', }, py_modules=['isympy'], packages=['sympy'] + modules + tests, ext_modules=[], package_data={ 'sympy.utilities.mathml': ['data/*.xsl'], 'sympy.logic.benchmarks': ['input/*.cnf'], 'sympy.parsing.autolev': [ '*.g4', 'test-examples/*.al', 'test-examples/*.py', 'test-examples/pydy-example-repo/*.al', 'test-examples/pydy-example-repo/*.py', 'test-examples/README.txt', ], 'sympy.parsing.latex': ['*.txt', '*.g4'], 'sympy.integrals.rubi.parsetools': ['header.py.txt'], 'sympy.plotting.tests': ['test_region_*.png'], 'sympy': ['py.typed'] }, data_files=[('share/man/man1', ['doc/man/isympy.1'])], cmdclass={'test': test_sympy, 'bench': run_benchmarks, 'clean': clean, 'audit': audit, 'antlr': antlr, 'sdist': sdist_sympy, }, python_requires='>=3.8', classifiers=[ 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Scientific/Engineering', 'Topic :: Scientific/Engineering :: Mathematics', 'Topic :: Scientific/Engineering :: Physics', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', ], install_requires=[ 'mpmath>=%s' % min_mpmath_version, ], **extra_kwargs )
8be627a3d2102343d2d9953c4792b545a4988d0e7751c6c67841231e6853b4b4
#!/usr/bin/env python """ Run tests for specific packages that use optional dependencies. The optional dependencies need to be installed before running this. """ # Add the local sympy to sys.path (needed for CI) from get_sympy import path_hack path_hack() class TestsFailedError(Exception): pass test_list = [ # numpy '*numpy*', 'sympy/core/', 'sympy/matrices/', 'sympy/physics/quantum/', 'sympy/utilities/tests/test_lambdify.py', 'sympy/physics/control/', # scipy '*scipy*', # matplotlib 'sympy/plotting/', # llvmlite '*llvm*', # aesara '*aesara*', # jax '*jax*', # gmpy 'sympy/polys', # gmpy, numpy, scipy, autowrap, matplotlib 'sympy/external', # autowrap '*autowrap*', # ipython '*ipython*', # antlr, lfortran, clang 'sympy/parsing/', # matchpy '*rubi*', # codegen 'sympy/codegen/', 'sympy/utilities/tests/test_codegen', 'sympy/utilities/_compilation/tests/test_compilation', 'sympy/external/tests/test_codegen.py', # cloudpickle 'pickling', # pycosat 'sympy/logic', 'sympy/assumptions', #stats 'sympy/stats', ] blacklist = [ 'sympy/physics/quantum/tests/test_circuitplot.py', ] doctest_list = [ # numpy 'sympy/matrices/', 'sympy/utilities/lambdify.py', # scipy '*scipy*', # matplotlib 'sympy/plotting/', # llvmlite '*llvm*', # aesara '*aesara*', # gmpy 'sympy/polys', # autowrap '*autowrap*', # ipython '*ipython*', # antlr, lfortran, clang 'sympy/parsing/', # matchpy '*rubi*', # codegen 'sympy/codegen/', # pycosat 'sympy/logic', 'sympy/assumptions', #stats 'sympy/stats', ] print('Testing optional dependencies') from sympy import test, doctest tests_passed = test(*test_list, blacklist=blacklist, force_colors=True) doctests_passed = doctest(*doctest_list, force_colors=True) if not tests_passed and not doctests_passed: raise TestsFailedError('Tests and doctests failed') elif not tests_passed: raise TestsFailedError('Doctests passed but tests failed') elif not doctests_passed: raise TestsFailedError('Tests passed but doctests failed')
c4dd4c9a025ff219095642a11587860e773a5161a63f67c8d22d04eacb34704c
#!/usr/bin/env python # -*- coding: utf-8 -*- """ A tool to generate AUTHORS. We started tracking authors before moving to git, so we have to do some manual rearrangement of the git history authors in order to get the order in AUTHORS. bin/mailmap_check.py should be run before committing the results. See here for instructions on using this script: https://github.com/sympy/sympy/wiki/Development-workflow#update-mailmap """ from __future__ import unicode_literals from __future__ import print_function import sys import os from pathlib import Path from subprocess import run, PIPE from collections import OrderedDict, defaultdict from argparse import ArgumentParser if sys.version_info < (3, 8): sys.exit("This script requires Python 3.8 or newer") def sympy_dir(): return Path(__file__).resolve().parent.parent # put sympy on the path sys.path.insert(0, str(sympy_dir())) import sympy from sympy.utilities.misc import filldedent from sympy.external.importtools import version_tuple def main(*args): parser = ArgumentParser(description='Update the .mailmap file') parser.add_argument('--skip-last-commit', action='store_true', help=filldedent(""" Do not check metadata from the most recent commit. This is used when the script runs in CI to ignore the merge commit that is implicitly created by github.""")) parser.add_argument('--update-authors', action='store_true', help=filldedent(""" Also updates the AUTHORS file. DO NOT use this option as part of a pull request. The AUTHORS file will be updated later at the time a new version of SymPy is released.""")) args = parser.parse_args(args) if not check_git_version(): return 1 # find who git knows ahout try: git_people = get_authors_from_git() if args.skip_last_commit: git_people_skip = get_authors_from_git(skip_last=True) else: git_people_skip = git_people except AssertionError as msg: print(red(msg)) return 1 lines_mailmap = read_lines(mailmap_path()) def key(line): # return lower case first address on line or # raise an error if not an entry if '#' in line: line = line.split('#')[0] L, R = line.count("<"), line.count(">") assert L == R and L in (1, 2) return line.split(">", 1)[0].split("<")[1].lower() who = OrderedDict() for i, line in enumerate(lines_mailmap): try: who.setdefault(key(line), []).append(line) except AssertionError: who[i] = [line] problems = False missing = False ambiguous = False dups = defaultdict(list) # # Here we use the git people with the most recent commit skipped. This # means we don't need to add .mailmap entries for the temporary merge # commit created in CI on a PR. # for person in git_people_skip: email = key(person) dups[email].append(person) if email not in who: print(red("This author is not included in the .mailmap file:")) print(person) missing = True elif not any(p.startswith(person) for p in who[email]): print(red("Ambiguous names in .mailmap")) print(red("This email address appears for multiple entries:")) print('Person:', person) print('Mailmap entries:') for line in who[email]: print(line) ambiguous = True if missing: print(red(filldedent(""" The .mailmap file needs to be updated because there are commits with unrecognised author/email metadata. """))) problems = True if ambiguous: print(red(filldedent(""" Lines should be added to .mailmap to indicate the correct name and email aliases for all commits. """))) problems = True for email, commitauthors in dups.items(): if len(commitauthors) > 2: print(red(filldedent(""" The following commits are recorded with different metadata but the same/ambiguous email address. The .mailmap file will need to be updated."""))) for author in commitauthors: print(author) problems = True lines_mailmap_sorted = sort_lines_mailmap(lines_mailmap) write_lines(mailmap_path(), lines_mailmap_sorted) if lines_mailmap_sorted != lines_mailmap: problems = True print(red("The mailmap file was reordered")) # Check if changes to AUTHORS file are also needed # # Here we don't skip the last commit. We need authors from the most recent # commit if the AUTHORS file was updated. lines_authors = make_authors_file_lines(git_people) old_lines_authors = read_lines(authors_path()) for person in old_lines_authors[8:]: if person not in git_people: print(red("This author is in the AUTHORS file but not .mailmap:")) print(person) problems = True if problems: print(red(filldedent(""" For instructions on updating the .mailmap file see: https://github.com/sympy/sympy/wiki/Development-workflow#add-your-name-and-email-address-to-the-mailmap-file""", break_on_hyphens=False, break_long_words=False))) else: print(green("No changes needed in .mailmap")) # Actually update the AUTHORS file (if --update-authors was passed) authors_changed = update_authors_file(lines_authors, old_lines_authors, args.update_authors) return int(problems) + int(authors_changed) def update_authors_file(lines, old_lines, update_yesno): if old_lines == lines: print(green('No changes needed in AUTHORS.')) return 0 # Actually write changes to the file? if update_yesno: write_lines(authors_path(), lines) print(red("Changes were made in the authors file")) # check for new additions new_authors = [] for i in sorted(set(lines) - set(old_lines)): try: author_name(i) new_authors.append(i) except AssertionError: continue if new_authors: if update_yesno: print(yellow("The following authors were added to AUTHORS.")) else: print(green(filldedent(""" The following authors will be added to the AUTHORS file at the time of the next SymPy release."""))) print() for i in sorted(new_authors, key=lambda x: x.lower()): print('\t%s' % i) if new_authors and update_yesno: return 1 else: return 0 def check_git_version(): # check git version minimal = '1.8.4.2' git_ver = run(['git', '--version'], stdout=PIPE, encoding='utf-8').stdout[12:] if version_tuple(git_ver) < version_tuple(minimal): print(yellow("Please use a git version >= %s" % minimal)) return False else: return True def authors_path(): return sympy_dir() / 'AUTHORS' def mailmap_path(): return sympy_dir() / '.mailmap' def red(text): return "\033[31m%s\033[0m" % text def yellow(text): return "\033[33m%s\033[0m" % text def green(text): return "\033[32m%s\033[0m" % text def author_name(line): assert line.count("<") == line.count(">") == 1 assert line.endswith(">") return line.split("<", 1)[0].strip() def get_authors_from_git(skip_last=False): git_command = ["git", "log", "--topo-order", "--reverse", "--format=%aN <%aE>"] if skip_last: # Skip the most recent commit. Used to ignore the merge commit created # when this script runs in CI. We use HEAD^2 rather than HEAD^1 to # select the parent commit that is part of the PR rather than the # parent commit that was the previous tip of master. git_command.append("HEAD^2") git_people = run(git_command, stdout=PIPE, encoding='utf-8').stdout.strip().split("\n") # remove duplicates, keeping the original order git_people = list(OrderedDict.fromkeys(git_people)) # Do the few changes necessary in order to reproduce AUTHORS: def move(l, i1, i2, who): x = l.pop(i1) # this will fail if the .mailmap is not right assert who == author_name(x), \ '%s was not found at line %i' % (who, i1) l.insert(i2, x) move(git_people, 2, 0, 'Ondřej Čertík') move(git_people, 42, 1, 'Fabian Pedregosa') move(git_people, 22, 2, 'Jurjen N.E. Bos') git_people.insert(4, "*Marc-Etienne M.Leveille <[email protected]>") move(git_people, 10, 5, 'Brian Jorgensen') git_people.insert(11, "*Ulrich Hecht <[email protected]>") # this will fail if the .mailmap is not right assert 'Kirill Smelkov' == author_name(git_people.pop(12) ), 'Kirill Smelkov was not found at line 12' move(git_people, 12, 32, 'Sebastian Krämer') move(git_people, 227, 35, 'Case Van Horsen') git_people.insert(43, "*Dan <[email protected]>") move(git_people, 57, 59, 'Aaron Meurer') move(git_people, 58, 57, 'Andrew Docherty') move(git_people, 67, 66, 'Chris Smith') move(git_people, 79, 76, 'Kevin Goodsell') git_people.insert(84, "*Chu-Ching Huang <[email protected]>") move(git_people, 93, 92, 'James Pearson') # this will fail if the .mailmap is not right assert 'Sergey B Kirpichev' == author_name(git_people.pop(226) ), 'Sergey B Kirpichev was not found at line 226.' index = git_people.index( "azure-pipelines[bot] " + "<azure-pipelines[bot]@users.noreply.github.com>") git_people.pop(index) index = git_people.index( "whitesource-bolt-for-github[bot] " + "<whitesource-bolt-for-github[bot]@users.noreply.github.com>") git_people.pop(index) return git_people def make_authors_file_lines(git_people): # define new lines for the file header = filldedent(""" All people who contributed to SymPy by sending at least a patch or more (in the order of the date of their first contribution), except those who explicitly didn't want to be mentioned. People with a * next to their names are not found in the metadata of the git history. This file is generated automatically by running `./bin/authors_update.py`. """).lstrip() header_extra = f"There are a total of {len(git_people)} authors.""" lines = header.splitlines() lines.append('') lines.append(header_extra) lines.append('') lines.extend(git_people) return lines def sort_lines_mailmap(lines): for n, line in enumerate(lines): if not line.startswith('#'): header_end = n break header = lines[:header_end] mailmap_lines = lines[header_end:] return header + sorted(mailmap_lines) def read_lines(path): with open(path, 'r', encoding='utf-8') as fin: return [line.strip() for line in fin.readlines()] def write_lines(path, lines): with open(path, 'w', encoding='utf-8') as fout: fout.write('\n'.join(lines)) fout.write('\n') if __name__ == "__main__": import sys sys.exit(main(*sys.argv[1:]))
bb96ce39018588416201d0a2574692da60f98a2eddf279a99d975057e4ea1125
#!/usr/bin/env python DESCRIPTION = """ Runs all the examples for testing purposes and reports successes and failures to stderr. An example is marked successful if the running thread does not throw an exception, for threaded examples, such as plotting, one needs to check the stderr messages as well. """ EPILOG = """ Example Usage: When no examples fail: $ ./all.py > out SUCCESSFUL: - beginner.basic [...] NO FAILED EXAMPLES $ When examples fail: $ ./all.py -w > out Traceback (most recent call last): File "./all.py", line 111, in run_examples [...] SUCCESSFUL: - beginner.basic [...] FAILED: - intermediate.mplot2D [...] $ Obviously, we want to achieve the first result. """ import optparse import os import sys import traceback # add local sympy to the module path this_file = os.path.abspath(__file__) sympy_dir = os.path.join(os.path.dirname(this_file), "..") sympy_dir = os.path.normpath(sympy_dir) sys.path.insert(0, sympy_dir) import sympy TERMINAL_EXAMPLES = [ "beginner.basic", "beginner.differentiation", "beginner.expansion", "beginner.functions", "beginner.limits_examples", "beginner.precision", "beginner.print_pretty", "beginner.series", "beginner.substitution", "intermediate.coupled_cluster", "intermediate.differential_equations", "intermediate.infinite_1d_box", "intermediate.partial_differential_eqs", "intermediate.trees", "intermediate.vandermonde", "advanced.curvilinear_coordinates", "advanced.dense_coding_example", "advanced.fem", "advanced.gibbs_phenomenon", "advanced.grover_example", "advanced.hydrogen", "advanced.pidigits", "advanced.qft", "advanced.relativity", ] WINDOWED_EXAMPLES = [ "beginner.plotting_nice_plot", "intermediate.mplot2d", "intermediate.mplot3d", "intermediate.print_gtk", "advanced.autowrap_integrators", "advanced.autowrap_ufuncify", "advanced.pyglet_plotting", ] EXAMPLE_DIR = os.path.dirname(__file__) def load_example_module(example): """Loads modules based upon the given package name""" from importlib import import_module exmod = os.path.split(EXAMPLE_DIR)[1] modname = exmod + '.' + example return import_module(modname) def run_examples(*, windowed=False, quiet=False, summary=True): """Run all examples in the list of modules. Returns a boolean value indicating whether all the examples were successful. """ successes = [] failures = [] examples = TERMINAL_EXAMPLES if windowed: examples += WINDOWED_EXAMPLES if quiet: from sympy.testing.runtests import PyTestReporter reporter = PyTestReporter() reporter.write("Testing Examples\n") reporter.write("-" * reporter.terminal_width) else: reporter = None for example in examples: if run_example(example, reporter=reporter): successes.append(example) else: failures.append(example) if summary: show_summary(successes, failures, reporter=reporter) return len(failures) == 0 def run_example(example, *, reporter=None): """Run a specific example. Returns a boolean value indicating whether the example was successful. """ if reporter: reporter.write(example) else: print("=" * 79) print("Running: ", example) try: mod = load_example_module(example) if reporter: suppress_output(mod.main) reporter.write("[PASS]", "Green", align="right") else: mod.main() return True except KeyboardInterrupt as e: raise e except: if reporter: reporter.write("[FAIL]", "Red", align="right") traceback.print_exc() return False class DummyFile: def write(self, x): pass def suppress_output(fn): """Suppresses the output of fn on sys.stdout.""" save_stdout = sys.stdout try: sys.stdout = DummyFile() fn() finally: sys.stdout = save_stdout def show_summary(successes, failures, *, reporter=None): """Shows a summary detailing which examples were successful and which failed.""" if reporter: reporter.write("-" * reporter.terminal_width) if failures: reporter.write("FAILED:\n", "Red") for example in failures: reporter.write(" %s\n" % example) else: reporter.write("ALL EXAMPLES PASSED\n", "Green") else: if successes: print("SUCCESSFUL: ", file=sys.stderr) for example in successes: print(" -", example, file=sys.stderr) else: print("NO SUCCESSFUL EXAMPLES", file=sys.stderr) if failures: print("FAILED: ", file=sys.stderr) for example in failures: print(" -", example, file=sys.stderr) else: print("NO FAILED EXAMPLES", file=sys.stderr) def main(*args, **kws): """Main script runner""" parser = optparse.OptionParser() parser.add_option('-w', '--windowed', action="store_true", dest="windowed", help="also run examples requiring windowed environment") parser.add_option('-q', '--quiet', action="store_true", dest="quiet", help="runs examples in 'quiet mode' suppressing example output and \ showing simple status messages.") parser.add_option('--no-summary', action="store_true", dest="no_summary", help="hides the summary at the end of testing the examples") (options, _) = parser.parse_args() return 0 if run_examples(windowed=options.windowed, quiet=options.quiet, summary=not options.no_summary) else 1 if __name__ == "__main__": sys.exit(main(*sys.argv[1:]))
b1523e1190d69073c0e1ba2b7ecf9af8176cfd5650e4d12536629b6961740a33
#!/usr/bin/env python """ This script creates logos of different formats from the source "sympy.svg" Requirements: rsvg-convert - for converting to *.png format (librsvg2-bin deb package) imagemagick - for converting to *.ico favicon format """ from argparse import ArgumentParser import xml.dom.minidom import os.path import logging import subprocess import sys from platform import system default_source_dir = os.path.join(os.path.dirname(__file__), "src", "logo") default_output_dir = os.path.join(os.path.dirname(__file__), "_build", "logo") default_source_svg = "sympy.svg" # those are the options for resizing versions without tail or text svg_sizes = {} svg_sizes['notail'] = { "prefix":"notail", "dx":-70, "dy":-20, "size":690, "title":"SymPy Logo, with no tail"} svg_sizes['notail-notext'] = { "prefix":"notailtext", "dx":-70, "dy":60, "size":690, "title":"SymPy Logo, with no tail, no text"} svg_sizes['notext'] = { "prefix":"notext", "dx":-7, "dy":90, "size":750, "title":"SymPy Logo, with no text"} # The list of identifiers of various versions versions = ['notail', 'notail-notext', 'notext'] parser = ArgumentParser(usage="%(prog)s [options ...]") parser.add_argument("--source-dir", type=str, dest="source_dir", help="Directory of the source *.svg file [default: %(default)s]", default=default_source_dir) parser.add_argument("--source-svg", type=str, dest="source_svg", help="File name of the source *.svg file [default: %(default)s]", default=default_source_svg) parser.add_argument("--svg", action="store_true", dest="generate_svg", help="Generate *.svg versions without tails " \ "and without text 'SymPy' [default: %(default)s]", default=False) parser.add_argument("--png", action="store_true", dest="generate_png", help="Generate *.png versions [default: %(default)s]", default=False) parser.add_argument("--ico", action="store_true", dest="generate_ico", help="Generate *.ico versions [default: %(default)s]", default=False) parser.add_argument("--clear", action="store_true", dest="clear", help="Remove temporary files [default: %(default)s]", default=False) parser.add_argument("-a", "--all", action="store_true", dest="generate_all", help="Shorthand for '--svg --png --ico --clear' options " \ "[default: %(default)s]", default=True) parser.add_argument("-s", "--sizes", type=str, dest="sizes", help="Sizes of png pictures [default: %(default)s]", default="160,500") parser.add_argument("--icon-sizes", type=str, dest="icon_sizes", help="Sizes of icons embedded in favicon file [default: %(default)s]", default="16,32,48,64") parser.add_argument("--output-dir", type=str, dest="output_dir", help="Output dir [default: %(default)s]", default=default_output_dir) parser.add_argument("-d", "--debug", action="store_true", dest="debug", help="Print debug log [default: %(default)s]", default=False) def main(): options, args = parser.parse_known_args() if options.debug: logging.basicConfig(level=logging.DEBUG) fn_source = os.path.join(options.source_dir, options.source_svg) if options.generate_svg or options.generate_all: generate_notail_notext_versions(fn_source, options.output_dir) if options.generate_png or options.generate_all: sizes = options.sizes.split(",") sizes = [int(s) for s in sizes] convert_to_png(fn_source, options.output_dir, sizes) if options.generate_ico or options.generate_all: sizes = options.icon_sizes.split(",") sizes = [int(s) for s in sizes] convert_to_ico(fn_source, options.output_dir, sizes) def generate_notail_notext_versions(fn_source, output_dir): for ver in versions: properties = svg_sizes[ver] doc = load_svg(fn_source) (notail, notext) = versionkey_to_boolean_tuple(ver) g_tail = searchElementById(doc, "SnakeTail", "g") if notail: g_tail.setAttribute("display", "none") g_text = searchElementById(doc, "SymPy_text", "g") if notext: g_text.setAttribute("display", "none") g_logo = searchElementById(doc, "SympyLogo", "g") dx = properties["dx"] dy = properties["dy"] transform = "translate(%d,%d)" % (dx, dy) g_logo.setAttribute("transform", transform) svg = searchElementById(doc, "svg_SympyLogo", "svg") newsize = properties["size"] svg.setAttribute("width", "%d" % newsize) svg.setAttribute("height", "%d" % newsize) title = svg.getElementsByTagName("title")[0] title.firstChild.data = properties["title"] desc = svg.getElementsByTagName("desc")[0] desc.appendChild( doc.createTextNode( "\n\nThis file is generated from %s !" % fn_source)) fn_out = get_svg_filename_from_versionkey(fn_source, ver) fn_out = os.path.join(output_dir, fn_out) save_svg(fn_out, doc) def convert_to_png(fn_source, output_dir, sizes): svgs = list(versions) svgs.insert(0, '') cmd = "rsvg-convert" p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) p.communicate() if p.returncode == 127: logging.error( "%s: command not found. Install librsvg" % cmd) sys.exit(p.returncode) for ver in svgs: if ver == '': fn_svg = fn_source if system()[0:3].lower() == "win": os.chdir(default_source_dir) else: fn_svg = get_svg_filename_from_versionkey(fn_source, ver) fn_svg = os.path.join(output_dir, fn_svg) if system()[0:3].lower() == "win": os.chdir(default_output_dir) basename = os.path.basename(fn_svg) name, ext = os.path.splitext(basename) for size in sizes: if system()[0:3].lower() == "win": fn_out = "%s-%dpx.png" % (name, size) fn_out = os.path.join(os.pardir, os.pardir, "_build", "logo", fn_out) name_c = "%s.svg" % (name) cmd = "rsvg-convert %s -f png -h %d -w %d > %s" % (name_c, size, size, fn_out) else: fn_out = "%s-%dpx.png" % (name, size) fn_out = os.path.join(output_dir, fn_out) cmd = "rsvg-convert %s -f png -o %s -h %d -w %d" % (fn_svg, fn_out, size, size) p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) p.communicate() if p.returncode != 0: logging.error("Return code is not 0: Command: %s" % cmd) logging.error("return code: %s" % p.returncode) sys.exit(p.returncode) else: logging.debug("command: %s" % cmd) logging.debug("return code: %s" % p.returncode) def convert_to_ico(fn_source, output_dir, sizes): # firstly prepare *.png files, which will be embedded # into the *.ico files. convert_to_png(fn_source, output_dir, sizes) svgs = list(versions) svgs.insert(0, '') if system()[0:3].lower() == "win": cmd = "magick" else: cmd = "convert" p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) p.communicate() if p.returncode == 127: logging.error("%s: command not found. Install imagemagick" % cmd) sys.exit(p.returncode) if system()[0:3].lower() == "win": os.chdir(default_output_dir) for ver in svgs: if ver == '': fn_svg = fn_source else: fn_svg = get_svg_filename_from_versionkey(fn_source, ver) fn_svg = os.path.join(output_dir, fn_svg) basename = os.path.basename(fn_svg) name, ext = os.path.splitext(basename) # calculate the list of *.png files pngs = [] for size in sizes: fn_png= "%s-%dpx.png" % (name, size) if system()[0:3].lower() != "win": fn_png = os.path.join(output_dir, fn_png) pngs.append(fn_png) # convert them to *.ico fn_out = "%s-favicon.ico" % name if system()[0:3].lower() != "win": fn_out = os.path.join(output_dir, fn_out) cmd = "{} {} {}".format(cmd, " ".join(pngs), fn_out) p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) p.communicate() if p.returncode != 0: logging.error("Return code is not 0: Command: %s" % cmd) logging.error("return code: %s" % p.returncode) sys.exit(p.returncode) else: logging.debug("command: %s" % cmd) logging.debug("return code: %s" % p.returncode) def versionkey_to_boolean_tuple(ver): notail = False notext = False vers = ver.split("-") notail = 'notail' in vers notext = 'notext' in vers return (notail, notext) def get_svg_filename_from_versionkey(fn_source, ver): basename = os.path.basename(fn_source) if ver == '': return basename name, ext = os.path.splitext(basename) prefix = svg_sizes[ver]["prefix"] fn_out = "{}-{}.svg".format(name, prefix) return fn_out def searchElementById(node, Id, tagname): """ Search element by id in all the children and descendants of node. id is lower case, not ID which is usually used for getElementById """ nodes = node.getElementsByTagName(tagname) for node in nodes: an = node.getAttributeNode('id') if an and an.nodeValue == Id: return node def load_svg(fn): doc = xml.dom.minidom.parse(fn) return doc def save_svg(fn, doc): with open(fn, "wb") as f: xmlstr = doc.toxml("utf-8") f.write(xmlstr) logging.info(" File saved: %s" % fn) main()
3145d702be8d1c29506bd3a64f8f2c36892da2dd4c8d7714f8cf166d12826569
#!/usr/bin/env python3 import json import subprocess import sys from os.path import join, splitext, basename from contextlib import contextmanager from tempfile import TemporaryDirectory from zipfile import ZipFile from shutil import copytree def main(sympy_doc_git, doc_html_zip, version, dev_version, push=None): """Run this as ./update_docs.py SYMPY_DOC_GIT DOC_HTML_ZIP VERSION [--push] !!!!!!!!!!!!!!!!! NOTE: This is intended to be run as part of the release script. NOTE: This script will automatically push to the sympy_doc repo. !!!!!!!!!!!!!!!!! Args ==== SYMPY_DOC_GIT: Path to the sympy_doc repo. DOC_HTML_ZIP: Path to the zip of the built html docs. VERSION: Version string of the release (e.g. "1.6") DEV_VERSION: Version string of the development version (e.g. "1.7.dev") --push (optional): Push the results (Warning this pushes direct to github) This script automates the "release docs" step described in the README of the sympy/sympy_doc repo: https://github.com/sympy/sympy_doc#release-docs """ if push is None: push = False elif push == "--push": push = True else: raise ValueError("Invalid arguments") update_docs(sympy_doc_git, doc_html_zip, version, dev_version, push) def update_docs(sympy_doc_git, doc_html_zip, version, dev_version, push): # We started with a clean tree so restore it on error with git_rollback_on_error(sympy_doc_git, branch='gh-pages') as run: # Delete docs for the last version run('git', 'rm', '-rf', 'latest') # Extract new docs in replacement extract_docs(sympy_doc_git, doc_html_zip) # Commit new docs run('git', 'add', 'latest') run('git', 'commit', '-m', 'Add sympy %s docs' % version) # Update versions.json with open(join(sympy_doc_git, 'versions.json'), 'w') as f: json.dump({'latest': version, 'dev': dev_version}, f) run('git', 'diff') run('git', 'add', 'versions.json') run('git', 'commit', '-m', 'Update versions.json') if push: run('git', 'push') else: print('Results are committed but not pushed') @contextmanager def git_rollback_on_error(gitroot_path, branch='master'): def run(*cmdline, **kwargs): """Run subprocess with cwd in sympy_doc""" print() print('Running: $ ' + ' '.join(cmdline)) print() return subprocess.run(cmdline, cwd=gitroot_path, check=True, **kwargs) unclean_msg = "The git repo should be completely clean before running this" try: run('git', 'diff', '--exit-code') # Error if tree is unclean except subprocess.CalledProcessError: raise ValueError(unclean_msg) if run('git', 'clean', '-n', stdout=subprocess.PIPE).stdout: raise ValueError(unclean_msg) run('git', 'checkout', branch) run('git', 'pull') bsha_start = run('git', 'rev-parse', 'HEAD', stdout=subprocess.PIPE).stdout sha_start = bsha_start.strip().decode('ascii') try: yield run except Exception as e: run('git', 'reset', '--hard', sha_start) raise e from None def extract_docs(sympy_doc_git, doc_html_zip): subdirname = splitext(basename(doc_html_zip))[0] with TemporaryDirectory() as tempdir: print() print('Extracting docs to ' + tempdir) print() ZipFile(doc_html_zip).extractall(tempdir) print() print('Copying to sympy_doc/latest') print() srcpath = join(tempdir, subdirname) dstpath = join(sympy_doc_git, 'latest') copytree(srcpath, dstpath) if __name__ == "__main__": main(*sys.argv[1:])
dd678be91edc94efc2cee8fa0979ec204903cff612bfaccf72926bb373d14008
#!/usr/bin/env python3 from os.path import join, basename, normpath from subprocess import check_call def main(version, prevversion, outdir): check_version(version, outdir) run_stage(['bin/mailmap_check.py', '--update-authors']) run_stage(['mkdir', '-p', outdir]) build_release_files('bdist_wheel', 'sympy-%s-py3-none-any.whl', outdir, version) build_release_files('sdist', 'sympy-%s.tar.gz', outdir, version) run_stage(['release/compare_tar_against_git.py', join(outdir, 'sympy-%s.tar.gz' % (version,)), '.']) run_stage(['release/build_docs.py', version, outdir]) run_stage(['release/sha256.py', version, outdir]) run_stage(['release/authors.py', version, prevversion, outdir]) def green(text): return "\033[32m%s\033[0m" % text def red(text): return "\033[31m%s\033[0m" % text def print_header(color, *msgs): newlines = '\n' vline = '-' * 80 print(color(newlines + vline)) for msg in msgs: print(color(msg)) print(color(vline + newlines)) def run_stage(cmd): cmdline = ' $ %s' % (' '.join(cmd),) print_header(green, 'running:', cmdline) try: check_call(cmd) except Exception as e: print_header(red, 'failed:', cmdline) raise e from None else: print_header(green, 'completed:', cmdline) def build_release_files(cmd, fname, outdir, version): fname = fname % (version,) run_stage(['python', 'setup.py', '-q', cmd]) src = join('dist', fname) dst = join(outdir, fname) run_stage(['mv', src, dst]) def check_version(version, outdir): from sympy.release import __version__ as checked_out_version if version != checked_out_version: msg = "version %s does not match checkout %s" raise AssertionError(msg % (version, checked_out_version)) if basename(normpath(outdir)) != 'release-%s' % (version,): msg = "version %s does not match output directory %s" raise AssertionError(msg % (version, outdir)) if __name__ == "__main__": import sys main(*sys.argv[1:])
cb6e5d3a4fa7feb5835c5cb611e2d3db31c468e3ec11ef66f8d000c72119d774
#!/usr/bin/env python3 from subprocess import check_output import sys import os.path def main(tarname, gitroot): """Run this as ./compare_tar_against_git.py TARFILE GITROOT Args ==== TARFILE: Path to the built sdist (sympy-xx.tar.gz) GITROOT: Path ro root of git (dir containing .git) """ compare_tar_against_git(tarname, gitroot) ## TARBALL WHITELISTS # If a file does not end up in the tarball that should, add it to setup.py if # it is Python, or MANIFEST.in if it is not. (There is a command at the top # of setup.py to gather all the things that should be there). # TODO: Also check that this whitelist isn't growing out of date from files # removed from git. # Files that are in git that should not be in the tarball git_whitelist = { # Git specific dotfiles '.gitattributes', '.gitignore', '.mailmap', # Travis and CI '.travis.yml', '.github/workflows/runtests.yml', '.github/workflows/ci-sage.yml', '.github/workflows/comment-on-pr.yml', '.github/workflows/release.yml', '.github/workflows/docs-preview.yml', '.ci/durations.json', '.ci/generate_durations_log.sh', '.ci/parse_durations_log.py', '.ci/blacklisted.json', '.ci/README.rst', '.circleci/config.yml', '.github/FUNDING.yml', '.editorconfig', '.coveragerc', 'CODEOWNERS', 'asv.conf.actions.json', 'asv.conf.travis.json', 'coveragerc_travis', 'codecov.yml', 'pytest.ini', 'MANIFEST.in', 'banner.svg', # Code of conduct 'CODE_OF_CONDUCT.md', # Pull request template 'PULL_REQUEST_TEMPLATE.md', # Contributing guide 'CONTRIBUTING.md', # Nothing from bin/ should be shipped unless we intend to install it. Most # of this stuff is for development anyway. To run the tests from the # tarball, use setup.py test, or import sympy and run sympy.test() or # sympy.doctest(). 'bin/adapt_paths.py', 'bin/ask_update.py', 'bin/authors_update.py', 'bin/build_doc.sh', 'bin/coverage_doctest.py', 'bin/coverage_report.py', 'bin/deploy_doc.sh', 'bin/diagnose_imports', 'bin/doctest', 'bin/generate_module_list.py', 'bin/generate_test_list.py', 'bin/get_sympy.py', 'bin/mailmap_update.py', 'bin/py.bench', 'bin/strip_whitespace', 'bin/sympy_time.py', 'bin/sympy_time_cache.py', 'bin/test', 'bin/test_external_imports.py', 'bin/test_executable.py', 'bin/test_import', 'bin/test_import.py', 'bin/test_isolated', 'bin/test_py2_import.py', 'bin/test_setup.py', 'bin/test_submodule_imports.py', 'bin/test_travis.sh', 'bin/test_optional_dependencies.py', 'bin/test_sphinx.sh', 'bin/mailmap_check.py', 'bin/test_symengine.py', 'bin/test_tensorflow.py', 'bin/test_pyodide.mjs', # The notebooks are not ready for shipping yet. They need to be cleaned # up, and preferably doctested. See also # https://github.com/sympy/sympy/issues/6039. 'examples/advanced/identitysearch_example.ipynb', 'examples/beginner/plot_advanced.ipynb', 'examples/beginner/plot_colors.ipynb', 'examples/beginner/plot_discont.ipynb', 'examples/beginner/plot_gallery.ipynb', 'examples/beginner/plot_intro.ipynb', 'examples/intermediate/limit_examples_advanced.ipynb', 'examples/intermediate/schwarzschild.ipynb', 'examples/notebooks/density.ipynb', 'examples/notebooks/fidelity.ipynb', 'examples/notebooks/fresnel_integrals.ipynb', 'examples/notebooks/qubits.ipynb', 'examples/notebooks/sho1d_example.ipynb', 'examples/notebooks/spin.ipynb', 'examples/notebooks/trace.ipynb', 'examples/notebooks/Bezout_Dixon_resultant.ipynb', 'examples/notebooks/IntegrationOverPolytopes.ipynb', 'examples/notebooks/Macaulay_resultant.ipynb', 'examples/notebooks/Sylvester_resultant.ipynb', 'examples/notebooks/README.txt', # This stuff :) 'release/.gitignore', 'release/README.md', 'release/compare_tar_against_git.py', 'release/update_docs.py', 'release/build_docs.py', 'release/github_release.py', 'release/helpers.py', 'release/releasecheck.py', 'release/sha256.py', 'release/authors.py', 'release/ci_release_script.sh', # This is just a distribute version of setup.py. Used mainly for setup.py # develop, which we don't care about in the release tarball 'setupegg.py', # pytest stuff 'conftest.py', # Encrypted deploy key for deploying dev docs to GitHub 'github_deploy_key.enc', } # Files that should be in the tarball should not be in git tarball_whitelist = { # Generated by setup.py. Contains metadata for PyPI. "PKG-INFO", # Generated by setuptools. More metadata. 'setup.cfg', 'sympy.egg-info/PKG-INFO', 'sympy.egg-info/SOURCES.txt', 'sympy.egg-info/dependency_links.txt', 'sympy.egg-info/requires.txt', 'sympy.egg-info/top_level.txt', 'sympy.egg-info/not-zip-safe', 'sympy.egg-info/entry_points.txt', # Not sure where this is generated from... 'doc/commit_hash.txt', } def blue(text): return "\033[34m%s\033[0m" % text def red(text): return "\033[31m%s\033[0m" % text def run(*cmdline, cwd=None): """ Run command in subprocess and get lines of output """ return check_output(cmdline, encoding='utf-8', cwd=cwd).splitlines() def full_path_split(path): """ Function to do a full split on a path. """ # Based on https://stackoverflow.com/a/13505966/161801 rest, tail = os.path.split(path) if not rest or rest == os.path.sep: return (tail,) return full_path_split(rest) + (tail,) def compare_tar_against_git(tarname, gitroot): """ Compare the contents of the tarball against git ls-files See the bottom of the file for the whitelists. """ git_lsfiles = set(i.strip() for i in run('git', 'ls-files', cwd=gitroot)) tar_output_orig = set(run('tar', 'tf', tarname)) tar_output = set() for file in tar_output_orig: # The tar files are like sympy-0.7.3/sympy/__init__.py, and the git # files are like sympy/__init__.py. split_path = full_path_split(file) if split_path[-1]: # Exclude directories, as git ls-files does not include them tar_output.add(os.path.join(*split_path[1:])) # print tar_output # print git_lsfiles fail = False print() print(blue("Files in the tarball from git that should not be there:")) print() for line in sorted(tar_output.intersection(git_whitelist)): fail = True print(line) print() print(blue("Files in git but not in the tarball:")) print() for line in sorted(git_lsfiles - tar_output - git_whitelist): fail = True print(line) print() print(blue("Files in the tarball but not in git:")) print() for line in sorted(tar_output - git_lsfiles - tarball_whitelist): fail = True print(line) print() if fail: sys.exit(red("Non-whitelisted files found or not found in the tarball")) if __name__ == "__main__": main(*sys.argv[1:])
3351160974ecaeab96af2843d195868d696d6fd6588e6cebce84fb2a89b3e44e
__version__ = "1.12.dev"
6536826d843f093d06dcd03bd678ee31020eb1b55fa8a2960991ed18eb5149e6
# # 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', 'sphinx_reredirects', 'sphinx_copybutton', 'sphinx.ext.graphviz', 'matplotlib.sphinxext.plot_directive', 'myst_parser', 'convert-svg-to-pdf', 'sphinx.ext.intersphinx' ] # Add redirects here. This should be done whenever a page that is in the # existing release docs is moved somewhere else so that the URLs don't break. # The format is # "page/path/without/extension": "../relative_path_with.html" # Note that the html path is relative to the redirected page. Always test the # redirect manually (they aren't tested automatically). See # https://documatt.gitlab.io/sphinx-reredirects/usage.html redirects = { "guides/getting_started/install": "../../install.html", "documentation-style-guide": "contributing/documentation-style-guide.html", "gotchas": "explanation/gotchas.html", "special_topics/classification": "../explanation/classification.html", "special_topics/finite_diff_derivatives": "../explanation/finite_diff_derivatives.html", "special_topics/intro": "../explanation/index.html", "special_topics/index": "../explanation/index.html", "modules/index": "../reference/index.html", "modules/physics/index": "../../reference/public/physics/index.html", "guides/contributing/index": "../../contributing/index.html", "guides/contributing/dev-setup": "../../contributing/dev-setup.html", "guides/contributing/dependencies": "../../contributing/dependencies.html", "guides/contributing/build-docs": "../../contributing/build-docs.html", "guides/contributing/debug": "../../contributing/debug.html", "guides/contributing/docstring": "../../contributing/docstring.html", "guides/documentation-style-guide": "../../contributing/contributing/documentation-style-guide.html", "guides/make-a-contribution": "../../contributing/make-a-contribution.html", "guides/contributing/deprecations": "../../contributing/deprecations.html", "tutorial/preliminaries": "../tutorials/intro-tutorial/preliminaries.html", "tutorial/intro": "../tutorials/intro-tutorial/intro.html", "tutorial/gotchas": "../tutorials/intro-tutorial/gotchas.html", "tutorial/features": "../tutorials/intro-tutorial/features.html", "tutorial/next": "../tutorials/intro-tutorial/next.html", "tutorial/basic_operations": "../tutorials/intro-tutorial/basic_operations.html", "tutorial/printing": "../tutorials/intro-tutorial/printing.html", "tutorial/simplification": "../tutorials/intro-tutorial/simplification.html", "tutorial/calculus": "../tutorials/intro-tutorial/calculus.html", "tutorial/solvers": "../tutorials/intro-tutorial/solvers.html", "tutorial/matrices": "../tutorials/intro-tutorial/matrices.html", "tutorial/manipulation": "../tutorials/intro-tutorial/manipulation.html", } html_baseurl = "https://docs.sympy.org/latest/" # Configure Sphinx copybutton (see https://sphinx-copybutton.readthedocs.io/en/latest/use.html) copybutton_prompt_text = r">>> |\.\.\. |\$ |In \[\d*\]: | {2,5}\.\.\.: | {5,8}: " copybutton_prompt_is_regexp = True # 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. sys.path.append(os.path.abspath("./_pygments")) pygments_style = 'styles.SphinxHighContrastStyle' pygments_dark_style = 'styles.NativeHighContrastStyle' # 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_theme = "furo" # Adjust the sidebar so that the entire sidebar is scrollable html_sidebars = { "**": [ "sidebar/scroll-start.html", "sidebar/brand.html", "sidebar/search.html", "sidebar/navigation.html", "sidebar/versions.html", "sidebar/scroll-end.html", ], } common_theme_variables = { # Main "SymPy green" colors. Many things uses these colors. "color-brand-primary": "#52833A", "color-brand-content": "#307748", # The left sidebar. "color-sidebar-background": "#3B5526", "color-sidebar-background-border": "var(--color-background-primary)", "color-sidebar-link-text": "#FFFFFF", "color-sidebar-brand-text": "var(--color-sidebar-link-text--top-level)", "color-sidebar-link-text--top-level": "#FFFFFF", "color-sidebar-item-background--hover": "var(--color-brand-primary)", "color-sidebar-item-expander-background--hover": "var(--color-brand-primary)", "color-link-underline--hover": "var(--color-link)", "color-api-keyword": "#000000bd", "color-api-name": "var(--color-brand-content)", "color-api-pre-name": "var(--color-brand-content)", "api-font-size": "var(--font-size--normal)", "color-foreground-secondary": "#53555B", # TODO: Add the other types of admonitions here if anyone uses them. "color-admonition-title-background--seealso": "#CCCCCC", "color-admonition-title--seealso": "black", "color-admonition-title-background--note": "#CCCCCC", "color-admonition-title--note": "black", "color-admonition-title-background--warning": "var(--color-problematic)", "color-admonition-title--warning": "white", "admonition-font-size": "var(--font-size--normal)", "admonition-title-font-size": "var(--font-size--normal)", # Note: this doesn't work. If we want to change this, we have to set # it as the .highlight background in custom.css. "color-code-background": "hsl(80deg 100% 95%)", "code-font-size": "var(--font-size--small)", "font-stack--monospace": 'DejaVu Sans Mono,"SFMono-Regular",Menlo,Consolas,Monaco,Liberation Mono,Lucida Console,monospace;' } html_theme_options = { "light_css_variables": common_theme_variables, # The dark variables automatically inherit values from the light variables "dark_css_variables": { **common_theme_variables, "color-brand-primary": "#33CB33", "color-brand-content": "#1DBD1D", "color-api-keyword": "#FFFFFFbd", "color-api-overall": "#FFFFFF90", "color-api-paren": "#FFFFFF90", "color-sidebar-item-background--hover": "#52833A", "color-sidebar-item-expander-background--hover": "#52833A", # This is the color of the text in the right sidebar "color-foreground-secondary": "#9DA1AC", "color-admonition-title-background--seealso": "#555555", "color-admonition-title-background--note": "#555555", "color-problematic": "#B30000", }, # See https://pradyunsg.me/furo/customisation/footer/ "footer_icons": [ { "name": "GitHub", "url": "https://github.com/sympy/sympy", "html": """ <svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 16 16"> <path fill-rule="evenodd" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"></path> </svg> """, "class": "", }, ], } # Add a header for PR preview builds. See the Circle CI configuration. if os.environ.get("CIRCLECI") == "true": PR_NUMBER = os.environ.get('CIRCLE_PR_NUMBER') SHA1 = os.environ.get('CIRCLE_SHA1') html_theme_options['announcement'] = f"""This is a preview build from SymPy pull request <a href="https://github.com/sympy/sympy/pull/{PR_NUMBER}"> #{PR_NUMBER}</a>. It was built against <a href="https://github.com/sympy/sympy/pull/{PR_NUMBER}/commits/{SHA1}">{SHA1[:7]}</a>. If you aren't looking for a PR preview, go to <a href="https://docs.sympy.org/">the main SymPy documentation</a>. """ # custom.css contains changes that aren't possible with the above because they # aren't specified in the Furo theme as CSS variables html_css_files = ['custom.css'] # html_js_files = [] # 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' language = 'en' # 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' html_favicon = '../_build/logo/sympy-notailtext-favicon.ico' # 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' # Enable links to other packages intersphinx_mapping = { 'matplotlib': ('https://matplotlib.org/stable/', None) } # Require :external: to reference intersphinx. Prevents accidentally linking # to something from matplotlib. intersphinx_disabled_reftypes = ['*'] # 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
ee0d543e6bcd66184f291491ea12ea7f4d6071fae60e576b76beaa06cf3ecfda
from __future__ import annotations """ Converts SVG images to PDF using chrome in case the builder does not support SVG images natively (e.g. LaTeX). """ from sphinx.transforms.post_transforms.images import ImageConverter from sphinx.util import logging import os import platform from typing import Any # NOQA from sphinx.application import Sphinx # NOQA logger = logging.getLogger(__name__) class Converter(ImageConverter): conversion_rules = [ ('image/svg+xml', 'application/pdf'), ] def is_available(self) -> bool: """Confirms if converter is available or not.""" return True def chrome_command(self) -> str | None: if platform.win32_ver()[0]: if os.system("where chrome") == 0: return "chrome" path = os.path.join(os.environ["PROGRAMW6432"], "Google\\Chrome\\Application\\chrome.exe") if os.path.exists(path): return f'"{path}"' return None if os.system("chrome --version") == 0: return "chrome" if platform.mac_ver()[0]: return "'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'" elif platform.libc_ver()[0]: return "google-chrome" return None def chromium_command(self) -> str | None: if platform.win32_ver()[0]: if os.system("where chromium") == 0: return "chromium" path = os.path.join(os.environ["PROGRAMW6432"], "Chromium\\Application\\chrome.exe") if os.path.exists(path): return f'"{path}"' return None if os.system("chromium --version") == 0: return "chromium" if platform.mac_ver()[0]: path = "/Applications/Chromium.app/Contents/MacOS/Chromium" if os.path.exists(path): return path elif platform.libc_ver()[0]: if os.system("chromium-browser --version") == 0: return "chromium-browser" return None def command_runner(self, chrome: str | None, _to: str, temp_name: str) -> int: if not chrome: return 1 command = f'{chrome} --headless --disable-gpu --disable-software-rasterizer --print-to-pdf={_to} {temp_name}' logger.error(command) return os.system(command) def convert(self, _from: str, _to: str) -> bool: """Converts the image from SVG to PDF using chrome.""" with open(_from, 'r') as f: svg = f.read() HTML = "<html><head><style>body {margin: 0; }</style><script>function init() {const element = document.querySelector('svg');const positionInfo = element.getBoundingClientRect();const height = positionInfo.height;const width = positionInfo.width;const style = document.createElement('style');style.innerHTML = `@page {margin: 0; size: ${width}px ${height}px}`;document.head.appendChild(style); }window.onload = init;</script></head><body>%s</body></html>" % (svg) temp_name = f'{_from}.html' with open(temp_name, 'w') as f: f.write(HTML) chromium = self.chromium_command() code = self.command_runner(chromium, _to, temp_name) if code != 0: chrome = self.chrome_command() code = self.command_runner(chrome, _to, temp_name) if code != 0: logger.error('Fail to convert svg to pdf. Make sure Chromium or Chrome is installed.') exit(1) return True def setup(app: Sphinx) -> dict[str, Any]: app.add_post_transform(Converter) return { 'version': 'builtin', 'parallel_read_safe': True, 'parallel_write_safe': True, }
1c6b826de46191c5ede71eec7c38d07094edbf6209e60a76c838a9ea4aaebf6b
""" Extract reference documentation from the NumPy source tree. """ import inspect import textwrap import re import pydoc from collections.abc import Mapping import sys class Reader: """ A line-based string reader. """ def __init__(self, data): """ Parameters ---------- data : str String with lines separated by '\n'. """ if isinstance(data, list): self._str = data else: self._str = data.split('\n') # store string as list of lines self.reset() def __getitem__(self, n): return self._str[n] def reset(self): self._l = 0 # current line nr def read(self): if not self.eof(): out = self[self._l] self._l += 1 return out else: return '' def seek_next_non_empty_line(self): for l in self[self._l:]: if l.strip(): break else: self._l += 1 def eof(self): return self._l >= len(self._str) def read_to_condition(self, condition_func): start = self._l for line in self[start:]: if condition_func(line): return self[start:self._l] self._l += 1 if self.eof(): return self[start:self._l + 1] return [] def read_to_next_empty_line(self): self.seek_next_non_empty_line() def is_empty(line): return not line.strip() return self.read_to_condition(is_empty) def read_to_next_unindented_line(self): def is_unindented(line): return (line.strip() and (len(line.lstrip()) == len(line))) return self.read_to_condition(is_unindented) def peek(self, n=0): if self._l + n < len(self._str): return self[self._l + n] else: return '' def is_empty(self): return not ''.join(self._str).strip() class NumpyDocString(Mapping): def __init__(self, docstring, config={}): docstring = textwrap.dedent(docstring).split('\n') self._doc = Reader(docstring) self._parsed_data = { 'Signature': '', 'Summary': [''], 'Extended Summary': [], 'Parameters': [], 'Returns': [], 'Yields': [], 'Raises': [], 'Warns': [], 'Other Parameters': [], 'Attributes': [], 'Methods': [], 'See Also': [], # 'Notes': [], 'Warnings': [], 'References': '', # 'Examples': '', 'index': {} } self._other_keys = [] self._parse() def __getitem__(self, key): return self._parsed_data[key] def __setitem__(self, key, val): if key not in self._parsed_data: self._other_keys.append(key) self._parsed_data[key] = val def __iter__(self): return iter(self._parsed_data) def __len__(self): return len(self._parsed_data) def _is_at_section(self): self._doc.seek_next_non_empty_line() if self._doc.eof(): return False l1 = self._doc.peek().strip() # e.g. Parameters if l1.startswith('.. index::'): return True l2 = self._doc.peek(1).strip() # ---------- or ========== return l2.startswith('-'*len(l1)) or l2.startswith('='*len(l1)) def _strip(self, doc): i = 0 j = 0 for i, line in enumerate(doc): if line.strip(): break for j, line in enumerate(doc[::-1]): if line.strip(): break return doc[i:len(doc) - j] def _read_to_next_section(self): section = self._doc.read_to_next_empty_line() while not self._is_at_section() and not self._doc.eof(): if not self._doc.peek(-1).strip(): # previous line was empty section += [''] section += self._doc.read_to_next_empty_line() return section def _read_sections(self): while not self._doc.eof(): data = self._read_to_next_section() name = data[0].strip() if name.startswith('..'): # index section yield name, data[1:] elif len(data) < 2: yield StopIteration else: yield name, self._strip(data[2:]) def _parse_param_list(self, content): r = Reader(content) params = [] while not r.eof(): header = r.read().strip() if ' : ' in header: arg_name, arg_type = header.split(' : ')[:2] else: arg_name, arg_type = header, '' desc = r.read_to_next_unindented_line() desc = dedent_lines(desc) params.append((arg_name, arg_type, desc)) return params _name_rgx = re.compile(r"^\s*(:(?P<role>\w+):`(?P<name>[a-zA-Z0-9_.-]+)`|" r" (?P<name2>[a-zA-Z0-9_.-]+))\s*", re.X) def _parse_see_also(self, content): """ func_name : Descriptive text continued text another_func_name : Descriptive text func_name1, func_name2, :meth:`func_name`, func_name3 """ items = [] def parse_item_name(text): """Match ':role:`name`' or 'name'""" m = self._name_rgx.match(text) if m: g = m.groups() if g[1] is None: return g[3], None else: return g[2], g[1] raise ValueError("%s is not an item name" % text) def push_item(name, rest): if not name: return name, role = parse_item_name(name) if '.' not in name: name = '~.' + name items.append((name, list(rest), role)) del rest[:] current_func = None rest = [] for line in content: if not line.strip(): continue m = self._name_rgx.match(line) if m and line[m.end():].strip().startswith(':'): push_item(current_func, rest) current_func, line = line[:m.end()], line[m.end():] rest = [line.split(':', 1)[1].strip()] if not rest[0]: rest = [] elif not line.startswith(' '): push_item(current_func, rest) current_func = None if ',' in line: for func in line.split(','): if func.strip(): push_item(func, []) elif line.strip(): current_func = line elif current_func is not None: rest.append(line.strip()) push_item(current_func, rest) return items def _parse_index(self, section, content): """ .. index: default :refguide: something, else, and more """ def strip_each_in(lst): return [s.strip() for s in lst] out = {} section = section.split('::') if len(section) > 1: out['default'] = strip_each_in(section[1].split(','))[0] for line in content: line = line.split(':') if len(line) > 2: out[line[1]] = strip_each_in(line[2].split(',')) return out def _parse_summary(self): """Grab signature (if given) and summary""" if self._is_at_section(): return # If several signatures present, take the last one while True: summary = self._doc.read_to_next_empty_line() summary_str = " ".join([s.strip() for s in summary]).strip() if re.compile(r'^([\w., ]+=)?\s*[\w\.]+\(.*\)$').match(summary_str): self['Signature'] = summary_str if not self._is_at_section(): continue break if summary is not None: self['Summary'] = summary if not self._is_at_section(): self['Extended Summary'] = self._read_to_next_section() def _parse(self): self._doc.reset() self._parse_summary() sections = list(self._read_sections()) section_names = {section for section, content in sections} has_returns = 'Returns' in section_names has_yields = 'Yields' in section_names # We could do more tests, but we are not. Arbitrarily. if has_returns and has_yields: msg = 'Docstring contains both a Returns and Yields section.' raise ValueError(msg) for (section, content) in sections: if not section.startswith('..'): section = (s.capitalize() for s in section.split(' ')) section = ' '.join(section) if section in ('Parameters', 'Returns', 'Yields', 'Raises', 'Warns', 'Other Parameters', 'Attributes', 'Methods'): self[section] = self._parse_param_list(content) elif section.startswith('.. index::'): self['index'] = self._parse_index(section, content) elif section == 'See Also': self['See Also'] = self._parse_see_also(content) else: self[section] = content # string conversion routines def _str_header(self, name, symbol='-'): return [name, len(name)*symbol] def _str_indent(self, doc, indent=4): out = [] for line in doc: out += [' '*indent + line] return out def _str_signature(self): if self['Signature']: return [self['Signature'].replace('*', r'\*')] + [''] else: return [''] def _str_summary(self): if self['Summary']: return self['Summary'] + [''] else: return [] def _str_extended_summary(self): if self['Extended Summary']: return self['Extended Summary'] + [''] else: return [] def _str_param_list(self, name): out = [] if self[name]: out += self._str_header(name) for param, param_type, desc in self[name]: if param_type: out += ['{} : {}'.format(param, param_type)] else: out += [param] out += self._str_indent(desc) out += [''] return out def _str_section(self, name): out = [] if self[name]: out += self._str_header(name) out += self[name] out += [''] return out def _str_see_also(self, func_role): if not self['See Also']: return [] out = [] out += self._str_header("See Also") last_had_desc = True for func, desc, role in self['See Also']: if role: link = ':{}:`{}`'.format(role, func) elif func_role: link = ':{}:`{}`'.format(func_role, func) else: link = "`%s`_" % func if desc or last_had_desc: out += [''] out += [link] else: out[-1] += ", %s" % link if desc: out += self._str_indent([' '.join(desc)]) last_had_desc = True else: last_had_desc = False out += [''] return out def _str_index(self): idx = self['index'] out = [] out += ['.. index:: %s' % idx.get('default', '')] for section, references in idx.items(): if section == 'default': continue out += [' :{}: {}'.format(section, ', '.join(references))] return out def __str__(self, func_role=''): out = [] out += self._str_signature() out += self._str_summary() out += self._str_extended_summary() for param_list in ('Parameters', 'Returns', 'Yields', 'Other Parameters', 'Raises', 'Warns'): out += self._str_param_list(param_list) out += self._str_section('Warnings') out += self._str_see_also(func_role) for s in ('Notes', 'References', 'Examples'): out += self._str_section(s) for param_list in ('Attributes', 'Methods'): out += self._str_param_list(param_list) out += self._str_index() return '\n'.join(out) def indent(str, indent=4): indent_str = ' '*indent if str is None: return indent_str lines = str.split('\n') return '\n'.join(indent_str + l for l in lines) def dedent_lines(lines): """Deindent a list of lines maximally""" return textwrap.dedent("\n".join(lines)).split("\n") def header(text, style='-'): return text + '\n' + style*len(text) + '\n' class FunctionDoc(NumpyDocString): def __init__(self, func, role='func', doc=None, config={}): self._f = func self._role = role # e.g. "func" or "meth" if doc is None: if func is None: raise ValueError("No function or docstring given") doc = inspect.getdoc(func) or '' NumpyDocString.__init__(self, doc) if not self['Signature'] and func is not None: func, func_name = self.get_func() try: # try to read signature argspec = str(inspect.signature(func)) argspec = argspec.replace('*', r'\*') signature = '{}{}'.format(func_name, argspec) except TypeError as e: signature = '%s()' % func_name self['Signature'] = signature def get_func(self): func_name = getattr(self._f, '__name__', self.__class__.__name__) if inspect.isclass(self._f): func = getattr(self._f, '__call__', self._f.__init__) else: func = self._f return func, func_name def __str__(self): out = '' func, func_name = self.get_func() signature = self['Signature'].replace('*', r'\*') roles = {'func': 'function', 'meth': 'method'} if self._role: if self._role not in roles: print("Warning: invalid role %s" % self._role) out += '.. {}:: {}\n \n\n'.format(roles.get(self._role, ''), func_name) out += super().__str__(func_role=self._role) return out class ClassDoc(NumpyDocString): extra_public_methods = ['__call__'] def __init__(self, cls, doc=None, modulename='', func_doc=FunctionDoc, config={}): if not inspect.isclass(cls) and cls is not None: raise ValueError("Expected a class or None, but got %r" % cls) self._cls = cls self.show_inherited_members = config.get( 'show_inherited_class_members', True) if modulename and not modulename.endswith('.'): modulename += '.' self._mod = modulename if doc is None: if cls is None: raise ValueError("No class or documentation string given") doc = pydoc.getdoc(cls) NumpyDocString.__init__(self, doc) if config.get('show_class_members', True): def splitlines_x(s): if not s: return [] else: return s.splitlines() for field, items in [('Methods', self.methods), ('Attributes', self.properties)]: if not self[field]: doc_list = [] for name in sorted(items): clsname = getattr(self._cls, name, None) if clsname is not None: doc_item = pydoc.getdoc(clsname) doc_list.append((name, '', splitlines_x(doc_item))) self[field] = doc_list @property def methods(self): if self._cls is None: return [] return [name for name, func in inspect.getmembers(self._cls) if ((not name.startswith('_') or name in self.extra_public_methods) and callable(func))] @property def properties(self): if self._cls is None: return [] return [name for name, func in inspect.getmembers(self._cls) if not name.startswith('_') and func is None]
e3314d996e8686ed6fbe0cbe5bb0fd8690f75bca2eebc581c6517f96ff4b890f
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 sympy_deprecation_warning 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): sympy_deprecation_warning( """ Calling the distribution method with a RandomIndexedSymbol argument, like X.distribution(X(t)) is deprecated. Instead, call distribution() with the given timestamp, like X.distribution(t) """, deprecated_since_version="1.7.1", active_deprecations_target="deprecated-distribution-randomindexedsymbol", stacklevel=4, ) 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 = {}, 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 >>> 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): sympy_deprecation_warning( """ DiscreteMarkovChain.absorbing_probabilites() is deprecated. Use absorbing_probabilities() instead (note the spelling difference). """, deprecated_since_version="1.7", active_deprecations_target="deprecated-absorbing_probabilites", ) 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 symbols >>> 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. Default: 1. failure: Integer/str The event which is considered to be failure. Default: 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, Logic 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, ``lambda > 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 it is often also called Brownian motion due to its historical connection with physical process of the same name originally observed by Scottish botanist Robert Brown. 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): r""" 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)
1f920e1efd53cd0326f62645428d35b0758dd13703e6c584d5c6b6a6243cf686
from math import prod from sympy.core.basic import Basic 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 pymc of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_pymc(dist, size, seed) @classmethod def _sample_pymc(cls, dist, size, seed): """Sample from PyMC.""" try: import pymc except ImportError: import pymc3 as pymc pymc_rv_map = { 'MatrixNormalDistribution': lambda dist: pymc.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: pymc.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 = pymc_rv_map.keys() if dist.__class__.__name__ not in dist_list: return None import logging logging.getLogger("pymc").setLevel(logging.ERROR) with pymc.Model(): pymc_rv_map[dist.__class__.__name__](dist) samps = pymc.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, 'pymc': 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', 'pymc'] 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)
fb4c343b46e42cbf98a428e01fd2f6e8ead045e808149f3d4c88fa09ae22b898
""" 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 math import prod 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 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.decorator import doctest_depends_on from sympy.utilities.exceptions import sympy_deprecation_warning from sympy.utilities.iterables import iterable 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 does not 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) 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 - 'pymc' : Sample using PyMC 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``. .. deprecated:: 1.9 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. See :ref:`deprecated-sympy-stats-numsamples` for details. 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 - 'pymc': 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: sympy_deprecation_warning( f""" The numsamples parameter to sympy.stats.sample() is deprecated. Either use a list comprehension, like [sample(...) for i in range({numsamples})] or add a dimension to size, like sample(..., size={(numsamples,) + size}) """, deprecated_since_version="1.9", active_deprecations_target="deprecated-sympy-stats-numsamples", ) 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) : p \le 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 - 'pymc': 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 in ('pymc', 'pymc3'): # Currently unable to lambdify in pymc # TODO : Remove when lambdify accepts 'pymc' 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', 'pymc'} 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 in ('pymc', 'pymc3'): from sympy.stats.sampling.sample_pymc import do_sample_pymc import logging logging.getLogger("pymc").setLevel(logging.ERROR) try: import pymc except ImportError: import pymc3 as pymc with pymc.Model(): if do_sample_pymc(self): samps = pymc.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 does not 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 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()
0dc8b194ed8c978827c0c9999365537a088756af3c0e42dd425393439ed242d7
""" Joint Random Variables Module See Also ======== sympy.stats.rv sympy.stats.frv sympy.stats.crv sympy.stats.drv """ from math import prod from sympy.core.basic import Basic from sympy.core.function import Lambda 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 = [[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 pymc of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_pymc(dist, size, seed) @classmethod def _sample_pymc(cls, dist, size, seed): """Sample from PyMC.""" try: import pymc except ImportError: import pymc3 as pymc pymc_rv_map = { 'MultivariateNormalDistribution': lambda dist: pymc.MvNormal('X', mu=matrix2numpy(dist.mu, float).flatten(), cov=matrix2numpy(dist.sigma, float), shape=(1, dist.mu.shape[0])), 'MultivariateBetaDistribution': lambda dist: pymc.Dirichlet('X', a=list2numpy(dist.alpha, float).flatten()), 'MultinomialDistribution': lambda dist: pymc.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 = pymc_rv_map.keys() if dist.__class__.__name__ not in dist_list: return None import logging logging.getLogger("pymc3").setLevel(logging.ERROR) with pymc.Model(): pymc_rv_map[dist.__class__.__name__](dist) samples = pymc.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, 'pymc': 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', 'pymc') 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)
7159f781927b29cabba3e958243633a77222c54ede0dfc367a7b3697dfdb1b5a
from sympy.ntheory import sieve, isprime from sympy.core.numbers import mod_inverse from sympy.core.power import integer_log from sympy.utilities.misc import as_int import random rgen = random.Random() #----------------------------------------------------------------------------# # # # Lenstra's Elliptic Curve Factorization # # # #----------------------------------------------------------------------------# class Point: """Montgomery form of Points in an elliptic curve. In this form, the addition and doubling of points does not need any y-coordinate information thus decreasing the number of operations. Using Montgomery form we try to perform point addition and doubling in least amount of multiplications. The elliptic curve used here is of the form (E : b*y**2*z = x**3 + a*x**2*z + x*z**2). The a_24 parameter is equal to (a + 2)/4. References ========== .. [1] http://www.hyperelliptic.org/tanja/SHARCS/talks06/Gaj.pdf """ def __init__(self, x_cord, z_cord, a_24, mod): """ Initial parameters for the Point class. Parameters ========== x_cord : X coordinate of the Point z_cord : Z coordinate of the Point a_24 : Parameter of the elliptic curve in Montgomery form mod : modulus """ self.x_cord = x_cord self.z_cord = z_cord self.a_24 = a_24 self.mod = mod def __eq__(self, other): """Two points are equal if X/Z of both points are equal """ if self.a_24 != other.a_24 or self.mod != other.mod: return False return self.x_cord * mod_inverse(self.z_cord, self.mod) % self.mod ==\ other.x_cord * mod_inverse(other.z_cord, self.mod) % self.mod def add(self, Q, diff): """ Add two points self and Q where diff = self - Q. Moreover the assumption is self.x_cord*Q.x_cord*(self.x_cord - Q.x_cord) != 0. This algorithm requires 6 multiplications. Here the difference between the points is already known and using this algorithm speeds up the addition by reducing the number of multiplication required. Also in the mont_ladder algorithm is constructed in a way so that the difference between intermediate points is always equal to the initial point. So, we always know what the difference between the point is. Parameters ========== Q : point on the curve in Montgomery form diff : self - Q Examples ======== >>> from sympy.ntheory.ecm import Point >>> p1 = Point(11, 16, 7, 29) >>> p2 = Point(13, 10, 7, 29) >>> p3 = p2.add(p1, p1) >>> p3.x_cord 23 >>> p3.z_cord 17 """ u = (self.x_cord - self.z_cord)*(Q.x_cord + Q.z_cord) v = (self.x_cord + self.z_cord)*(Q.x_cord - Q.z_cord) add, subt = u + v, u - v x_cord = diff.z_cord * add * add % self.mod z_cord = diff.x_cord * subt * subt % self.mod return Point(x_cord, z_cord, self.a_24, self.mod) def double(self): """ Doubles a point in an elliptic curve in Montgomery form. This algorithm requires 5 multiplications. Examples ======== >>> from sympy.ntheory.ecm import Point >>> p1 = Point(11, 16, 7, 29) >>> p2 = p1.double() >>> p2.x_cord 13 >>> p2.z_cord 10 """ u, v = self.x_cord + self.z_cord, self.x_cord - self.z_cord u, v = u*u, v*v diff = u - v x_cord = u*v % self.mod z_cord = diff*(v + self.a_24*diff) % self.mod return Point(x_cord, z_cord, self.a_24, self.mod) def mont_ladder(self, k): """ Scalar multiplication of a point in Montgomery form using Montgomery Ladder Algorithm. A total of 11 multiplications are required in each step of this algorithm. Parameters ========== k : The positive integer multiplier Examples ======== >>> from sympy.ntheory.ecm import Point >>> p1 = Point(11, 16, 7, 29) >>> p3 = p1.mont_ladder(3) >>> p3.x_cord 23 >>> p3.z_cord 17 """ Q = self R = self.double() for i in bin(k)[3:]: if i == '1': Q = R.add(Q, self) R = R.double() else: R = Q.add(R, self) Q = Q.double() return Q def _ecm_one_factor(n, B1=10000, B2=100000, max_curve=200): """Returns one factor of n using Lenstra's 2 Stage Elliptic curve Factorization with Suyama's Parameterization. Here Montgomery arithmetic is used for fast computation of addition and doubling of points in elliptic curve. This ECM method considers elliptic curves in Montgomery form (E : b*y**2*z = x**3 + a*x**2*z + x*z**2) and involves elliptic curve operations (mod N), where the elements in Z are reduced (mod N). Since N is not a prime, E over FF(N) is not really an elliptic curve but we can still do point additions and doubling as if FF(N) was a field. Stage 1 : The basic algorithm involves taking a random point (P) on an elliptic curve in FF(N). The compute k*P using Montgomery ladder algorithm. Let q be an unknown factor of N. Then the order of the curve E, |E(FF(q))|, might be a smooth number that divides k. Then we have k = l * |E(FF(q))| for some l. For any point belonging to the curve E, |E(FF(q))|*P = O, hence k*P = l*|E(FF(q))|*P. Thus kP.z_cord = 0 (mod q), and the unknownn factor of N (q) can be recovered by taking gcd(kP.z_cord, N). Stage 2 : This is a continuation of Stage 1 if k*P != O. The idea utilize the fact that even if kP != 0, the value of k might miss just one large prime divisor of |E(FF(q))|. In this case we only need to compute the scalar multiplication by p to get p*k*P = O. Here a second bound B2 restrict the size of possible values of p. Parameters ========== n : Number to be Factored B1 : Stage 1 Bound B2 : Stage 2 Bound max_curve : Maximum number of curves generated References ========== .. [1] Carl Pomerance and Richard Crandall "Prime Numbers: A Computational Perspective" (2nd Ed.), page 344 """ n = as_int(n) if B1 % 2 != 0 or B2 % 2 != 0: raise ValueError("The Bounds should be an even integer") sieve.extend(B2) if isprime(n): return n from sympy.functions.elementary.miscellaneous import sqrt from sympy.polys.polytools import gcd curve = 0 D = int(sqrt(B2)) beta = [0]*(D + 1) S = [0]*(D + 1) k = 1 for p in sieve.primerange(1, B1 + 1): k *= pow(p, integer_log(B1, p)[0]) while(curve <= max_curve): curve += 1 #Suyama's Paramatrization sigma = rgen.randint(6, n - 1) u = (sigma*sigma - 5) % n v = (4*sigma) % n diff = v - u u_3 = pow(u, 3, n) try: C = (pow(diff, 3, n)*(3*u + v)*mod_inverse(4*u_3*v, n) - 2) % n except ValueError: #If the mod_inverse(4*u_3*v, n) doesn't exist return gcd(4*u_3*v, n) a24 = (C + 2)*mod_inverse(4, n) % n Q = Point(u_3, pow(v, 3, n), a24, n) Q = Q.mont_ladder(k) g = gcd(Q.z_cord, n) #Stage 1 factor if g != 1 and g != n: return g #Stage 1 failure. Q.z = 0, Try another curve elif g == n: continue #Stage 2 - Improved Standard Continuation S[1] = Q.double() S[2] = S[1].double() beta[1] = (S[1].x_cord*S[1].z_cord) % n beta[2] = (S[2].x_cord*S[2].z_cord) % n for d in range(3, D + 1): S[d] = S[d - 1].add(S[1], S[d - 2]) beta[d] = (S[d].x_cord*S[d].z_cord) % n g = 1 B = B1 - 1 T = Q.mont_ladder(B - 2*D) R = Q.mont_ladder(B) for r in range(B, B2, 2*D): alpha = (R.x_cord*R.z_cord) % n for q in sieve.primerange(r + 2, r + 2*D + 1): delta = (q - r) // 2 f = (R.x_cord - S[d].x_cord)*(R.z_cord + S[d].z_cord) -\ alpha + beta[delta] g = (g*f) % n #Swap T, R = R, R.add(S[D], T) g = gcd(n, g) #Stage 2 Factor found if g != 1 and g != n: return g #ECM failed, Increase the bounds raise ValueError("Increase the bounds") def ecm(n, B1=10000, B2=100000, max_curve=200, seed=1234): """Performs factorization using Lenstra's Elliptic curve method. This function repeatedly calls `ecm_one_factor` to compute the factors of n. First all the small factors are taken out using trial division. Then `ecm_one_factor` is used to compute one factor at a time. Parameters ========== n : Number to be Factored B1 : Stage 1 Bound B2 : Stage 2 Bound max_curve : Maximum number of curves generated seed : Initialize pseudorandom generator Examples ======== >>> from sympy.ntheory import ecm >>> ecm(25645121643901801) {5394769, 4753701529} >>> ecm(9804659461513846513) {4641991, 2112166839943} """ _factors = set() for prime in sieve.primerange(1, 100000): if n % prime == 0: _factors.add(prime) while(n % prime == 0): n //= prime rgen.seed(seed) while(n > 1): try: factor = _ecm_one_factor(n, B1, B2, max_curve) except ValueError: raise ValueError("Increase the bounds") _factors.add(factor) n //= factor factors = set() for factor in _factors: if isprime(factor): factors.add(factor) continue factors |= ecm(factor) return factors
661673c9d5beb63f23f195e6316e7f9cd89a9d25f3edbb53fc26af5bf6eec705
from __future__ import annotations from sympy.core.function import Function from sympy.core.numbers import igcd, igcdex, mod_inverse from sympy.core.power import isqrt from sympy.core.singleton import S from sympy.polys import Poly from sympy.polys.domains import ZZ from sympy.polys.galoistools import gf_crt1, gf_crt2, linear_congruence from .primetest import isprime from .factor_ import factorint, trailing, totient, multiplicity from sympy.utilities.misc import as_int from sympy.core.random import _randint, randint from itertools import cycle, product def n_order(a, n): """Returns the order of ``a`` modulo ``n``. The order of ``a`` modulo ``n`` is the smallest integer ``k`` such that ``a**k`` leaves a remainder of 1 with ``n``. Examples ======== >>> from sympy.ntheory import n_order >>> n_order(3, 7) 6 >>> n_order(4, 7) 3 """ from collections import defaultdict a, n = as_int(a), as_int(n) if igcd(a, n) != 1: raise ValueError("The two numbers should be relatively prime") factors = defaultdict(int) f = factorint(n) for px, kx in f.items(): if kx > 1: factors[px] += kx - 1 fpx = factorint(px - 1) for py, ky in fpx.items(): factors[py] += ky group_order = 1 for px, kx in factors.items(): group_order *= px**kx order = 1 if a > n: a = a % n for p, e in factors.items(): exponent = group_order for f in range(e + 1): if pow(a, exponent, n) != 1: order *= p ** (e - f + 1) break exponent = exponent // p return order def _primitive_root_prime_iter(p): """ Generates the primitive roots for a prime ``p`` Examples ======== >>> from sympy.ntheory.residue_ntheory import _primitive_root_prime_iter >>> list(_primitive_root_prime_iter(19)) [2, 3, 10, 13, 14, 15] References ========== .. [1] W. Stein "Elementary Number Theory" (2011), page 44 """ # it is assumed that p is an int v = [(p - 1) // i for i in factorint(p - 1).keys()] a = 2 while a < p: for pw in v: # a TypeError below may indicate that p was not an int if pow(a, pw, p) == 1: break else: yield a a += 1 def primitive_root(p): """ Returns the smallest primitive root or None Parameters ========== p : positive integer Examples ======== >>> from sympy.ntheory.residue_ntheory import primitive_root >>> primitive_root(19) 2 References ========== .. [1] W. Stein "Elementary Number Theory" (2011), page 44 .. [2] P. Hackman "Elementary Number Theory" (2009), Chapter C """ p = as_int(p) if p < 1: raise ValueError('p is required to be positive') if p <= 2: return 1 f = factorint(p) if len(f) > 2: return None if len(f) == 2: if 2 not in f or f[2] > 1: return None # case p = 2*p1**k, p1 prime for p1, e1 in f.items(): if p1 != 2: break i = 1 while i < p: i += 2 if i % p1 == 0: continue if is_primitive_root(i, p): return i else: if 2 in f: if p == 4: return 3 return None p1, n = list(f.items())[0] if n > 1: # see Ref [2], page 81 g = primitive_root(p1) if is_primitive_root(g, p1**2): return g else: for i in range(2, g + p1 + 1): if igcd(i, p) == 1 and is_primitive_root(i, p): return i return next(_primitive_root_prime_iter(p)) def is_primitive_root(a, p): """ Returns True if ``a`` is a primitive root of ``p`` ``a`` is said to be the primitive root of ``p`` if gcd(a, p) == 1 and totient(p) is the smallest positive number s.t. a**totient(p) cong 1 mod(p) Examples ======== >>> from sympy.ntheory import is_primitive_root, n_order, totient >>> is_primitive_root(3, 10) True >>> is_primitive_root(9, 10) False >>> n_order(3, 10) == totient(10) True >>> n_order(9, 10) == totient(10) False """ a, p = as_int(a), as_int(p) if igcd(a, p) != 1: raise ValueError("The two numbers should be relatively prime") if a > p: a = a % p return n_order(a, p) == totient(p) def _sqrt_mod_tonelli_shanks(a, p): """ Returns the square root in the case of ``p`` prime with ``p == 1 (mod 8)`` References ========== .. [1] R. Crandall and C. Pomerance "Prime Numbers", 2nt Ed., page 101 """ s = trailing(p - 1) t = p >> s # find a non-quadratic residue while 1: d = randint(2, p - 1) r = legendre_symbol(d, p) if r == -1: break #assert legendre_symbol(d, p) == -1 A = pow(a, t, p) D = pow(d, t, p) m = 0 for i in range(s): adm = A*pow(D, m, p) % p adm = pow(adm, 2**(s - 1 - i), p) if adm % p == p - 1: m += 2**i #assert A*pow(D, m, p) % p == 1 x = pow(a, (t + 1)//2, p)*pow(D, m//2, p) % p return x def sqrt_mod(a, p, all_roots=False): """ Find a root of ``x**2 = a mod p`` Parameters ========== a : integer p : positive integer all_roots : if True the list of roots is returned or None Notes ===== If there is no root it is returned None; else the returned root is less or equal to ``p // 2``; in general is not the smallest one. It is returned ``p // 2`` only if it is the only root. Use ``all_roots`` only when it is expected that all the roots fit in memory; otherwise use ``sqrt_mod_iter``. Examples ======== >>> from sympy.ntheory import sqrt_mod >>> sqrt_mod(11, 43) 21 >>> sqrt_mod(17, 32, True) [7, 9, 23, 25] """ if all_roots: return sorted(list(sqrt_mod_iter(a, p))) try: p = abs(as_int(p)) it = sqrt_mod_iter(a, p) r = next(it) if r > p // 2: return p - r elif r < p // 2: return r else: try: r = next(it) if r > p // 2: return p - r except StopIteration: pass return r except StopIteration: return None def _product(*iters): """ Cartesian product generator Notes ===== Unlike itertools.product, it works also with iterables which do not fit in memory. See http://bugs.python.org/issue10109 Author: Fernando Sumudu with small changes """ inf_iters = tuple(cycle(enumerate(it)) for it in iters) num_iters = len(inf_iters) cur_val = [None]*num_iters first_v = True while True: i, p = 0, num_iters while p and not i: p -= 1 i, cur_val[p] = next(inf_iters[p]) if not p and not i: if first_v: first_v = False else: break yield cur_val def sqrt_mod_iter(a, p, domain=int): """ Iterate over solutions to ``x**2 = a mod p`` Parameters ========== a : integer p : positive integer domain : integer domain, ``int``, ``ZZ`` or ``Integer`` Examples ======== >>> from sympy.ntheory.residue_ntheory import sqrt_mod_iter >>> list(sqrt_mod_iter(11, 43)) [21, 22] """ a, p = as_int(a), abs(as_int(p)) if isprime(p): a = a % p if a == 0: res = _sqrt_mod1(a, p, 1) else: res = _sqrt_mod_prime_power(a, p, 1) if res: if domain is ZZ: yield from res else: for x in res: yield domain(x) else: f = factorint(p) v = [] pv = [] for px, ex in f.items(): if a % px == 0: rx = _sqrt_mod1(a, px, ex) if not rx: return else: rx = _sqrt_mod_prime_power(a, px, ex) if not rx: return v.append(rx) pv.append(px**ex) mm, e, s = gf_crt1(pv, ZZ) if domain is ZZ: for vx in _product(*v): r = gf_crt2(vx, pv, mm, e, s, ZZ) yield r else: for vx in _product(*v): r = gf_crt2(vx, pv, mm, e, s, ZZ) yield domain(r) def _sqrt_mod_prime_power(a, p, k): """ Find the solutions to ``x**2 = a mod p**k`` when ``a % p != 0`` Parameters ========== a : integer p : prime number k : positive integer Examples ======== >>> from sympy.ntheory.residue_ntheory import _sqrt_mod_prime_power >>> _sqrt_mod_prime_power(11, 43, 1) [21, 22] References ========== .. [1] P. Hackman "Elementary Number Theory" (2009), page 160 .. [2] http://www.numbertheory.org/php/squareroot.html .. [3] [Gathen99]_ """ pk = p**k a = a % pk if k == 1: if p == 2: return [ZZ(a)] if not (a % p < 2 or pow(a, (p - 1) // 2, p) == 1): return None if p % 4 == 3: res = pow(a, (p + 1) // 4, p) elif p % 8 == 5: sign = pow(a, (p - 1) // 4, p) if sign == 1: res = pow(a, (p + 3) // 8, p) else: b = pow(4*a, (p - 5) // 8, p) x = (2*a*b) % p if pow(x, 2, p) == a: res = x else: res = _sqrt_mod_tonelli_shanks(a, p) # ``_sqrt_mod_tonelli_shanks(a, p)`` is not deterministic; # sort to get always the same result return sorted([ZZ(res), ZZ(p - res)]) if k > 1: # see Ref.[2] if p == 2: if a % 8 != 1: return None if k <= 3: s = set() for i in range(0, pk, 4): s.add(1 + i) s.add(-1 + i) return list(s) # according to Ref.[2] for k > 2 there are two solutions # (mod 2**k-1), that is four solutions (mod 2**k), which can be # obtained from the roots of x**2 = 0 (mod 8) rv = [ZZ(1), ZZ(3), ZZ(5), ZZ(7)] # hensel lift them to solutions of x**2 = 0 (mod 2**k) # if r**2 - a = 0 mod 2**nx but not mod 2**(nx+1) # then r + 2**(nx - 1) is a root mod 2**(nx+1) n = 3 res = [] for r in rv: nx = n while nx < k: r1 = (r**2 - a) >> nx if r1 % 2: r = r + (1 << (nx - 1)) #assert (r**2 - a)% (1 << (nx + 1)) == 0 nx += 1 if r not in res: res.append(r) x = r + (1 << (k - 1)) #assert (x**2 - a) % pk == 0 if x < (1 << nx) and x not in res: if (x**2 - a) % pk == 0: res.append(x) return res rv = _sqrt_mod_prime_power(a, p, 1) if not rv: return None r = rv[0] fr = r**2 - a # hensel lifting with Newton iteration, see Ref.[3] chapter 9 # with f(x) = x**2 - a; one has f'(a) != 0 (mod p) for p != 2 n = 1 px = p while 1: n1 = n n1 *= 2 if n1 > k: break n = n1 px = px**2 frinv = igcdex(2*r, px)[0] r = (r - fr*frinv) % px fr = r**2 - a if n < k: px = p**k frinv = igcdex(2*r, px)[0] r = (r - fr*frinv) % px return [r, px - r] def _sqrt_mod1(a, p, n): """ Find solution to ``x**2 == a mod p**n`` when ``a % p == 0`` see http://www.numbertheory.org/php/squareroot.html """ pn = p**n a = a % pn if a == 0: # case gcd(a, p**k) = p**n m = n // 2 if n % 2 == 1: pm1 = p**(m + 1) def _iter0a(): i = 0 while i < pn: yield i i += pm1 return _iter0a() else: pm = p**m def _iter0b(): i = 0 while i < pn: yield i i += pm return _iter0b() # case gcd(a, p**k) = p**r, r < n f = factorint(a) r = f[p] if r % 2 == 1: return None m = r // 2 a1 = a >> r if p == 2: if n - r == 1: pnm1 = 1 << (n - m + 1) pm1 = 1 << (m + 1) def _iter1(): k = 1 << (m + 2) i = 1 << m while i < pnm1: j = i while j < pn: yield j j += k i += pm1 return _iter1() if n - r == 2: res = _sqrt_mod_prime_power(a1, p, n - r) if res is None: return None pnm = 1 << (n - m) def _iter2(): s = set() for r in res: i = 0 while i < pn: x = (r << m) + i if x not in s: s.add(x) yield x i += pnm return _iter2() if n - r > 2: res = _sqrt_mod_prime_power(a1, p, n - r) if res is None: return None pnm1 = 1 << (n - m - 1) def _iter3(): s = set() for r in res: i = 0 while i < pn: x = ((r << m) + i) % pn if x not in s: s.add(x) yield x i += pnm1 return _iter3() else: m = r // 2 a1 = a // p**r res1 = _sqrt_mod_prime_power(a1, p, n - r) if res1 is None: return None pm = p**m pnr = p**(n-r) pnm = p**(n-m) def _iter4(): s = set() pm = p**m for rx in res1: i = 0 while i < pnm: x = ((rx + i) % pn) if x not in s: s.add(x) yield x*pm i += pnr return _iter4() def is_quad_residue(a, p): """ Returns True if ``a`` (mod ``p``) is in the set of squares mod ``p``, i.e a % p in set([i**2 % p for i in range(p)]). If ``p`` is an odd prime, an iterative method is used to make the determination: >>> from sympy.ntheory import is_quad_residue >>> sorted(set([i**2 % 7 for i in range(7)])) [0, 1, 2, 4] >>> [j for j in range(7) if is_quad_residue(j, 7)] [0, 1, 2, 4] See Also ======== legendre_symbol, jacobi_symbol """ a, p = as_int(a), as_int(p) if p < 1: raise ValueError('p must be > 0') if a >= p or a < 0: a = a % p if a < 2 or p < 3: return True if not isprime(p): if p % 2 and jacobi_symbol(a, p) == -1: return False r = sqrt_mod(a, p) if r is None: return False else: return True return pow(a, (p - 1) // 2, p) == 1 def is_nthpow_residue(a, n, m): """ Returns True if ``x**n == a (mod m)`` has solutions. References ========== .. [1] P. Hackman "Elementary Number Theory" (2009), page 76 """ a = a % m a, n, m = as_int(a), as_int(n), as_int(m) if m <= 0: raise ValueError('m must be > 0') if n < 0: raise ValueError('n must be >= 0') if n == 0: if m == 1: return False return a == 1 if a == 0: return True if n == 1: return True if n == 2: return is_quad_residue(a, m) return _is_nthpow_residue_bign(a, n, m) def _is_nthpow_residue_bign(a, n, m): r"""Returns True if `x^n = a \pmod{n}` has solutions for `n > 2`.""" # assert n > 2 # assert a > 0 and m > 0 if primitive_root(m) is None or igcd(a, m) != 1: # assert m >= 8 for prime, power in factorint(m).items(): if not _is_nthpow_residue_bign_prime_power(a, n, prime, power): return False return True f = totient(m) k = int(f // igcd(f, n)) return pow(a, k, int(m)) == 1 def _is_nthpow_residue_bign_prime_power(a, n, p, k): r"""Returns True/False if a solution for `x^n = a \pmod{p^k}` does/does not exist.""" # assert a > 0 # assert n > 2 # assert p is prime # assert k > 0 if a % p: if p != 2: return _is_nthpow_residue_bign(a, n, pow(p, k)) if n & 1: return True c = trailing(n) return a % pow(2, min(c + 2, k)) == 1 else: a %= pow(p, k) if not a: return True mu = multiplicity(p, a) if mu % n: return False pm = pow(p, mu) return _is_nthpow_residue_bign_prime_power(a//pm, n, p, k - mu) def _nthroot_mod2(s, q, p): f = factorint(q) v = [] for b, e in f.items(): v.extend([b]*e) for qx in v: s = _nthroot_mod1(s, qx, p, False) return s def _nthroot_mod1(s, q, p, all_roots): """ Root of ``x**q = s mod p``, ``p`` prime and ``q`` divides ``p - 1`` References ========== .. [1] A. M. Johnston "A Generalized qth Root Algorithm" """ g = primitive_root(p) if not isprime(q): r = _nthroot_mod2(s, q, p) else: f = p - 1 assert (p - 1) % q == 0 # determine k k = 0 while f % q == 0: k += 1 f = f // q # find z, x, r1 f1 = igcdex(-f, q)[0] % q z = f*f1 x = (1 + z) // q r1 = pow(s, x, p) s1 = pow(s, f, p) h = pow(g, f*q, p) t = discrete_log(p, s1, h) g2 = pow(g, z*t, p) g3 = igcdex(g2, p)[0] r = r1*g3 % p #assert pow(r, q, p) == s res = [r] h = pow(g, (p - 1) // q, p) #assert pow(h, q, p) == 1 hx = r for i in range(q - 1): hx = (hx*h) % p res.append(hx) if all_roots: res.sort() return res return min(res) def _help(m, prime_modulo_method, diff_method, expr_val): """ Helper function for _nthroot_mod_composite and polynomial_congruence. Parameters ========== m : positive integer prime_modulo_method : function to calculate the root of the congruence equation for the prime divisors of m diff_method : function to calculate derivative of expression at any given point expr_val : function to calculate value of the expression at any given point """ from sympy.ntheory.modular import crt f = factorint(m) dd = {} for p, e in f.items(): tot_roots = set() if e == 1: tot_roots.update(prime_modulo_method(p)) else: for root in prime_modulo_method(p): diff = diff_method(root, p) if diff != 0: ppow = p m_inv = mod_inverse(diff, p) for j in range(1, e): ppow *= p root = (root - expr_val(root, ppow) * m_inv) % ppow tot_roots.add(root) else: new_base = p roots_in_base = {root} while new_base < pow(p, e): new_base *= p new_roots = set() for k in roots_in_base: if expr_val(k, new_base)!= 0: continue while k not in new_roots: new_roots.add(k) k = (k + (new_base // p)) % new_base roots_in_base = new_roots tot_roots = tot_roots | roots_in_base if tot_roots == set(): return [] dd[pow(p, e)] = tot_roots a = [] m = [] for x, y in dd.items(): m.append(x) a.append(list(y)) return sorted({crt(m, list(i))[0] for i in product(*a)}) def _nthroot_mod_composite(a, n, m): """ Find the solutions to ``x**n = a mod m`` when m is not prime. """ return _help(m, lambda p: nthroot_mod(a, n, p, True), lambda root, p: (pow(root, n - 1, p) * (n % p)) % p, lambda root, p: (pow(root, n, p) - a) % p) def nthroot_mod(a, n, p, all_roots=False): """ Find the solutions to ``x**n = a mod p`` Parameters ========== a : integer n : positive integer p : positive integer all_roots : if False returns the smallest root, else the list of roots Examples ======== >>> from sympy.ntheory.residue_ntheory import nthroot_mod >>> nthroot_mod(11, 4, 19) 8 >>> nthroot_mod(11, 4, 19, True) [8, 11] >>> nthroot_mod(68, 3, 109) 23 """ a = a % p a, n, p = as_int(a), as_int(n), as_int(p) if n == 2: return sqrt_mod(a, p, all_roots) # see Hackman "Elementary Number Theory" (2009), page 76 if not isprime(p): return _nthroot_mod_composite(a, n, p) if a % p == 0: return [0] if not is_nthpow_residue(a, n, p): return [] if all_roots else None if (p - 1) % n == 0: return _nthroot_mod1(a, n, p, all_roots) # The roots of ``x**n - a = 0 (mod p)`` are roots of # ``gcd(x**n - a, x**(p - 1) - 1) = 0 (mod p)`` pa = n pb = p - 1 b = 1 if pa < pb: a, pa, b, pb = b, pb, a, pa while pb: # x**pa - a = 0; x**pb - b = 0 # x**pa - a = x**(q*pb + r) - a = (x**pb)**q * x**r - a = # b**q * x**r - a; x**r - c = 0; c = b**-q * a mod p q, r = divmod(pa, pb) c = pow(b, q, p) c = igcdex(c, p)[0] c = (c * a) % p pa, pb = pb, r a, b = b, c if pa == 1: if all_roots: res = [a] else: res = a elif pa == 2: return sqrt_mod(a, p, all_roots) else: res = _nthroot_mod1(a, pa, p, all_roots) return res def quadratic_residues(p) -> list[int]: """ Returns the list of quadratic residues. Examples ======== >>> from sympy.ntheory.residue_ntheory import quadratic_residues >>> quadratic_residues(7) [0, 1, 2, 4] """ p = as_int(p) r = {pow(i, 2, p) for i in range(p // 2 + 1)} return sorted(r) def legendre_symbol(a, p): r""" Returns the Legendre symbol `(a / p)`. For an integer ``a`` and an odd prime ``p``, the Legendre symbol is defined as .. math :: \genfrac(){}{}{a}{p} = \begin{cases} 0 & \text{if } p \text{ divides } a\\ 1 & \text{if } a \text{ is a quadratic residue modulo } p\\ -1 & \text{if } a \text{ is a quadratic nonresidue modulo } p \end{cases} Parameters ========== a : integer p : odd prime Examples ======== >>> from sympy.ntheory import legendre_symbol >>> [legendre_symbol(i, 7) for i in range(7)] [0, 1, 1, -1, 1, -1, -1] >>> sorted(set([i**2 % 7 for i in range(7)])) [0, 1, 2, 4] See Also ======== is_quad_residue, jacobi_symbol """ a, p = as_int(a), as_int(p) if not isprime(p) or p == 2: raise ValueError("p should be an odd prime") a = a % p if not a: return 0 if pow(a, (p - 1) // 2, p) == 1: return 1 return -1 def jacobi_symbol(m, n): r""" Returns the Jacobi symbol `(m / n)`. For any integer ``m`` and any positive odd integer ``n`` the Jacobi symbol is defined as the product of the Legendre symbols corresponding to the prime factors of ``n``: .. math :: \genfrac(){}{}{m}{n} = \genfrac(){}{}{m}{p^{1}}^{\alpha_1} \genfrac(){}{}{m}{p^{2}}^{\alpha_2} ... \genfrac(){}{}{m}{p^{k}}^{\alpha_k} \text{ where } n = p_1^{\alpha_1} p_2^{\alpha_2} ... p_k^{\alpha_k} Like the Legendre symbol, if the Jacobi symbol `\genfrac(){}{}{m}{n} = -1` then ``m`` is a quadratic nonresidue modulo ``n``. But, unlike the Legendre symbol, if the Jacobi symbol `\genfrac(){}{}{m}{n} = 1` then ``m`` may or may not be a quadratic residue modulo ``n``. Parameters ========== m : integer n : odd positive integer Examples ======== >>> from sympy.ntheory import jacobi_symbol, legendre_symbol >>> from sympy import S >>> jacobi_symbol(45, 77) -1 >>> jacobi_symbol(60, 121) 1 The relationship between the ``jacobi_symbol`` and ``legendre_symbol`` can be demonstrated as follows: >>> L = legendre_symbol >>> S(45).factors() {3: 2, 5: 1} >>> jacobi_symbol(7, 45) == L(7, 3)**2 * L(7, 5)**1 True See Also ======== is_quad_residue, legendre_symbol """ m, n = as_int(m), as_int(n) if n < 0 or not n % 2: raise ValueError("n should be an odd positive integer") if m < 0 or m > n: m %= n if not m: return int(n == 1) if n == 1 or m == 1: return 1 if igcd(m, n) != 1: return 0 j = 1 while m != 0: while m % 2 == 0 and m > 0: m >>= 1 if n % 8 in [3, 5]: j = -j m, n = n, m if m % 4 == n % 4 == 3: j = -j m %= n return j class mobius(Function): """ Mobius function maps natural number to {-1, 0, 1} It is defined as follows: 1) `1` if `n = 1`. 2) `0` if `n` has a squared prime factor. 3) `(-1)^k` if `n` is a square-free positive integer with `k` number of prime factors. It is an important multiplicative function in number theory and combinatorics. It has applications in mathematical series, algebraic number theory and also physics (Fermion operator has very concrete realization with Mobius Function model). Parameters ========== n : positive integer Examples ======== >>> from sympy.ntheory import mobius >>> mobius(13*7) 1 >>> mobius(1) 1 >>> mobius(13*7*5) -1 >>> mobius(13**2) 0 References ========== .. [1] https://en.wikipedia.org/wiki/M%C3%B6bius_function .. [2] Thomas Koshy "Elementary Number Theory with Applications" """ @classmethod def eval(cls, n): if n.is_integer: if n.is_positive is not True: raise ValueError("n should be a positive integer") else: raise TypeError("n should be an integer") if n.is_prime: return S.NegativeOne elif n is S.One: return S.One elif n.is_Integer: a = factorint(n) if any(i > 1 for i in a.values()): return S.Zero return S.NegativeOne**len(a) def _discrete_log_trial_mul(n, a, b, order=None): """ Trial multiplication algorithm for computing the discrete logarithm of ``a`` to the base ``b`` modulo ``n``. The algorithm finds the discrete logarithm using exhaustive search. This naive method is used as fallback algorithm of ``discrete_log`` when the group order is very small. Examples ======== >>> from sympy.ntheory.residue_ntheory import _discrete_log_trial_mul >>> _discrete_log_trial_mul(41, 15, 7) 3 See Also ======== discrete_log References ========== .. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., & Vanstone, S. A. (1997). """ a %= n b %= n if order is None: order = n x = 1 for i in range(order): if x == a: return i x = x * b % n raise ValueError("Log does not exist") def _discrete_log_shanks_steps(n, a, b, order=None): """ Baby-step giant-step algorithm for computing the discrete logarithm of ``a`` to the base ``b`` modulo ``n``. The algorithm is a time-memory trade-off of the method of exhaustive search. It uses `O(sqrt(m))` memory, where `m` is the group order. Examples ======== >>> from sympy.ntheory.residue_ntheory import _discrete_log_shanks_steps >>> _discrete_log_shanks_steps(41, 15, 7) 3 See Also ======== discrete_log References ========== .. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., & Vanstone, S. A. (1997). """ a %= n b %= n if order is None: order = n_order(b, n) m = isqrt(order) + 1 T = {} x = 1 for i in range(m): T[x] = i x = x * b % n z = mod_inverse(b, n) z = pow(z, m, n) x = a for i in range(m): if x in T: return i * m + T[x] x = x * z % n raise ValueError("Log does not exist") def _discrete_log_pollard_rho(n, a, b, order=None, retries=10, rseed=None): """ Pollard's Rho algorithm for computing the discrete logarithm of ``a`` to the base ``b`` modulo ``n``. It is a randomized algorithm with the same expected running time as ``_discrete_log_shanks_steps``, but requires a negligible amount of memory. Examples ======== >>> from sympy.ntheory.residue_ntheory import _discrete_log_pollard_rho >>> _discrete_log_pollard_rho(227, 3**7, 3) 7 See Also ======== discrete_log References ========== .. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., & Vanstone, S. A. (1997). """ a %= n b %= n if order is None: order = n_order(b, n) randint = _randint(rseed) for i in range(retries): aa = randint(1, order - 1) ba = randint(1, order - 1) xa = pow(b, aa, n) * pow(a, ba, n) % n c = xa % 3 if c == 0: xb = a * xa % n ab = aa bb = (ba + 1) % order elif c == 1: xb = xa * xa % n ab = (aa + aa) % order bb = (ba + ba) % order else: xb = b * xa % n ab = (aa + 1) % order bb = ba for j in range(order): c = xa % 3 if c == 0: xa = a * xa % n ba = (ba + 1) % order elif c == 1: xa = xa * xa % n aa = (aa + aa) % order ba = (ba + ba) % order else: xa = b * xa % n aa = (aa + 1) % order c = xb % 3 if c == 0: xb = a * xb % n bb = (bb + 1) % order elif c == 1: xb = xb * xb % n ab = (ab + ab) % order bb = (bb + bb) % order else: xb = b * xb % n ab = (ab + 1) % order c = xb % 3 if c == 0: xb = a * xb % n bb = (bb + 1) % order elif c == 1: xb = xb * xb % n ab = (ab + ab) % order bb = (bb + bb) % order else: xb = b * xb % n ab = (ab + 1) % order if xa == xb: r = (ba - bb) % order try: e = mod_inverse(r, order) * (ab - aa) % order if (pow(b, e, n) - a) % n == 0: return e except ValueError: pass break raise ValueError("Pollard's Rho failed to find logarithm") def _discrete_log_pohlig_hellman(n, a, b, order=None): """ Pohlig-Hellman algorithm for computing the discrete logarithm of ``a`` to the base ``b`` modulo ``n``. In order to compute the discrete logarithm, the algorithm takes advantage of the factorization of the group order. It is more efficient when the group order factors into many small primes. Examples ======== >>> from sympy.ntheory.residue_ntheory import _discrete_log_pohlig_hellman >>> _discrete_log_pohlig_hellman(251, 210, 71) 197 See Also ======== discrete_log References ========== .. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., & Vanstone, S. A. (1997). """ from .modular import crt a %= n b %= n if order is None: order = n_order(b, n) f = factorint(order) l = [0] * len(f) for i, (pi, ri) in enumerate(f.items()): for j in range(ri): gj = pow(b, l[i], n) aj = pow(a * mod_inverse(gj, n), order // pi**(j + 1), n) bj = pow(b, order // pi, n) cj = discrete_log(n, aj, bj, pi, True) l[i] += cj * pi**j d, _ = crt([pi**ri for pi, ri in f.items()], l) return d def discrete_log(n, a, b, order=None, prime_order=None): """ Compute the discrete logarithm of ``a`` to the base ``b`` modulo ``n``. This is a recursive function to reduce the discrete logarithm problem in cyclic groups of composite order to the problem in cyclic groups of prime order. It employs different algorithms depending on the problem (subgroup order size, prime order or not): * Trial multiplication * Baby-step giant-step * Pollard's Rho * Pohlig-Hellman Examples ======== >>> from sympy.ntheory import discrete_log >>> discrete_log(41, 15, 7) 3 References ========== .. [1] http://mathworld.wolfram.com/DiscreteLogarithm.html .. [2] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., & Vanstone, S. A. (1997). """ n, a, b = as_int(n), as_int(a), as_int(b) if order is None: order = n_order(b, n) if prime_order is None: prime_order = isprime(order) if order < 1000: return _discrete_log_trial_mul(n, a, b, order) elif prime_order: if order < 1000000000000: return _discrete_log_shanks_steps(n, a, b, order) return _discrete_log_pollard_rho(n, a, b, order) return _discrete_log_pohlig_hellman(n, a, b, order) def quadratic_congruence(a, b, c, p): """ Find the solutions to ``a x**2 + b x + c = 0 mod p a : integer b : integer c : integer p : positive integer """ a = as_int(a) b = as_int(b) c = as_int(c) p = as_int(p) a = a % p b = b % p c = c % p if a == 0: return linear_congruence(b, -c, p) if p == 2: roots = [] if c % 2 == 0: roots.append(0) if (a + b + c) % 2 == 0: roots.append(1) return roots if isprime(p): inv_a = mod_inverse(a, p) b *= inv_a c *= inv_a if b % 2 == 1: b = b + p d = ((b * b) // 4 - c) % p y = sqrt_mod(d, p, all_roots=True) res = set() for i in y: res.add((i - b // 2) % p) return sorted(res) y = sqrt_mod(b * b - 4 * a * c, 4 * a * p, all_roots=True) res = set() for i in y: root = linear_congruence(2 * a, i - b, 4 * a * p) for j in root: res.add(j % p) return sorted(res) def _polynomial_congruence_prime(coefficients, p): """A helper function used by polynomial_congruence. It returns the root of a polynomial modulo prime number by naive search from [0, p). Parameters ========== coefficients : list of integers p : prime number """ roots = [] rank = len(coefficients) for i in range(0, p): f_val = 0 for coeff in range(0,rank - 1): f_val = (f_val + pow(i, int(rank - coeff - 1), p) * coefficients[coeff]) % p f_val = f_val + coefficients[-1] if f_val % p == 0: roots.append(i) return roots def _diff_poly(root, coefficients, p): """A helper function used by polynomial_congruence. It returns the derivative of the polynomial evaluated at the root (mod p). Parameters ========== coefficients : list of integers p : prime number root : integer """ diff = 0 rank = len(coefficients) for coeff in range(0, rank - 1): if not coefficients[coeff]: continue diff = (diff + pow(root, rank - coeff - 2, p)*(rank - coeff - 1)* coefficients[coeff]) % p return diff % p def _val_poly(root, coefficients, p): """A helper function used by polynomial_congruence. It returns value of the polynomial at root (mod p). Parameters ========== coefficients : list of integers p : prime number root : integer """ rank = len(coefficients) f_val = 0 for coeff in range(0, rank - 1): f_val = (f_val + pow(root, rank - coeff - 1, p)* coefficients[coeff]) % p f_val = f_val + coefficients[-1] return f_val % p def _valid_expr(expr): """ return coefficients of expr if it is a univariate polynomial with integer coefficients else raise a ValueError. """ if not expr.is_polynomial(): raise ValueError("The expression should be a polynomial") polynomial = Poly(expr) if not polynomial.is_univariate: raise ValueError("The expression should be univariate") if not polynomial.domain == ZZ: raise ValueError("The expression should should have integer coefficients") return polynomial.all_coeffs() def polynomial_congruence(expr, m): """ Find the solutions to a polynomial congruence equation modulo m. Parameters ========== coefficients : Coefficients of the Polynomial m : positive integer Examples ======== >>> from sympy.ntheory import polynomial_congruence >>> from sympy.abc import x >>> expr = x**6 - 2*x**5 -35 >>> polynomial_congruence(expr, 6125) [3257] """ coefficients = _valid_expr(expr) coefficients = [num % m for num in coefficients] rank = len(coefficients) if rank == 3: return quadratic_congruence(*coefficients, m) if rank == 2: return quadratic_congruence(0, *coefficients, m) if coefficients[0] == 1 and 1 + coefficients[-1] == sum(coefficients): return nthroot_mod(-coefficients[-1], rank - 1, m, True) if isprime(m): return _polynomial_congruence_prime(coefficients, m) return _help(m, lambda p: _polynomial_congruence_prime(coefficients, p), lambda root, p: _diff_poly(root, coefficients, p), lambda root, p: _val_poly(root, coefficients, p))
7c0dffa2f25c3eaaf04f66cf8e677871218f0f2546e8748cf683f4ec73f547fb
from functools import reduce from math import prod from sympy.core.numbers import igcdex, igcd from sympy.ntheory.primetest import isprime from sympy.polys.domains import ZZ from sympy.polys.galoistools import gf_crt, gf_crt1, gf_crt2 from sympy.utilities.misc import as_int def symmetric_residue(a, m): """Return the residual mod m such that it is within half of the modulus. >>> from sympy.ntheory.modular import symmetric_residue >>> symmetric_residue(1, 6) 1 >>> symmetric_residue(4, 6) -2 """ if a <= m // 2: return a return a - m def crt(m, v, symmetric=False, check=True): r"""Chinese Remainder Theorem. The moduli in m are assumed to be pairwise coprime. The output is then an integer f, such that f = v_i mod m_i for each pair out of v and m. If ``symmetric`` is False a positive integer will be returned, else \|f\| will be less than or equal to the LCM of the moduli, and thus f may be negative. If the moduli are not co-prime the correct result will be returned if/when the test of the result is found to be incorrect. This result will be None if there is no solution. The keyword ``check`` can be set to False if it is known that the moduli are coprime. Examples ======== As an example consider a set of residues ``U = [49, 76, 65]`` and a set of moduli ``M = [99, 97, 95]``. Then we have:: >>> from sympy.ntheory.modular import crt >>> crt([99, 97, 95], [49, 76, 65]) (639985, 912285) This is the correct result because:: >>> [639985 % m for m in [99, 97, 95]] [49, 76, 65] If the moduli are not co-prime, you may receive an incorrect result if you use ``check=False``: >>> crt([12, 6, 17], [3, 4, 2], check=False) (954, 1224) >>> [954 % m for m in [12, 6, 17]] [6, 0, 2] >>> crt([12, 6, 17], [3, 4, 2]) is None True >>> crt([3, 6], [2, 5]) (5, 6) Note: the order of gf_crt's arguments is reversed relative to crt, and that solve_congruence takes residue, modulus pairs. Programmer's note: rather than checking that all pairs of moduli share no GCD (an O(n**2) test) and rather than factoring all moduli and seeing that there is no factor in common, a check that the result gives the indicated residuals is performed -- an O(n) operation. See Also ======== solve_congruence sympy.polys.galoistools.gf_crt : low level crt routine used by this routine """ if check: m = list(map(as_int, m)) v = list(map(as_int, v)) result = gf_crt(v, m, ZZ) mm = prod(m) if check: if not all(v % m == result % m for v, m in zip(v, m)): result = solve_congruence(*list(zip(v, m)), check=False, symmetric=symmetric) if result is None: return result result, mm = result if symmetric: return symmetric_residue(result, mm), mm return result, mm def crt1(m): """First part of Chinese Remainder Theorem, for multiple application. Examples ======== >>> from sympy.ntheory.modular import crt1 >>> crt1([18, 42, 6]) (4536, [252, 108, 756], [0, 2, 0]) """ return gf_crt1(m, ZZ) def crt2(m, v, mm, e, s, symmetric=False): """Second part of Chinese Remainder Theorem, for multiple application. Examples ======== >>> from sympy.ntheory.modular import crt1, crt2 >>> mm, e, s = crt1([18, 42, 6]) >>> crt2([18, 42, 6], [0, 0, 0], mm, e, s) (0, 4536) """ result = gf_crt2(v, m, mm, e, s, ZZ) if symmetric: return symmetric_residue(result, mm), mm return result, mm def solve_congruence(*remainder_modulus_pairs, **hint): """Compute the integer ``n`` that has the residual ``ai`` when it is divided by ``mi`` where the ``ai`` and ``mi`` are given as pairs to this function: ((a1, m1), (a2, m2), ...). If there is no solution, return None. Otherwise return ``n`` and its modulus. The ``mi`` values need not be co-prime. If it is known that the moduli are not co-prime then the hint ``check`` can be set to False (default=True) and the check for a quicker solution via crt() (valid when the moduli are co-prime) will be skipped. If the hint ``symmetric`` is True (default is False), the value of ``n`` will be within 1/2 of the modulus, possibly negative. Examples ======== >>> from sympy.ntheory.modular import solve_congruence What number is 2 mod 3, 3 mod 5 and 2 mod 7? >>> solve_congruence((2, 3), (3, 5), (2, 7)) (23, 105) >>> [23 % m for m in [3, 5, 7]] [2, 3, 2] If you prefer to work with all remainder in one list and all moduli in another, send the arguments like this: >>> solve_congruence(*zip((2, 3, 2), (3, 5, 7))) (23, 105) The moduli need not be co-prime; in this case there may or may not be a solution: >>> solve_congruence((2, 3), (4, 6)) is None True >>> solve_congruence((2, 3), (5, 6)) (5, 6) The symmetric flag will make the result be within 1/2 of the modulus: >>> solve_congruence((2, 3), (5, 6), symmetric=True) (-1, 6) See Also ======== crt : high level routine implementing the Chinese Remainder Theorem """ def combine(c1, c2): """Return the tuple (a, m) which satisfies the requirement that n = a + i*m satisfy n = a1 + j*m1 and n = a2 = k*m2. References ========== .. [1] https://en.wikipedia.org/wiki/Method_of_successive_substitution """ a1, m1 = c1 a2, m2 = c2 a, b, c = m1, a2 - a1, m2 g = reduce(igcd, [a, b, c]) a, b, c = [i//g for i in [a, b, c]] if a != 1: inv_a, _, g = igcdex(a, c) if g != 1: return None b *= inv_a a, m = a1 + m1*b, m1*c return a, m rm = remainder_modulus_pairs symmetric = hint.get('symmetric', False) if hint.get('check', True): rm = [(as_int(r), as_int(m)) for r, m in rm] # ignore redundant pairs but raise an error otherwise; also # make sure that a unique set of bases is sent to gf_crt if # they are all prime. # # The routine will work out less-trivial violations and # return None, e.g. for the pairs (1,3) and (14,42) there # is no answer because 14 mod 42 (having a gcd of 14) implies # (14/2) mod (42/2), (14/7) mod (42/7) and (14/14) mod (42/14) # which, being 0 mod 3, is inconsistent with 1 mod 3. But to # preprocess the input beyond checking of another pair with 42 # or 3 as the modulus (for this example) is not necessary. uniq = {} for r, m in rm: r %= m if m in uniq: if r != uniq[m]: return None continue uniq[m] = r rm = [(r, m) for m, r in uniq.items()] del uniq # if the moduli are co-prime, the crt will be significantly faster; # checking all pairs for being co-prime gets to be slow but a prime # test is a good trade-off if all(isprime(m) for r, m in rm): r, m = list(zip(*rm)) return crt(m, r, symmetric=symmetric, check=False) rv = (0, 1) for rmi in rm: rv = combine(rv, rmi) if rv is None: break n, m = rv n = n % m else: if symmetric: return symmetric_residue(n, m), m return n, m
11dde6b69f32780554b6bfb22c881d5d6b60b4e2b1fb4bd58aef79559d81698f
""" Integer factorization """ from collections import defaultdict from functools import reduce 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 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 """ try: p, n = as_int(p), as_int(n) except ValueError: from sympy.functions.combinatorial.factorials import factorial 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 does not 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 did not 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) was not 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, 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): 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 """ 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): 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=S.One): 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(math.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=S.One): 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): 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): 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
7eee921718f600514a19456ebad9bcd0e5c07d4e1b6c30e1877c7b2e27484ad9
from mpmath.libmp import (fzero, from_int, from_rational, fone, fhalf, bitcount, to_int, to_str, mpf_mul, mpf_div, mpf_sub, mpf_add, mpf_sqrt, mpf_pi, mpf_cosh_sinh, mpf_cos, mpf_sin) from sympy.core.numbers import igcd from .residue_ntheory import (_sqrt_mod_prime_power, legendre_symbol, jacobi_symbol, is_quad_residue) import math def _pre(): maxn = 10**5 global _factor global _totient _factor = [0]*maxn _totient = [1]*maxn lim = int(maxn**0.5) + 5 for i in range(2, lim): if _factor[i] == 0: for j in range(i*i, maxn, i): if _factor[j] == 0: _factor[j] = i for i in range(2, maxn): if _factor[i] == 0: _factor[i] = i _totient[i] = i-1 continue x = _factor[i] y = i//x if y % x == 0: _totient[i] = _totient[y]*x else: _totient[i] = _totient[y]*(x - 1) def _a(n, k, prec): """ Compute the inner sum in HRR formula [1]_ References ========== .. [1] http://msp.org/pjm/1956/6-1/pjm-v6-n1-p18-p.pdf """ if k == 1: return fone k1 = k e = 0 p = _factor[k] while k1 % p == 0: k1 //= p e += 1 k2 = k//k1 # k2 = p^e v = 1 - 24*n pi = mpf_pi(prec) if k1 == 1: # k = p^e if p == 2: mod = 8*k v = mod + v % mod v = (v*pow(9, k - 1, mod)) % mod m = _sqrt_mod_prime_power(v, 2, e + 3)[0] arg = mpf_div(mpf_mul( from_int(4*m), pi, prec), from_int(mod), prec) return mpf_mul(mpf_mul( from_int((-1)**e*jacobi_symbol(m - 1, m)), mpf_sqrt(from_int(k), prec), prec), mpf_sin(arg, prec), prec) if p == 3: mod = 3*k v = mod + v % mod if e > 1: v = (v*pow(64, k//3 - 1, mod)) % mod m = _sqrt_mod_prime_power(v, 3, e + 1)[0] arg = mpf_div(mpf_mul(from_int(4*m), pi, prec), from_int(mod), prec) return mpf_mul(mpf_mul( from_int(2*(-1)**(e + 1)*legendre_symbol(m, 3)), mpf_sqrt(from_int(k//3), prec), prec), mpf_sin(arg, prec), prec) v = k + v % k if v % p == 0: if e == 1: return mpf_mul( from_int(jacobi_symbol(3, k)), mpf_sqrt(from_int(k), prec), prec) return fzero if not is_quad_residue(v, p): return fzero _phi = p**(e - 1)*(p - 1) v = (v*pow(576, _phi - 1, k)) m = _sqrt_mod_prime_power(v, p, e)[0] arg = mpf_div( mpf_mul(from_int(4*m), pi, prec), from_int(k), prec) return mpf_mul(mpf_mul( from_int(2*jacobi_symbol(3, k)), mpf_sqrt(from_int(k), prec), prec), mpf_cos(arg, prec), prec) if p != 2 or e >= 3: d1, d2 = igcd(k1, 24), igcd(k2, 24) e = 24//(d1*d2) n1 = ((d2*e*n + (k2**2 - 1)//d1)* pow(e*k2*k2*d2, _totient[k1] - 1, k1)) % k1 n2 = ((d1*e*n + (k1**2 - 1)//d2)* pow(e*k1*k1*d1, _totient[k2] - 1, k2)) % k2 return mpf_mul(_a(n1, k1, prec), _a(n2, k2, prec), prec) if e == 2: n1 = ((8*n + 5)*pow(128, _totient[k1] - 1, k1)) % k1 n2 = (4 + ((n - 2 - (k1**2 - 1)//8)*(k1**2)) % 4) % 4 return mpf_mul(mpf_mul( from_int(-1), _a(n1, k1, prec), prec), _a(n2, k2, prec)) n1 = ((8*n + 1)*pow(32, _totient[k1] - 1, k1)) % k1 n2 = (2 + (n - (k1**2 - 1)//8) % 2) % 2 return mpf_mul(_a(n1, k1, prec), _a(n2, k2, prec), prec) def _d(n, j, prec, sq23pi, sqrt8): """ Compute the sinh term in the outer sum of the HRR formula. The constants sqrt(2/3*pi) and sqrt(8) must be precomputed. """ j = from_int(j) pi = mpf_pi(prec) a = mpf_div(sq23pi, j, prec) b = mpf_sub(from_int(n), from_rational(1, 24, prec), prec) c = mpf_sqrt(b, prec) ch, sh = mpf_cosh_sinh(mpf_mul(a, c), prec) D = mpf_div( mpf_sqrt(j, prec), mpf_mul(mpf_mul(sqrt8, b), pi), prec) E = mpf_sub(mpf_mul(a, ch), mpf_div(sh, c, prec), prec) return mpf_mul(D, E) def npartitions(n, verbose=False): """ Calculate the partition function P(n), i.e. the number of ways that n can be written as a sum of positive integers. P(n) is computed using the Hardy-Ramanujan-Rademacher formula [1]_. The correctness of this implementation has been tested through $10^{10}$. Examples ======== >>> from sympy.ntheory import npartitions >>> npartitions(25) 1958 References ========== .. [1] http://mathworld.wolfram.com/PartitionFunctionP.html """ n = int(n) if n < 0: return 0 if n <= 5: return [1, 1, 2, 3, 5, 7][n] if '_factor' not in globals(): _pre() # Estimate number of bits in p(n). This formula could be tidied pbits = int(( math.pi*(2*n/3.)**0.5 - math.log(4*n))/math.log(10) + 1) * \ math.log(10, 2) prec = p = int(pbits*1.1 + 100) s = fzero M = max(6, int(0.24*n**0.5 + 4)) if M > 10**5: raise ValueError("Input too big") # Corresponds to n > 1.7e11 sq23pi = mpf_mul(mpf_sqrt(from_rational(2, 3, p), p), mpf_pi(p), p) sqrt8 = mpf_sqrt(from_int(8), p) for q in range(1, M): a = _a(n, q, p) d = _d(n, q, p, sq23pi, sqrt8) s = mpf_add(s, mpf_mul(a, d), prec) if verbose: print("step", q, "of", M, to_str(a, 10), to_str(d, 10)) # On average, the terms decrease rapidly in magnitude. # Dynamically reducing the precision greatly improves # performance. p = bitcount(abs(to_int(d))) + 50 return int(to_int(mpf_add(s, fhalf, prec))) __all__ = ['npartitions']
86a6c7ffcce2ef555311af87c8b7ea8b27e43a24eb852483532c8e2457d138d4
from math import factorial as _factorial, log, prod from itertools import chain, islice, product 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.core.random import _randrange, randrange, choice from sympy.core.symbol import Symbol from sympy.core.sympify import _sympify from sympy.functions.combinatorial.factorials import factorial from sympy.ntheory import primefactors, sieve from sympy.ntheory.factor_ import (factorint, multiplicity) from sympy.ntheory.primetest import isprime from sympy.utilities.iterables import has_variety, is_sequence, uniq 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, PermutationGroup >>> from sympy.combinatorics import Polyhedron 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, 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 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, PermutationGroup >>> a = Permutation([0, 2, 1]) >>> b = Permutation([1, 0, 2]) >>> G = PermutationGroup([a, b]) >>> G.abelian_invariants() [2] >>> from sympy.combinatorics 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(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, 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 = _factorial(n) 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, 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, 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 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 import Permutation, 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, 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, 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 import Permutation, 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, 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 import Permutation, 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 import Permutation, 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 m = prod([len(x) for x in self.basic_transversals]) self._order = m return m def index(self, H): """ Returns the index of a permutation group. Examples ======== >>> from sympy.combinatorics import Permutation, 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 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 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, \dots$ 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, 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 import Permutation, 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 does not belong to the orbit. For the algorithm and its correctness, see [2], pp.78-80. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> 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 does not 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 import Permutation, PermutationGroup >>> 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) 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 import free_group, Permutation, PermutationGroup >>> from sympy.combinatorics.homomorphisms import homomorphism >>> 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 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(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, PermutationGroup >>> from sympy.combinatorics.perm_groups import _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 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, 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
36674ec455782d9d560c300712388ab40f667cc5bc6e7a2319bebcb0001d9a2c
from collections import deque 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): 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'] for i, s in enumerate(word.letter_form_elm): next_state_name = current_state.transitions[s] 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
6a75cca1b52b4f7835f3d2784a2c185705eadf37366c80e2a7560131df7c9aa7
""" The Schur number S(k) is the largest integer n for which the interval [1,n] can be partitioned into k sum-free sets.(http://mathworld.wolfram.com/SchurNumber.html) """ import math from sympy.core import S from sympy.core.basic import Basic from sympy.core.function import Function from sympy.core.numbers import Integer class SchurNumber(Function): r""" This function creates a SchurNumber object which is evaluated for `k \le 5` otherwise only the lower bound information can be retrieved. Examples ======== >>> from sympy.combinatorics.schur_number import SchurNumber Since S(3) = 13, hence the output is a number >>> SchurNumber(3) 13 We do not know the Schur number for values greater than 5, hence only the object is returned >>> SchurNumber(6) SchurNumber(6) Now, the lower bound information can be retrieved using lower_bound() method >>> SchurNumber(6).lower_bound() 536 """ @classmethod def eval(cls, k): if k.is_Number: if k is S.Infinity: return S.Infinity if k.is_zero: return S.Zero if not k.is_integer or k.is_negative: raise ValueError("k should be a positive integer") first_known_schur_numbers = {1: 1, 2: 4, 3: 13, 4: 44, 5: 160} if k <= 5: return Integer(first_known_schur_numbers[k]) def lower_bound(self): f_ = self.args[0] # Improved lower bounds known for S(6) and S(7) if f_ == 6: return Integer(536) if f_ == 7: return Integer(1680) # For other cases, use general expression if f_.is_Integer: return 3*self.func(f_ - 1).lower_bound() - 1 return (3**f_ - 1)/2 def _schur_subsets_number(n): if n is S.Infinity: raise ValueError("Input must be finite") if n <= 0: raise ValueError("n must be a non-zero positive integer.") elif n <= 3: min_k = 1 else: min_k = math.ceil(math.log(2*n + 1, 3)) return Integer(min_k) def schur_partition(n): """ This function returns the partition in the minimum number of sum-free subsets according to the lower bound given by the Schur Number. Parameters ========== n: a number n is the upper limit of the range [1, n] for which we need to find and return the minimum number of free subsets according to the lower bound of schur number Returns ======= List of lists List of the minimum number of sum-free subsets Notes ===== It is possible for some n to make the partition into less subsets since the only known Schur numbers are: S(1) = 1, S(2) = 4, S(3) = 13, S(4) = 44. e.g for n = 44 the lower bound from the function above is 5 subsets but it has been proven that can be done with 4 subsets. Examples ======== For n = 1, 2, 3 the answer is the set itself >>> from sympy.combinatorics.schur_number import schur_partition >>> schur_partition(2) [[1, 2]] For n > 3, the answer is the minimum number of sum-free subsets: >>> schur_partition(5) [[3, 2], [5], [1, 4]] >>> schur_partition(8) [[3, 2], [6, 5, 8], [1, 4, 7]] """ if isinstance(n, Basic) and not n.is_Number: raise ValueError("Input value must be a number") number_of_subsets = _schur_subsets_number(n) if n == 1: sum_free_subsets = [[1]] elif n == 2: sum_free_subsets = [[1, 2]] elif n == 3: sum_free_subsets = [[1, 2, 3]] else: sum_free_subsets = [[1, 4], [2, 3]] while len(sum_free_subsets) < number_of_subsets: sum_free_subsets = _generate_next_list(sum_free_subsets, n) missed_elements = [3*k + 1 for k in range(len(sum_free_subsets), (n-1)//3 + 1)] sum_free_subsets[-1] += missed_elements return sum_free_subsets def _generate_next_list(current_list, n): new_list = [] for item in current_list: temp_1 = [number*3 for number in item if number*3 <= n] temp_2 = [number*3 - 1 for number in item if number*3 - 1 <= n] new_item = temp_1 + temp_2 new_list.append(new_item) last_list = [3*k + 1 for k in range(len(current_list)+1) if 3*k + 1 <= n] new_list.append(last_list) current_list = new_list return current_list
17c5eb502dc27fcb6431cb1d2c7c4ef784a16ee159778c6c50e6b44dfb3a8997
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 = [min(dx) if dx else None for dx in dummies] 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 base_i, gens_i, n_i, sym_i in v: # 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, (base_i, gens_i, n_i, sym_i) in enumerate(v): free_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
c856833c519ee58424b8f4e5875406e3885d828f612bfb540ed34b6a5b59a171
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 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 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 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 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 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 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 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 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 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 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(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 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
0373b9975b64166175984aa269bd3c781711ea501d8aa289dae3daa3751cbe59
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 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 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(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
6d9774a5c743ff5148e0770c5ae01bfd91f1c5bcb8b0beb4cffabd693d28a50f
"""Various algorithms for helping identifying numbers and sequences.""" from sympy.concrete.products import (Product, product) from sympy.core import Function, S from sympy.core.add import Add from sympy.core.numbers import Integer, Rational from sympy.core.symbol import Symbol, symbols from sympy.core.sympify import sympify from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.integers import floor from sympy.integrals.integrals import integrate from sympy.polys.polyfuncs import rational_interpolate as rinterp from sympy.polys.polytools import lcm from sympy.simplify.radsimp import denom from sympy.utilities import public @public def find_simple_recurrence_vector(l): """ This function is used internally by other functions from the sympy.concrete.guess module. While most users may want to rather use the function find_simple_recurrence when looking for recurrence relations among rational numbers, the current function may still be useful when some post-processing has to be done. Explanation =========== The function returns a vector of length n when a recurrence relation of order n is detected in the sequence of rational numbers v. If the returned vector has a length 1, then the returned value is always the list [0], which means that no relation has been found. While the functions is intended to be used with rational numbers, it should work for other kinds of real numbers except for some cases involving quadratic numbers; for that reason it should be used with some caution when the argument is not a list of rational numbers. Examples ======== >>> from sympy.concrete.guess import find_simple_recurrence_vector >>> from sympy import fibonacci >>> find_simple_recurrence_vector([fibonacci(k) for k in range(12)]) [1, -1, -1] See Also ======== See the function sympy.concrete.guess.find_simple_recurrence which is more user-friendly. """ q1 = [0] q2 = [1] b, z = 0, len(l) >> 1 while len(q2) <= z: while l[b]==0: b += 1 if b == len(l): c = 1 for x in q2: c = lcm(c, denom(x)) if q2[0]*c < 0: c = -c for k in range(len(q2)): q2[k] = int(q2[k]*c) return q2 a = S.One/l[b] m = [a] for k in range(b+1, len(l)): m.append(-sum(l[j+1]*m[b-j-1] for j in range(b, k))*a) l, m = m, [0] * max(len(q2), b+len(q1)) for k, q in enumerate(q2): m[k] = a*q for k, q in enumerate(q1): m[k+b] += q while m[-1]==0: m.pop() # because trailing zeros can occur q1, q2, b = q2, m, 1 return [0] @public def find_simple_recurrence(v, A=Function('a'), N=Symbol('n')): """ Detects and returns a recurrence relation from a sequence of several integer (or rational) terms. The name of the function in the returned expression is 'a' by default; the main variable is 'n' by default. The smallest index in the returned expression is always n (and never n-1, n-2, etc.). Examples ======== >>> from sympy.concrete.guess import find_simple_recurrence >>> from sympy import fibonacci >>> find_simple_recurrence([fibonacci(k) for k in range(12)]) -a(n) - a(n + 1) + a(n + 2) >>> from sympy import Function, Symbol >>> a = [1, 1, 1] >>> for k in range(15): a.append(5*a[-1]-3*a[-2]+8*a[-3]) >>> find_simple_recurrence(a, A=Function('f'), N=Symbol('i')) -8*f(i) + 3*f(i + 1) - 5*f(i + 2) + f(i + 3) """ p = find_simple_recurrence_vector(v) n = len(p) if n <= 1: return S.Zero return Add(*[A(N+n-1-k)*p[k] for k in range(n)]) @public def rationalize(x, maxcoeff=10000): """ Helps identifying a rational number from a float (or mpmath.mpf) value by using a continued fraction. The algorithm stops as soon as a large partial quotient is detected (greater than 10000 by default). Examples ======== >>> from sympy.concrete.guess import rationalize >>> from mpmath import cos, pi >>> rationalize(cos(pi/3)) 1/2 >>> from mpmath import mpf >>> rationalize(mpf("0.333333333333333")) 1/3 While the function is rather intended to help 'identifying' rational values, it may be used in some cases for approximating real numbers. (Though other functions may be more relevant in that case.) >>> rationalize(pi, maxcoeff = 250) 355/113 See Also ======== Several other methods can approximate a real number as a rational, like: * fractions.Fraction.from_decimal * fractions.Fraction.from_float * mpmath.identify * mpmath.pslq by using the following syntax: mpmath.pslq([x, 1]) * mpmath.findpoly by using the following syntax: mpmath.findpoly(x, 1) * sympy.simplify.nsimplify (which is a more general function) The main difference between the current function and all these variants is that control focuses on magnitude of partial quotients here rather than on global precision of the approximation. If the real is "known to be" a rational number, the current function should be able to detect it correctly with the default settings even when denominator is great (unless its expansion contains unusually big partial quotients) which may occur when studying sequences of increasing numbers. If the user cares more on getting simple fractions, other methods may be more convenient. """ p0, p1 = 0, 1 q0, q1 = 1, 0 a = floor(x) while a < maxcoeff or q1==0: p = a*p1 + p0 q = a*q1 + q0 p0, p1 = p1, p q0, q1 = q1, q if x==a: break x = 1/(x-a) a = floor(x) return sympify(p) / q @public def guess_generating_function_rational(v, X=Symbol('x')): """ Tries to "guess" a rational generating function for a sequence of rational numbers v. Examples ======== >>> from sympy.concrete.guess import guess_generating_function_rational >>> from sympy import fibonacci >>> l = [fibonacci(k) for k in range(5,15)] >>> guess_generating_function_rational(l) (3*x + 5)/(-x**2 - x + 1) See Also ======== sympy.series.approximants mpmath.pade """ # a) compute the denominator as q q = find_simple_recurrence_vector(v) n = len(q) if n <= 1: return None # b) compute the numerator as p p = [sum(v[i-k]*q[k] for k in range(min(i+1, n))) for i in range(len(v)>>1)] return (sum(p[k]*X**k for k in range(len(p))) / sum(q[k]*X**k for k in range(n))) @public def guess_generating_function(v, X=Symbol('x'), types=['all'], maxsqrtn=2): """ Tries to "guess" a generating function for a sequence of rational numbers v. Only a few patterns are implemented yet. Explanation =========== The function returns a dictionary where keys are the name of a given type of generating function. Six types are currently implemented: type | formal definition -------+---------------------------------------------------------------- ogf | f(x) = Sum( a_k * x^k , k: 0..infinity ) egf | f(x) = Sum( a_k * x^k / k! , k: 0..infinity ) lgf | f(x) = Sum( (-1)^(k+1) a_k * x^k / k , k: 1..infinity ) | (with initial index being hold as 1 rather than 0) hlgf | f(x) = Sum( a_k * x^k / k , k: 1..infinity ) | (with initial index being hold as 1 rather than 0) lgdogf | f(x) = derivate( log(Sum( a_k * x^k, k: 0..infinity )), x) lgdegf | f(x) = derivate( log(Sum( a_k * x^k / k!, k: 0..infinity )), x) In order to spare time, the user can select only some types of generating functions (default being ['all']). While forgetting to use a list in the case of a single type may seem to work most of the time as in: types='ogf' this (convenient) syntax may lead to unexpected extra results in some cases. Discarding a type when calling the function does not mean that the type will not be present in the returned dictionary; it only means that no extra computation will be performed for that type, but the function may still add it in the result when it can be easily converted from another type. Two generating functions (lgdogf and lgdegf) are not even computed if the initial term of the sequence is 0; it may be useful in that case to try again after having removed the leading zeros. Examples ======== >>> from sympy.concrete.guess import guess_generating_function as ggf >>> ggf([k+1 for k in range(12)], types=['ogf', 'lgf', 'hlgf']) {'hlgf': 1/(1 - x), 'lgf': 1/(x + 1), 'ogf': 1/(x**2 - 2*x + 1)} >>> from sympy import sympify >>> l = sympify("[3/2, 11/2, 0, -121/2, -363/2, 121]") >>> ggf(l) {'ogf': (x + 3/2)/(11*x**2 - 3*x + 1)} >>> from sympy import fibonacci >>> ggf([fibonacci(k) for k in range(5, 15)], types=['ogf']) {'ogf': (3*x + 5)/(-x**2 - x + 1)} >>> from sympy import factorial >>> ggf([factorial(k) for k in range(12)], types=['ogf', 'egf', 'lgf']) {'egf': 1/(1 - x)} >>> ggf([k+1 for k in range(12)], types=['egf']) {'egf': (x + 1)*exp(x), 'lgdegf': (x + 2)/(x + 1)} N-th root of a rational function can also be detected (below is an example coming from the sequence A108626 from http://oeis.org). The greatest n-th root to be tested is specified as maxsqrtn (default 2). >>> ggf([1, 2, 5, 14, 41, 124, 383, 1200, 3799, 12122, 38919])['ogf'] sqrt(1/(x**4 + 2*x**2 - 4*x + 1)) References ========== .. [1] "Concrete Mathematics", R.L. Graham, D.E. Knuth, O. Patashnik .. [2] https://oeis.org/wiki/Generating_functions """ # List of all types of all g.f. known by the algorithm if 'all' in types: types = ('ogf', 'egf', 'lgf', 'hlgf', 'lgdogf', 'lgdegf') result = {} # Ordinary Generating Function (ogf) if 'ogf' in types: # Perform some convolutions of the sequence with itself t = [1] + [0]*(len(v) - 1) for d in range(max(1, maxsqrtn)): t = [sum(t[n-i]*v[i] for i in range(n+1)) for n in range(len(v))] g = guess_generating_function_rational(t, X=X) if g: result['ogf'] = g**Rational(1, d+1) break # Exponential Generating Function (egf) if 'egf' in types: # Transform sequence (division by factorial) w, f = [], S.One for i, k in enumerate(v): f *= i if i else 1 w.append(k/f) # Perform some convolutions of the sequence with itself t = [1] + [0]*(len(w) - 1) for d in range(max(1, maxsqrtn)): t = [sum(t[n-i]*w[i] for i in range(n+1)) for n in range(len(w))] g = guess_generating_function_rational(t, X=X) if g: result['egf'] = g**Rational(1, d+1) break # Logarithmic Generating Function (lgf) if 'lgf' in types: # Transform sequence (multiplication by (-1)^(n+1) / n) w, f = [], S.NegativeOne for i, k in enumerate(v): f = -f w.append(f*k/Integer(i+1)) # Perform some convolutions of the sequence with itself t = [1] + [0]*(len(w) - 1) for d in range(max(1, maxsqrtn)): t = [sum(t[n-i]*w[i] for i in range(n+1)) for n in range(len(w))] g = guess_generating_function_rational(t, X=X) if g: result['lgf'] = g**Rational(1, d+1) break # Hyperbolic logarithmic Generating Function (hlgf) if 'hlgf' in types: # Transform sequence (division by n+1) w = [] for i, k in enumerate(v): w.append(k/Integer(i+1)) # Perform some convolutions of the sequence with itself t = [1] + [0]*(len(w) - 1) for d in range(max(1, maxsqrtn)): t = [sum(t[n-i]*w[i] for i in range(n+1)) for n in range(len(w))] g = guess_generating_function_rational(t, X=X) if g: result['hlgf'] = g**Rational(1, d+1) break # Logarithmic derivative of ordinary generating Function (lgdogf) if v[0] != 0 and ('lgdogf' in types or ('ogf' in types and 'ogf' not in result)): # Transform sequence by computing f'(x)/f(x) # because log(f(x)) = integrate( f'(x)/f(x) ) a, w = sympify(v[0]), [] for n in range(len(v)-1): w.append( (v[n+1]*(n+1) - sum(w[-i-1]*v[i+1] for i in range(n)))/a) # Perform some convolutions of the sequence with itself t = [1] + [0]*(len(w) - 1) for d in range(max(1, maxsqrtn)): t = [sum(t[n-i]*w[i] for i in range(n+1)) for n in range(len(w))] g = guess_generating_function_rational(t, X=X) if g: result['lgdogf'] = g**Rational(1, d+1) if 'ogf' not in result: result['ogf'] = exp(integrate(result['lgdogf'], X)) break # Logarithmic derivative of exponential generating Function (lgdegf) if v[0] != 0 and ('lgdegf' in types or ('egf' in types and 'egf' not in result)): # Transform sequence / step 1 (division by factorial) z, f = [], S.One for i, k in enumerate(v): f *= i if i else 1 z.append(k/f) # Transform sequence / step 2 by computing f'(x)/f(x) # because log(f(x)) = integrate( f'(x)/f(x) ) a, w = z[0], [] for n in range(len(z)-1): w.append( (z[n+1]*(n+1) - sum(w[-i-1]*z[i+1] for i in range(n)))/a) # Perform some convolutions of the sequence with itself t = [1] + [0]*(len(w) - 1) for d in range(max(1, maxsqrtn)): t = [sum(t[n-i]*w[i] for i in range(n+1)) for n in range(len(w))] g = guess_generating_function_rational(t, X=X) if g: result['lgdegf'] = g**Rational(1, d+1) if 'egf' not in result: result['egf'] = exp(integrate(result['lgdegf'], X)) break return result @public def guess(l, all=False, evaluate=True, niter=2, variables=None): """ This function is adapted from the Rate.m package for Mathematica written by Christian Krattenthaler. It tries to guess a formula from a given sequence of rational numbers. Explanation =========== In order to speed up the process, the 'all' variable is set to False by default, stopping the computation as some results are returned during an iteration; the variable can be set to True if more iterations are needed (other formulas may be found; however they may be equivalent to the first ones). Another option is the 'evaluate' variable (default is True); setting it to False will leave the involved products unevaluated. By default, the number of iterations is set to 2 but a greater value (up to len(l)-1) can be specified with the optional 'niter' variable. More and more convoluted results are found when the order of the iteration gets higher: * first iteration returns polynomial or rational functions; * second iteration returns products of rising factorials and their inverses; * third iteration returns products of products of rising factorials and their inverses; * etc. The returned formulas contain symbols i0, i1, i2, ... where the main variables is i0 (and auxiliary variables are i1, i2, ...). A list of other symbols can be provided in the 'variables' option; the length of the least should be the value of 'niter' (more is acceptable but only the first symbols will be used); in this case, the main variable will be the first symbol in the list. Examples ======== >>> from sympy.concrete.guess import guess >>> guess([1,2,6,24,120], evaluate=False) [Product(i1 + 1, (i1, 1, i0 - 1))] >>> from sympy import symbols >>> r = guess([1,2,7,42,429,7436,218348,10850216], niter=4) >>> i0 = symbols("i0") >>> [r[0].subs(i0,n).doit() for n in range(1,10)] [1, 2, 7, 42, 429, 7436, 218348, 10850216, 911835460] """ if any(a==0 for a in l[:-1]): return [] N = len(l) niter = min(N-1, niter) myprod = product if evaluate else Product g = [] res = [] if variables is None: symb = symbols('i:'+str(niter)) else: symb = variables for k, s in enumerate(symb): g.append(l) n, r = len(l), [] for i in range(n-2-1, -1, -1): ri = rinterp(enumerate(g[k][:-1], start=1), i, X=s) if ((denom(ri).subs({s:n}) != 0) and (ri.subs({s:n}) - g[k][-1] == 0) and ri not in r): r.append(ri) if r: for i in range(k-1, -1, -1): r = list(map(lambda v: g[i][0] * myprod(v, (symb[i+1], 1, symb[i]-1)), r)) if not all: return r res += r l = [Rational(l[i+1], l[i]) for i in range(N-k-1)] return res
7120291813699363b49cb86370fc26e7dd0ee6da36f15725ddf57223ffbbfb8b
from typing import Tuple as tTuple from sympy.calculus.singularities import is_decreasing from sympy.calculus.accumulationbounds import AccumulationBounds from .expr_with_intlimits import ExprWithIntLimits from .expr_with_limits import AddWithLimits from .gosper import gosper_sum from sympy.core.expr import Expr from sympy.core.add import Add from sympy.core.containers import Tuple from sympy.core.function import Derivative, expand from sympy.core.mul import Mul from sympy.core.numbers import Float, _illegal from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.sorting import ordered from sympy.core.symbol import Dummy, Wild, Symbol, symbols from sympy.functions.combinatorial.factorials import factorial from sympy.functions.combinatorial.numbers import bernoulli, harmonic from sympy.functions.elementary.exponential import exp, log from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import cot, csc from sympy.functions.special.hyper import hyper from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.functions.special.zeta_functions import zeta from sympy.integrals.integrals import Integral from sympy.logic.boolalg import And from sympy.polys.partfrac import apart from sympy.polys.polyerrors import PolynomialError, PolificationFailed from sympy.polys.polytools import parallel_poly_from_expr, Poly, factor from sympy.polys.rationaltools import together from sympy.series.limitseq import limit_seq from sympy.series.order import O from sympy.series.residues import residue from sympy.sets.sets import FiniteSet, Interval from sympy.utilities.iterables import sift import itertools class Sum(AddWithLimits, ExprWithIntLimits): r""" Represents unevaluated summation. Explanation =========== ``Sum`` represents a finite or infinite series, with the first argument being the general form of terms in the series, and the second argument being ``(dummy_variable, start, end)``, with ``dummy_variable`` taking all integer values from ``start`` through ``end``. In accordance with long-standing mathematical convention, the end term is included in the summation. Finite sums =========== For finite sums (and sums with symbolic limits assumed to be finite) we follow the summation convention described by Karr [1], especially definition 3 of section 1.4. The sum: .. math:: \sum_{m \leq i < n} f(i) has *the obvious meaning* for `m < n`, namely: .. math:: \sum_{m \leq i < n} f(i) = f(m) + f(m+1) + \ldots + f(n-2) + f(n-1) with the upper limit value `f(n)` excluded. The sum over an empty set is zero if and only if `m = n`: .. math:: \sum_{m \leq i < n} f(i) = 0 \quad \mathrm{for} \quad m = n Finally, for all other sums over empty sets we assume the following definition: .. math:: \sum_{m \leq i < n} f(i) = - \sum_{n \leq i < m} f(i) \quad \mathrm{for} \quad m > n It is important to note that Karr defines all sums with the upper limit being exclusive. This is in contrast to the usual mathematical notation, but does not affect the summation convention. Indeed we have: .. math:: \sum_{m \leq i < n} f(i) = \sum_{i = m}^{n - 1} f(i) where the difference in notation is intentional to emphasize the meaning, with limits typeset on the top being inclusive. Examples ======== >>> from sympy.abc import i, k, m, n, x >>> from sympy import Sum, factorial, oo, IndexedBase, Function >>> Sum(k, (k, 1, m)) Sum(k, (k, 1, m)) >>> Sum(k, (k, 1, m)).doit() m**2/2 + m/2 >>> Sum(k**2, (k, 1, m)) Sum(k**2, (k, 1, m)) >>> Sum(k**2, (k, 1, m)).doit() m**3/3 + m**2/2 + m/6 >>> Sum(x**k, (k, 0, oo)) Sum(x**k, (k, 0, oo)) >>> Sum(x**k, (k, 0, oo)).doit() Piecewise((1/(1 - x), Abs(x) < 1), (Sum(x**k, (k, 0, oo)), True)) >>> Sum(x**k/factorial(k), (k, 0, oo)).doit() exp(x) Here are examples to do summation with symbolic indices. You can use either Function of IndexedBase classes: >>> f = Function('f') >>> Sum(f(n), (n, 0, 3)).doit() f(0) + f(1) + f(2) + f(3) >>> Sum(f(n), (n, 0, oo)).doit() Sum(f(n), (n, 0, oo)) >>> f = IndexedBase('f') >>> Sum(f[n]**2, (n, 0, 3)).doit() f[0]**2 + f[1]**2 + f[2]**2 + f[3]**2 An example showing that the symbolic result of a summation is still valid for seemingly nonsensical values of the limits. Then the Karr convention allows us to give a perfectly valid interpretation to those sums by interchanging the limits according to the above rules: >>> S = Sum(i, (i, 1, n)).doit() >>> S n**2/2 + n/2 >>> S.subs(n, -4) 6 >>> Sum(i, (i, 1, -4)).doit() 6 >>> Sum(-i, (i, -3, 0)).doit() 6 An explicit example of the Karr summation convention: >>> S1 = Sum(i**2, (i, m, m+n-1)).doit() >>> S1 m**2*n + m*n**2 - m*n + n**3/3 - n**2/2 + n/6 >>> S2 = Sum(i**2, (i, m+n, m-1)).doit() >>> S2 -m**2*n - m*n**2 + m*n - n**3/3 + n**2/2 - n/6 >>> S1 + S2 0 >>> S3 = Sum(i, (i, m, m-1)).doit() >>> S3 0 See Also ======== summation Product, sympy.concrete.products.product References ========== .. [1] Michael Karr, "Summation in Finite Terms", Journal of the ACM, Volume 28 Issue 2, April 1981, Pages 305-350 http://dl.acm.org/citation.cfm?doid=322248.322255 .. [2] https://en.wikipedia.org/wiki/Summation#Capital-sigma_notation .. [3] https://en.wikipedia.org/wiki/Empty_sum """ __slots__ = () limits: tTuple[tTuple[Symbol, Expr, Expr]] def __new__(cls, function, *symbols, **assumptions): obj = AddWithLimits.__new__(cls, function, *symbols, **assumptions) if not hasattr(obj, 'limits'): return obj if any(len(l) != 3 or None in l for l in obj.limits): raise ValueError('Sum requires values for lower and upper bounds.') return obj def _eval_is_zero(self): # a Sum is only zero if its function is zero or if all terms # cancel out. This only answers whether the summand is zero; if # not then None is returned since we don't analyze whether all # terms cancel out. if self.function.is_zero or self.has_empty_sequence: return True def _eval_is_extended_real(self): if self.has_empty_sequence: return True return self.function.is_extended_real def _eval_is_positive(self): if self.has_finite_limits and self.has_reversed_limits is False: return self.function.is_positive def _eval_is_negative(self): if self.has_finite_limits and self.has_reversed_limits is False: return self.function.is_negative def _eval_is_finite(self): if self.has_finite_limits and self.function.is_finite: return True def doit(self, **hints): if hints.get('deep', True): f = self.function.doit(**hints) else: f = self.function # first make sure any definite limits have summation # variables with matching assumptions reps = {} for xab in self.limits: d = _dummy_with_inherited_properties_concrete(xab) if d: reps[xab[0]] = d if reps: undo = {v: k for k, v in reps.items()} did = self.xreplace(reps).doit(**hints) if isinstance(did, tuple): # when separate=True did = tuple([i.xreplace(undo) for i in did]) elif did is not None: did = did.xreplace(undo) else: did = self return did if self.function.is_Matrix: expanded = self.expand() if self != expanded: return expanded.doit() return _eval_matrix_sum(self) for n, limit in enumerate(self.limits): i, a, b = limit dif = b - a if dif == -1: # Any summation over an empty set is zero return S.Zero if dif.is_integer and dif.is_negative: a, b = b + 1, a - 1 f = -f newf = eval_sum(f, (i, a, b)) if newf is None: if f == self.function: zeta_function = self.eval_zeta_function(f, (i, a, b)) if zeta_function is not None: return zeta_function return self else: return self.func(f, *self.limits[n:]) f = newf if hints.get('deep', True): # eval_sum could return partially unevaluated # result with Piecewise. In this case we won't # doit() recursively. if not isinstance(f, Piecewise): return f.doit(**hints) return f def eval_zeta_function(self, f, limits): """ Check whether the function matches with the zeta function. If it matches, then return a `Piecewise` expression because zeta function does not converge unless `s > 1` and `q > 0` """ i, a, b = limits w, y, z = Wild('w', exclude=[i]), Wild('y', exclude=[i]), Wild('z', exclude=[i]) result = f.match((w * i + y) ** (-z)) if result is not None and b is S.Infinity: coeff = 1 / result[w] ** result[z] s = result[z] q = result[y] / result[w] + a return Piecewise((coeff * zeta(s, q), And(q > 0, s > 1)), (self, True)) def _eval_derivative(self, x): """ Differentiate wrt x as long as x is not in the free symbols of any of the upper or lower limits. Explanation =========== Sum(a*b*x, (x, 1, a)) can be differentiated wrt x or b but not `a` since the value of the sum is discontinuous in `a`. In a case involving a limit variable, the unevaluated derivative is returned. """ # diff already confirmed that x is in the free symbols of self, but we # don't want to differentiate wrt any free symbol in the upper or lower # limits # XXX remove this test for free_symbols when the default _eval_derivative is in if isinstance(x, Symbol) and x not in self.free_symbols: return S.Zero # get limits and the function f, limits = self.function, list(self.limits) limit = limits.pop(-1) if limits: # f is the argument to a Sum f = self.func(f, *limits) _, a, b = limit if x in a.free_symbols or x in b.free_symbols: return None df = Derivative(f, x, evaluate=True) rv = self.func(df, limit) return rv def _eval_difference_delta(self, n, step): k, _, upper = self.args[-1] new_upper = upper.subs(n, n + step) if len(self.args) == 2: f = self.args[0] else: f = self.func(*self.args[:-1]) return Sum(f, (k, upper + 1, new_upper)).doit() def _eval_simplify(self, **kwargs): # 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 from sympy.simplify.simplify import factor_sum, sum_combine result = Add(sum_combine(s_t), *o_t) return factor_sum(result, limits=self.limits) def is_convergent(self): r""" Checks for the convergence of a Sum. Explanation =========== We divide the study of convergence of infinite sums and products in two parts. First Part: One part is the question whether all the terms are well defined, i.e., they are finite in a sum and also non-zero in a product. Zero is the analogy of (minus) infinity in products as :math:`e^{-\infty} = 0`. Second Part: The second part is the question of convergence after infinities, and zeros in products, have been omitted assuming that their number is finite. This means that we only consider the tail of the sum or product, starting from some point after which all terms are well defined. For example, in a sum of the form: .. math:: \sum_{1 \leq i < \infty} \frac{1}{n^2 + an + b} where a and b are numbers. The routine will return true, even if there are infinities in the term sequence (at most two). An analogous product would be: .. math:: \prod_{1 \leq i < \infty} e^{\frac{1}{n^2 + an + b}} This is how convergence is interpreted. It is concerned with what happens at the limit. Finding the bad terms is another independent matter. Note: It is responsibility of user to see that the sum or product is well defined. There are various tests employed to check the convergence like divergence test, root test, integral test, alternating series test, comparison tests, Dirichlet tests. It returns true if Sum is convergent and false if divergent and NotImplementedError if it cannot be checked. References ========== .. [1] https://en.wikipedia.org/wiki/Convergence_tests Examples ======== >>> from sympy import factorial, S, Sum, Symbol, oo >>> n = Symbol('n', integer=True) >>> Sum(n/(n - 1), (n, 4, 7)).is_convergent() True >>> Sum(n/(2*n + 1), (n, 1, oo)).is_convergent() False >>> Sum(factorial(n)/5**n, (n, 1, oo)).is_convergent() False >>> Sum(1/n**(S(6)/5), (n, 1, oo)).is_convergent() True See Also ======== Sum.is_absolutely_convergent() sympy.concrete.products.Product.is_convergent() """ p, q, r = symbols('p q r', cls=Wild) sym = self.limits[0][0] lower_limit = self.limits[0][1] upper_limit = self.limits[0][2] sequence_term = self.function.simplify() if len(sequence_term.free_symbols) > 1: raise NotImplementedError("convergence checking for more than one symbol " "containing series is not handled") if lower_limit.is_finite and upper_limit.is_finite: return S.true # transform sym -> -sym and swap the upper_limit = S.Infinity # and lower_limit = - upper_limit if lower_limit is S.NegativeInfinity: if upper_limit is S.Infinity: return Sum(sequence_term, (sym, 0, S.Infinity)).is_convergent() and \ Sum(sequence_term, (sym, S.NegativeInfinity, 0)).is_convergent() from sympy.simplify.simplify import simplify sequence_term = simplify(sequence_term.xreplace({sym: -sym})) lower_limit = -upper_limit upper_limit = S.Infinity sym_ = Dummy(sym.name, integer=True, positive=True) sequence_term = sequence_term.xreplace({sym: sym_}) sym = sym_ interval = Interval(lower_limit, upper_limit) # Piecewise function handle if sequence_term.is_Piecewise: for func, cond in sequence_term.args: # see if it represents something going to oo if cond == True or cond.as_set().sup is S.Infinity: s = Sum(func, (sym, lower_limit, upper_limit)) return s.is_convergent() return S.true ### -------- Divergence test ----------- ### try: lim_val = limit_seq(sequence_term, sym) if lim_val is not None and lim_val.is_zero is False: return S.false except NotImplementedError: pass try: lim_val_abs = limit_seq(abs(sequence_term), sym) if lim_val_abs is not None and lim_val_abs.is_zero is False: return S.false except NotImplementedError: pass order = O(sequence_term, (sym, S.Infinity)) ### --------- p-series test (1/n**p) ---------- ### p_series_test = order.expr.match(sym**p) if p_series_test is not None: if p_series_test[p] < -1: return S.true if p_series_test[p] >= -1: return S.false ### ------------- comparison test ------------- ### # 1/(n**p*log(n)**q*log(log(n))**r) comparison n_log_test = (order.expr.match(1/(sym**p*log(1/sym)**q*log(-log(1/sym))**r)) or order.expr.match(1/(sym**p*(-log(1/sym))**q*log(-log(1/sym))**r))) if n_log_test is not None: if (n_log_test[p] > 1 or (n_log_test[p] == 1 and n_log_test[q] > 1) or (n_log_test[p] == n_log_test[q] == 1 and n_log_test[r] > 1)): return S.true return S.false ### ------------- Limit comparison test -----------### # (1/n) comparison try: lim_comp = limit_seq(sym*sequence_term, sym) if lim_comp is not None and lim_comp.is_number and lim_comp > 0: return S.false except NotImplementedError: pass ### ----------- ratio test ---------------- ### next_sequence_term = sequence_term.xreplace({sym: sym + 1}) from sympy.simplify.combsimp import combsimp from sympy.simplify.powsimp import powsimp ratio = combsimp(powsimp(next_sequence_term/sequence_term)) try: lim_ratio = limit_seq(ratio, sym) if lim_ratio is not None and lim_ratio.is_number: if abs(lim_ratio) > 1: return S.false if abs(lim_ratio) < 1: return S.true except NotImplementedError: lim_ratio = None ### ---------- Raabe's test -------------- ### if lim_ratio == 1: # ratio test inconclusive test_val = sym*(sequence_term/ sequence_term.subs(sym, sym + 1) - 1) test_val = test_val.gammasimp() try: lim_val = limit_seq(test_val, sym) if lim_val is not None and lim_val.is_number: if lim_val > 1: return S.true if lim_val < 1: return S.false except NotImplementedError: pass ### ----------- root test ---------------- ### # lim = Limit(abs(sequence_term)**(1/sym), sym, S.Infinity) try: lim_evaluated = limit_seq(abs(sequence_term)**(1/sym), sym) if lim_evaluated is not None and lim_evaluated.is_number: if lim_evaluated < 1: return S.true if lim_evaluated > 1: return S.false except NotImplementedError: pass ### ------------- alternating series test ----------- ### dict_val = sequence_term.match(S.NegativeOne**(sym + p)*q) if not dict_val[p].has(sym) and is_decreasing(dict_val[q], interval): return S.true ### ------------- integral test -------------- ### check_interval = None from sympy.solvers.solveset import solveset maxima = solveset(sequence_term.diff(sym), sym, interval) if not maxima: check_interval = interval elif isinstance(maxima, FiniteSet) and maxima.sup.is_number: check_interval = Interval(maxima.sup, interval.sup) if (check_interval is not None and (is_decreasing(sequence_term, check_interval) or is_decreasing(-sequence_term, check_interval))): integral_val = Integral( sequence_term, (sym, lower_limit, upper_limit)) try: integral_val_evaluated = integral_val.doit() if integral_val_evaluated.is_number: return S(integral_val_evaluated.is_finite) except NotImplementedError: pass ### ----- Dirichlet and bounded times convergent tests ----- ### # TODO # # Dirichlet_test # https://en.wikipedia.org/wiki/Dirichlet%27s_test # # Bounded times convergent test # It is based on comparison theorems for series. # In particular, if the general term of a series can # be written as a product of two terms a_n and b_n # and if a_n is bounded and if Sum(b_n) is absolutely # convergent, then the original series Sum(a_n * b_n) # is absolutely convergent and so convergent. # # The following code can grows like 2**n where n is the # number of args in order.expr # Possibly combined with the potentially slow checks # inside the loop, could make this test extremely slow # for larger summation expressions. if order.expr.is_Mul: args = order.expr.args argset = set(args) ### -------------- Dirichlet tests -------------- ### m = Dummy('m', integer=True) def _dirichlet_test(g_n): try: ing_val = limit_seq(Sum(g_n, (sym, interval.inf, m)).doit(), m) if ing_val is not None and ing_val.is_finite: return S.true except NotImplementedError: pass ### -------- bounded times convergent test ---------### def _bounded_convergent_test(g1_n, g2_n): try: lim_val = limit_seq(g1_n, sym) if lim_val is not None and (lim_val.is_finite or ( isinstance(lim_val, AccumulationBounds) and (lim_val.max - lim_val.min).is_finite)): if Sum(g2_n, (sym, lower_limit, upper_limit)).is_absolutely_convergent(): return S.true except NotImplementedError: pass for n in range(1, len(argset)): for a_tuple in itertools.combinations(args, n): b_set = argset - set(a_tuple) a_n = Mul(*a_tuple) b_n = Mul(*b_set) if is_decreasing(a_n, interval): dirich = _dirichlet_test(b_n) if dirich is not None: return dirich bc_test = _bounded_convergent_test(a_n, b_n) if bc_test is not None: return bc_test _sym = self.limits[0][0] sequence_term = sequence_term.xreplace({sym: _sym}) raise NotImplementedError("The algorithm to find the Sum convergence of %s " "is not yet implemented" % (sequence_term)) def is_absolutely_convergent(self): """ Checks for the absolute convergence of an infinite series. Same as checking convergence of absolute value of sequence_term of an infinite series. References ========== .. [1] https://en.wikipedia.org/wiki/Absolute_convergence Examples ======== >>> from sympy import Sum, Symbol, oo >>> n = Symbol('n', integer=True) >>> Sum((-1)**n, (n, 1, oo)).is_absolutely_convergent() False >>> Sum((-1)**n/n**2, (n, 1, oo)).is_absolutely_convergent() True See Also ======== Sum.is_convergent() """ return Sum(abs(self.function), self.limits).is_convergent() def euler_maclaurin(self, m=0, n=0, eps=0, eval_integral=True): """ Return an Euler-Maclaurin approximation of self, where m is the number of leading terms to sum directly and n is the number of terms in the tail. With m = n = 0, this is simply the corresponding integral plus a first-order endpoint correction. Returns (s, e) where s is the Euler-Maclaurin approximation and e is the estimated error (taken to be the magnitude of the first omitted term in the tail): >>> from sympy.abc import k, a, b >>> from sympy import Sum >>> Sum(1/k, (k, 2, 5)).doit().evalf() 1.28333333333333 >>> s, e = Sum(1/k, (k, 2, 5)).euler_maclaurin() >>> s -log(2) + 7/20 + log(5) >>> from sympy import sstr >>> print(sstr((s.evalf(), e.evalf()), full_prec=True)) (1.26629073187415, 0.0175000000000000) The endpoints may be symbolic: >>> s, e = Sum(1/k, (k, a, b)).euler_maclaurin() >>> s -log(a) + log(b) + 1/(2*b) + 1/(2*a) >>> e Abs(1/(12*b**2) - 1/(12*a**2)) If the function is a polynomial of degree at most 2n+1, the Euler-Maclaurin formula becomes exact (and e = 0 is returned): >>> Sum(k, (k, 2, b)).euler_maclaurin() (b**2/2 + b/2 - 1, 0) >>> Sum(k, (k, 2, b)).doit() b**2/2 + b/2 - 1 With a nonzero eps specified, the summation is ended as soon as the remainder term is less than the epsilon. """ m = int(m) n = int(n) f = self.function if len(self.limits) != 1: raise ValueError("More than 1 limit") i, a, b = self.limits[0] if (a > b) == True: if a - b == 1: return S.Zero, S.Zero a, b = b + 1, a - 1 f = -f s = S.Zero if m: if b.is_Integer and a.is_Integer: m = min(m, b - a + 1) if not eps or f.is_polynomial(i): s = Add(*[f.subs(i, a + k) for k in range(m)]) else: term = f.subs(i, a) if term: test = abs(term.evalf(3)) < eps if test == True: return s, abs(term) elif not (test == False): # a symbolic Relational class, can't go further return term, S.Zero s = term for k in range(1, m): term = f.subs(i, a + k) if abs(term.evalf(3)) < eps and term != 0: return s, abs(term) s += term if b - a + 1 == m: return s, S.Zero a += m x = Dummy('x') I = Integral(f.subs(i, x), (x, a, b)) if eval_integral: I = I.doit() s += I def fpoint(expr): if b is S.Infinity: return expr.subs(i, a), 0 return expr.subs(i, a), expr.subs(i, b) fa, fb = fpoint(f) iterm = (fa + fb)/2 g = f.diff(i) for k in range(1, n + 2): ga, gb = fpoint(g) term = bernoulli(2*k)/factorial(2*k)*(gb - ga) if k > n: break if eps and term: term_evalf = term.evalf(3) if term_evalf is S.NaN: return S.NaN, S.NaN if abs(term_evalf) < eps: break s += term g = g.diff(i, 2, simplify=False) return s + iterm, abs(term) def reverse_order(self, *indices): """ Reverse the order of a limit in a Sum. Explanation =========== ``reverse_order(self, *indices)`` reverses some limits in the expression ``self`` which can be either a ``Sum`` or a ``Product``. The selectors in the argument ``indices`` specify some indices whose limits get reversed. These selectors are either variable names or numerical indices counted starting from the inner-most limit tuple. Examples ======== >>> from sympy import Sum >>> from sympy.abc import x, y, a, b, c, d >>> Sum(x, (x, 0, 3)).reverse_order(x) Sum(-x, (x, 4, -1)) >>> Sum(x*y, (x, 1, 5), (y, 0, 6)).reverse_order(x, y) Sum(x*y, (x, 6, 0), (y, 7, -1)) >>> Sum(x, (x, a, b)).reverse_order(x) Sum(-x, (x, b + 1, a - 1)) >>> Sum(x, (x, a, b)).reverse_order(0) Sum(-x, (x, b + 1, a - 1)) While one should prefer variable names when specifying which limits to reverse, the index counting notation comes in handy in case there are several symbols with the same name. >>> S = Sum(x**2, (x, a, b), (x, c, d)) >>> S Sum(x**2, (x, a, b), (x, c, d)) >>> S0 = S.reverse_order(0) >>> S0 Sum(-x**2, (x, b + 1, a - 1), (x, c, d)) >>> S1 = S0.reverse_order(1) >>> S1 Sum(x**2, (x, b + 1, a - 1), (x, d + 1, c - 1)) Of course we can mix both notations: >>> Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(x, 1) Sum(x*y, (x, b + 1, a - 1), (y, 6, 1)) >>> Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(y, x) Sum(x*y, (x, b + 1, a - 1), (y, 6, 1)) See Also ======== sympy.concrete.expr_with_intlimits.ExprWithIntLimits.index, reorder_limit, sympy.concrete.expr_with_intlimits.ExprWithIntLimits.reorder References ========== .. [1] Michael Karr, "Summation in Finite Terms", Journal of the ACM, Volume 28 Issue 2, April 1981, Pages 305-350 http://dl.acm.org/citation.cfm?doid=322248.322255 """ l_indices = list(indices) for i, indx in enumerate(l_indices): if not isinstance(indx, int): l_indices[i] = self.index(indx) e = 1 limits = [] for i, limit in enumerate(self.limits): l = limit if i in l_indices: e = -e l = (limit[0], limit[2] + 1, limit[1] - 1) limits.append(l) return Sum(e * self.function, *limits) def _eval_rewrite_as_Product(self, *args, **kwargs): from sympy.concrete.products import Product if self.function.is_extended_real: return log(Product(exp(self.function), *self.limits)) def summation(f, *symbols, **kwargs): r""" Compute the summation of f with respect to symbols. Explanation =========== The notation for symbols is similar to the notation used in Integral. summation(f, (i, a, b)) computes the sum of f with respect to i from a to b, i.e., :: b ____ \ ` summation(f, (i, a, b)) = ) f /___, i = a If it cannot compute the sum, it returns an unevaluated Sum object. Repeated sums can be computed by introducing additional symbols tuples:: Examples ======== >>> from sympy import summation, oo, symbols, log >>> i, n, m = symbols('i n m', integer=True) >>> summation(2*i - 1, (i, 1, n)) n**2 >>> summation(1/2**i, (i, 0, oo)) 2 >>> summation(1/log(n)**n, (n, 2, oo)) Sum(log(n)**(-n), (n, 2, oo)) >>> summation(i, (i, 0, n), (n, 0, m)) m**3/6 + m**2/2 + m/3 >>> from sympy.abc import x >>> from sympy import factorial >>> summation(x**n/factorial(n), (n, 0, oo)) exp(x) See Also ======== Sum Product, sympy.concrete.products.product """ return Sum(f, *symbols, **kwargs).doit(deep=False) def telescopic_direct(L, R, n, limits): """ Returns the direct summation of the terms of a telescopic sum Explanation =========== L is the term with lower index R is the term with higher index n difference between the indexes of L and R Examples ======== >>> from sympy.concrete.summations import telescopic_direct >>> from sympy.abc import k, a, b >>> telescopic_direct(1/k, -1/(k+2), 2, (k, a, b)) -1/(b + 2) - 1/(b + 1) + 1/(a + 1) + 1/a """ (i, a, b) = limits return Add(*[L.subs(i, a + m) + R.subs(i, b - m) for m in range(n)]) def telescopic(L, R, limits): ''' Tries to perform the summation using the telescopic property. Return None if not possible. ''' (i, a, b) = limits if L.is_Add or R.is_Add: return None # We want to solve(L.subs(i, i + m) + R, m) # First we try a simple match since this does things that # solve doesn't do, e.g. solve(cos(k+m)-cos(k), m) gives # a more complicated solution than m == 0. k = Wild("k") sol = (-R).match(L.subs(i, i + k)) s = None if sol and k in sol: s = sol[k] if not (s.is_Integer and L.subs(i, i + s) + R == 0): # invalid match or match didn't work s = None # But there are things that match doesn't do that solve # can do, e.g. determine that 1/(x + m) = 1/(1 - x) when m = 1 if s is None: m = Dummy('m') try: from sympy.solvers.solvers import solve sol = solve(L.subs(i, i + m) + R, m) or [] except NotImplementedError: return None sol = [si for si in sol if si.is_Integer and (L.subs(i, i + si) + R).expand().is_zero] if len(sol) != 1: return None s = sol[0] if s < 0: return telescopic_direct(R, L, abs(s), (i, a, b)) elif s > 0: return telescopic_direct(L, R, s, (i, a, b)) def eval_sum(f, limits): (i, a, b) = limits if f.is_zero: return S.Zero if i not in f.free_symbols: return f*(b - a + 1) if a == b: return f.subs(i, a) if isinstance(f, Piecewise): if not any(i in arg.args[1].free_symbols for arg in f.args): # Piecewise conditions do not depend on the dummy summation variable, # therefore we can fold: Sum(Piecewise((e, c), ...), limits) # --> Piecewise((Sum(e, limits), c), ...) newargs = [] for arg in f.args: newexpr = eval_sum(arg.expr, limits) if newexpr is None: return None newargs.append((newexpr, arg.cond)) return f.func(*newargs) if f.has(KroneckerDelta): from .delta import deltasummation, _has_simple_delta f = f.replace( lambda x: isinstance(x, Sum), lambda x: x.factor() ) if _has_simple_delta(f, limits[0]): return deltasummation(f, limits) dif = b - a definite = dif.is_Integer # Doing it directly may be faster if there are very few terms. if definite and (dif < 100): return eval_sum_direct(f, (i, a, b)) if isinstance(f, Piecewise): return None # Try to do it symbolically. Even when the number of terms is # known, this can save time when b-a is big. value = eval_sum_symbolic(f.expand(), (i, a, b)) if value is not None: return value # Do it directly if definite: return eval_sum_direct(f, (i, a, b)) def eval_sum_direct(expr, limits): """ Evaluate expression directly, but perform some simple checks first to possibly result in a smaller expression and faster execution. """ (i, a, b) = limits dif = b - a # Linearity if expr.is_Mul: # Try factor out everything not including i without_i, with_i = expr.as_independent(i) if without_i != 1: s = eval_sum_direct(with_i, (i, a, b)) if s: r = without_i*s if r is not S.NaN: return r else: # Try term by term L, R = expr.as_two_terms() if not L.has(i): sR = eval_sum_direct(R, (i, a, b)) if sR: return L*sR if not R.has(i): sL = eval_sum_direct(L, (i, a, b)) if sL: return sL*R # do this whether its an Add or Mul # e.g. apart(1/(25*i**2 + 45*i + 14)) and # apart(1/((5*i + 2)*(5*i + 7))) -> # -1/(5*(5*i + 7)) + 1/(5*(5*i + 2)) try: expr = apart(expr, i) # see if it becomes an Add except PolynomialError: pass if expr.is_Add: # Try factor out everything not including i without_i, with_i = expr.as_independent(i) if without_i != 0: s = eval_sum_direct(with_i, (i, a, b)) if s: r = without_i*(dif + 1) + s if r is not S.NaN: return r else: # Try term by term L, R = expr.as_two_terms() lsum = eval_sum_direct(L, (i, a, b)) rsum = eval_sum_direct(R, (i, a, b)) if None not in (lsum, rsum): r = lsum + rsum if r is not S.NaN: return r return Add(*[expr.subs(i, a + j) for j in range(dif + 1)]) def eval_sum_symbolic(f, limits): f_orig = f (i, a, b) = limits if not f.has(i): return f*(b - a + 1) # Linearity if f.is_Mul: # Try factor out everything not including i without_i, with_i = f.as_independent(i) if without_i != 1: s = eval_sum_symbolic(with_i, (i, a, b)) if s: r = without_i*s if r is not S.NaN: return r else: # Try term by term L, R = f.as_two_terms() if not L.has(i): sR = eval_sum_symbolic(R, (i, a, b)) if sR: return L*sR if not R.has(i): sL = eval_sum_symbolic(L, (i, a, b)) if sL: return sL*R # do this whether its an Add or Mul # e.g. apart(1/(25*i**2 + 45*i + 14)) and # apart(1/((5*i + 2)*(5*i + 7))) -> # -1/(5*(5*i + 7)) + 1/(5*(5*i + 2)) try: f = apart(f, i) except PolynomialError: pass if f.is_Add: L, R = f.as_two_terms() lrsum = telescopic(L, R, (i, a, b)) if lrsum: return lrsum # Try factor out everything not including i without_i, with_i = f.as_independent(i) if without_i != 0: s = eval_sum_symbolic(with_i, (i, a, b)) if s: r = without_i*(b - a + 1) + s if r is not S.NaN: return r else: # Try term by term lsum = eval_sum_symbolic(L, (i, a, b)) rsum = eval_sum_symbolic(R, (i, a, b)) if None not in (lsum, rsum): r = lsum + rsum if r is not S.NaN: return r # Polynomial terms with Faulhaber's formula n = Wild('n') result = f.match(i**n) if result is not None: n = result[n] if n.is_Integer: if n >= 0: if (b is S.Infinity and a is not S.NegativeInfinity) or \ (a is S.NegativeInfinity and b is not S.Infinity): return S.Infinity return ((bernoulli(n + 1, b + 1) - bernoulli(n + 1, a))/(n + 1)).expand() elif a.is_Integer and a >= 1: if n == -1: return harmonic(b) - harmonic(a - 1) else: return harmonic(b, abs(n)) - harmonic(a - 1, abs(n)) if not (a.has(S.Infinity, S.NegativeInfinity) or b.has(S.Infinity, S.NegativeInfinity)): # Geometric terms c1 = Wild('c1', exclude=[i]) c2 = Wild('c2', exclude=[i]) c3 = Wild('c3', exclude=[i]) wexp = Wild('wexp') # Here we first attempt powsimp on f for easier matching with the # exponential pattern, and attempt expansion on the exponent for easier # matching with the linear pattern. e = f.powsimp().match(c1 ** wexp) if e is not None: e_exp = e.pop(wexp).expand().match(c2*i + c3) if e_exp is not None: e.update(e_exp) p = (c1**c3).subs(e) q = (c1**c2).subs(e) r = p*(q**a - q**(b + 1))/(1 - q) l = p*(b - a + 1) return Piecewise((l, Eq(q, S.One)), (r, True)) r = gosper_sum(f, (i, a, b)) if isinstance(r, (Mul,Add)): from sympy.simplify.radsimp import denom from sympy.solvers.solvers import solve non_limit = r.free_symbols - Tuple(*limits[1:]).free_symbols den = denom(together(r)) den_sym = non_limit & den.free_symbols args = [] for v in ordered(den_sym): try: s = solve(den, v) m = Eq(v, s[0]) if s else S.false if m != False: args.append((Sum(f_orig.subs(*m.args), limits).doit(), m)) break except NotImplementedError: continue args.append((r, True)) return Piecewise(*args) if r not in (None, S.NaN): return r h = eval_sum_hyper(f_orig, (i, a, b)) if h is not None: return h r = eval_sum_residue(f_orig, (i, a, b)) if r is not None: return r factored = f_orig.factor() if factored != f_orig: return eval_sum_symbolic(factored, (i, a, b)) def _eval_sum_hyper(f, i, a): """ Returns (res, cond). Sums from a to oo. """ if a != 0: return _eval_sum_hyper(f.subs(i, i + a), i, 0) if f.subs(i, 0) == 0: from sympy.simplify.simplify import simplify if simplify(f.subs(i, Dummy('i', integer=True, positive=True))) == 0: return S.Zero, True return _eval_sum_hyper(f.subs(i, i + 1), i, 0) from sympy.simplify.simplify import hypersimp hs = hypersimp(f, i) if hs is None: return None if isinstance(hs, Float): from sympy.simplify.simplify import nsimplify hs = nsimplify(hs) from sympy.simplify.combsimp import combsimp from sympy.simplify.hyperexpand import hyperexpand from sympy.simplify.radsimp import fraction numer, denom = fraction(factor(hs)) top, topl = numer.as_coeff_mul(i) bot, botl = denom.as_coeff_mul(i) ab = [top, bot] factors = [topl, botl] params = [[], []] for k in range(2): for fac in factors[k]: mul = 1 if fac.is_Pow: mul = fac.exp fac = fac.base if not mul.is_Integer: return None p = Poly(fac, i) if p.degree() != 1: return None m, n = p.all_coeffs() ab[k] *= m**mul params[k] += [n/m]*mul # Add "1" to numerator parameters, to account for implicit n! in # hypergeometric series. ap = params[0] + [1] bq = params[1] x = ab[0]/ab[1] h = hyper(ap, bq, x) f = combsimp(f) return f.subs(i, 0)*hyperexpand(h), h.convergence_statement def eval_sum_hyper(f, i_a_b): i, a, b = i_a_b if f.is_hypergeometric(i) is False: return if (b - a).is_Integer: # We are never going to do better than doing the sum in the obvious way return None old_sum = Sum(f, (i, a, b)) if b != S.Infinity: if a is S.NegativeInfinity: res = _eval_sum_hyper(f.subs(i, -i), i, -b) if res is not None: return Piecewise(res, (old_sum, True)) else: n_illegal = lambda x: sum(x.count(_) for _ in _illegal) had = n_illegal(f) # check that no extra illegals are introduced res1 = _eval_sum_hyper(f, i, a) if res1 is None or n_illegal(res1) > had: return res2 = _eval_sum_hyper(f, i, b + 1) if res2 is None or n_illegal(res2) > had: return (res1, cond1), (res2, cond2) = res1, res2 cond = And(cond1, cond2) if cond == False: return None return Piecewise((res1 - res2, cond), (old_sum, True)) if a is S.NegativeInfinity: res1 = _eval_sum_hyper(f.subs(i, -i), i, 1) res2 = _eval_sum_hyper(f, i, 0) if res1 is None or res2 is None: return None res1, cond1 = res1 res2, cond2 = res2 cond = And(cond1, cond2) if cond == False or cond.as_set() == S.EmptySet: return None return Piecewise((res1 + res2, cond), (old_sum, True)) # Now b == oo, a != -oo res = _eval_sum_hyper(f, i, a) if res is not None: r, c = res if c == False: if r.is_number: f = f.subs(i, Dummy('i', integer=True, positive=True) + a) if f.is_positive or f.is_zero: return S.Infinity elif f.is_negative: return S.NegativeInfinity return None return Piecewise(res, (old_sum, True)) def eval_sum_residue(f, i_a_b): r"""Compute the infinite summation with residues Notes ===== If $f(n), g(n)$ are polynomials with $\deg(g(n)) - \deg(f(n)) \ge 2$, some infinite summations can be computed by the following residue evaluations. .. math:: \sum_{n=-\infty, g(n) \ne 0}^{\infty} \frac{f(n)}{g(n)} = -\pi \sum_{\alpha|g(\alpha)=0} \text{Res}(\cot(\pi x) \frac{f(x)}{g(x)}, \alpha) .. math:: \sum_{n=-\infty, g(n) \ne 0}^{\infty} (-1)^n \frac{f(n)}{g(n)} = -\pi \sum_{\alpha|g(\alpha)=0} \text{Res}(\csc(\pi x) \frac{f(x)}{g(x)}, \alpha) Examples ======== >>> from sympy import Sum, oo, Symbol >>> x = Symbol('x') Doubly infinite series of rational functions. >>> Sum(1 / (x**2 + 1), (x, -oo, oo)).doit() pi/tanh(pi) Doubly infinite alternating series of rational functions. >>> Sum((-1)**x / (x**2 + 1), (x, -oo, oo)).doit() pi/sinh(pi) Infinite series of even rational functions. >>> Sum(1 / (x**2 + 1), (x, 0, oo)).doit() 1/2 + pi/(2*tanh(pi)) Infinite series of alternating even rational functions. >>> Sum((-1)**x / (x**2 + 1), (x, 0, oo)).doit() pi/(2*sinh(pi)) + 1/2 This also have heuristics to transform arbitrarily shifted summand or arbitrarily shifted summation range to the canonical problem the formula can handle. >>> Sum(1 / (x**2 + 2*x + 2), (x, -1, oo)).doit() 1/2 + pi/(2*tanh(pi)) >>> Sum(1 / (x**2 + 4*x + 5), (x, -2, oo)).doit() 1/2 + pi/(2*tanh(pi)) >>> Sum(1 / (x**2 + 1), (x, 1, oo)).doit() -1/2 + pi/(2*tanh(pi)) >>> Sum(1 / (x**2 + 1), (x, 2, oo)).doit() -1 + pi/(2*tanh(pi)) References ========== .. [#] http://www.supermath.info/InfiniteSeriesandtheResidueTheorem.pdf .. [#] Asmar N.H., Grafakos L. (2018) Residue Theory. In: Complex Analysis with Applications. Undergraduate Texts in Mathematics. Springer, Cham. https://doi.org/10.1007/978-3-319-94063-2_5 """ i, a, b = i_a_b def is_even_function(numer, denom): """Test if the rational function is an even function""" numer_even = all(i % 2 == 0 for (i,) in numer.monoms()) denom_even = all(i % 2 == 0 for (i,) in denom.monoms()) numer_odd = all(i % 2 == 1 for (i,) in numer.monoms()) denom_odd = all(i % 2 == 1 for (i,) in denom.monoms()) return (numer_even and denom_even) or (numer_odd and denom_odd) def match_rational(f, i): numer, denom = f.as_numer_denom() try: (numer, denom), opt = parallel_poly_from_expr((numer, denom), i) except (PolificationFailed, PolynomialError): return None return numer, denom def get_poles(denom): roots = denom.sqf_part().all_roots() roots = sift(roots, lambda x: x.is_integer) if None in roots: return None int_roots, nonint_roots = roots[True], roots[False] return int_roots, nonint_roots def get_shift(denom): n = denom.degree(i) a = denom.coeff_monomial(i**n) b = denom.coeff_monomial(i**(n-1)) shift = - b / a / n return shift #Need a dummy symbol with no assumptions set for get_residue_factor z = Dummy('z') def get_residue_factor(numer, denom, alternating): residue_factor = (numer.as_expr() / denom.as_expr()).subs(i, z) if not alternating: residue_factor *= cot(S.Pi * z) else: residue_factor *= csc(S.Pi * z) return residue_factor # We don't know how to deal with symbolic constants in summand if f.free_symbols - set([i]): return None if not (a.is_Integer or a in (S.Infinity, S.NegativeInfinity)): return None if not (b.is_Integer or b in (S.Infinity, S.NegativeInfinity)): return None # Quick exit heuristic for the sums which doesn't have infinite range if a != S.NegativeInfinity and b != S.Infinity: return None match = match_rational(f, i) if match: alternating = False numer, denom = match else: match = match_rational(f / S.NegativeOne**i, i) if match: alternating = True numer, denom = match else: return None if denom.degree(i) - numer.degree(i) < 2: return None if (a, b) == (S.NegativeInfinity, S.Infinity): poles = get_poles(denom) if poles is None: return None int_roots, nonint_roots = poles if int_roots: return None residue_factor = get_residue_factor(numer, denom, alternating) residues = [residue(residue_factor, z, root) for root in nonint_roots] return -S.Pi * sum(residues) if not (a.is_finite and b is S.Infinity): return None if not is_even_function(numer, denom): # Try shifting summation and check if the summand can be made # and even function from the origin. # Sum(f(n), (n, a, b)) => Sum(f(n + s), (n, a - s, b - s)) shift = get_shift(denom) if not shift.is_Integer: return None if shift == 0: return None numer = numer.shift(shift) denom = denom.shift(shift) if not is_even_function(numer, denom): return None if alternating: f = S.NegativeOne**i * (S.NegativeOne**shift * numer.as_expr() / denom.as_expr()) else: f = numer.as_expr() / denom.as_expr() return eval_sum_residue(f, (i, a-shift, b-shift)) poles = get_poles(denom) if poles is None: return None int_roots, nonint_roots = poles if int_roots: int_roots = [int(root) for root in int_roots] int_roots_max = max(int_roots) int_roots_min = min(int_roots) # Integer valued poles must be next to each other # and also symmetric from origin (Because the function is even) if not len(int_roots) == int_roots_max - int_roots_min + 1: return None # Check whether the summation indices contain poles if a <= max(int_roots): return None residue_factor = get_residue_factor(numer, denom, alternating) residues = [residue(residue_factor, z, root) for root in int_roots + nonint_roots] full_sum = -S.Pi * sum(residues) if not int_roots: # Compute Sum(f, (i, 0, oo)) by adding a extraneous evaluation # at the origin. half_sum = (full_sum + f.xreplace({i: 0})) / 2 # Add and subtract extraneous evaluations extraneous_neg = [f.xreplace({i: i0}) for i0 in range(int(a), 0)] extraneous_pos = [f.xreplace({i: i0}) for i0 in range(0, int(a))] result = half_sum + sum(extraneous_neg) - sum(extraneous_pos) return result # Compute Sum(f, (i, min(poles) + 1, oo)) half_sum = full_sum / 2 # Subtract extraneous evaluations extraneous = [f.xreplace({i: i0}) for i0 in range(max(int_roots) + 1, int(a))] result = half_sum - sum(extraneous) return result def _eval_matrix_sum(expression): f = expression.function for n, limit in enumerate(expression.limits): i, a, b = limit dif = b - a if dif.is_Integer: if (dif < 0) == True: a, b = b + 1, a - 1 f = -f newf = eval_sum_direct(f, (i, a, b)) if newf is not None: return newf.doit() def _dummy_with_inherited_properties_concrete(limits): """ Return a Dummy symbol that inherits as many assumptions as possible from the provided symbol and limits. If the symbol already has all True assumption shared by the limits then return None. """ x, a, b = limits l = [a, b] assumptions_to_consider = ['extended_nonnegative', 'nonnegative', 'extended_nonpositive', 'nonpositive', 'extended_positive', 'positive', 'extended_negative', 'negative', 'integer', 'rational', 'finite', 'zero', 'real', 'extended_real'] assumptions_to_keep = {} assumptions_to_add = {} for assum in assumptions_to_consider: assum_true = x._assumptions.get(assum, None) if assum_true: assumptions_to_keep[assum] = True elif all(getattr(i, 'is_' + assum) for i in l): assumptions_to_add[assum] = True if assumptions_to_add: assumptions_to_keep.update(assumptions_to_add) return Dummy('d', **assumptions_to_keep)
fc5e45554cd560ba67e1feb59b760cef0356541523fe0477fd41ea0c8cd91f13
""" 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.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""" from sympy.simplify.powsimp import powsimp 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): from sympy.simplify import logcombine 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 from sympy.simplify.powsimp import powdenest 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. """ from sympy.simplify.powsimp import powdenest 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 from sympy.simplify.powsimp import powsimp 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 does not 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 in (oo, I*oo): e0 = e elif z0 in (-oo, -I*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)
52a58c1c62ede62682f6aa5cd8579a994edf7f6bdd087c1ee99ce3f58f1079f3
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, _illegal from sympy.functions.combinatorial.factorials import factorial from sympy.functions.elementary.complexes import (Abs, sign, arg) 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 .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 = [] from sympy.simplify.simplify import together 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, rval in enumerate(r): if isinstance(rval, AccumBounds): r2.append(rval) 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: from sympy.simplify.ratsimp import ratsimp 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 in (S.Infinity, S.ImaginaryUnit*S.Infinity): dir = "-" elif z0 in (S.NegativeInfinity, S.ImaginaryUnit*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 str(dir) == '+-': r = limit(e, z, z0, dir='+') l = limit(e, z, z0, dir='-') if isinstance(r, Limit) and isinstance(l, Limit): if r.args[0] == l.args[0]: return self if r == l: return l if r.is_infinite and l.is_infinite: return S.ComplexInfinity raise ValueError("The limit does not exist since " "left hand limit = %s and right hand limit = %s" % (l, r)) 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(*_illegal): 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) arg_flag = isinstance(expr, arg) sign_flag = isinstance(expr, sign) if abs_flag or sign_flag or arg_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 if sign_flag else S.Pi) elif (sig > 0) == True: return (expr.args[0] if abs_flag else S.One if sign_flag else S.Zero) 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 from sympy.simplify.simplify import nsimplify 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 from sympy.simplify.powsimp import powsimp e = powsimp(e) if e.is_Pow: r = self.pow_heuristics(e) if r is not None: return r else: if isinstance(coeff, AccumBounds) and ex == S.Zero: return coeff if coeff.has(S.Infinity, S.NegativeInfinity, S.ComplexInfinity, S.NaN): 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: 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
773568e1567c3a40fd6126c111842e769707704755306ecb7e72114cc7782f38
"""Fourier Series""" from sympy.core.numbers import (oo, pi) from sympy.core.symbol import Wild from sympy.core.expr import Expr from sympy.core.add import Add from sympy.core.containers import Tuple from sympy.core.singleton import S from sympy.core.symbol import Dummy, Symbol from sympy.core.sympify import sympify from sympy.functions.elementary.trigonometric import sin, cos, sinc from sympy.series.series_class import SeriesBase from sympy.series.sequences import SeqFormula from sympy.sets.sets import Interval from sympy.utilities.iterables import is_sequence def fourier_cos_seq(func, limits, n): """Returns the cos sequence in a Fourier series""" from sympy.integrals import integrate x, L = limits[0], limits[2] - limits[1] cos_term = cos(2*n*pi*x / L) formula = 2 * cos_term * integrate(func * cos_term, limits) / L a0 = formula.subs(n, S.Zero) / 2 return a0, SeqFormula(2 * cos_term * integrate(func * cos_term, limits) / L, (n, 1, oo)) def fourier_sin_seq(func, limits, n): """Returns the sin sequence in a Fourier series""" from sympy.integrals import integrate x, L = limits[0], limits[2] - limits[1] sin_term = sin(2*n*pi*x / L) return SeqFormula(2 * sin_term * integrate(func * sin_term, limits) / L, (n, 1, oo)) def _process_limits(func, limits): """ Limits should be of the form (x, start, stop). x should be a symbol. Both start and stop should be bounded. Explanation =========== * If x is not given, x is determined from func. * If limits is None. Limit of the form (x, -pi, pi) is returned. Examples ======== >>> from sympy.series.fourier import _process_limits as pari >>> from sympy.abc import x >>> pari(x**2, (x, -2, 2)) (x, -2, 2) >>> pari(x**2, (-2, 2)) (x, -2, 2) >>> pari(x**2, None) (x, -pi, pi) """ def _find_x(func): free = func.free_symbols if len(free) == 1: return free.pop() elif not free: return Dummy('k') else: raise ValueError( " specify dummy variables for %s. If the function contains" " more than one free symbol, a dummy variable should be" " supplied explicitly e.g. FourierSeries(m*n**2, (n, -pi, pi))" % func) x, start, stop = None, None, None if limits is None: x, start, stop = _find_x(func), -pi, pi if is_sequence(limits, Tuple): if len(limits) == 3: x, start, stop = limits elif len(limits) == 2: x = _find_x(func) start, stop = limits if not isinstance(x, Symbol) or start is None or stop is None: raise ValueError('Invalid limits given: %s' % str(limits)) unbounded = [S.NegativeInfinity, S.Infinity] if start in unbounded or stop in unbounded: raise ValueError("Both the start and end value should be bounded") return sympify((x, start, stop)) def finite_check(f, x, L): def check_fx(exprs, x): return x not in exprs.free_symbols def check_sincos(_expr, x, L): if isinstance(_expr, (sin, cos)): sincos_args = _expr.args[0] if sincos_args.match(a*(pi/L)*x + b) is not None: return True else: return False from sympy.simplify.fu import TR2, TR1, sincos_to_sum _expr = sincos_to_sum(TR2(TR1(f))) add_coeff = _expr.as_coeff_add() a = Wild('a', properties=[lambda k: k.is_Integer, lambda k: k != S.Zero, ]) b = Wild('b', properties=[lambda k: x not in k.free_symbols, ]) for s in add_coeff[1]: mul_coeffs = s.as_coeff_mul()[1] for t in mul_coeffs: if not (check_fx(t, x) or check_sincos(t, x, L)): return False, f return True, _expr class FourierSeries(SeriesBase): r"""Represents Fourier sine/cosine series. Explanation =========== This class only represents a fourier series. No computation is performed. For how to compute Fourier series, see the :func:`fourier_series` docstring. See Also ======== sympy.series.fourier.fourier_series """ def __new__(cls, *args): args = map(sympify, args) return Expr.__new__(cls, *args) @property def function(self): return self.args[0] @property def x(self): return self.args[1][0] @property def period(self): return (self.args[1][1], self.args[1][2]) @property def a0(self): return self.args[2][0] @property def an(self): return self.args[2][1] @property def bn(self): return self.args[2][2] @property def interval(self): return Interval(0, oo) @property def start(self): return self.interval.inf @property def stop(self): return self.interval.sup @property def length(self): return oo @property def L(self): return abs(self.period[1] - self.period[0]) / 2 def _eval_subs(self, old, new): x = self.x if old.has(x): return self def truncate(self, n=3): """ Return the first n nonzero terms of the series. If ``n`` is None return an iterator. Parameters ========== n : int or None Amount of non-zero terms in approximation or None. Returns ======= Expr or iterator : Approximation of function expanded into Fourier series. Examples ======== >>> from sympy import fourier_series, pi >>> from sympy.abc import x >>> s = fourier_series(x, (x, -pi, pi)) >>> s.truncate(4) 2*sin(x) - sin(2*x) + 2*sin(3*x)/3 - sin(4*x)/2 See Also ======== sympy.series.fourier.FourierSeries.sigma_approximation """ if n is None: return iter(self) terms = [] for t in self: if len(terms) == n: break if t is not S.Zero: terms.append(t) return Add(*terms) def sigma_approximation(self, n=3): r""" Return :math:`\sigma`-approximation of Fourier series with respect to order n. Explanation =========== Sigma approximation adjusts a Fourier summation to eliminate the Gibbs phenomenon which would otherwise occur at discontinuities. A sigma-approximated summation for a Fourier series of a T-periodical function can be written as .. math:: s(\theta) = \frac{1}{2} a_0 + \sum _{k=1}^{m-1} \operatorname{sinc} \Bigl( \frac{k}{m} \Bigr) \cdot \left[ a_k \cos \Bigl( \frac{2\pi k}{T} \theta \Bigr) + b_k \sin \Bigl( \frac{2\pi k}{T} \theta \Bigr) \right], where :math:`a_0, a_k, b_k, k=1,\ldots,{m-1}` are standard Fourier series coefficients and :math:`\operatorname{sinc} \Bigl( \frac{k}{m} \Bigr)` is a Lanczos :math:`\sigma` factor (expressed in terms of normalized :math:`\operatorname{sinc}` function). Parameters ========== n : int Highest order of the terms taken into account in approximation. Returns ======= Expr : Sigma approximation of function expanded into Fourier series. Examples ======== >>> from sympy import fourier_series, pi >>> from sympy.abc import x >>> s = fourier_series(x, (x, -pi, pi)) >>> s.sigma_approximation(4) 2*sin(x)*sinc(pi/4) - 2*sin(2*x)/pi + 2*sin(3*x)*sinc(3*pi/4)/3 See Also ======== sympy.series.fourier.FourierSeries.truncate Notes ===== The behaviour of :meth:`~sympy.series.fourier.FourierSeries.sigma_approximation` is different from :meth:`~sympy.series.fourier.FourierSeries.truncate` - it takes all nonzero terms of degree smaller than n, rather than first n nonzero ones. References ========== .. [1] https://en.wikipedia.org/wiki/Gibbs_phenomenon .. [2] https://en.wikipedia.org/wiki/Sigma_approximation """ terms = [sinc(pi * i / n) * t for i, t in enumerate(self[:n]) if t is not S.Zero] return Add(*terms) def shift(self, s): """ Shift the function by a term independent of x. Explanation =========== f(x) -> f(x) + s This is fast, if Fourier series of f(x) is already computed. Examples ======== >>> from sympy import fourier_series, pi >>> from sympy.abc import x >>> s = fourier_series(x**2, (x, -pi, pi)) >>> s.shift(1).truncate() -4*cos(x) + cos(2*x) + 1 + pi**2/3 """ s, x = sympify(s), self.x if x in s.free_symbols: raise ValueError("'%s' should be independent of %s" % (s, x)) a0 = self.a0 + s sfunc = self.function + s return self.func(sfunc, self.args[1], (a0, self.an, self.bn)) def shiftx(self, s): """ Shift x by a term independent of x. Explanation =========== f(x) -> f(x + s) This is fast, if Fourier series of f(x) is already computed. Examples ======== >>> from sympy import fourier_series, pi >>> from sympy.abc import x >>> s = fourier_series(x**2, (x, -pi, pi)) >>> s.shiftx(1).truncate() -4*cos(x + 1) + cos(2*x + 2) + pi**2/3 """ s, x = sympify(s), self.x if x in s.free_symbols: raise ValueError("'%s' should be independent of %s" % (s, x)) an = self.an.subs(x, x + s) bn = self.bn.subs(x, x + s) sfunc = self.function.subs(x, x + s) return self.func(sfunc, self.args[1], (self.a0, an, bn)) def scale(self, s): """ Scale the function by a term independent of x. Explanation =========== f(x) -> s * f(x) This is fast, if Fourier series of f(x) is already computed. Examples ======== >>> from sympy import fourier_series, pi >>> from sympy.abc import x >>> s = fourier_series(x**2, (x, -pi, pi)) >>> s.scale(2).truncate() -8*cos(x) + 2*cos(2*x) + 2*pi**2/3 """ s, x = sympify(s), self.x if x in s.free_symbols: raise ValueError("'%s' should be independent of %s" % (s, x)) an = self.an.coeff_mul(s) bn = self.bn.coeff_mul(s) a0 = self.a0 * s sfunc = self.args[0] * s return self.func(sfunc, self.args[1], (a0, an, bn)) def scalex(self, s): """ Scale x by a term independent of x. Explanation =========== f(x) -> f(s*x) This is fast, if Fourier series of f(x) is already computed. Examples ======== >>> from sympy import fourier_series, pi >>> from sympy.abc import x >>> s = fourier_series(x**2, (x, -pi, pi)) >>> s.scalex(2).truncate() -4*cos(2*x) + cos(4*x) + pi**2/3 """ s, x = sympify(s), self.x if x in s.free_symbols: raise ValueError("'%s' should be independent of %s" % (s, x)) an = self.an.subs(x, x * s) bn = self.bn.subs(x, x * s) sfunc = self.function.subs(x, x * s) return self.func(sfunc, self.args[1], (self.a0, an, bn)) def _eval_as_leading_term(self, x, logx=None, cdir=0): for t in self: if t is not S.Zero: return t def _eval_term(self, pt): if pt == 0: return self.a0 return self.an.coeff(pt) + self.bn.coeff(pt) def __neg__(self): return self.scale(-1) def __add__(self, other): if isinstance(other, FourierSeries): if self.period != other.period: raise ValueError("Both the series should have same periods") x, y = self.x, other.x function = self.function + other.function.subs(y, x) if self.x not in function.free_symbols: return function an = self.an + other.an bn = self.bn + other.bn a0 = self.a0 + other.a0 return self.func(function, self.args[1], (a0, an, bn)) return Add(self, other) def __sub__(self, other): return self.__add__(-other) class FiniteFourierSeries(FourierSeries): r"""Represents Finite Fourier sine/cosine series. For how to compute Fourier series, see the :func:`fourier_series` docstring. Parameters ========== f : Expr Expression for finding fourier_series limits : ( x, start, stop) x is the independent variable for the expression f (start, stop) is the period of the fourier series exprs: (a0, an, bn) or Expr a0 is the constant term a0 of the fourier series an is a dictionary of coefficients of cos terms an[k] = coefficient of cos(pi*(k/L)*x) bn is a dictionary of coefficients of sin terms bn[k] = coefficient of sin(pi*(k/L)*x) or exprs can be an expression to be converted to fourier form Methods ======= This class is an extension of FourierSeries class. Please refer to sympy.series.fourier.FourierSeries for further information. See Also ======== sympy.series.fourier.FourierSeries sympy.series.fourier.fourier_series """ def __new__(cls, f, limits, exprs): f = sympify(f) limits = sympify(limits) exprs = sympify(exprs) if not (isinstance(exprs, Tuple) and len(exprs) == 3): # exprs is not of form (a0, an, bn) # Converts the expression to fourier form c, e = exprs.as_coeff_add() from sympy.simplify.fu import TR10 rexpr = c + Add(*[TR10(i) for i in e]) a0, exp_ls = rexpr.expand(trig=False, power_base=False, power_exp=False, log=False).as_coeff_add() x = limits[0] L = abs(limits[2] - limits[1]) / 2 a = Wild('a', properties=[lambda k: k.is_Integer, lambda k: k is not S.Zero, ]) b = Wild('b', properties=[lambda k: x not in k.free_symbols, ]) an = {} bn = {} # separates the coefficients of sin and cos terms in dictionaries an, and bn for p in exp_ls: t = p.match(b * cos(a * (pi / L) * x)) q = p.match(b * sin(a * (pi / L) * x)) if t: an[t[a]] = t[b] + an.get(t[a], S.Zero) elif q: bn[q[a]] = q[b] + bn.get(q[a], S.Zero) else: a0 += p exprs = Tuple(a0, an, bn) return Expr.__new__(cls, f, limits, exprs) @property def interval(self): _length = 1 if self.a0 else 0 _length += max(set(self.an.keys()).union(set(self.bn.keys()))) + 1 return Interval(0, _length) @property def length(self): return self.stop - self.start def shiftx(self, s): s, x = sympify(s), self.x if x in s.free_symbols: raise ValueError("'%s' should be independent of %s" % (s, x)) _expr = self.truncate().subs(x, x + s) sfunc = self.function.subs(x, x + s) return self.func(sfunc, self.args[1], _expr) def scale(self, s): s, x = sympify(s), self.x if x in s.free_symbols: raise ValueError("'%s' should be independent of %s" % (s, x)) _expr = self.truncate() * s sfunc = self.function * s return self.func(sfunc, self.args[1], _expr) def scalex(self, s): s, x = sympify(s), self.x if x in s.free_symbols: raise ValueError("'%s' should be independent of %s" % (s, x)) _expr = self.truncate().subs(x, x * s) sfunc = self.function.subs(x, x * s) return self.func(sfunc, self.args[1], _expr) def _eval_term(self, pt): if pt == 0: return self.a0 _term = self.an.get(pt, S.Zero) * cos(pt * (pi / self.L) * self.x) \ + self.bn.get(pt, S.Zero) * sin(pt * (pi / self.L) * self.x) return _term def __add__(self, other): if isinstance(other, FourierSeries): return other.__add__(fourier_series(self.function, self.args[1],\ finite=False)) elif isinstance(other, FiniteFourierSeries): if self.period != other.period: raise ValueError("Both the series should have same periods") x, y = self.x, other.x function = self.function + other.function.subs(y, x) if self.x not in function.free_symbols: return function return fourier_series(function, limits=self.args[1]) def fourier_series(f, limits=None, finite=True): r"""Computes the Fourier trigonometric series expansion. Explanation =========== Fourier trigonometric series of $f(x)$ over the interval $(a, b)$ is defined as: .. math:: \frac{a_0}{2} + \sum_{n=1}^{\infty} (a_n \cos(\frac{2n \pi x}{L}) + b_n \sin(\frac{2n \pi x}{L})) where the coefficients are: .. math:: L = b - a .. math:: a_0 = \frac{2}{L} \int_{a}^{b}{f(x) dx} .. math:: a_n = \frac{2}{L} \int_{a}^{b}{f(x) \cos(\frac{2n \pi x}{L}) dx} .. math:: b_n = \frac{2}{L} \int_{a}^{b}{f(x) \sin(\frac{2n \pi x}{L}) dx} The condition whether the function $f(x)$ given should be periodic or not is more than necessary, because it is sufficient to consider the series to be converging to $f(x)$ only in the given interval, not throughout the whole real line. This also brings a lot of ease for the computation because you do not have to make $f(x)$ artificially periodic by wrapping it with piecewise, modulo operations, but you can shape the function to look like the desired periodic function only in the interval $(a, b)$, and the computed series will automatically become the series of the periodic version of $f(x)$. This property is illustrated in the examples section below. Parameters ========== limits : (sym, start, end), optional *sym* denotes the symbol the series is computed with respect to. *start* and *end* denotes the start and the end of the interval where the fourier series converges to the given function. Default range is specified as $-\pi$ and $\pi$. Returns ======= FourierSeries A symbolic object representing the Fourier trigonometric series. Examples ======== Computing the Fourier series of $f(x) = x^2$: >>> from sympy import fourier_series, pi >>> from sympy.abc import x >>> f = x**2 >>> s = fourier_series(f, (x, -pi, pi)) >>> s1 = s.truncate(n=3) >>> s1 -4*cos(x) + cos(2*x) + pi**2/3 Shifting of the Fourier series: >>> s.shift(1).truncate() -4*cos(x) + cos(2*x) + 1 + pi**2/3 >>> s.shiftx(1).truncate() -4*cos(x + 1) + cos(2*x + 2) + pi**2/3 Scaling of the Fourier series: >>> s.scale(2).truncate() -8*cos(x) + 2*cos(2*x) + 2*pi**2/3 >>> s.scalex(2).truncate() -4*cos(2*x) + cos(4*x) + pi**2/3 Computing the Fourier series of $f(x) = x$: This illustrates how truncating to the higher order gives better convergence. .. plot:: :context: reset :format: doctest :include-source: True >>> from sympy import fourier_series, pi, plot >>> from sympy.abc import x >>> f = x >>> s = fourier_series(f, (x, -pi, pi)) >>> s1 = s.truncate(n = 3) >>> s2 = s.truncate(n = 5) >>> s3 = s.truncate(n = 7) >>> p = plot(f, s1, s2, s3, (x, -pi, pi), show=False, legend=True) >>> p[0].line_color = (0, 0, 0) >>> p[0].label = 'x' >>> p[1].line_color = (0.7, 0.7, 0.7) >>> p[1].label = 'n=3' >>> p[2].line_color = (0.5, 0.5, 0.5) >>> p[2].label = 'n=5' >>> p[3].line_color = (0.3, 0.3, 0.3) >>> p[3].label = 'n=7' >>> p.show() This illustrates how the series converges to different sawtooth waves if the different ranges are specified. .. plot:: :context: close-figs :format: doctest :include-source: True >>> s1 = fourier_series(x, (x, -1, 1)).truncate(10) >>> s2 = fourier_series(x, (x, -pi, pi)).truncate(10) >>> s3 = fourier_series(x, (x, 0, 1)).truncate(10) >>> p = plot(x, s1, s2, s3, (x, -5, 5), show=False, legend=True) >>> p[0].line_color = (0, 0, 0) >>> p[0].label = 'x' >>> p[1].line_color = (0.7, 0.7, 0.7) >>> p[1].label = '[-1, 1]' >>> p[2].line_color = (0.5, 0.5, 0.5) >>> p[2].label = '[-pi, pi]' >>> p[3].line_color = (0.3, 0.3, 0.3) >>> p[3].label = '[0, 1]' >>> p.show() Notes ===== Computing Fourier series can be slow due to the integration required in computing an, bn. It is faster to compute Fourier series of a function by using shifting and scaling on an already computed Fourier series rather than computing again. e.g. If the Fourier series of ``x**2`` is known the Fourier series of ``x**2 - 1`` can be found by shifting by ``-1``. See Also ======== sympy.series.fourier.FourierSeries References ========== .. [1] https://mathworld.wolfram.com/FourierSeries.html """ f = sympify(f) limits = _process_limits(f, limits) x = limits[0] if x not in f.free_symbols: return f if finite: L = abs(limits[2] - limits[1]) / 2 is_finite, res_f = finite_check(f, x, L) if is_finite: return FiniteFourierSeries(f, limits, res_f) n = Dummy('n') center = (limits[1] + limits[2]) / 2 if center.is_zero: neg_f = f.subs(x, -x) if f == neg_f: a0, an = fourier_cos_seq(f, limits, n) bn = SeqFormula(0, (1, oo)) return FourierSeries(f, limits, (a0, an, bn)) elif f == -neg_f: a0 = S.Zero an = SeqFormula(0, (1, oo)) bn = fourier_sin_seq(f, limits, n) return FourierSeries(f, limits, (a0, an, bn)) a0, an = fourier_cos_seq(f, limits, n) bn = fourier_sin_seq(f, limits, n) return FourierSeries(f, limits, (a0, an, bn))
0ad473893508b4077c1bdcfffe327db3b75120700e75e1da8dd3e6341dc74606
"""Formal Power Series""" from collections import defaultdict from sympy.core.numbers import (nan, oo, zoo) from sympy.core.add import Add from sympy.core.expr import Expr from sympy.core.function import Derivative, Function, expand from sympy.core.mul import Mul from sympy.core.numbers import Rational from sympy.core.relational import Eq from sympy.sets.sets import Interval from sympy.core.singleton import S from sympy.core.symbol import Wild, Dummy, symbols, Symbol from sympy.core.sympify import sympify from sympy.discrete.convolutions import convolution from sympy.functions.combinatorial.factorials import binomial, factorial, rf from sympy.functions.combinatorial.numbers import bell from sympy.functions.elementary.integers import floor, frac, ceiling from sympy.functions.elementary.miscellaneous import Min, Max from sympy.functions.elementary.piecewise import Piecewise from sympy.series.limits import Limit from sympy.series.order import Order from sympy.series.sequences import sequence from sympy.series.series_class import SeriesBase from sympy.utilities.iterables import iterable def rational_algorithm(f, x, k, order=4, full=False): """ Rational algorithm for computing formula of coefficients of Formal Power Series of a function. Explanation =========== Applicable when f(x) or some derivative of f(x) is a rational function in x. :func:`rational_algorithm` uses :func:`~.apart` function for partial fraction decomposition. :func:`~.apart` by default uses 'undetermined coefficients method'. By setting ``full=True``, 'Bronstein's algorithm' can be used instead. Looks for derivative of a function up to 4'th order (by default). This can be overridden using order option. Parameters ========== x : Symbol order : int, optional Order of the derivative of ``f``, Default is 4. full : bool Returns ======= formula : Expr ind : Expr Independent terms. order : int full : bool Examples ======== >>> from sympy import log, atan >>> from sympy.series.formal import rational_algorithm as ra >>> from sympy.abc import x, k >>> ra(1 / (1 - x), x, k) (1, 0, 0) >>> ra(log(1 + x), x, k) (-1/((-1)**k*k), 0, 1) >>> ra(atan(x), x, k, full=True) ((-I/(2*(-I)**k) + I/(2*I**k))/k, 0, 1) Notes ===== By setting ``full=True``, range of admissible functions to be solved using ``rational_algorithm`` can be increased. This option should be used carefully as it can significantly slow down the computation as ``doit`` is performed on the :class:`~.RootSum` object returned by the :func:`~.apart` function. Use ``full=False`` whenever possible. See Also ======== sympy.polys.partfrac.apart References ========== .. [1] Formal Power Series - Dominik Gruntz, Wolfram Koepf .. [2] Power Series in Computer Algebra - Wolfram Koepf """ from sympy.polys import RootSum, apart from sympy.integrals import integrate diff = f ds = [] # list of diff for i in range(order + 1): if i: diff = diff.diff(x) if diff.is_rational_function(x): coeff, sep = S.Zero, S.Zero terms = apart(diff, x, full=full) if terms.has(RootSum): terms = terms.doit() for t in Add.make_args(terms): num, den = t.as_numer_denom() if not den.has(x): sep += t else: if isinstance(den, Mul): # m*(n*x - a)**j -> (n*x - a)**j ind = den.as_independent(x) den = ind[1] num /= ind[0] # (n*x - a)**j -> (x - b) den, j = den.as_base_exp() a, xterm = den.as_coeff_add(x) # term -> m/x**n if not a: sep += t continue xc = xterm[0].coeff(x) a /= -xc num /= xc**j ak = ((-1)**j * num * binomial(j + k - 1, k).rewrite(factorial) / a**(j + k)) coeff += ak # Hacky, better way? if coeff.is_zero: return None if (coeff.has(x) or coeff.has(zoo) or coeff.has(oo) or coeff.has(nan)): return None for j in range(i): coeff = (coeff / (k + j + 1)) sep = integrate(sep, x) sep += (ds.pop() - sep).limit(x, 0) # constant of integration return (coeff.subs(k, k - i), sep, i) else: ds.append(diff) return None def rational_independent(terms, x): """ Returns a list of all the rationally independent terms. Examples ======== >>> from sympy import sin, cos >>> from sympy.series.formal import rational_independent >>> from sympy.abc import x >>> rational_independent([cos(x), sin(x)], x) [cos(x), sin(x)] >>> rational_independent([x**2, sin(x), x*sin(x), x**3], x) [x**3 + x**2, x*sin(x) + sin(x)] """ if not terms: return [] ind = terms[0:1] for t in terms[1:]: n = t.as_independent(x)[1] for i, term in enumerate(ind): d = term.as_independent(x)[1] q = (n / d).cancel() if q.is_rational_function(x): ind[i] += t break else: ind.append(t) return ind def simpleDE(f, x, g, order=4): r""" Generates simple DE. Explanation =========== DE is of the form .. math:: f^k(x) + \sum\limits_{j=0}^{k-1} A_j f^j(x) = 0 where :math:`A_j` should be rational function in x. Generates DE's upto order 4 (default). DE's can also have free parameters. By increasing order, higher order DE's can be found. Yields a tuple of (DE, order). """ from sympy.solvers.solveset import linsolve a = symbols('a:%d' % (order)) def _makeDE(k): eq = f.diff(x, k) + Add(*[a[i]*f.diff(x, i) for i in range(0, k)]) DE = g(x).diff(x, k) + Add(*[a[i]*g(x).diff(x, i) for i in range(0, k)]) return eq, DE found = False for k in range(1, order + 1): eq, DE = _makeDE(k) eq = eq.expand() terms = eq.as_ordered_terms() ind = rational_independent(terms, x) if found or len(ind) == k: sol = dict(zip(a, (i for s in linsolve(ind, a[:k]) for i in s))) if sol: found = True DE = DE.subs(sol) DE = DE.as_numer_denom()[0] DE = DE.factor().as_coeff_mul(Derivative)[1][0] yield DE.collect(Derivative(g(x))), k def exp_re(DE, r, k): """Converts a DE with constant coefficients (explike) into a RE. Explanation =========== Performs the substitution: .. math:: f^j(x) \\to r(k + j) Normalises the terms so that lowest order of a term is always r(k). Examples ======== >>> from sympy import Function, Derivative >>> from sympy.series.formal import exp_re >>> from sympy.abc import x, k >>> f, r = Function('f'), Function('r') >>> exp_re(-f(x) + Derivative(f(x)), r, k) -r(k) + r(k + 1) >>> exp_re(Derivative(f(x), x) + Derivative(f(x), (x, 2)), r, k) r(k) + r(k + 1) See Also ======== sympy.series.formal.hyper_re """ RE = S.Zero g = DE.atoms(Function).pop() mini = None for t in Add.make_args(DE): coeff, d = t.as_independent(g) if isinstance(d, Derivative): j = d.derivative_count else: j = 0 if mini is None or j < mini: mini = j RE += coeff * r(k + j) if mini: RE = RE.subs(k, k - mini) return RE def hyper_re(DE, r, k): """ Converts a DE into a RE. Explanation =========== Performs the substitution: .. math:: x^l f^j(x) \\to (k + 1 - l)_j . a_{k + j - l} Normalises the terms so that lowest order of a term is always r(k). Examples ======== >>> from sympy import Function, Derivative >>> from sympy.series.formal import hyper_re >>> from sympy.abc import x, k >>> f, r = Function('f'), Function('r') >>> hyper_re(-f(x) + Derivative(f(x)), r, k) (k + 1)*r(k + 1) - r(k) >>> hyper_re(-x*f(x) + Derivative(f(x), (x, 2)), r, k) (k + 2)*(k + 3)*r(k + 3) - r(k) See Also ======== sympy.series.formal.exp_re """ RE = S.Zero g = DE.atoms(Function).pop() x = g.atoms(Symbol).pop() mini = None for t in Add.make_args(DE.expand()): coeff, d = t.as_independent(g) c, v = coeff.as_independent(x) l = v.as_coeff_exponent(x)[1] if isinstance(d, Derivative): j = d.derivative_count else: j = 0 RE += c * rf(k + 1 - l, j) * r(k + j - l) if mini is None or j - l < mini: mini = j - l RE = RE.subs(k, k - mini) m = Wild('m') return RE.collect(r(k + m)) def _transformation_a(f, x, P, Q, k, m, shift): f *= x**(-shift) P = P.subs(k, k + shift) Q = Q.subs(k, k + shift) return f, P, Q, m def _transformation_c(f, x, P, Q, k, m, scale): f = f.subs(x, x**scale) P = P.subs(k, k / scale) Q = Q.subs(k, k / scale) m *= scale return f, P, Q, m def _transformation_e(f, x, P, Q, k, m): f = f.diff(x) P = P.subs(k, k + 1) * (k + m + 1) Q = Q.subs(k, k + 1) * (k + 1) return f, P, Q, m def _apply_shift(sol, shift): return [(res, cond + shift) for res, cond in sol] def _apply_scale(sol, scale): return [(res, cond / scale) for res, cond in sol] def _apply_integrate(sol, x, k): return [(res / ((cond + 1)*(cond.as_coeff_Add()[1].coeff(k))), cond + 1) for res, cond in sol] def _compute_formula(f, x, P, Q, k, m, k_max): """Computes the formula for f.""" from sympy.polys import roots sol = [] for i in range(k_max + 1, k_max + m + 1): if (i < 0) == True: continue r = f.diff(x, i).limit(x, 0) / factorial(i) if r.is_zero: continue kterm = m*k + i res = r p = P.subs(k, kterm) q = Q.subs(k, kterm) c1 = p.subs(k, 1/k).leadterm(k)[0] c2 = q.subs(k, 1/k).leadterm(k)[0] res *= (-c1 / c2)**k res *= Mul(*[rf(-r, k)**mul for r, mul in roots(p, k).items()]) res /= Mul(*[rf(-r, k)**mul for r, mul in roots(q, k).items()]) sol.append((res, kterm)) return sol def _rsolve_hypergeometric(f, x, P, Q, k, m): """ Recursive wrapper to rsolve_hypergeometric. Explanation =========== Returns a Tuple of (formula, series independent terms, maximum power of x in independent terms) if successful otherwise ``None``. See :func:`rsolve_hypergeometric` for details. """ from sympy.polys import lcm, roots from sympy.integrals import integrate # transformation - c proots, qroots = roots(P, k), roots(Q, k) all_roots = dict(proots) all_roots.update(qroots) scale = lcm([r.as_numer_denom()[1] for r, t in all_roots.items() if r.is_rational]) f, P, Q, m = _transformation_c(f, x, P, Q, k, m, scale) # transformation - a qroots = roots(Q, k) if qroots: k_min = Min(*qroots.keys()) else: k_min = S.Zero shift = k_min + m f, P, Q, m = _transformation_a(f, x, P, Q, k, m, shift) l = (x*f).limit(x, 0) if not isinstance(l, Limit) and l != 0: # Ideally should only be l != 0 return None qroots = roots(Q, k) if qroots: k_max = Max(*qroots.keys()) else: k_max = S.Zero ind, mp = S.Zero, -oo for i in range(k_max + m + 1): r = f.diff(x, i).limit(x, 0) / factorial(i) if r.is_finite is False: old_f = f f, P, Q, m = _transformation_a(f, x, P, Q, k, m, i) f, P, Q, m = _transformation_e(f, x, P, Q, k, m) sol, ind, mp = _rsolve_hypergeometric(f, x, P, Q, k, m) sol = _apply_integrate(sol, x, k) sol = _apply_shift(sol, i) ind = integrate(ind, x) ind += (old_f - ind).limit(x, 0) # constant of integration mp += 1 return sol, ind, mp elif r: ind += r*x**(i + shift) pow_x = Rational((i + shift), scale) if pow_x > mp: mp = pow_x # maximum power of x ind = ind.subs(x, x**(1/scale)) sol = _compute_formula(f, x, P, Q, k, m, k_max) sol = _apply_shift(sol, shift) sol = _apply_scale(sol, scale) return sol, ind, mp def rsolve_hypergeometric(f, x, P, Q, k, m): """ Solves RE of hypergeometric type. Explanation =========== Attempts to solve RE of the form Q(k)*a(k + m) - P(k)*a(k) Transformations that preserve Hypergeometric type: a. x**n*f(x): b(k + m) = R(k - n)*b(k) b. f(A*x): b(k + m) = A**m*R(k)*b(k) c. f(x**n): b(k + n*m) = R(k/n)*b(k) d. f(x**(1/m)): b(k + 1) = R(k*m)*b(k) e. f'(x): b(k + m) = ((k + m + 1)/(k + 1))*R(k + 1)*b(k) Some of these transformations have been used to solve the RE. Returns ======= formula : Expr ind : Expr Independent terms. order : int Examples ======== >>> from sympy import exp, ln, S >>> from sympy.series.formal import rsolve_hypergeometric as rh >>> from sympy.abc import x, k >>> rh(exp(x), x, -S.One, (k + 1), k, 1) (Piecewise((1/factorial(k), Eq(Mod(k, 1), 0)), (0, True)), 1, 1) >>> rh(ln(1 + x), x, k**2, k*(k + 1), k, 1) (Piecewise(((-1)**(k - 1)*factorial(k - 1)/RisingFactorial(2, k - 1), Eq(Mod(k, 1), 0)), (0, True)), x, 2) References ========== .. [1] Formal Power Series - Dominik Gruntz, Wolfram Koepf .. [2] Power Series in Computer Algebra - Wolfram Koepf """ result = _rsolve_hypergeometric(f, x, P, Q, k, m) if result is None: return None sol_list, ind, mp = result sol_dict = defaultdict(lambda: S.Zero) for res, cond in sol_list: j, mk = cond.as_coeff_Add() c = mk.coeff(k) if j.is_integer is False: res *= x**frac(j) j = floor(j) res = res.subs(k, (k - j) / c) cond = Eq(k % c, j % c) sol_dict[cond] += res # Group together formula for same conditions sol = [] for cond, res in sol_dict.items(): sol.append((res, cond)) sol.append((S.Zero, True)) sol = Piecewise(*sol) if mp is -oo: s = S.Zero elif mp.is_integer is False: s = ceiling(mp) else: s = mp + 1 # save all the terms of # form 1/x**k in ind if s < 0: ind += sum(sequence(sol * x**k, (k, s, -1))) s = S.Zero return (sol, ind, s) def _solve_hyper_RE(f, x, RE, g, k): """See docstring of :func:`rsolve_hypergeometric` for details.""" terms = Add.make_args(RE) if len(terms) == 2: gs = list(RE.atoms(Function)) P, Q = map(RE.coeff, gs) m = gs[1].args[0] - gs[0].args[0] if m < 0: P, Q = Q, P m = abs(m) return rsolve_hypergeometric(f, x, P, Q, k, m) def _solve_explike_DE(f, x, DE, g, k): """Solves DE with constant coefficients.""" from sympy.solvers import rsolve for t in Add.make_args(DE): coeff, d = t.as_independent(g) if coeff.free_symbols: return RE = exp_re(DE, g, k) init = {} for i in range(len(Add.make_args(RE))): if i: f = f.diff(x) init[g(k).subs(k, i)] = f.limit(x, 0) sol = rsolve(RE, g(k), init) if sol: return (sol / factorial(k), S.Zero, S.Zero) def _solve_simple(f, x, DE, g, k): """Converts DE into RE and solves using :func:`rsolve`.""" from sympy.solvers import rsolve RE = hyper_re(DE, g, k) init = {} for i in range(len(Add.make_args(RE))): if i: f = f.diff(x) init[g(k).subs(k, i)] = f.limit(x, 0) / factorial(i) sol = rsolve(RE, g(k), init) if sol: return (sol, S.Zero, S.Zero) def _transform_explike_DE(DE, g, x, order, syms): """Converts DE with free parameters into DE with constant coefficients.""" from sympy.solvers.solveset import linsolve eq = [] highest_coeff = DE.coeff(Derivative(g(x), x, order)) for i in range(order): coeff = DE.coeff(Derivative(g(x), x, i)) coeff = (coeff / highest_coeff).expand().collect(x) for t in Add.make_args(coeff): eq.append(t) temp = [] for e in eq: if e.has(x): break elif e.has(Symbol): temp.append(e) else: eq = temp if eq: sol = dict(zip(syms, (i for s in linsolve(eq, list(syms)) for i in s))) if sol: DE = DE.subs(sol) DE = DE.factor().as_coeff_mul(Derivative)[1][0] DE = DE.collect(Derivative(g(x))) return DE def _transform_DE_RE(DE, g, k, order, syms): """Converts DE with free parameters into RE of hypergeometric type.""" from sympy.solvers.solveset import linsolve RE = hyper_re(DE, g, k) eq = [] for i in range(1, order): coeff = RE.coeff(g(k + i)) eq.append(coeff) sol = dict(zip(syms, (i for s in linsolve(eq, list(syms)) for i in s))) if sol: m = Wild('m') RE = RE.subs(sol) RE = RE.factor().as_numer_denom()[0].collect(g(k + m)) RE = RE.as_coeff_mul(g)[1][0] for i in range(order): # smallest order should be g(k) if RE.coeff(g(k + i)) and i: RE = RE.subs(k, k - i) break return RE def solve_de(f, x, DE, order, g, k): """ Solves the DE. Explanation =========== Tries to solve DE by either converting into a RE containing two terms or converting into a DE having constant coefficients. Returns ======= formula : Expr ind : Expr Independent terms. order : int Examples ======== >>> from sympy import Derivative as D, Function >>> from sympy import exp, ln >>> from sympy.series.formal import solve_de >>> from sympy.abc import x, k >>> f = Function('f') >>> solve_de(exp(x), x, D(f(x), x) - f(x), 1, f, k) (Piecewise((1/factorial(k), Eq(Mod(k, 1), 0)), (0, True)), 1, 1) >>> solve_de(ln(1 + x), x, (x + 1)*D(f(x), x, 2) + D(f(x)), 2, f, k) (Piecewise(((-1)**(k - 1)*factorial(k - 1)/RisingFactorial(2, k - 1), Eq(Mod(k, 1), 0)), (0, True)), x, 2) """ sol = None syms = DE.free_symbols.difference({g, x}) if syms: RE = _transform_DE_RE(DE, g, k, order, syms) else: RE = hyper_re(DE, g, k) if not RE.free_symbols.difference({k}): sol = _solve_hyper_RE(f, x, RE, g, k) if sol: return sol if syms: DE = _transform_explike_DE(DE, g, x, order, syms) if not DE.free_symbols.difference({x}): sol = _solve_explike_DE(f, x, DE, g, k) if sol: return sol def hyper_algorithm(f, x, k, order=4): """ Hypergeometric algorithm for computing Formal Power Series. Explanation =========== Steps: * Generates DE * Convert the DE into RE * Solves the RE Examples ======== >>> from sympy import exp, ln >>> from sympy.series.formal import hyper_algorithm >>> from sympy.abc import x, k >>> hyper_algorithm(exp(x), x, k) (Piecewise((1/factorial(k), Eq(Mod(k, 1), 0)), (0, True)), 1, 1) >>> hyper_algorithm(ln(1 + x), x, k) (Piecewise(((-1)**(k - 1)*factorial(k - 1)/RisingFactorial(2, k - 1), Eq(Mod(k, 1), 0)), (0, True)), x, 2) See Also ======== sympy.series.formal.simpleDE sympy.series.formal.solve_de """ g = Function('g') des = [] # list of DE's sol = None for DE, i in simpleDE(f, x, g, order): if DE is not None: sol = solve_de(f, x, DE, i, g, k) if sol: return sol if not DE.free_symbols.difference({x}): des.append(DE) # If nothing works # Try plain rsolve for DE in des: sol = _solve_simple(f, x, DE, g, k) if sol: return sol def _compute_fps(f, x, x0, dir, hyper, order, rational, full): """Recursive wrapper to compute fps. See :func:`compute_fps` for details. """ if x0 in [S.Infinity, S.NegativeInfinity]: dir = S.One if x0 is S.Infinity else -S.One temp = f.subs(x, 1/x) result = _compute_fps(temp, x, 0, dir, hyper, order, rational, full) if result is None: return None return (result[0], result[1].subs(x, 1/x), result[2].subs(x, 1/x)) elif x0 or dir == -S.One: if dir == -S.One: rep = -x + x0 rep2 = -x rep2b = x0 else: rep = x + x0 rep2 = x rep2b = -x0 temp = f.subs(x, rep) result = _compute_fps(temp, x, 0, S.One, hyper, order, rational, full) if result is None: return None return (result[0], result[1].subs(x, rep2 + rep2b), result[2].subs(x, rep2 + rep2b)) if f.is_polynomial(x): k = Dummy('k') ak = sequence(Coeff(f, x, k), (k, 1, oo)) xk = sequence(x**k, (k, 0, oo)) ind = f.coeff(x, 0) return ak, xk, ind # Break instances of Add # this allows application of different # algorithms on different terms increasing the # range of admissible functions. if isinstance(f, Add): result = False ak = sequence(S.Zero, (0, oo)) ind, xk = S.Zero, None for t in Add.make_args(f): res = _compute_fps(t, x, 0, S.One, hyper, order, rational, full) if res: if not result: result = True xk = res[1] if res[0].start > ak.start: seq = ak s, f = ak.start, res[0].start else: seq = res[0] s, f = res[0].start, ak.start save = Add(*[z[0]*z[1] for z in zip(seq[0:(f - s)], xk[s:f])]) ak += res[0] ind += res[2] + save else: ind += t if result: return ak, xk, ind return None # The symbolic term - symb, if present, is being separated from the function # Otherwise symb is being set to S.One syms = f.free_symbols.difference({x}) (f, symb) = expand(f).as_independent(*syms) result = None # from here on it's x0=0 and dir=1 handling k = Dummy('k') if rational: result = rational_algorithm(f, x, k, order, full) if result is None and hyper: result = hyper_algorithm(f, x, k, order) if result is None: return None from sympy.simplify.powsimp import powsimp if symb.is_zero: symb = S.One else: symb = powsimp(symb) ak = sequence(result[0], (k, result[2], oo)) xk_formula = powsimp(x**k * symb) xk = sequence(xk_formula, (k, 0, oo)) ind = powsimp(result[1] * symb) return ak, xk, ind def compute_fps(f, x, x0=0, dir=1, hyper=True, order=4, rational=True, full=False): """ Computes the formula for Formal Power Series of a function. Explanation =========== Tries to compute the formula by applying the following techniques (in order): * rational_algorithm * Hypergeometric algorithm Parameters ========== x : Symbol x0 : number, optional Point to perform series expansion about. Default is 0. dir : {1, -1, '+', '-'}, optional If dir is 1 or '+' the series is calculated from the right and for -1 or '-' the series is calculated from the left. For smooth functions this flag will not alter the results. Default is 1. hyper : {True, False}, optional Set hyper to False to skip the hypergeometric algorithm. By default it is set to False. order : int, optional Order of the derivative of ``f``, Default is 4. rational : {True, False}, optional Set rational to False to skip rational algorithm. By default it is set to True. full : {True, False}, optional Set full to True to increase the range of rational algorithm. See :func:`rational_algorithm` for details. By default it is set to False. Returns ======= ak : sequence Sequence of coefficients. xk : sequence Sequence of powers of x. ind : Expr Independent terms. mul : Pow Common terms. See Also ======== sympy.series.formal.rational_algorithm sympy.series.formal.hyper_algorithm """ f = sympify(f) x = sympify(x) if not f.has(x): return None x0 = sympify(x0) if dir == '+': dir = S.One elif dir == '-': dir = -S.One elif dir not in [S.One, -S.One]: raise ValueError("Dir must be '+' or '-'") else: dir = sympify(dir) return _compute_fps(f, x, x0, dir, hyper, order, rational, full) class Coeff(Function): """ Coeff(p, x, n) represents the nth coefficient of the polynomial p in x """ @classmethod def eval(cls, p, x, n): if p.is_polynomial(x) and n.is_integer: return p.coeff(x, n) class FormalPowerSeries(SeriesBase): """ Represents Formal Power Series of a function. Explanation =========== No computation is performed. This class should only to be used to represent a series. No checks are performed. For computing a series use :func:`fps`. See Also ======== sympy.series.formal.fps """ def __new__(cls, *args): args = map(sympify, args) return Expr.__new__(cls, *args) def __init__(self, *args): ak = args[4][0] k = ak.variables[0] self.ak_seq = sequence(ak.formula, (k, 1, oo)) self.fact_seq = sequence(factorial(k), (k, 1, oo)) self.bell_coeff_seq = self.ak_seq * self.fact_seq self.sign_seq = sequence((-1, 1), (k, 1, oo)) @property def function(self): return self.args[0] @property def x(self): return self.args[1] @property def x0(self): return self.args[2] @property def dir(self): return self.args[3] @property def ak(self): return self.args[4][0] @property def xk(self): return self.args[4][1] @property def ind(self): return self.args[4][2] @property def interval(self): return Interval(0, oo) @property def start(self): return self.interval.inf @property def stop(self): return self.interval.sup @property def length(self): return oo @property def infinite(self): """Returns an infinite representation of the series""" from sympy.concrete import Sum ak, xk = self.ak, self.xk k = ak.variables[0] inf_sum = Sum(ak.formula * xk.formula, (k, ak.start, ak.stop)) return self.ind + inf_sum def _get_pow_x(self, term): """Returns the power of x in a term.""" xterm, pow_x = term.as_independent(self.x)[1].as_base_exp() if not xterm.has(self.x): return S.Zero return pow_x def polynomial(self, n=6): """ Truncated series as polynomial. Explanation =========== Returns series expansion of ``f`` upto order ``O(x**n)`` as a polynomial(without ``O`` term). """ terms = [] sym = self.free_symbols for i, t in enumerate(self): xp = self._get_pow_x(t) if xp.has(*sym): xp = xp.as_coeff_add(*sym)[0] if xp >= n: break elif xp.is_integer is True and i == n + 1: break elif t is not S.Zero: terms.append(t) return Add(*terms) def truncate(self, n=6): """ Truncated series. Explanation =========== Returns truncated series expansion of f upto order ``O(x**n)``. If n is ``None``, returns an infinite iterator. """ if n is None: return iter(self) x, x0 = self.x, self.x0 pt_xk = self.xk.coeff(n) if x0 is S.NegativeInfinity: x0 = S.Infinity return self.polynomial(n) + Order(pt_xk, (x, x0)) def zero_coeff(self): return self._eval_term(0) def _eval_term(self, pt): try: pt_xk = self.xk.coeff(pt) pt_ak = self.ak.coeff(pt).simplify() # Simplify the coefficients except IndexError: term = S.Zero else: term = (pt_ak * pt_xk) if self.ind: ind = S.Zero sym = self.free_symbols for t in Add.make_args(self.ind): pow_x = self._get_pow_x(t) if pow_x.has(*sym): pow_x = pow_x.as_coeff_add(*sym)[0] if pt == 0 and pow_x < 1: ind += t elif pow_x >= pt and pow_x < pt + 1: ind += t term += ind return term.collect(self.x) def _eval_subs(self, old, new): x = self.x if old.has(x): return self def _eval_as_leading_term(self, x, logx=None, cdir=0): for t in self: if t is not S.Zero: return t def _eval_derivative(self, x): f = self.function.diff(x) ind = self.ind.diff(x) pow_xk = self._get_pow_x(self.xk.formula) ak = self.ak k = ak.variables[0] if ak.formula.has(x): form = [] for e, c in ak.formula.args: temp = S.Zero for t in Add.make_args(e): pow_x = self._get_pow_x(t) temp += t * (pow_xk + pow_x) form.append((temp, c)) form = Piecewise(*form) ak = sequence(form.subs(k, k + 1), (k, ak.start - 1, ak.stop)) else: ak = sequence((ak.formula * pow_xk).subs(k, k + 1), (k, ak.start - 1, ak.stop)) return self.func(f, self.x, self.x0, self.dir, (ak, self.xk, ind)) def integrate(self, x=None, **kwargs): """ Integrate Formal Power Series. Examples ======== >>> from sympy import fps, sin, integrate >>> from sympy.abc import x >>> f = fps(sin(x)) >>> f.integrate(x).truncate() -1 + x**2/2 - x**4/24 + O(x**6) >>> integrate(f, (x, 0, 1)) 1 - cos(1) """ from sympy.integrals import integrate if x is None: x = self.x elif iterable(x): return integrate(self.function, x) f = integrate(self.function, x) ind = integrate(self.ind, x) ind += (f - ind).limit(x, 0) # constant of integration pow_xk = self._get_pow_x(self.xk.formula) ak = self.ak k = ak.variables[0] if ak.formula.has(x): form = [] for e, c in ak.formula.args: temp = S.Zero for t in Add.make_args(e): pow_x = self._get_pow_x(t) temp += t / (pow_xk + pow_x + 1) form.append((temp, c)) form = Piecewise(*form) ak = sequence(form.subs(k, k - 1), (k, ak.start + 1, ak.stop)) else: ak = sequence((ak.formula / (pow_xk + 1)).subs(k, k - 1), (k, ak.start + 1, ak.stop)) return self.func(f, self.x, self.x0, self.dir, (ak, self.xk, ind)) def product(self, other, x=None, n=6): """ Multiplies two Formal Power Series, using discrete convolution and return the truncated terms upto specified order. Parameters ========== n : Number, optional Specifies the order of the term up to which the polynomial should be truncated. Examples ======== >>> from sympy import fps, sin, exp >>> from sympy.abc import x >>> f1 = fps(sin(x)) >>> f2 = fps(exp(x)) >>> f1.product(f2, x).truncate(4) x + x**2 + x**3/3 + O(x**4) See Also ======== sympy.discrete.convolutions sympy.series.formal.FormalPowerSeriesProduct """ if n is None: return iter(self) other = sympify(other) if not isinstance(other, FormalPowerSeries): raise ValueError("Both series should be an instance of FormalPowerSeries" " class.") if self.dir != other.dir: raise ValueError("Both series should be calculated from the" " same direction.") elif self.x0 != other.x0: raise ValueError("Both series should be calculated about the" " same point.") elif self.x != other.x: raise ValueError("Both series should have the same symbol.") return FormalPowerSeriesProduct(self, other) def coeff_bell(self, n): r""" self.coeff_bell(n) returns a sequence of Bell polynomials of the second kind. Note that ``n`` should be a integer. The second kind of Bell polynomials (are sometimes called "partial" Bell polynomials or incomplete Bell polynomials) are defined as .. math:: B_{n,k}(x_1, x_2,\dotsc x_{n-k+1}) = \sum_{j_1+j_2+j_2+\dotsb=k \atop j_1+2j_2+3j_2+\dotsb=n} \frac{n!}{j_1!j_2!\dotsb j_{n-k+1}!} \left(\frac{x_1}{1!} \right)^{j_1} \left(\frac{x_2}{2!} \right)^{j_2} \dotsb \left(\frac{x_{n-k+1}}{(n-k+1)!} \right) ^{j_{n-k+1}}. * ``bell(n, k, (x1, x2, ...))`` gives Bell polynomials of the second kind, `B_{n,k}(x_1, x_2, \dotsc, x_{n-k+1})`. See Also ======== sympy.functions.combinatorial.numbers.bell """ inner_coeffs = [bell(n, j, tuple(self.bell_coeff_seq[:n-j+1])) for j in range(1, n+1)] k = Dummy('k') return sequence(tuple(inner_coeffs), (k, 1, oo)) def compose(self, other, x=None, n=6): r""" Returns the truncated terms of the formal power series of the composed function, up to specified ``n``. Explanation =========== If ``f`` and ``g`` are two formal power series of two different functions, then the coefficient sequence ``ak`` of the composed formal power series `fp` will be as follows. .. math:: \sum\limits_{k=0}^{n} b_k B_{n,k}(x_1, x_2, \dotsc, x_{n-k+1}) Parameters ========== n : Number, optional Specifies the order of the term up to which the polynomial should be truncated. Examples ======== >>> from sympy import fps, sin, exp >>> from sympy.abc import x >>> f1 = fps(exp(x)) >>> f2 = fps(sin(x)) >>> f1.compose(f2, x).truncate() 1 + x + x**2/2 - x**4/8 - x**5/15 + O(x**6) >>> f1.compose(f2, x).truncate(8) 1 + x + x**2/2 - x**4/8 - x**5/15 - x**6/240 + x**7/90 + O(x**8) See Also ======== sympy.functions.combinatorial.numbers.bell sympy.series.formal.FormalPowerSeriesCompose References ========== .. [1] Comtet, Louis: Advanced combinatorics; the art of finite and infinite expansions. Reidel, 1974. """ if n is None: return iter(self) other = sympify(other) if not isinstance(other, FormalPowerSeries): raise ValueError("Both series should be an instance of FormalPowerSeries" " class.") if self.dir != other.dir: raise ValueError("Both series should be calculated from the" " same direction.") elif self.x0 != other.x0: raise ValueError("Both series should be calculated about the" " same point.") elif self.x != other.x: raise ValueError("Both series should have the same symbol.") if other._eval_term(0).as_coeff_mul(other.x)[0] is not S.Zero: raise ValueError("The formal power series of the inner function should not have any " "constant coefficient term.") return FormalPowerSeriesCompose(self, other) def inverse(self, x=None, n=6): r""" Returns the truncated terms of the inverse of the formal power series, up to specified ``n``. Explanation =========== If ``f`` and ``g`` are two formal power series of two different functions, then the coefficient sequence ``ak`` of the composed formal power series ``fp`` will be as follows. .. math:: \sum\limits_{k=0}^{n} (-1)^{k} x_0^{-k-1} B_{n,k}(x_1, x_2, \dotsc, x_{n-k+1}) Parameters ========== n : Number, optional Specifies the order of the term up to which the polynomial should be truncated. Examples ======== >>> from sympy import fps, exp, cos >>> from sympy.abc import x >>> f1 = fps(exp(x)) >>> f2 = fps(cos(x)) >>> f1.inverse(x).truncate() 1 - x + x**2/2 - x**3/6 + x**4/24 - x**5/120 + O(x**6) >>> f2.inverse(x).truncate(8) 1 + x**2/2 + 5*x**4/24 + 61*x**6/720 + O(x**8) See Also ======== sympy.functions.combinatorial.numbers.bell sympy.series.formal.FormalPowerSeriesInverse References ========== .. [1] Comtet, Louis: Advanced combinatorics; the art of finite and infinite expansions. Reidel, 1974. """ if n is None: return iter(self) if self._eval_term(0).is_zero: raise ValueError("Constant coefficient should exist for an inverse of a formal" " power series to exist.") return FormalPowerSeriesInverse(self) def __add__(self, other): other = sympify(other) if isinstance(other, FormalPowerSeries): if self.dir != other.dir: raise ValueError("Both series should be calculated from the" " same direction.") elif self.x0 != other.x0: raise ValueError("Both series should be calculated about the" " same point.") x, y = self.x, other.x f = self.function + other.function.subs(y, x) if self.x not in f.free_symbols: return f ak = self.ak + other.ak if self.ak.start > other.ak.start: seq = other.ak s, e = other.ak.start, self.ak.start else: seq = self.ak s, e = self.ak.start, other.ak.start save = Add(*[z[0]*z[1] for z in zip(seq[0:(e - s)], self.xk[s:e])]) ind = self.ind + other.ind + save return self.func(f, x, self.x0, self.dir, (ak, self.xk, ind)) elif not other.has(self.x): f = self.function + other ind = self.ind + other return self.func(f, self.x, self.x0, self.dir, (self.ak, self.xk, ind)) return Add(self, other) def __radd__(self, other): return self.__add__(other) def __neg__(self): return self.func(-self.function, self.x, self.x0, self.dir, (-self.ak, self.xk, -self.ind)) def __sub__(self, other): return self.__add__(-other) def __rsub__(self, other): return (-self).__add__(other) def __mul__(self, other): other = sympify(other) if other.has(self.x): return Mul(self, other) f = self.function * other ak = self.ak.coeff_mul(other) ind = self.ind * other return self.func(f, self.x, self.x0, self.dir, (ak, self.xk, ind)) def __rmul__(self, other): return self.__mul__(other) class FiniteFormalPowerSeries(FormalPowerSeries): """Base Class for Product, Compose and Inverse classes""" def __init__(self, *args): pass @property def ffps(self): return self.args[0] @property def gfps(self): return self.args[1] @property def f(self): return self.ffps.function @property def g(self): return self.gfps.function @property def infinite(self): raise NotImplementedError("No infinite version for an object of" " FiniteFormalPowerSeries class.") def _eval_terms(self, n): raise NotImplementedError("(%s)._eval_terms()" % self) def _eval_term(self, pt): raise NotImplementedError("By the current logic, one can get terms" "upto a certain order, instead of getting term by term.") def polynomial(self, n): return self._eval_terms(n) def truncate(self, n=6): ffps = self.ffps pt_xk = ffps.xk.coeff(n) x, x0 = ffps.x, ffps.x0 return self.polynomial(n) + Order(pt_xk, (x, x0)) def _eval_derivative(self, x): raise NotImplementedError def integrate(self, x): raise NotImplementedError class FormalPowerSeriesProduct(FiniteFormalPowerSeries): """Represents the product of two formal power series of two functions. Explanation =========== No computation is performed. Terms are calculated using a term by term logic, instead of a point by point logic. There are two differences between a :obj:`FormalPowerSeries` object and a :obj:`FormalPowerSeriesProduct` object. The first argument contains the two functions involved in the product. Also, the coefficient sequence contains both the coefficient sequence of the formal power series of the involved functions. See Also ======== sympy.series.formal.FormalPowerSeries sympy.series.formal.FiniteFormalPowerSeries """ def __init__(self, *args): ffps, gfps = self.ffps, self.gfps k = ffps.ak.variables[0] self.coeff1 = sequence(ffps.ak.formula, (k, 0, oo)) k = gfps.ak.variables[0] self.coeff2 = sequence(gfps.ak.formula, (k, 0, oo)) @property def function(self): """Function of the product of two formal power series.""" return self.f * self.g def _eval_terms(self, n): """ Returns the first ``n`` terms of the product formal power series. Term by term logic is implemented here. Examples ======== >>> from sympy import fps, sin, exp >>> from sympy.abc import x >>> f1 = fps(sin(x)) >>> f2 = fps(exp(x)) >>> fprod = f1.product(f2, x) >>> fprod._eval_terms(4) x**3/3 + x**2 + x See Also ======== sympy.series.formal.FormalPowerSeries.product """ coeff1, coeff2 = self.coeff1, self.coeff2 aks = convolution(coeff1[:n], coeff2[:n]) terms = [] for i in range(0, n): terms.append(aks[i] * self.ffps.xk.coeff(i)) return Add(*terms) class FormalPowerSeriesCompose(FiniteFormalPowerSeries): """ Represents the composed formal power series of two functions. Explanation =========== No computation is performed. Terms are calculated using a term by term logic, instead of a point by point logic. There are two differences between a :obj:`FormalPowerSeries` object and a :obj:`FormalPowerSeriesCompose` object. The first argument contains the outer function and the inner function involved in the omposition. Also, the coefficient sequence contains the generic sequence which is to be multiplied by a custom ``bell_seq`` finite sequence. The finite terms will then be added up to get the final terms. See Also ======== sympy.series.formal.FormalPowerSeries sympy.series.formal.FiniteFormalPowerSeries """ @property def function(self): """Function for the composed formal power series.""" f, g, x = self.f, self.g, self.ffps.x return f.subs(x, g) def _eval_terms(self, n): """ Returns the first `n` terms of the composed formal power series. Term by term logic is implemented here. Explanation =========== The coefficient sequence of the :obj:`FormalPowerSeriesCompose` object is the generic sequence. It is multiplied by ``bell_seq`` to get a sequence, whose terms are added up to get the final terms for the polynomial. Examples ======== >>> from sympy import fps, sin, exp >>> from sympy.abc import x >>> f1 = fps(exp(x)) >>> f2 = fps(sin(x)) >>> fcomp = f1.compose(f2, x) >>> fcomp._eval_terms(6) -x**5/15 - x**4/8 + x**2/2 + x + 1 >>> fcomp._eval_terms(8) x**7/90 - x**6/240 - x**5/15 - x**4/8 + x**2/2 + x + 1 See Also ======== sympy.series.formal.FormalPowerSeries.compose sympy.series.formal.FormalPowerSeries.coeff_bell """ ffps, gfps = self.ffps, self.gfps terms = [ffps.zero_coeff()] for i in range(1, n): bell_seq = gfps.coeff_bell(i) seq = (ffps.bell_coeff_seq * bell_seq) terms.append(Add(*(seq[:i])) / ffps.fact_seq[i-1] * ffps.xk.coeff(i)) return Add(*terms) class FormalPowerSeriesInverse(FiniteFormalPowerSeries): """ Represents the Inverse of a formal power series. Explanation =========== No computation is performed. Terms are calculated using a term by term logic, instead of a point by point logic. There is a single difference between a :obj:`FormalPowerSeries` object and a :obj:`FormalPowerSeriesInverse` object. The coefficient sequence contains the generic sequence which is to be multiplied by a custom ``bell_seq`` finite sequence. The finite terms will then be added up to get the final terms. See Also ======== sympy.series.formal.FormalPowerSeries sympy.series.formal.FiniteFormalPowerSeries """ def __init__(self, *args): ffps = self.ffps k = ffps.xk.variables[0] inv = ffps.zero_coeff() inv_seq = sequence(inv ** (-(k + 1)), (k, 1, oo)) self.aux_seq = ffps.sign_seq * ffps.fact_seq * inv_seq @property def function(self): """Function for the inverse of a formal power series.""" f = self.f return 1 / f @property def g(self): raise ValueError("Only one function is considered while performing" "inverse of a formal power series.") @property def gfps(self): raise ValueError("Only one function is considered while performing" "inverse of a formal power series.") def _eval_terms(self, n): """ Returns the first ``n`` terms of the composed formal power series. Term by term logic is implemented here. Explanation =========== The coefficient sequence of the `FormalPowerSeriesInverse` object is the generic sequence. It is multiplied by ``bell_seq`` to get a sequence, whose terms are added up to get the final terms for the polynomial. Examples ======== >>> from sympy import fps, exp, cos >>> from sympy.abc import x >>> f1 = fps(exp(x)) >>> f2 = fps(cos(x)) >>> finv1, finv2 = f1.inverse(), f2.inverse() >>> finv1._eval_terms(6) -x**5/120 + x**4/24 - x**3/6 + x**2/2 - x + 1 >>> finv2._eval_terms(8) 61*x**6/720 + 5*x**4/24 + x**2/2 + 1 See Also ======== sympy.series.formal.FormalPowerSeries.inverse sympy.series.formal.FormalPowerSeries.coeff_bell """ ffps = self.ffps terms = [ffps.zero_coeff()] for i in range(1, n): bell_seq = ffps.coeff_bell(i) seq = (self.aux_seq * bell_seq) terms.append(Add(*(seq[:i])) / ffps.fact_seq[i-1] * ffps.xk.coeff(i)) return Add(*terms) def fps(f, x=None, x0=0, dir=1, hyper=True, order=4, rational=True, full=False): """ Generates Formal Power Series of ``f``. Explanation =========== Returns the formal series expansion of ``f`` around ``x = x0`` with respect to ``x`` in the form of a ``FormalPowerSeries`` object. Formal Power Series is represented using an explicit formula computed using different algorithms. See :func:`compute_fps` for the more details regarding the computation of formula. Parameters ========== x : Symbol, optional If x is None and ``f`` is univariate, the univariate symbols will be supplied, otherwise an error will be raised. x0 : number, optional Point to perform series expansion about. Default is 0. dir : {1, -1, '+', '-'}, optional If dir is 1 or '+' the series is calculated from the right and for -1 or '-' the series is calculated from the left. For smooth functions this flag will not alter the results. Default is 1. hyper : {True, False}, optional Set hyper to False to skip the hypergeometric algorithm. By default it is set to False. order : int, optional Order of the derivative of ``f``, Default is 4. rational : {True, False}, optional Set rational to False to skip rational algorithm. By default it is set to True. full : {True, False}, optional Set full to True to increase the range of rational algorithm. See :func:`rational_algorithm` for details. By default it is set to False. Examples ======== >>> from sympy import fps, ln, atan, sin >>> from sympy.abc import x, n Rational Functions >>> fps(ln(1 + x)).truncate() x - x**2/2 + x**3/3 - x**4/4 + x**5/5 + O(x**6) >>> fps(atan(x), full=True).truncate() x - x**3/3 + x**5/5 + O(x**6) Symbolic Functions >>> fps(x**n*sin(x**2), x).truncate(8) -x**(n + 6)/6 + x**(n + 2) + O(x**(n + 8)) See Also ======== sympy.series.formal.FormalPowerSeries sympy.series.formal.compute_fps """ f = sympify(f) if x is None: free = f.free_symbols if len(free) == 1: x = free.pop() elif not free: return f else: raise NotImplementedError("multivariate formal power series") result = compute_fps(f, x, x0, dir, hyper, order, rational, full) if result is None: return f return FormalPowerSeries(f, x, x0, dir, result)
0d6988bd85ad13b4c9279d3f1361752b5c34e9169265412112d962e8f5b55aca
""" 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 math import prod 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.matrices import Matrix, eye, zeros from sympy.polys import apart, poly, Poly from sympy.series import residue 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. """ 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): 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. """ 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) * prod(Poly(b - _x, _x) for b in bm) * prod(Poly(_x - b, _x) for b in bq) A = Dummy('A') D = Poly(bi - A, A) n = Poly(z, A) * prod((D + 1 - a) for a in an) * prod((-D + a - 1) for a in ap) 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 fac *= Mul(*[rf(b, k) for b in nbq]) fac /= Mul(*[rf(a, k) for a in nap]) ops += [MultOperator(fac)] p = 0 for n in range(k): m = z**n/factorial(n) m *= Mul(*[rf(a, n) for a in nap]) m /= Mul(*[rf(b, n) for b in nbq]) 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 fac *= Mul(*[a + n for a in func.ap]) fac /= Mul(*[b + n for b in func.bq]) 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. # 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. 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)) 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. 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)
4e6142c107c291e83a463672f392a400fc1fc996e9bf06cc0fc4afa3ee729a6a
from collections import defaultdict from sympy import SYMPY_DEBUG from sympy.core import sympify, S, Mul, Derivative, Pow from sympy.core.add import _unevaluated_Add, Add from sympy.core.assumptions import assumptions from sympy.core.exprtools import Factors, gcd_terms from sympy.core.function import _mexpand, expand_mul, expand_power_base from sympy.core.mul import _keep_coeff, _unevaluated_Mul, _mulsort from sympy.core.numbers import Rational, zoo, nan from sympy.core.parameters import global_parameters from sympy.core.sorting import ordered, default_sort_key from sympy.core.symbol import Dummy, Wild, symbols from sympy.functions import exp, sqrt, log from sympy.functions.elementary.complexes import Abs from sympy.polys import gcd from sympy.simplify.sqrtdenest import sqrtdenest from sympy.utilities.iterables import iterable, sift def collect(expr, syms, func=None, evaluate=None, exact=False, distribute_order_term=True): """ Collect additive terms of an expression. Explanation =========== This function collects additive terms of an expression with respect to a list of expression up to powers with rational exponents. By the term symbol here are meant arbitrary expressions, which can contain powers, products, sums etc. In other words symbol is a pattern which will be searched for in the expression's terms. The input expression is not expanded by :func:`collect`, so user is expected to provide an expression in an appropriate form. This makes :func:`collect` more predictable as there is no magic happening behind the scenes. However, it is important to note, that powers of products are converted to products of powers using the :func:`~.expand_power_base` function. There are two possible types of output. First, if ``evaluate`` flag is set, this function will return an expression with collected terms or else it will return a dictionary with expressions up to rational powers as keys and collected coefficients as values. Examples ======== >>> from sympy import S, collect, expand, factor, Wild >>> from sympy.abc import a, b, c, x, y This function can collect symbolic coefficients in polynomials or rational expressions. It will manage to find all integer or rational powers of collection variable:: >>> collect(a*x**2 + b*x**2 + a*x - b*x + c, x) c + x**2*(a + b) + x*(a - b) The same result can be achieved in dictionary form:: >>> d = collect(a*x**2 + b*x**2 + a*x - b*x + c, x, evaluate=False) >>> d[x**2] a + b >>> d[x] a - b >>> d[S.One] c You can also work with multivariate polynomials. However, remember that this function is greedy so it will care only about a single symbol at time, in specification order:: >>> collect(x**2 + y*x**2 + x*y + y + a*y, [x, y]) x**2*(y + 1) + x*y + y*(a + 1) Also more complicated expressions can be used as patterns:: >>> from sympy import sin, log >>> collect(a*sin(2*x) + b*sin(2*x), sin(2*x)) (a + b)*sin(2*x) >>> collect(a*x*log(x) + b*(x*log(x)), x*log(x)) x*(a + b)*log(x) You can use wildcards in the pattern:: >>> w = Wild('w1') >>> collect(a*x**y - b*x**y, w**y) x**y*(a - b) It is also possible to work with symbolic powers, although it has more complicated behavior, because in this case power's base and symbolic part of the exponent are treated as a single symbol:: >>> collect(a*x**c + b*x**c, x) a*x**c + b*x**c >>> collect(a*x**c + b*x**c, x**c) x**c*(a + b) However if you incorporate rationals to the exponents, then you will get well known behavior:: >>> collect(a*x**(2*c) + b*x**(2*c), x**c) x**(2*c)*(a + b) Note also that all previously stated facts about :func:`collect` function apply to the exponential function, so you can get:: >>> from sympy import exp >>> collect(a*exp(2*x) + b*exp(2*x), exp(x)) (a + b)*exp(2*x) If you are interested only in collecting specific powers of some symbols then set ``exact`` flag to True:: >>> collect(a*x**7 + b*x**7, x, exact=True) a*x**7 + b*x**7 >>> collect(a*x**7 + b*x**7, x**7, exact=True) x**7*(a + b) If you want to collect on any object containing symbols, set ``exact`` to None: >>> collect(x*exp(x) + sin(x)*y + sin(x)*2 + 3*x, x, exact=None) x*exp(x) + 3*x + (y + 2)*sin(x) >>> collect(a*x*y + x*y + b*x + x, [x, y], exact=None) x*y*(a + 1) + x*(b + 1) You can also apply this function to differential equations, where derivatives of arbitrary order can be collected. Note that if you collect with respect to a function or a derivative of a function, all derivatives of that function will also be collected. Use ``exact=True`` to prevent this from happening:: >>> from sympy import Derivative as D, collect, Function >>> f = Function('f') (x) >>> collect(a*D(f,x) + b*D(f,x), D(f,x)) (a + b)*Derivative(f(x), x) >>> collect(a*D(D(f,x),x) + b*D(D(f,x),x), f) (a + b)*Derivative(f(x), (x, 2)) >>> collect(a*D(D(f,x),x) + b*D(D(f,x),x), D(f,x), exact=True) a*Derivative(f(x), (x, 2)) + b*Derivative(f(x), (x, 2)) >>> collect(a*D(f,x) + b*D(f,x) + a*f + b*f, f) (a + b)*f(x) + (a + b)*Derivative(f(x), x) Or you can even match both derivative order and exponent at the same time:: >>> collect(a*D(D(f,x),x)**2 + b*D(D(f,x),x)**2, D(f,x)) (a + b)*Derivative(f(x), (x, 2))**2 Finally, you can apply a function to each of the collected coefficients. For example you can factorize symbolic coefficients of polynomial:: >>> f = expand((x + a + 1)**3) >>> collect(f, x, factor) x**3 + 3*x**2*(a + 1) + 3*x*(a + 1)**2 + (a + 1)**3 .. note:: Arguments are expected to be in expanded form, so you might have to call :func:`~.expand` prior to calling this function. See Also ======== collect_const, collect_sqrt, rcollect """ expr = sympify(expr) syms = [sympify(i) for i in (syms if iterable(syms) else [syms])] # replace syms[i] if it is not x, -x or has Wild symbols cond = lambda x: x.is_Symbol or (-x).is_Symbol or bool( x.atoms(Wild)) _, nonsyms = sift(syms, cond, binary=True) if nonsyms: reps = dict(zip(nonsyms, [Dummy(**assumptions(i)) for i in nonsyms])) syms = [reps.get(s, s) for s in syms] rv = collect(expr.subs(reps), syms, func=func, evaluate=evaluate, exact=exact, distribute_order_term=distribute_order_term) urep = {v: k for k, v in reps.items()} if not isinstance(rv, dict): return rv.xreplace(urep) else: return {urep.get(k, k).xreplace(urep): v.xreplace(urep) for k, v in rv.items()} # see if other expressions should be considered if exact is None: _syms = set() for i in Add.make_args(expr): if not i.has_free(*syms) or i in syms: continue if not i.is_Mul and i not in syms: _syms.add(i) else: # identify compound generators g = i._new_rawargs(*i.as_coeff_mul(*syms)[1]) if g not in syms: _syms.add(g) simple = all(i.is_Pow and i.base in syms for i in _syms) syms = syms + list(ordered(_syms)) if not simple: return collect(expr, syms, func=func, evaluate=evaluate, exact=False, distribute_order_term=distribute_order_term) if evaluate is None: evaluate = global_parameters.evaluate def make_expression(terms): product = [] for term, rat, sym, deriv in terms: if deriv is not None: var, order = deriv while order > 0: term, order = Derivative(term, var), order - 1 if sym is None: if rat is S.One: product.append(term) else: product.append(Pow(term, rat)) else: product.append(Pow(term, rat*sym)) return Mul(*product) def parse_derivative(deriv): # scan derivatives tower in the input expression and return # underlying function and maximal differentiation order expr, sym, order = deriv.expr, deriv.variables[0], 1 for s in deriv.variables[1:]: if s == sym: order += 1 else: raise NotImplementedError( 'Improve MV Derivative support in collect') while isinstance(expr, Derivative): s0 = expr.variables[0] for s in expr.variables: if s != s0: raise NotImplementedError( 'Improve MV Derivative support in collect') if s0 == sym: expr, order = expr.expr, order + len(expr.variables) else: break return expr, (sym, Rational(order)) def parse_term(expr): """Parses expression expr and outputs tuple (sexpr, rat_expo, sym_expo, deriv) where: - sexpr is the base expression - rat_expo is the rational exponent that sexpr is raised to - sym_expo is the symbolic exponent that sexpr is raised to - deriv contains the derivatives of the expression For example, the output of x would be (x, 1, None, None) the output of 2**x would be (2, 1, x, None). """ rat_expo, sym_expo = S.One, None sexpr, deriv = expr, None if expr.is_Pow: if isinstance(expr.base, Derivative): sexpr, deriv = parse_derivative(expr.base) else: sexpr = expr.base if expr.base == S.Exp1: arg = expr.exp if arg.is_Rational: sexpr, rat_expo = S.Exp1, arg elif arg.is_Mul: coeff, tail = arg.as_coeff_Mul(rational=True) sexpr, rat_expo = exp(tail), coeff elif expr.exp.is_Number: rat_expo = expr.exp else: coeff, tail = expr.exp.as_coeff_Mul() if coeff.is_Number: rat_expo, sym_expo = coeff, tail else: sym_expo = expr.exp elif isinstance(expr, exp): arg = expr.exp if arg.is_Rational: sexpr, rat_expo = S.Exp1, arg elif arg.is_Mul: coeff, tail = arg.as_coeff_Mul(rational=True) sexpr, rat_expo = exp(tail), coeff elif isinstance(expr, Derivative): sexpr, deriv = parse_derivative(expr) return sexpr, rat_expo, sym_expo, deriv def parse_expression(terms, pattern): """Parse terms searching for a pattern. Terms is a list of tuples as returned by parse_terms; Pattern is an expression treated as a product of factors. """ pattern = Mul.make_args(pattern) if len(terms) < len(pattern): # pattern is longer than matched product # so no chance for positive parsing result return None else: pattern = [parse_term(elem) for elem in pattern] terms = terms[:] # need a copy elems, common_expo, has_deriv = [], None, False for elem, e_rat, e_sym, e_ord in pattern: if elem.is_Number and e_rat == 1 and e_sym is None: # a constant is a match for everything continue for j in range(len(terms)): if terms[j] is None: continue term, t_rat, t_sym, t_ord = terms[j] # keeping track of whether one of the terms had # a derivative or not as this will require rebuilding # the expression later if t_ord is not None: has_deriv = True if (term.match(elem) is not None and (t_sym == e_sym or t_sym is not None and e_sym is not None and t_sym.match(e_sym) is not None)): if exact is False: # we don't have to be exact so find common exponent # for both expression's term and pattern's element expo = t_rat / e_rat if common_expo is None: # first time common_expo = expo else: # common exponent was negotiated before so # there is no chance for a pattern match unless # common and current exponents are equal if common_expo != expo: common_expo = 1 else: # we ought to be exact so all fields of # interest must match in every details if e_rat != t_rat or e_ord != t_ord: continue # found common term so remove it from the expression # and try to match next element in the pattern elems.append(terms[j]) terms[j] = None break else: # pattern element not found return None return [_f for _f in terms if _f], elems, common_expo, has_deriv if evaluate: if expr.is_Add: o = expr.getO() or 0 expr = expr.func(*[ collect(a, syms, func, True, exact, distribute_order_term) for a in expr.args if a != o]) + o elif expr.is_Mul: return expr.func(*[ collect(term, syms, func, True, exact, distribute_order_term) for term in expr.args]) elif expr.is_Pow: b = collect( expr.base, syms, func, True, exact, distribute_order_term) return Pow(b, expr.exp) syms = [expand_power_base(i, deep=False) for i in syms] order_term = None if distribute_order_term: order_term = expr.getO() if order_term is not None: if order_term.has(*syms): order_term = None else: expr = expr.removeO() summa = [expand_power_base(i, deep=False) for i in Add.make_args(expr)] collected, disliked = defaultdict(list), S.Zero for product in summa: c, nc = product.args_cnc(split_1=False) args = list(ordered(c)) + nc terms = [parse_term(i) for i in args] small_first = True for symbol in syms: if SYMPY_DEBUG: print("DEBUG: parsing of expression %s with symbol %s " % ( str(terms), str(symbol)) ) if isinstance(symbol, Derivative) and small_first: terms = list(reversed(terms)) small_first = not small_first result = parse_expression(terms, symbol) if SYMPY_DEBUG: print("DEBUG: returned %s" % str(result)) if result is not None: if not symbol.is_commutative: raise AttributeError("Can not collect noncommutative symbol") terms, elems, common_expo, has_deriv = result # when there was derivative in current pattern we # will need to rebuild its expression from scratch if not has_deriv: margs = [] for elem in elems: if elem[2] is None: e = elem[1] else: e = elem[1]*elem[2] margs.append(Pow(elem[0], e)) index = Mul(*margs) else: index = make_expression(elems) terms = expand_power_base(make_expression(terms), deep=False) index = expand_power_base(index, deep=False) collected[index].append(terms) break else: # none of the patterns matched disliked += product # add terms now for each key collected = {k: Add(*v) for k, v in collected.items()} if disliked is not S.Zero: collected[S.One] = disliked if order_term is not None: for key, val in collected.items(): collected[key] = val + order_term if func is not None: collected = { key: func(val) for key, val in collected.items()} if evaluate: return Add(*[key*val for key, val in collected.items()]) else: return collected def rcollect(expr, *vars): """ Recursively collect sums in an expression. Examples ======== >>> from sympy.simplify import rcollect >>> from sympy.abc import x, y >>> expr = (x**2*y + x*y + x + y)/(x + y) >>> rcollect(expr, y) (x + y*(x**2 + x + 1))/(x + y) See Also ======== collect, collect_const, collect_sqrt """ if expr.is_Atom or not expr.has(*vars): return expr else: expr = expr.__class__(*[rcollect(arg, *vars) for arg in expr.args]) if expr.is_Add: return collect(expr, vars) else: return expr def collect_sqrt(expr, evaluate=None): """Return expr with terms having common square roots collected together. If ``evaluate`` is False a count indicating the number of sqrt-containing terms will be returned and, if non-zero, the terms of the Add will be returned, else the expression itself will be returned as a single term. If ``evaluate`` is True, the expression with any collected terms will be returned. Note: since I = sqrt(-1), it is collected, too. Examples ======== >>> from sympy import sqrt >>> from sympy.simplify.radsimp import collect_sqrt >>> from sympy.abc import a, b >>> r2, r3, r5 = [sqrt(i) for i in [2, 3, 5]] >>> collect_sqrt(a*r2 + b*r2) sqrt(2)*(a + b) >>> collect_sqrt(a*r2 + b*r2 + a*r3 + b*r3) sqrt(2)*(a + b) + sqrt(3)*(a + b) >>> collect_sqrt(a*r2 + b*r2 + a*r3 + b*r5) sqrt(3)*a + sqrt(5)*b + sqrt(2)*(a + b) If evaluate is False then the arguments will be sorted and returned as a list and a count of the number of sqrt-containing terms will be returned: >>> collect_sqrt(a*r2 + b*r2 + a*r3 + b*r5, evaluate=False) ((sqrt(3)*a, sqrt(5)*b, sqrt(2)*(a + b)), 3) >>> collect_sqrt(a*sqrt(2) + b, evaluate=False) ((b, sqrt(2)*a), 1) >>> collect_sqrt(a + b, evaluate=False) ((a + b,), 0) See Also ======== collect, collect_const, rcollect """ if evaluate is None: evaluate = global_parameters.evaluate # this step will help to standardize any complex arguments # of sqrts coeff, expr = expr.as_content_primitive() vars = set() for a in Add.make_args(expr): for m in a.args_cnc()[0]: if m.is_number and ( m.is_Pow and m.exp.is_Rational and m.exp.q == 2 or m is S.ImaginaryUnit): vars.add(m) # we only want radicals, so exclude Number handling; in this case # d will be evaluated d = collect_const(expr, *vars, Numbers=False) hit = expr != d if not evaluate: nrad = 0 # make the evaluated args canonical args = list(ordered(Add.make_args(d))) for i, m in enumerate(args): c, nc = m.args_cnc() for ci in c: # XXX should this be restricted to ci.is_number as above? if ci.is_Pow and ci.exp.is_Rational and ci.exp.q == 2 or \ ci is S.ImaginaryUnit: nrad += 1 break args[i] *= coeff if not (hit or nrad): args = [Add(*args)] return tuple(args), nrad return coeff*d def collect_abs(expr): """Return ``expr`` with arguments of multiple Abs in a term collected under a single instance. Examples ======== >>> from sympy.simplify.radsimp import collect_abs >>> from sympy.abc import x >>> collect_abs(abs(x + 1)/abs(x**2 - 1)) Abs((x + 1)/(x**2 - 1)) >>> collect_abs(abs(1/x)) Abs(1/x) """ def _abs(mul): c, nc = mul.args_cnc() a = [] o = [] for i in c: if isinstance(i, Abs): a.append(i.args[0]) elif isinstance(i, Pow) and isinstance(i.base, Abs) and i.exp.is_real: a.append(i.base.args[0]**i.exp) else: o.append(i) if len(a) < 2 and not any(i.exp.is_negative for i in a if isinstance(i, Pow)): return mul absarg = Mul(*a) A = Abs(absarg) args = [A] args.extend(o) if not A.has(Abs): args.extend(nc) return Mul(*args) if not isinstance(A, Abs): # reevaluate and make it unevaluated A = Abs(absarg, evaluate=False) args[0] = A _mulsort(args) args.extend(nc) # nc always go last return Mul._from_args(args, is_commutative=not nc) return expr.replace( lambda x: isinstance(x, Mul), lambda x: _abs(x)).replace( lambda x: isinstance(x, Pow), lambda x: _abs(x)) def collect_const(expr, *vars, Numbers=True): """A non-greedy collection of terms with similar number coefficients in an Add expr. If ``vars`` is given then only those constants will be targeted. Although any Number can also be targeted, if this is not desired set ``Numbers=False`` and no Float or Rational will be collected. Parameters ========== expr : SymPy expression This parameter defines the expression the expression from which terms with similar coefficients are to be collected. A non-Add expression is returned as it is. vars : variable length collection of Numbers, optional Specifies the constants to target for collection. Can be multiple in number. Numbers : bool Specifies to target all instance of :class:`sympy.core.numbers.Number` class. If ``Numbers=False``, then no Float or Rational will be collected. Returns ======= expr : Expr Returns an expression with similar coefficient terms collected. Examples ======== >>> from sympy import sqrt >>> from sympy.abc import s, x, y, z >>> from sympy.simplify.radsimp import collect_const >>> collect_const(sqrt(3) + sqrt(3)*(1 + sqrt(2))) sqrt(3)*(sqrt(2) + 2) >>> collect_const(sqrt(3)*s + sqrt(7)*s + sqrt(3) + sqrt(7)) (sqrt(3) + sqrt(7))*(s + 1) >>> s = sqrt(2) + 2 >>> collect_const(sqrt(3)*s + sqrt(3) + sqrt(7)*s + sqrt(7)) (sqrt(2) + 3)*(sqrt(3) + sqrt(7)) >>> collect_const(sqrt(3)*s + sqrt(3) + sqrt(7)*s + sqrt(7), sqrt(3)) sqrt(7) + sqrt(3)*(sqrt(2) + 3) + sqrt(7)*(sqrt(2) + 2) The collection is sign-sensitive, giving higher precedence to the unsigned values: >>> collect_const(x - y - z) x - (y + z) >>> collect_const(-y - z) -(y + z) >>> collect_const(2*x - 2*y - 2*z, 2) 2*(x - y - z) >>> collect_const(2*x - 2*y - 2*z, -2) 2*x - 2*(y + z) See Also ======== collect, collect_sqrt, rcollect """ if not expr.is_Add: return expr recurse = False if not vars: recurse = True vars = set() for a in expr.args: for m in Mul.make_args(a): if m.is_number: vars.add(m) else: vars = sympify(vars) if not Numbers: vars = [v for v in vars if not v.is_Number] vars = list(ordered(vars)) for v in vars: terms = defaultdict(list) Fv = Factors(v) for m in Add.make_args(expr): f = Factors(m) q, r = f.div(Fv) if r.is_one: # only accept this as a true factor if # it didn't change an exponent from an Integer # to a non-Integer, e.g. 2/sqrt(2) -> sqrt(2) # -- we aren't looking for this sort of change fwas = f.factors.copy() fnow = q.factors if not any(k in fwas and fwas[k].is_Integer and not fnow[k].is_Integer for k in fnow): terms[v].append(q.as_expr()) continue terms[S.One].append(m) args = [] hit = False uneval = False for k in ordered(terms): v = terms[k] if k is S.One: args.extend(v) continue if len(v) > 1: v = Add(*v) hit = True if recurse and v != expr: vars.append(v) else: v = v[0] # be careful not to let uneval become True unless # it must be because it's going to be more expensive # to rebuild the expression as an unevaluated one if Numbers and k.is_Number and v.is_Add: args.append(_keep_coeff(k, v, sign=True)) uneval = True else: args.append(k*v) if hit: if uneval: expr = _unevaluated_Add(*args) else: expr = Add(*args) if not expr.is_Add: break return expr def radsimp(expr, symbolic=True, max_terms=4): r""" Rationalize the denominator by removing square roots. Explanation =========== The expression returned from radsimp must be used with caution since if the denominator contains symbols, it will be possible to make substitutions that violate the assumptions of the simplification process: that for a denominator matching a + b*sqrt(c), a != +/-b*sqrt(c). (If there are no symbols, this assumptions is made valid by collecting terms of sqrt(c) so the match variable ``a`` does not contain ``sqrt(c)``.) If you do not want the simplification to occur for symbolic denominators, set ``symbolic`` to False. If there are more than ``max_terms`` radical terms then the expression is returned unchanged. Examples ======== >>> from sympy import radsimp, sqrt, Symbol, pprint >>> from sympy import factor_terms, fraction, signsimp >>> from sympy.simplify.radsimp import collect_sqrt >>> from sympy.abc import a, b, c >>> radsimp(1/(2 + sqrt(2))) (2 - sqrt(2))/2 >>> x,y = map(Symbol, 'xy') >>> e = ((2 + 2*sqrt(2))*x + (2 + sqrt(8))*y)/(2 + sqrt(2)) >>> radsimp(e) sqrt(2)*(x + y) No simplification beyond removal of the gcd is done. One might want to polish the result a little, however, by collecting square root terms: >>> r2 = sqrt(2) >>> r5 = sqrt(5) >>> ans = radsimp(1/(y*r2 + x*r2 + a*r5 + b*r5)); pprint(ans) ___ ___ ___ ___ \/ 5 *a + \/ 5 *b - \/ 2 *x - \/ 2 *y ------------------------------------------ 2 2 2 2 5*a + 10*a*b + 5*b - 2*x - 4*x*y - 2*y >>> n, d = fraction(ans) >>> pprint(factor_terms(signsimp(collect_sqrt(n))/d, radical=True)) ___ ___ \/ 5 *(a + b) - \/ 2 *(x + y) ------------------------------------------ 2 2 2 2 5*a + 10*a*b + 5*b - 2*x - 4*x*y - 2*y If radicals in the denominator cannot be removed or there is no denominator, the original expression will be returned. >>> radsimp(sqrt(2)*x + sqrt(2)) sqrt(2)*x + sqrt(2) Results with symbols will not always be valid for all substitutions: >>> eq = 1/(a + b*sqrt(c)) >>> eq.subs(a, b*sqrt(c)) 1/(2*b*sqrt(c)) >>> radsimp(eq).subs(a, b*sqrt(c)) nan If ``symbolic=False``, symbolic denominators will not be transformed (but numeric denominators will still be processed): >>> radsimp(eq, symbolic=False) 1/(a + b*sqrt(c)) """ from sympy.simplify.simplify import signsimp syms = symbols("a:d A:D") def _num(rterms): # return the multiplier that will simplify the expression described # by rterms [(sqrt arg, coeff), ... ] a, b, c, d, A, B, C, D = syms if len(rterms) == 2: reps = dict(list(zip([A, a, B, b], [j for i in rterms for j in i]))) return ( sqrt(A)*a - sqrt(B)*b).xreplace(reps) if len(rterms) == 3: reps = dict(list(zip([A, a, B, b, C, c], [j for i in rterms for j in i]))) return ( (sqrt(A)*a + sqrt(B)*b - sqrt(C)*c)*(2*sqrt(A)*sqrt(B)*a*b - A*a**2 - B*b**2 + C*c**2)).xreplace(reps) elif len(rterms) == 4: reps = dict(list(zip([A, a, B, b, C, c, D, d], [j for i in rterms for j in i]))) return ((sqrt(A)*a + sqrt(B)*b - sqrt(C)*c - sqrt(D)*d)*(2*sqrt(A)*sqrt(B)*a*b - A*a**2 - B*b**2 - 2*sqrt(C)*sqrt(D)*c*d + C*c**2 + D*d**2)*(-8*sqrt(A)*sqrt(B)*sqrt(C)*sqrt(D)*a*b*c*d + A**2*a**4 - 2*A*B*a**2*b**2 - 2*A*C*a**2*c**2 - 2*A*D*a**2*d**2 + B**2*b**4 - 2*B*C*b**2*c**2 - 2*B*D*b**2*d**2 + C**2*c**4 - 2*C*D*c**2*d**2 + D**2*d**4)).xreplace(reps) elif len(rterms) == 1: return sqrt(rterms[0][0]) else: raise NotImplementedError def ispow2(d, log2=False): if not d.is_Pow: return False e = d.exp if e.is_Rational and e.q == 2 or symbolic and denom(e) == 2: return True if log2: q = 1 if e.is_Rational: q = e.q elif symbolic: d = denom(e) if d.is_Integer: q = d if q != 1 and log(q, 2).is_Integer: return True return False def handle(expr): # Handle first reduces to the case # expr = 1/d, where d is an add, or d is base**p/2. # We do this by recursively calling handle on each piece. from sympy.simplify.simplify import nsimplify n, d = fraction(expr) if expr.is_Atom or (d.is_Atom and n.is_Atom): return expr elif not n.is_Atom: n = n.func(*[handle(a) for a in n.args]) return _unevaluated_Mul(n, handle(1/d)) elif n is not S.One: return _unevaluated_Mul(n, handle(1/d)) elif d.is_Mul: return _unevaluated_Mul(*[handle(1/d) for d in d.args]) # By this step, expr is 1/d, and d is not a mul. if not symbolic and d.free_symbols: return expr if ispow2(d): d2 = sqrtdenest(sqrt(d.base))**numer(d.exp) if d2 != d: return handle(1/d2) elif d.is_Pow and (d.exp.is_integer or d.base.is_positive): # (1/d**i) = (1/d)**i return handle(1/d.base)**d.exp if not (d.is_Add or ispow2(d)): return 1/d.func(*[handle(a) for a in d.args]) # handle 1/d treating d as an Add (though it may not be) keep = True # keep changes that are made # flatten it and collect radicals after checking for special # conditions d = _mexpand(d) # did it change? if d.is_Atom: return 1/d # is it a number that might be handled easily? if d.is_number: _d = nsimplify(d) if _d.is_Number and _d.equals(d): return 1/_d while True: # collect similar terms collected = defaultdict(list) for m in Add.make_args(d): # d might have become non-Add p2 = [] other = [] for i in Mul.make_args(m): if ispow2(i, log2=True): p2.append(i.base if i.exp is S.Half else i.base**(2*i.exp)) elif i is S.ImaginaryUnit: p2.append(S.NegativeOne) else: other.append(i) collected[tuple(ordered(p2))].append(Mul(*other)) rterms = list(ordered(list(collected.items()))) rterms = [(Mul(*i), Add(*j)) for i, j in rterms] nrad = len(rterms) - (1 if rterms[0][0] is S.One else 0) if nrad < 1: break elif nrad > max_terms: # there may have been invalid operations leading to this point # so don't keep changes, e.g. this expression is troublesome # in collecting terms so as not to raise the issue of 2834: # r = sqrt(sqrt(5) + 5) # eq = 1/(sqrt(5)*r + 2*sqrt(5)*sqrt(-sqrt(5) + 5) + 5*r) keep = False break if len(rterms) > 4: # in general, only 4 terms can be removed with repeated squaring # but other considerations can guide selection of radical terms # so that radicals are removed if all(x.is_Integer and (y**2).is_Rational for x, y in rterms): nd, d = rad_rationalize(S.One, Add._from_args( [sqrt(x)*y for x, y in rterms])) n *= nd else: # is there anything else that might be attempted? keep = False break from sympy.simplify.powsimp import powsimp, powdenest num = powsimp(_num(rterms)) n *= num d *= num d = powdenest(_mexpand(d), force=symbolic) if d.has(S.Zero, nan, zoo): return expr if d.is_Atom: break if not keep: return expr return _unevaluated_Mul(n, 1/d) coeff, expr = expr.as_coeff_Add() expr = expr.normal() old = fraction(expr) n, d = fraction(handle(expr)) if old != (n, d): if not d.is_Atom: was = (n, d) n = signsimp(n, evaluate=False) d = signsimp(d, evaluate=False) u = Factors(_unevaluated_Mul(n, 1/d)) u = _unevaluated_Mul(*[k**v for k, v in u.factors.items()]) n, d = fraction(u) if old == (n, d): n, d = was n = expand_mul(n) if d.is_Number or d.is_Add: n2, d2 = fraction(gcd_terms(_unevaluated_Mul(n, 1/d))) if d2.is_Number or (d2.count_ops() <= d.count_ops()): n, d = [signsimp(i) for i in (n2, d2)] if n.is_Mul and n.args[0].is_Number: n = n.func(*n.args) return coeff + _unevaluated_Mul(n, 1/d) def rad_rationalize(num, den): """ Rationalize ``num/den`` by removing square roots in the denominator; num and den are sum of terms whose squares are positive rationals. Examples ======== >>> from sympy import sqrt >>> from sympy.simplify.radsimp import rad_rationalize >>> rad_rationalize(sqrt(3), 1 + sqrt(2)/3) (-sqrt(3) + sqrt(6)/3, -7/9) """ if not den.is_Add: return num, den g, a, b = split_surds(den) a = a*sqrt(g) num = _mexpand((a - b)*num) den = _mexpand(a**2 - b**2) return rad_rationalize(num, den) def fraction(expr, exact=False): """Returns a pair with expression's numerator and denominator. If the given expression is not a fraction then this function will return the tuple (expr, 1). This function will not make any attempt to simplify nested fractions or to do any term rewriting at all. If only one of the numerator/denominator pair is needed then use numer(expr) or denom(expr) functions respectively. >>> from sympy import fraction, Rational, Symbol >>> from sympy.abc import x, y >>> fraction(x/y) (x, y) >>> fraction(x) (x, 1) >>> fraction(1/y**2) (1, y**2) >>> fraction(x*y/2) (x*y, 2) >>> fraction(Rational(1, 2)) (1, 2) This function will also work fine with assumptions: >>> k = Symbol('k', negative=True) >>> fraction(x * y**k) (x, y**(-k)) If we know nothing about sign of some exponent and ``exact`` flag is unset, then structure this exponent's structure will be analyzed and pretty fraction will be returned: >>> from sympy import exp, Mul >>> fraction(2*x**(-y)) (2, x**y) >>> fraction(exp(-x)) (1, exp(x)) >>> fraction(exp(-x), exact=True) (exp(-x), 1) The ``exact`` flag will also keep any unevaluated Muls from being evaluated: >>> u = Mul(2, x + 1, evaluate=False) >>> fraction(u) (2*x + 2, 1) >>> fraction(u, exact=True) (2*(x + 1), 1) """ expr = sympify(expr) numer, denom = [], [] for term in Mul.make_args(expr): if term.is_commutative and (term.is_Pow or isinstance(term, exp)): b, ex = term.as_base_exp() if ex.is_negative: if ex is S.NegativeOne: denom.append(b) elif exact: if ex.is_constant(): denom.append(Pow(b, -ex)) else: numer.append(term) else: denom.append(Pow(b, -ex)) elif ex.is_positive: numer.append(term) elif not exact and ex.is_Mul: n, d = term.as_numer_denom() if n != 1: numer.append(n) denom.append(d) else: numer.append(term) elif term.is_Rational and not term.is_Integer: if term.p != 1: numer.append(term.p) denom.append(term.q) else: numer.append(term) return Mul(*numer, evaluate=not exact), Mul(*denom, evaluate=not exact) def numer(expr): return fraction(expr)[0] def denom(expr): return fraction(expr)[1] def fraction_expand(expr, **hints): return expr.expand(frac=True, **hints) def numer_expand(expr, **hints): a, b = fraction(expr) return a.expand(numer=True, **hints) / b def denom_expand(expr, **hints): a, b = fraction(expr) return a / b.expand(denom=True, **hints) expand_numer = numer_expand expand_denom = denom_expand expand_fraction = fraction_expand def split_surds(expr): """ Split an expression with terms whose squares are positive rationals into a sum of terms whose surds squared have gcd equal to g and a sum of terms with surds squared prime with g. Examples ======== >>> from sympy import sqrt >>> from sympy.simplify.radsimp import split_surds >>> split_surds(3*sqrt(3) + sqrt(5)/7 + sqrt(6) + sqrt(10) + sqrt(15)) (3, sqrt(2) + sqrt(5) + 3, sqrt(5)/7 + sqrt(10)) """ args = sorted(expr.args, key=default_sort_key) coeff_muls = [x.as_coeff_Mul() for x in args] surds = [x[1]**2 for x in coeff_muls if x[1].is_Pow] surds.sort(key=default_sort_key) g, b1, b2 = _split_gcd(*surds) g2 = g if not b2 and len(b1) >= 2: b1n = [x/g for x in b1] b1n = [x for x in b1n if x != 1] # only a common factor has been factored; split again g1, b1n, b2 = _split_gcd(*b1n) g2 = g*g1 a1v, a2v = [], [] for c, s in coeff_muls: if s.is_Pow and s.exp == S.Half: s1 = s.base if s1 in b1: a1v.append(c*sqrt(s1/g2)) else: a2v.append(c*s) else: a2v.append(c*s) a = Add(*a1v) b = Add(*a2v) return g2, a, b def _split_gcd(*a): """ Split the list of integers ``a`` into a list of integers, ``a1`` having ``g = gcd(a1)``, and a list ``a2`` whose elements are not divisible by ``g``. Returns ``g, a1, a2``. Examples ======== >>> from sympy.simplify.radsimp import _split_gcd >>> _split_gcd(55, 35, 22, 14, 77, 10) (5, [55, 35, 10], [22, 14, 77]) """ g = a[0] b1 = [g] b2 = [] for x in a[1:]: g1 = gcd(g, x) if g1 == 1: b2.append(x) else: g = g1 b1.append(x) return g, b1, b2
ca7b883f2f458da83975afb8dd61563dc2afb9ab5d0e36d80123c9739947d60d
from sympy.core import Add, Expr, Mul, S, sympify from sympy.core.function import _mexpand, count_ops, expand_mul from sympy.core.sorting import default_sort_key from sympy.core.symbol import Dummy from sympy.functions import root, sign, sqrt from sympy.polys import Poly, PolynomialError def is_sqrt(expr): """Return True if expr is a sqrt, otherwise False.""" return expr.is_Pow and expr.exp.is_Rational and abs(expr.exp) is S.Half def sqrt_depth(p): """Return the maximum depth of any square root argument of p. >>> from sympy.functions.elementary.miscellaneous import sqrt >>> from sympy.simplify.sqrtdenest import sqrt_depth Neither of these square roots contains any other square roots so the depth is 1: >>> sqrt_depth(1 + sqrt(2)*(1 + sqrt(3))) 1 The sqrt(3) is contained within a square root so the depth is 2: >>> sqrt_depth(1 + sqrt(2)*sqrt(1 + sqrt(3))) 2 """ if p is S.ImaginaryUnit: return 1 if p.is_Atom: return 0 elif p.is_Add or p.is_Mul: return max([sqrt_depth(x) for x in p.args], key=default_sort_key) elif is_sqrt(p): return sqrt_depth(p.base) + 1 else: return 0 def is_algebraic(p): """Return True if p is comprised of only Rationals or square roots of Rationals and algebraic operations. Examples ======== >>> from sympy.functions.elementary.miscellaneous import sqrt >>> from sympy.simplify.sqrtdenest import is_algebraic >>> from sympy import cos >>> is_algebraic(sqrt(2)*(3/(sqrt(7) + sqrt(5)*sqrt(2)))) True >>> is_algebraic(sqrt(2)*(3/(sqrt(7) + sqrt(5)*cos(2)))) False """ if p.is_Rational: return True elif p.is_Atom: return False elif is_sqrt(p) or p.is_Pow and p.exp.is_Integer: return is_algebraic(p.base) elif p.is_Add or p.is_Mul: return all(is_algebraic(x) for x in p.args) else: return False def _subsets(n): """ Returns all possible subsets of the set (0, 1, ..., n-1) except the empty set, listed in reversed lexicographical order according to binary representation, so that the case of the fourth root is treated last. Examples ======== >>> from sympy.simplify.sqrtdenest import _subsets >>> _subsets(2) [[1, 0], [0, 1], [1, 1]] """ if n == 1: a = [[1]] elif n == 2: a = [[1, 0], [0, 1], [1, 1]] elif n == 3: a = [[1, 0, 0], [0, 1, 0], [1, 1, 0], [0, 0, 1], [1, 0, 1], [0, 1, 1], [1, 1, 1]] else: b = _subsets(n - 1) a0 = [x + [0] for x in b] a1 = [x + [1] for x in b] a = a0 + [[0]*(n - 1) + [1]] + a1 return a def sqrtdenest(expr, max_iter=3): """Denests sqrts in an expression that contain other square roots if possible, otherwise returns the expr unchanged. This is based on the algorithms of [1]. Examples ======== >>> from sympy.simplify.sqrtdenest import sqrtdenest >>> from sympy import sqrt >>> sqrtdenest(sqrt(5 + 2 * sqrt(6))) sqrt(2) + sqrt(3) See Also ======== sympy.solvers.solvers.unrad References ========== .. [1] http://researcher.watson.ibm.com/researcher/files/us-fagin/symb85.pdf .. [2] D. J. Jeffrey and A. D. Rich, 'Symplifying Square Roots of Square Roots by Denesting' (available at http://www.cybertester.com/data/denest.pdf) """ expr = expand_mul(expr) for i in range(max_iter): z = _sqrtdenest0(expr) if expr == z: return expr expr = z return expr def _sqrt_match(p): """Return [a, b, r] for p.match(a + b*sqrt(r)) where, in addition to matching, sqrt(r) also has then maximal sqrt_depth among addends of p. Examples ======== >>> from sympy.functions.elementary.miscellaneous import sqrt >>> from sympy.simplify.sqrtdenest import _sqrt_match >>> _sqrt_match(1 + sqrt(2) + sqrt(2)*sqrt(3) + 2*sqrt(1+sqrt(5))) [1 + sqrt(2) + sqrt(6), 2, 1 + sqrt(5)] """ from sympy.simplify.radsimp import split_surds p = _mexpand(p) if p.is_Number: res = (p, S.Zero, S.Zero) elif p.is_Add: pargs = sorted(p.args, key=default_sort_key) sqargs = [x**2 for x in pargs] if all(sq.is_Rational and sq.is_positive for sq in sqargs): r, b, a = split_surds(p) res = a, b, r return list(res) # to make the process canonical, the argument is included in the tuple # so when the max is selected, it will be the largest arg having a # given depth v = [(sqrt_depth(x), x, i) for i, x in enumerate(pargs)] nmax = max(v, key=default_sort_key) if nmax[0] == 0: res = [] else: # select r depth, _, i = nmax r = pargs.pop(i) v.pop(i) b = S.One if r.is_Mul: bv = [] rv = [] for x in r.args: if sqrt_depth(x) < depth: bv.append(x) else: rv.append(x) b = Mul._from_args(bv) r = Mul._from_args(rv) # collect terms comtaining r a1 = [] b1 = [b] for x in v: if x[0] < depth: a1.append(x[1]) else: x1 = x[1] if x1 == r: b1.append(1) else: if x1.is_Mul: x1args = list(x1.args) if r in x1args: x1args.remove(r) b1.append(Mul(*x1args)) else: a1.append(x[1]) else: a1.append(x[1]) a = Add(*a1) b = Add(*b1) res = (a, b, r**2) else: b, r = p.as_coeff_Mul() if is_sqrt(r): res = (S.Zero, b, r**2) else: res = [] return list(res) class SqrtdenestStopIteration(StopIteration): pass def _sqrtdenest0(expr): """Returns expr after denesting its arguments.""" if is_sqrt(expr): n, d = expr.as_numer_denom() if d is S.One: # n is a square root if n.base.is_Add: args = sorted(n.base.args, key=default_sort_key) if len(args) > 2 and all((x**2).is_Integer for x in args): try: return _sqrtdenest_rec(n) except SqrtdenestStopIteration: pass expr = sqrt(_mexpand(Add(*[_sqrtdenest0(x) for x in args]))) return _sqrtdenest1(expr) else: n, d = [_sqrtdenest0(i) for i in (n, d)] return n/d if isinstance(expr, Add): cs = [] args = [] for arg in expr.args: c, a = arg.as_coeff_Mul() cs.append(c) args.append(a) if all(c.is_Rational for c in cs) and all(is_sqrt(arg) for arg in args): return _sqrt_ratcomb(cs, args) if isinstance(expr, Expr): args = expr.args if args: return expr.func(*[_sqrtdenest0(a) for a in args]) return expr def _sqrtdenest_rec(expr): """Helper that denests the square root of three or more surds. Explanation =========== It returns the denested expression; if it cannot be denested it throws SqrtdenestStopIteration Algorithm: expr.base is in the extension Q_m = Q(sqrt(r_1),..,sqrt(r_k)); split expr.base = a + b*sqrt(r_k), where `a` and `b` are on Q_(m-1) = Q(sqrt(r_1),..,sqrt(r_(k-1))); then a**2 - b**2*r_k is on Q_(m-1); denest sqrt(a**2 - b**2*r_k) and so on. See [1], section 6. Examples ======== >>> from sympy import sqrt >>> from sympy.simplify.sqrtdenest import _sqrtdenest_rec >>> _sqrtdenest_rec(sqrt(-72*sqrt(2) + 158*sqrt(5) + 498)) -sqrt(10) + sqrt(2) + 9 + 9*sqrt(5) >>> w=-6*sqrt(55)-6*sqrt(35)-2*sqrt(22)-2*sqrt(14)+2*sqrt(77)+6*sqrt(10)+65 >>> _sqrtdenest_rec(sqrt(w)) -sqrt(11) - sqrt(7) + sqrt(2) + 3*sqrt(5) """ from sympy.simplify.radsimp import radsimp, rad_rationalize, split_surds if not expr.is_Pow: return sqrtdenest(expr) if expr.base < 0: return sqrt(-1)*_sqrtdenest_rec(sqrt(-expr.base)) g, a, b = split_surds(expr.base) a = a*sqrt(g) if a < b: a, b = b, a c2 = _mexpand(a**2 - b**2) if len(c2.args) > 2: g, a1, b1 = split_surds(c2) a1 = a1*sqrt(g) if a1 < b1: a1, b1 = b1, a1 c2_1 = _mexpand(a1**2 - b1**2) c_1 = _sqrtdenest_rec(sqrt(c2_1)) d_1 = _sqrtdenest_rec(sqrt(a1 + c_1)) num, den = rad_rationalize(b1, d_1) c = _mexpand(d_1/sqrt(2) + num/(den*sqrt(2))) else: c = _sqrtdenest1(sqrt(c2)) if sqrt_depth(c) > 1: raise SqrtdenestStopIteration ac = a + c if len(ac.args) >= len(expr.args): if count_ops(ac) >= count_ops(expr.base): raise SqrtdenestStopIteration d = sqrtdenest(sqrt(ac)) if sqrt_depth(d) > 1: raise SqrtdenestStopIteration num, den = rad_rationalize(b, d) r = d/sqrt(2) + num/(den*sqrt(2)) r = radsimp(r) return _mexpand(r) def _sqrtdenest1(expr, denester=True): """Return denested expr after denesting with simpler methods or, that failing, using the denester.""" from sympy.simplify.simplify import radsimp if not is_sqrt(expr): return expr a = expr.base if a.is_Atom: return expr val = _sqrt_match(a) if not val: return expr a, b, r = val # try a quick numeric denesting d2 = _mexpand(a**2 - b**2*r) if d2.is_Rational: if d2.is_positive: z = _sqrt_numeric_denest(a, b, r, d2) if z is not None: return z else: # fourth root case # sqrtdenest(sqrt(3 + 2*sqrt(3))) = # sqrt(2)*3**(1/4)/2 + sqrt(2)*3**(3/4)/2 dr2 = _mexpand(-d2*r) dr = sqrt(dr2) if dr.is_Rational: z = _sqrt_numeric_denest(_mexpand(b*r), a, r, dr2) if z is not None: return z/root(r, 4) else: z = _sqrt_symbolic_denest(a, b, r) if z is not None: return z if not denester or not is_algebraic(expr): return expr res = sqrt_biquadratic_denest(expr, a, b, r, d2) if res: return res # now call to the denester av0 = [a, b, r, d2] z = _denester([radsimp(expr**2)], av0, 0, sqrt_depth(expr))[0] if av0[1] is None: return expr if z is not None: if sqrt_depth(z) == sqrt_depth(expr) and count_ops(z) > count_ops(expr): return expr return z return expr def _sqrt_symbolic_denest(a, b, r): """Given an expression, sqrt(a + b*sqrt(b)), return the denested expression or None. Explanation =========== If r = ra + rb*sqrt(rr), try replacing sqrt(rr) in ``a`` with (y**2 - ra)/rb, and if the result is a quadratic, ca*y**2 + cb*y + cc, and (cb + b)**2 - 4*ca*cc is 0, then sqrt(a + b*sqrt(r)) can be rewritten as sqrt(ca*(sqrt(r) + (cb + b)/(2*ca))**2). Examples ======== >>> from sympy.simplify.sqrtdenest import _sqrt_symbolic_denest, sqrtdenest >>> from sympy import sqrt, Symbol >>> from sympy.abc import x >>> a, b, r = 16 - 2*sqrt(29), 2, -10*sqrt(29) + 55 >>> _sqrt_symbolic_denest(a, b, r) sqrt(11 - 2*sqrt(29)) + sqrt(5) If the expression is numeric, it will be simplified: >>> w = sqrt(sqrt(sqrt(3) + 1) + 1) + 1 + sqrt(2) >>> sqrtdenest(sqrt((w**2).expand())) 1 + sqrt(2) + sqrt(1 + sqrt(1 + sqrt(3))) Otherwise, it will only be simplified if assumptions allow: >>> w = w.subs(sqrt(3), sqrt(x + 3)) >>> sqrtdenest(sqrt((w**2).expand())) sqrt((sqrt(sqrt(sqrt(x + 3) + 1) + 1) + 1 + sqrt(2))**2) Notice that the argument of the sqrt is a square. If x is made positive then the sqrt of the square is resolved: >>> _.subs(x, Symbol('x', positive=True)) sqrt(sqrt(sqrt(x + 3) + 1) + 1) + 1 + sqrt(2) """ a, b, r = map(sympify, (a, b, r)) rval = _sqrt_match(r) if not rval: return None ra, rb, rr = rval if rb: y = Dummy('y', positive=True) try: newa = Poly(a.subs(sqrt(rr), (y**2 - ra)/rb), y) except PolynomialError: return None if newa.degree() == 2: ca, cb, cc = newa.all_coeffs() cb += b if _mexpand(cb**2 - 4*ca*cc).equals(0): z = sqrt(ca*(sqrt(r) + cb/(2*ca))**2) if z.is_number: z = _mexpand(Mul._from_args(z.as_content_primitive())) return z def _sqrt_numeric_denest(a, b, r, d2): r"""Helper that denest $\sqrt{a + b \sqrt{r}}, d^2 = a^2 - b^2 r > 0$ If it cannot be denested, it returns ``None``. """ d = sqrt(d2) s = a + d # sqrt_depth(res) <= sqrt_depth(s) + 1 # sqrt_depth(expr) = sqrt_depth(r) + 2 # there is denesting if sqrt_depth(s) + 1 < sqrt_depth(r) + 2 # if s**2 is Number there is a fourth root if sqrt_depth(s) < sqrt_depth(r) + 1 or (s**2).is_Rational: s1, s2 = sign(s), sign(b) if s1 == s2 == -1: s1 = s2 = 1 res = (s1 * sqrt(a + d) + s2 * sqrt(a - d)) * sqrt(2) / 2 return res.expand() def sqrt_biquadratic_denest(expr, a, b, r, d2): """denest expr = sqrt(a + b*sqrt(r)) where a, b, r are linear combinations of square roots of positive rationals on the rationals (SQRR) and r > 0, b != 0, d2 = a**2 - b**2*r > 0 If it cannot denest it returns None. Explanation =========== Search for a solution A of type SQRR of the biquadratic equation 4*A**4 - 4*a*A**2 + b**2*r = 0 (1) sqd = sqrt(a**2 - b**2*r) Choosing the sqrt to be positive, the possible solutions are A = sqrt(a/2 +/- sqd/2) Since a, b, r are SQRR, then a**2 - b**2*r is a SQRR, so if sqd can be denested, it is done by _sqrtdenest_rec, and the result is a SQRR. Similarly for A. Examples of solutions (in both cases a and sqd are positive): Example of expr with solution sqrt(a/2 + sqd/2) but not solution sqrt(a/2 - sqd/2): expr = sqrt(-sqrt(15) - sqrt(2)*sqrt(-sqrt(5) + 5) - sqrt(3) + 8) a = -sqrt(15) - sqrt(3) + 8; sqd = -2*sqrt(5) - 2 + 4*sqrt(3) Example of expr with solution sqrt(a/2 - sqd/2) but not solution sqrt(a/2 + sqd/2): w = 2 + r2 + r3 + (1 + r3)*sqrt(2 + r2 + 5*r3) expr = sqrt((w**2).expand()) a = 4*sqrt(6) + 8*sqrt(2) + 47 + 28*sqrt(3) sqd = 29 + 20*sqrt(3) Define B = b/2*A; eq.(1) implies a = A**2 + B**2*r; then expr**2 = a + b*sqrt(r) = (A + B*sqrt(r))**2 Examples ======== >>> from sympy import sqrt >>> from sympy.simplify.sqrtdenest import _sqrt_match, sqrt_biquadratic_denest >>> z = sqrt((2*sqrt(2) + 4)*sqrt(2 + sqrt(2)) + 5*sqrt(2) + 8) >>> a, b, r = _sqrt_match(z**2) >>> d2 = a**2 - b**2*r >>> sqrt_biquadratic_denest(z, a, b, r, d2) sqrt(2) + sqrt(sqrt(2) + 2) + 2 """ from sympy.simplify.radsimp import radsimp, rad_rationalize if r <= 0 or d2 < 0 or not b or sqrt_depth(expr.base) < 2: return None for x in (a, b, r): for y in x.args: y2 = y**2 if not y2.is_Integer or not y2.is_positive: return None sqd = _mexpand(sqrtdenest(sqrt(radsimp(d2)))) if sqrt_depth(sqd) > 1: return None x1, x2 = [a/2 + sqd/2, a/2 - sqd/2] # look for a solution A with depth 1 for x in (x1, x2): A = sqrtdenest(sqrt(x)) if sqrt_depth(A) > 1: continue Bn, Bd = rad_rationalize(b, _mexpand(2*A)) B = Bn/Bd z = A + B*sqrt(r) if z < 0: z = -z return _mexpand(z) return None def _denester(nested, av0, h, max_depth_level): """Denests a list of expressions that contain nested square roots. Explanation =========== Algorithm based on <http://www.almaden.ibm.com/cs/people/fagin/symb85.pdf>. It is assumed that all of the elements of 'nested' share the same bottom-level radicand. (This is stated in the paper, on page 177, in the paragraph immediately preceding the algorithm.) When evaluating all of the arguments in parallel, the bottom-level radicand only needs to be denested once. This means that calling _denester with x arguments results in a recursive invocation with x+1 arguments; hence _denester has polynomial complexity. However, if the arguments were evaluated separately, each call would result in two recursive invocations, and the algorithm would have exponential complexity. This is discussed in the paper in the middle paragraph of page 179. """ from sympy.simplify.simplify import radsimp if h > max_depth_level: return None, None if av0[1] is None: return None, None if (av0[0] is None and all(n.is_Number for n in nested)): # no arguments are nested for f in _subsets(len(nested)): # test subset 'f' of nested p = _mexpand(Mul(*[nested[i] for i in range(len(f)) if f[i]])) if f.count(1) > 1 and f[-1]: p = -p sqp = sqrt(p) if sqp.is_Rational: return sqp, f # got a perfect square so return its square root. # Otherwise, return the radicand from the previous invocation. return sqrt(nested[-1]), [0]*len(nested) else: R = None if av0[0] is not None: values = [av0[:2]] R = av0[2] nested2 = [av0[3], R] av0[0] = None else: values = list(filter(None, [_sqrt_match(expr) for expr in nested])) for v in values: if v[2]: # Since if b=0, r is not defined if R is not None: if R != v[2]: av0[1] = None return None, None else: R = v[2] if R is None: # return the radicand from the previous invocation return sqrt(nested[-1]), [0]*len(nested) nested2 = [_mexpand(v[0]**2) - _mexpand(R*v[1]**2) for v in values] + [R] d, f = _denester(nested2, av0, h + 1, max_depth_level) if not f: return None, None if not any(f[i] for i in range(len(nested))): v = values[-1] return sqrt(v[0] + _mexpand(v[1]*d)), f else: p = Mul(*[nested[i] for i in range(len(nested)) if f[i]]) v = _sqrt_match(p) if 1 in f and f.index(1) < len(nested) - 1 and f[len(nested) - 1]: v[0] = -v[0] v[1] = -v[1] if not f[len(nested)]: # Solution denests with square roots vad = _mexpand(v[0] + d) if vad <= 0: # return the radicand from the previous invocation. return sqrt(nested[-1]), [0]*len(nested) if not(sqrt_depth(vad) <= sqrt_depth(R) + 1 or (vad**2).is_Number): av0[1] = None return None, None sqvad = _sqrtdenest1(sqrt(vad), denester=False) if not (sqrt_depth(sqvad) <= sqrt_depth(R) + 1): av0[1] = None return None, None sqvad1 = radsimp(1/sqvad) res = _mexpand(sqvad/sqrt(2) + (v[1]*sqrt(R)*sqvad1/sqrt(2))) return res, f # sign(v[1])*sqrt(_mexpand(v[1]**2*R*vad1/2))), f else: # Solution requires a fourth root s2 = _mexpand(v[1]*R) + d if s2 <= 0: return sqrt(nested[-1]), [0]*len(nested) FR, s = root(_mexpand(R), 4), sqrt(s2) return _mexpand(s/(sqrt(2)*FR) + v[0]*FR/(sqrt(2)*s)), f def _sqrt_ratcomb(cs, args): """Denest rational combinations of radicals. Based on section 5 of [1]. Examples ======== >>> from sympy import sqrt >>> from sympy.simplify.sqrtdenest import sqrtdenest >>> z = sqrt(1+sqrt(3)) + sqrt(3+3*sqrt(3)) - sqrt(10+6*sqrt(3)) >>> sqrtdenest(z) 0 """ from sympy.simplify.radsimp import radsimp # check if there exists a pair of sqrt that can be denested def find(a): n = len(a) for i in range(n - 1): for j in range(i + 1, n): s1 = a[i].base s2 = a[j].base p = _mexpand(s1 * s2) s = sqrtdenest(sqrt(p)) if s != sqrt(p): return s, i, j indices = find(args) if indices is None: return Add(*[c * arg for c, arg in zip(cs, args)]) s, i1, i2 = indices c2 = cs.pop(i2) args.pop(i2) a1 = args[i1] # replace a2 by s/a1 cs[i1] += radsimp(c2 * s / a1.base) return _sqrt_ratcomb(cs, args)
0448f6e449d832a83ef998403ebdd2169de0decf228acc44f89bc47e94fd860b
from collections import defaultdict from functools import reduce from math import prod from sympy.core.function import expand_log, count_ops, _coeff_isneg from sympy.core import sympify, Basic, Dummy, S, Add, Mul, Pow, expand_mul, factor_terms from sympy.core.sorting import ordered, default_sort_key from sympy.core.numbers import Integer, Rational from sympy.core.mul import _keep_coeff from sympy.core.rules import Transform from sympy.functions import exp_polar, exp, log, root, polarify, unpolarify from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.polys import lcm, gcd from sympy.ntheory.factor_ import multiplicity def powsimp(expr, deep=False, combine='all', force=False, measure=count_ops): """ 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)) """ def recurse(arg, **kwargs): _deep = kwargs.get('deep', deep) _combine = kwargs.get('combine', combine) _force = kwargs.get('force', force) _measure = kwargs.get('measure', measure) return powsimp(arg, _deep, _combine, _force, _measure) expr = sympify(expr) if (not isinstance(expr, Basic) or isinstance(expr, MatrixSymbol) or ( expr.is_Atom or expr in (exp_polar(0), exp_polar(1)))): return expr if deep or expr.is_Add or expr.is_Mul and _y not in expr.args: expr = expr.func(*[recurse(w) for w in expr.args]) if expr.is_Pow: return recurse(expr*_y, deep=False)/_y if not expr.is_Mul: return expr # handle the Mul if combine in ('exp', 'all'): # Collect base/exp data, while maintaining order in the # non-commutative parts of the product c_powers = defaultdict(list) nc_part = [] newexpr = [] coeff = S.One for term in expr.args: if term.is_Rational: coeff *= term continue if term.is_Pow: term = _denest_pow(term) if term.is_commutative: b, e = term.as_base_exp() if deep: b, e = [recurse(i) for i in [b, e]] if b.is_Pow or isinstance(b, exp): # don't let smthg like sqrt(x**a) split into x**a, 1/2 # or else it will be joined as x**(a/2) later b, e = b**e, S.One c_powers[b].append(e) else: # This is the logic that combines exponents for equal, # but non-commutative bases: A**x*A**y == A**(x+y). if nc_part: b1, e1 = nc_part[-1].as_base_exp() b2, e2 = term.as_base_exp() if (b1 == b2 and e1.is_commutative and e2.is_commutative): nc_part[-1] = Pow(b1, Add(e1, e2)) continue nc_part.append(term) # add up exponents of common bases for b, e in ordered(iter(c_powers.items())): # allow 2**x/4 -> 2**(x - 2); don't do this when b and e are # Numbers since autoevaluation will undo it, e.g. # 2**(1/3)/4 -> 2**(1/3 - 2) -> 2**(1/3)/4 if (b and b.is_Rational and not all(ei.is_Number for ei in e) and \ coeff is not S.One and b not in (S.One, S.NegativeOne)): m = multiplicity(abs(b), abs(coeff)) if m: e.append(m) coeff /= b**m c_powers[b] = Add(*e) if coeff is not S.One: if coeff in c_powers: c_powers[coeff] += S.One else: c_powers[coeff] = S.One # convert to plain dictionary c_powers = dict(c_powers) # check for base and inverted base pairs be = list(c_powers.items()) skip = set() # skip if we already saw them for b, e in be: if b in skip: continue bpos = b.is_positive or b.is_polar if bpos: binv = 1/b if b != binv and binv in c_powers: if b.as_numer_denom()[0] is S.One: c_powers.pop(b) c_powers[binv] -= e else: skip.add(binv) e = c_powers.pop(binv) c_powers[b] -= e # check for base and negated base pairs be = list(c_powers.items()) _n = S.NegativeOne for b, e in be: if (b.is_Symbol or b.is_Add) and -b in c_powers and b in c_powers: if (b.is_positive is not None or e.is_integer): if e.is_integer or b.is_negative: c_powers[-b] += c_powers.pop(b) else: # (-b).is_positive so use its e e = c_powers.pop(-b) c_powers[b] += e if _n in c_powers: c_powers[_n] += e else: c_powers[_n] = e # filter c_powers and convert to a list c_powers = [(b, e) for b, e in c_powers.items() if e] # ============================================================== # check for Mul bases of Rational powers that can be combined with # separated bases, e.g. x*sqrt(x*y)*sqrt(x*sqrt(x*y)) -> # (x*sqrt(x*y))**(3/2) # ---------------- helper functions def ratq(x): '''Return Rational part of x's exponent as it appears in the bkey. ''' return bkey(x)[0][1] def bkey(b, e=None): '''Return (b**s, c.q), c.p where e -> c*s. If e is not given then it will be taken by using as_base_exp() on the input b. e.g. x**3/2 -> (x, 2), 3 x**y -> (x**y, 1), 1 x**(2*y/3) -> (x**y, 3), 2 exp(x/2) -> (exp(a), 2), 1 ''' if e is not None: # coming from c_powers or from below if e.is_Integer: return (b, S.One), e elif e.is_Rational: return (b, Integer(e.q)), Integer(e.p) else: c, m = e.as_coeff_Mul(rational=True) if c is not S.One: if m.is_integer: return (b, Integer(c.q)), m*Integer(c.p) return (b**m, Integer(c.q)), Integer(c.p) else: return (b**e, S.One), S.One else: return bkey(*b.as_base_exp()) def update(b): '''Decide what to do with base, b. If its exponent is now an integer multiple of the Rational denominator, then remove it and put the factors of its base in the common_b dictionary or update the existing bases if necessary. If it has been zeroed out, simply remove the base. ''' newe, r = divmod(common_b[b], b[1]) if not r: common_b.pop(b) if newe: for m in Mul.make_args(b[0]**newe): b, e = bkey(m) if b not in common_b: common_b[b] = 0 common_b[b] += e if b[1] != 1: bases.append(b) # ---------------- end of helper functions # assemble a dictionary of the factors having a Rational power common_b = {} done = [] bases = [] for b, e in c_powers: b, e = bkey(b, e) if b in common_b: common_b[b] = common_b[b] + e else: common_b[b] = e if b[1] != 1 and b[0].is_Mul: bases.append(b) bases.sort(key=default_sort_key) # this makes tie-breaking canonical bases.sort(key=measure, reverse=True) # handle longest first for base in bases: if base not in common_b: # it may have been removed already continue b, exponent = base last = False # True when no factor of base is a radical qlcm = 1 # the lcm of the radical denominators while True: bstart = b qstart = qlcm bb = [] # list of factors ee = [] # (factor's expo. and it's current value in common_b) for bi in Mul.make_args(b): bib, bie = bkey(bi) if bib not in common_b or common_b[bib] < bie: ee = bb = [] # failed break ee.append([bie, common_b[bib]]) bb.append(bib) if ee: # find the number of integral extractions possible # e.g. [(1, 2), (2, 2)] -> min(2/1, 2/2) -> 1 min1 = ee[0][1]//ee[0][0] for i in range(1, len(ee)): rat = ee[i][1]//ee[i][0] if rat < 1: break min1 = min(min1, rat) else: # update base factor counts # e.g. if ee = [(2, 5), (3, 6)] then min1 = 2 # and the new base counts will be 5-2*2 and 6-2*3 for i in range(len(bb)): common_b[bb[i]] -= min1*ee[i][0] update(bb[i]) # update the count of the base # e.g. x**2*y*sqrt(x*sqrt(y)) the count of x*sqrt(y) # will increase by 4 to give bkey (x*sqrt(y), 2, 5) common_b[base] += min1*qstart*exponent if (last # no more radicals in base or len(common_b) == 1 # nothing left to join with or all(k[1] == 1 for k in common_b) # no rad's in common_b ): break # see what we can exponentiate base by to remove any radicals # so we know what to search for # e.g. if base were x**(1/2)*y**(1/3) then we should # exponentiate by 6 and look for powers of x and y in the ratio # of 2 to 3 qlcm = lcm([ratq(bi) for bi in Mul.make_args(bstart)]) if qlcm == 1: break # we are done b = bstart**qlcm qlcm *= qstart if all(ratq(bi) == 1 for bi in Mul.make_args(b)): last = True # we are going to be done after this next pass # this base no longer can find anything to join with and # since it was longer than any other we are done with it b, q = base done.append((b, common_b.pop(base)*Rational(1, q))) # update c_powers and get ready to continue with powsimp c_powers = done # there may be terms still in common_b that were bases that were # identified as needing processing, so remove those, too for (b, q), e in common_b.items(): if (b.is_Pow or isinstance(b, exp)) and \ q is not S.One and not b.exp.is_Rational: b, be = b.as_base_exp() b = b**(be/q) else: b = root(b, q) c_powers.append((b, e)) check = len(c_powers) c_powers = dict(c_powers) assert len(c_powers) == check # there should have been no duplicates # ============================================================== # rebuild the expression newexpr = expr.func(*(newexpr + [Pow(b, e) for b, e in c_powers.items()])) if combine == 'exp': return expr.func(newexpr, expr.func(*nc_part)) else: return recurse(expr.func(*nc_part), combine='base') * \ recurse(newexpr, combine='base') elif combine == 'base': # Build c_powers and nc_part. These must both be lists not # dicts because exp's are not combined. c_powers = [] nc_part = [] for term in expr.args: if term.is_commutative: c_powers.append(list(term.as_base_exp())) else: nc_part.append(term) # Pull out numerical coefficients from exponent if assumptions allow # e.g., 2**(2*x) => 4**x for i in range(len(c_powers)): b, e = c_powers[i] if not (all(x.is_nonnegative for x in b.as_numer_denom()) or e.is_integer or force or b.is_polar): continue exp_c, exp_t = e.as_coeff_Mul(rational=True) if exp_c is not S.One and exp_t is not S.One: c_powers[i] = [Pow(b, exp_c), exp_t] # Combine bases whenever they have the same exponent and # assumptions allow # first gather the potential bases under the common exponent c_exp = defaultdict(list) for b, e in c_powers: if deep: e = recurse(e) if e.is_Add and (b.is_positive or e.is_integer): e = factor_terms(e) if _coeff_isneg(e): e = -e b = 1/b c_exp[e].append(b) del c_powers # Merge back in the results of the above to form a new product c_powers = defaultdict(list) for e in c_exp: bases = c_exp[e] # calculate the new base for e if len(bases) == 1: new_base = bases[0] elif e.is_integer or force: new_base = expr.func(*bases) else: # see which ones can be joined unk = [] nonneg = [] neg = [] for bi in bases: if bi.is_negative: neg.append(bi) elif bi.is_nonnegative: nonneg.append(bi) elif bi.is_polar: nonneg.append( bi) # polar can be treated like non-negative else: unk.append(bi) if len(unk) == 1 and not neg or len(neg) == 1 and not unk: # a single neg or a single unk can join the rest nonneg.extend(unk + neg) unk = neg = [] elif neg: # their negative signs cancel in groups of 2*q if we know # that e = p/q else we have to treat them as unknown israt = False if e.is_Rational: israt = True else: p, d = e.as_numer_denom() if p.is_integer and d.is_integer: israt = True if israt: neg = [-w for w in neg] unk.extend([S.NegativeOne]*len(neg)) else: unk.extend(neg) neg = [] del israt # these shouldn't be joined for b in unk: c_powers[b].append(e) # here is a new joined base new_base = expr.func(*(nonneg + neg)) # if there are positive parts they will just get separated # again unless some change is made def _terms(e): # return the number of terms of this expression # when multiplied out -- assuming no joining of terms if e.is_Add: return sum([_terms(ai) for ai in e.args]) if e.is_Mul: return prod([_terms(mi) for mi in e.args]) return 1 xnew_base = expand_mul(new_base, deep=False) if len(Add.make_args(xnew_base)) < _terms(new_base): new_base = factor_terms(xnew_base) c_powers[new_base].append(e) # break out the powers from c_powers now c_part = [Pow(b, ei) for b, e in c_powers.items() for ei in e] # we're done return expr.func(*(c_part + nc_part)) else: raise ValueError("combine must be one of ('all', 'exp', 'base').") def powdenest(eq, force=False, polar=False): r""" Collect exponents on powers as assumptions allow. Explanation =========== Given ``(bb**be)**e``, this can be simplified as follows: * if ``bb`` is positive, or * ``e`` is an integer, or * ``|be| < 1`` then this simplifies to ``bb**(be*e)`` Given a product of powers raised to a power, ``(bb1**be1 * bb2**be2...)**e``, simplification can be done as follows: - if e is positive, the gcd of all bei can be joined with e; - all non-negative bb can be separated from those that are negative and their gcd can be joined with e; autosimplification already handles this separation. - integer factors from powers that have integers in the denominator of the exponent can be removed from any term and the gcd of such integers can be joined with e Setting ``force`` to ``True`` will make symbols that are not explicitly negative behave as though they are positive, resulting in more denesting. Setting ``polar`` to ``True`` will do simplifications on the Riemann surface of the logarithm, also resulting in more denestings. When there are sums of logs in exp() then a product of powers may be obtained e.g. ``exp(3*(log(a) + 2*log(b)))`` - > ``a**3*b**6``. Examples ======== >>> from sympy.abc import a, b, x, y, z >>> from sympy import Symbol, exp, log, sqrt, symbols, powdenest >>> powdenest((x**(2*a/3))**(3*x)) (x**(2*a/3))**(3*x) >>> powdenest(exp(3*x*log(2))) 2**(3*x) Assumptions may prevent expansion: >>> powdenest(sqrt(x**2)) sqrt(x**2) >>> p = symbols('p', positive=True) >>> powdenest(sqrt(p**2)) p No other expansion is done. >>> i, j = symbols('i,j', integer=True) >>> powdenest((x**x)**(i + j)) # -X-> (x**x)**i*(x**x)**j x**(x*(i + j)) But exp() will be denested by moving all non-log terms outside of the function; this may result in the collapsing of the exp to a power with a different base: >>> powdenest(exp(3*y*log(x))) x**(3*y) >>> powdenest(exp(y*(log(a) + log(b)))) (a*b)**y >>> powdenest(exp(3*(log(a) + log(b)))) a**3*b**3 If assumptions allow, symbols can also be moved to the outermost exponent: >>> i = Symbol('i', integer=True) >>> powdenest(((x**(2*i))**(3*y))**x) ((x**(2*i))**(3*y))**x >>> powdenest(((x**(2*i))**(3*y))**x, force=True) x**(6*i*x*y) >>> powdenest(((x**(2*a/3))**(3*y/i))**x) ((x**(2*a/3))**(3*y/i))**x >>> powdenest((x**(2*i)*y**(4*i))**z, force=True) (x*y**2)**(2*i*z) >>> n = Symbol('n', negative=True) >>> powdenest((x**i)**y, force=True) x**(i*y) >>> powdenest((n**i)**x, force=True) (n**i)**x """ from sympy.simplify.simplify import posify if force: def _denest(b, e): if not isinstance(b, (Pow, exp)): return b.is_positive, Pow(b, e, evaluate=False) return _denest(b.base, b.exp*e) reps = [] for p in eq.atoms(Pow, exp): if isinstance(p.base, (Pow, exp)): ok, dp = _denest(*p.args) if ok is not False: reps.append((p, dp)) if reps: eq = eq.subs(reps) eq, reps = posify(eq) return powdenest(eq, force=False, polar=polar).xreplace(reps) if polar: eq, rep = polarify(eq) return unpolarify(powdenest(unpolarify(eq, exponents_only=True)), rep) new = powsimp(eq) return new.xreplace(Transform( _denest_pow, filter=lambda m: m.is_Pow or isinstance(m, exp))) _y = Dummy('y') def _denest_pow(eq): """ Denest powers. This is a helper function for powdenest that performs the actual transformation. """ from sympy.simplify.simplify import logcombine b, e = eq.as_base_exp() if b.is_Pow or isinstance(b, exp) and e != 1: new = b._eval_power(e) if new is not None: eq = new b, e = new.as_base_exp() # denest exp with log terms in exponent if b is S.Exp1 and e.is_Mul: logs = [] other = [] for ei in e.args: if any(isinstance(ai, log) for ai in Add.make_args(ei)): logs.append(ei) else: other.append(ei) logs = logcombine(Mul(*logs)) return Pow(exp(logs), Mul(*other)) _, be = b.as_base_exp() if be is S.One and not (b.is_Mul or b.is_Rational and b.q != 1 or b.is_positive): return eq # denest eq which is either pos**e or Pow**e or Mul**e or # Mul(b1**e1, b2**e2) # handle polar numbers specially polars, nonpolars = [], [] for bb in Mul.make_args(b): if bb.is_polar: polars.append(bb.as_base_exp()) else: nonpolars.append(bb) if len(polars) == 1 and not polars[0][0].is_Mul: return Pow(polars[0][0], polars[0][1]*e)*powdenest(Mul(*nonpolars)**e) elif polars: return Mul(*[powdenest(bb**(ee*e)) for (bb, ee) in polars]) \ *powdenest(Mul(*nonpolars)**e) if b.is_Integer: # use log to see if there is a power here logb = expand_log(log(b)) if logb.is_Mul: c, logb = logb.args e *= c base = logb.args[0] return Pow(base, e) # if b is not a Mul or any factor is an atom then there is nothing to do if not b.is_Mul or any(s.is_Atom for s in Mul.make_args(b)): return eq # let log handle the case of the base of the argument being a Mul, e.g. # sqrt(x**(2*i)*y**(6*i)) -> x**i*y**(3**i) if x and y are positive; we # will take the log, expand it, and then factor out the common powers that # now appear as coefficient. We do this manually since terms_gcd pulls out # fractions, terms_gcd(x+x*y/2) -> x*(y + 2)/2 and we don't want the 1/2; # gcd won't pull out numerators from a fraction: gcd(3*x, 9*x/2) -> x but # we want 3*x. Neither work with noncommutatives. def nc_gcd(aa, bb): a, b = [i.as_coeff_Mul() for i in [aa, bb]] c = gcd(a[0], b[0]).as_numer_denom()[0] g = Mul(*(a[1].args_cnc(cset=True)[0] & b[1].args_cnc(cset=True)[0])) return _keep_coeff(c, g) glogb = expand_log(log(b)) if glogb.is_Add: args = glogb.args g = reduce(nc_gcd, args) if g != 1: cg, rg = g.as_coeff_Mul() glogb = _keep_coeff(cg, rg*Add(*[a/g for a in args])) # now put the log back together again if isinstance(glogb, log) or not glogb.is_Mul: if glogb.args[0].is_Pow or isinstance(glogb.args[0], exp): glogb = _denest_pow(glogb.args[0]) if (abs(glogb.exp) < 1) == True: return Pow(glogb.base, glogb.exp*e) return eq # the log(b) was a Mul so join any adds with logcombine add = [] other = [] for a in glogb.args: if a.is_Add: add.append(a) else: other.append(a) return Pow(exp(logcombine(Mul(*add))), e*Mul(*other))
90ec1ecab3fd5d4315c82ead5d2e2640652a47629dfc710f5214de984be6fdca
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 = int(b) if n > 0: return Mul(*[a + i for i in range(n)]) elif n < 0: return 1/Mul(*[a - i for i in range(1, -n + 1)]) 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)
22c406f453b8ebbf2c23f70cc01c4d6fb791ee9effaa24bd5547a11d953857d4
""" Tools for doing common subexpression elimination. """ from collections import defaultdict from sympy.core import Basic, Mul, Add, Pow, sympify from sympy.core.containers import Tuple, OrderedSet from sympy.core.exprtools import factor_terms from sympy.core.singleton import S from sympy.core.sorting import ordered from sympy.core.symbol import symbols, Symbol from sympy.matrices import (MatrixBase, Matrix, ImmutableMatrix, SparseMatrix, ImmutableSparseMatrix) from sympy.matrices.expressions import (MatrixExpr, MatrixSymbol, MatMul, MatAdd, MatPow) from sympy.matrices.expressions.matexpr import MatrixElement from sympy.polys.rootoftools import RootOf from sympy.utilities.iterables import numbered_symbols, sift, \ topological_sort, iterable from . import cse_opts # (preprocessor, postprocessor) pairs which are commonly useful. They should # each take a SymPy expression and return a possibly transformed expression. # When used in the function ``cse()``, the target expressions will be transformed # by each of the preprocessor functions in order. After the common # subexpressions are eliminated, each resulting expression will have the # postprocessor functions transform them in *reverse* order in order to undo the # transformation if necessary. This allows the algorithm to operate on # a representation of the expressions that allows for more optimization # opportunities. # ``None`` can be used to specify no transformation for either the preprocessor or # postprocessor. basic_optimizations = [(cse_opts.sub_pre, cse_opts.sub_post), (factor_terms, None)] # sometimes we want the output in a different format; non-trivial # transformations can be put here for users # =============================================================== def reps_toposort(r): """Sort replacements ``r`` so (k1, v1) appears before (k2, v2) if k2 is in v1's free symbols. This orders items in the way that cse returns its results (hence, in order to use the replacements in a substitution option it would make sense to reverse the order). Examples ======== >>> from sympy.simplify.cse_main import reps_toposort >>> from sympy.abc import x, y >>> from sympy import Eq >>> for l, r in reps_toposort([(x, y + 1), (y, 2)]): ... print(Eq(l, r)) ... Eq(y, 2) Eq(x, y + 1) """ r = sympify(r) E = [] for c1, (k1, v1) in enumerate(r): for c2, (k2, v2) in enumerate(r): if k1 in v2.free_symbols: E.append((c1, c2)) return [r[i] for i in topological_sort((range(len(r)), E))] def cse_separate(r, e): """Move expressions that are in the form (symbol, expr) out of the expressions and sort them into the replacements using the reps_toposort. Examples ======== >>> from sympy.simplify.cse_main import cse_separate >>> from sympy.abc import x, y, z >>> from sympy import cos, exp, cse, Eq, symbols >>> x0, x1 = symbols('x:2') >>> eq = (x + 1 + exp((x + 1)/(y + 1)) + cos(y + 1)) >>> cse([eq, Eq(x, z + 1), z - 2], postprocess=cse_separate) in [ ... [[(x0, y + 1), (x, z + 1), (x1, x + 1)], ... [x1 + exp(x1/x0) + cos(x0), z - 2]], ... [[(x1, y + 1), (x, z + 1), (x0, x + 1)], ... [x0 + exp(x0/x1) + cos(x1), z - 2]]] ... True """ d = sift(e, lambda w: w.is_Equality and w.lhs.is_Symbol) r = r + [w.args for w in d[True]] e = d[False] return [reps_toposort(r), e] def cse_release_variables(r, e): """ Return tuples giving ``(a, b)`` where ``a`` is a symbol and ``b`` is either an expression or None. The value of None is used when a symbol is no longer needed for subsequent expressions. Use of such output can reduce the memory footprint of lambdified expressions that contain large, repeated subexpressions. Examples ======== >>> from sympy import cse >>> from sympy.simplify.cse_main import cse_release_variables >>> from sympy.abc import x, y >>> eqs = [(x + y - 1)**2, x, x + y, (x + y)/(2*x + 1) + (x + y - 1)**2, (2*x + 1)**(x + y)] >>> defs, rvs = cse_release_variables(*cse(eqs)) >>> for i in defs: ... print(i) ... (x0, x + y) (x1, (x0 - 1)**2) (x2, 2*x + 1) (_3, x0/x2 + x1) (_4, x2**x0) (x2, None) (_0, x1) (x1, None) (_2, x0) (x0, None) (_1, x) >>> print(rvs) (_0, _1, _2, _3, _4) """ if not r: return r, e s, p = zip(*r) esyms = symbols('_:%d' % len(e)) syms = list(esyms) s = list(s) in_use = set(s) p = list(p) # sort e so those with most sub-expressions appear first e = [(e[i], syms[i]) for i in range(len(e))] e, syms = zip(*sorted(e, key=lambda x: -sum([p[s.index(i)].count_ops() for i in x[0].free_symbols & in_use]))) syms = list(syms) p += e rv = [] i = len(p) - 1 while i >= 0: _p = p.pop() c = in_use & _p.free_symbols if c: # sorting for canonical results rv.extend([(s, None) for s in sorted(c, key=str)]) if i >= len(r): rv.append((syms.pop(), _p)) else: rv.append((s[i], _p)) in_use -= c i -= 1 rv.reverse() return rv, esyms # ====end of cse postprocess idioms=========================== def preprocess_for_cse(expr, optimizations): """ Preprocess an expression to optimize for common subexpression elimination. Parameters ========== expr : SymPy expression The target expression to optimize. optimizations : list of (callable, callable) pairs The (preprocessor, postprocessor) pairs. Returns ======= expr : SymPy expression The transformed expression. """ for pre, post in optimizations: if pre is not None: expr = pre(expr) return expr def postprocess_for_cse(expr, optimizations): """Postprocess an expression after common subexpression elimination to return the expression to canonical SymPy form. Parameters ========== expr : SymPy expression The target expression to transform. optimizations : list of (callable, callable) pairs, optional The (preprocessor, postprocessor) pairs. The postprocessors will be applied in reversed order to undo the effects of the preprocessors correctly. Returns ======= expr : SymPy expression The transformed expression. """ for pre, post in reversed(optimizations): if post is not None: expr = post(expr) return expr class FuncArgTracker: """ A class which manages a mapping from functions to arguments and an inverse mapping from arguments to functions. """ def __init__(self, funcs): # To minimize the number of symbolic comparisons, all function arguments # get assigned a value number. self.value_numbers = {} self.value_number_to_value = [] # Both of these maps use integer indices for arguments / functions. self.arg_to_funcset = [] self.func_to_argset = [] for func_i, func in enumerate(funcs): func_argset = OrderedSet() for func_arg in func.args: arg_number = self.get_or_add_value_number(func_arg) func_argset.add(arg_number) self.arg_to_funcset[arg_number].add(func_i) self.func_to_argset.append(func_argset) def get_args_in_value_order(self, argset): """ Return the list of arguments in sorted order according to their value numbers. """ return [self.value_number_to_value[argn] for argn in sorted(argset)] def get_or_add_value_number(self, value): """ Return the value number for the given argument. """ nvalues = len(self.value_numbers) value_number = self.value_numbers.setdefault(value, nvalues) if value_number == nvalues: self.value_number_to_value.append(value) self.arg_to_funcset.append(OrderedSet()) return value_number def stop_arg_tracking(self, func_i): """ Remove the function func_i from the argument to function mapping. """ for arg in self.func_to_argset[func_i]: self.arg_to_funcset[arg].remove(func_i) def get_common_arg_candidates(self, argset, min_func_i=0): """Return a dict whose keys are function numbers. The entries of the dict are the number of arguments said function has in common with ``argset``. Entries have at least 2 items in common. All keys have value at least ``min_func_i``. """ count_map = defaultdict(lambda: 0) if not argset: return count_map funcsets = [self.arg_to_funcset[arg] for arg in argset] # As an optimization below, we handle the largest funcset separately from # the others. largest_funcset = max(funcsets, key=len) for funcset in funcsets: if largest_funcset is funcset: continue for func_i in funcset: if func_i >= min_func_i: count_map[func_i] += 1 # We pick the smaller of the two containers (count_map, largest_funcset) # to iterate over to reduce the number of iterations needed. (smaller_funcs_container, larger_funcs_container) = sorted( [largest_funcset, count_map], key=len) for func_i in smaller_funcs_container: # Not already in count_map? It can't possibly be in the output, so # skip it. if count_map[func_i] < 1: continue if func_i in larger_funcs_container: count_map[func_i] += 1 return {k: v for k, v in count_map.items() if v >= 2} def get_subset_candidates(self, argset, restrict_to_funcset=None): """ Return a set of functions each of which whose argument list contains ``argset``, optionally filtered only to contain functions in ``restrict_to_funcset``. """ iarg = iter(argset) indices = OrderedSet( fi for fi in self.arg_to_funcset[next(iarg)]) if restrict_to_funcset is not None: indices &= restrict_to_funcset for arg in iarg: indices &= self.arg_to_funcset[arg] return indices def update_func_argset(self, func_i, new_argset): """ Update a function with a new set of arguments. """ new_args = OrderedSet(new_argset) old_args = self.func_to_argset[func_i] for deleted_arg in old_args - new_args: self.arg_to_funcset[deleted_arg].remove(func_i) for added_arg in new_args - old_args: self.arg_to_funcset[added_arg].add(func_i) self.func_to_argset[func_i].clear() self.func_to_argset[func_i].update(new_args) class Unevaluated: def __init__(self, func, args): self.func = func self.args = args def __str__(self): return "Uneval<{}>({})".format( self.func, ", ".join(str(a) for a in self.args)) def as_unevaluated_basic(self): return self.func(*self.args, evaluate=False) @property def free_symbols(self): return set().union(*[a.free_symbols for a in self.args]) __repr__ = __str__ def match_common_args(func_class, funcs, opt_subs): """ Recognize and extract common subexpressions of function arguments within a set of function calls. For instance, for the following function calls:: x + z + y sin(x + y) this will extract a common subexpression of `x + y`:: w = x + y w + z sin(w) The function we work with is assumed to be associative and commutative. Parameters ========== func_class: class The function class (e.g. Add, Mul) funcs: list of functions A list of function calls. opt_subs: dict A dictionary of substitutions which this function may update. """ # Sort to ensure that whole-function subexpressions come before the items # that use them. funcs = sorted(funcs, key=lambda f: len(f.args)) arg_tracker = FuncArgTracker(funcs) changed = OrderedSet() for i in range(len(funcs)): common_arg_candidates_counts = arg_tracker.get_common_arg_candidates( arg_tracker.func_to_argset[i], min_func_i=i + 1) # Sort the candidates in order of match size. # This makes us try combining smaller matches first. common_arg_candidates = OrderedSet(sorted( common_arg_candidates_counts.keys(), key=lambda k: (common_arg_candidates_counts[k], k))) while common_arg_candidates: j = common_arg_candidates.pop(last=False) com_args = arg_tracker.func_to_argset[i].intersection( arg_tracker.func_to_argset[j]) if len(com_args) <= 1: # This may happen if a set of common arguments was already # combined in a previous iteration. continue # For all sets, replace the common symbols by the function # over them, to allow recursive matches. diff_i = arg_tracker.func_to_argset[i].difference(com_args) if diff_i: # com_func needs to be unevaluated to allow for recursive matches. com_func = Unevaluated( func_class, arg_tracker.get_args_in_value_order(com_args)) com_func_number = arg_tracker.get_or_add_value_number(com_func) arg_tracker.update_func_argset(i, diff_i | OrderedSet([com_func_number])) changed.add(i) else: # Treat the whole expression as a CSE. # # The reason this needs to be done is somewhat subtle. Within # tree_cse(), to_eliminate only contains expressions that are # seen more than once. The problem is unevaluated expressions # do not compare equal to the evaluated equivalent. So # tree_cse() won't mark funcs[i] as a CSE if we use an # unevaluated version. com_func_number = arg_tracker.get_or_add_value_number(funcs[i]) diff_j = arg_tracker.func_to_argset[j].difference(com_args) arg_tracker.update_func_argset(j, diff_j | OrderedSet([com_func_number])) changed.add(j) for k in arg_tracker.get_subset_candidates( com_args, common_arg_candidates): diff_k = arg_tracker.func_to_argset[k].difference(com_args) arg_tracker.update_func_argset(k, diff_k | OrderedSet([com_func_number])) changed.add(k) if i in changed: opt_subs[funcs[i]] = Unevaluated(func_class, arg_tracker.get_args_in_value_order(arg_tracker.func_to_argset[i])) arg_tracker.stop_arg_tracking(i) def opt_cse(exprs, order='canonical'): """Find optimization opportunities in Adds, Muls, Pows and negative coefficient Muls. Parameters ========== exprs : list of SymPy expressions The expressions to optimize. order : string, 'none' or 'canonical' The order by which Mul and Add arguments are processed. For large expressions where speed is a concern, use the setting order='none'. Returns ======= opt_subs : dictionary of expression substitutions The expression substitutions which can be useful to optimize CSE. Examples ======== >>> from sympy.simplify.cse_main import opt_cse >>> from sympy.abc import x >>> opt_subs = opt_cse([x**-2]) >>> k, v = list(opt_subs.keys())[0], list(opt_subs.values())[0] >>> print((k, v.as_unevaluated_basic())) (x**(-2), 1/(x**2)) """ opt_subs = {} adds = OrderedSet() muls = OrderedSet() seen_subexp = set() def _find_opts(expr): if not isinstance(expr, (Basic, Unevaluated)): return if expr.is_Atom or expr.is_Order: return if iterable(expr): list(map(_find_opts, expr)) return if expr in seen_subexp: return expr seen_subexp.add(expr) list(map(_find_opts, expr.args)) if expr.could_extract_minus_sign(): neg_expr = -expr if not neg_expr.is_Atom: opt_subs[expr] = Unevaluated(Mul, (S.NegativeOne, neg_expr)) seen_subexp.add(neg_expr) expr = neg_expr if isinstance(expr, (Mul, MatMul)): muls.add(expr) elif isinstance(expr, (Add, MatAdd)): adds.add(expr) elif isinstance(expr, (Pow, MatPow)): base, exp = expr.base, expr.exp if exp.could_extract_minus_sign(): opt_subs[expr] = Unevaluated(Pow, (Pow(base, -exp), -1)) for e in exprs: if isinstance(e, (Basic, Unevaluated)): _find_opts(e) # split muls into commutative commutative_muls = OrderedSet() for m in muls: c, nc = m.args_cnc(cset=False) if c: c_mul = m.func(*c) if nc: if c_mul == 1: new_obj = m.func(*nc) else: new_obj = m.func(c_mul, m.func(*nc), evaluate=False) opt_subs[m] = new_obj if len(c) > 1: commutative_muls.add(c_mul) match_common_args(Add, adds, opt_subs) match_common_args(Mul, commutative_muls, opt_subs) return opt_subs def tree_cse(exprs, symbols, opt_subs=None, order='canonical', ignore=()): """Perform raw CSE on expression tree, taking opt_subs into account. Parameters ========== exprs : list of SymPy expressions The expressions to reduce. symbols : infinite iterator yielding unique Symbols The symbols used to label the common subexpressions which are pulled out. opt_subs : dictionary of expression substitutions The expressions to be substituted before any CSE action is performed. order : string, 'none' or 'canonical' The order by which Mul and Add arguments are processed. For large expressions where speed is a concern, use the setting order='none'. ignore : iterable of Symbols Substitutions containing any Symbol from ``ignore`` will be ignored. """ if opt_subs is None: opt_subs = {} ## Find repeated sub-expressions to_eliminate = set() seen_subexp = set() excluded_symbols = set() def _find_repeated(expr): if not isinstance(expr, (Basic, Unevaluated)): return if isinstance(expr, RootOf): return if isinstance(expr, Basic) and ( expr.is_Atom or expr.is_Order or isinstance(expr, (MatrixSymbol, MatrixElement))): if expr.is_Symbol: excluded_symbols.add(expr) return if iterable(expr): args = expr else: if expr in seen_subexp: for ign in ignore: if ign in expr.free_symbols: break else: to_eliminate.add(expr) return seen_subexp.add(expr) if expr in opt_subs: expr = opt_subs[expr] args = expr.args list(map(_find_repeated, args)) for e in exprs: if isinstance(e, Basic): _find_repeated(e) ## Rebuild tree # Remove symbols from the generator that conflict with names in the expressions. symbols = (symbol for symbol in symbols if symbol not in excluded_symbols) replacements = [] subs = {} def _rebuild(expr): if not isinstance(expr, (Basic, Unevaluated)): return expr if not expr.args: return expr if iterable(expr): new_args = [_rebuild(arg) for arg in expr] return expr.func(*new_args) if expr in subs: return subs[expr] orig_expr = expr if expr in opt_subs: expr = opt_subs[expr] # If enabled, parse Muls and Adds arguments by order to ensure # replacement order independent from hashes if order != 'none': if isinstance(expr, (Mul, MatMul)): c, nc = expr.args_cnc() if c == [1]: args = nc else: args = list(ordered(c)) + nc elif isinstance(expr, (Add, MatAdd)): args = list(ordered(expr.args)) else: args = expr.args else: args = expr.args new_args = list(map(_rebuild, args)) if isinstance(expr, Unevaluated) or new_args != args: new_expr = expr.func(*new_args) else: new_expr = expr if orig_expr in to_eliminate: try: sym = next(symbols) except StopIteration: raise ValueError("Symbols iterator ran out of symbols.") if isinstance(orig_expr, MatrixExpr): sym = MatrixSymbol(sym.name, orig_expr.rows, orig_expr.cols) subs[orig_expr] = sym replacements.append((sym, new_expr)) return sym else: return new_expr reduced_exprs = [] for e in exprs: if isinstance(e, Basic): reduced_e = _rebuild(e) else: reduced_e = e reduced_exprs.append(reduced_e) return replacements, reduced_exprs def cse(exprs, symbols=None, optimizations=None, postprocess=None, order='canonical', ignore=(), list=True): """ Perform common subexpression elimination on an expression. Parameters ========== exprs : list of SymPy expressions, or a single SymPy expression The expressions to reduce. symbols : infinite iterator yielding unique Symbols The symbols used to label the common subexpressions which are pulled out. The ``numbered_symbols`` generator is useful. The default is a stream of symbols of the form "x0", "x1", etc. This must be an infinite iterator. optimizations : list of (callable, callable) pairs The (preprocessor, postprocessor) pairs of external optimization functions. Optionally 'basic' can be passed for a set of predefined basic optimizations. Such 'basic' optimizations were used by default in old implementation, however they can be really slow on larger expressions. Now, no pre or post optimizations are made by default. postprocess : a function which accepts the two return values of cse and returns the desired form of output from cse, e.g. if you want the replacements reversed the function might be the following lambda: lambda r, e: return reversed(r), e order : string, 'none' or 'canonical' The order by which Mul and Add arguments are processed. If set to 'canonical', arguments will be canonically ordered. If set to 'none', ordering will be faster but dependent on expressions hashes, thus machine dependent and variable. For large expressions where speed is a concern, use the setting order='none'. ignore : iterable of Symbols Substitutions containing any Symbol from ``ignore`` will be ignored. list : bool, (default True) Returns expression in list or else with same type as input (when False). Returns ======= replacements : list of (Symbol, expression) pairs All of the common subexpressions that were replaced. Subexpressions earlier in this list might show up in subexpressions later in this list. reduced_exprs : list of SymPy expressions The reduced expressions with all of the replacements above. Examples ======== >>> from sympy import cse, SparseMatrix >>> from sympy.abc import x, y, z, w >>> cse(((w + x + y + z)*(w + y + z))/(w + x)**3) ([(x0, y + z), (x1, w + x)], [(w + x0)*(x0 + x1)/x1**3]) List of expressions with recursive substitutions: >>> m = SparseMatrix([x + y, x + y + z]) >>> cse([(x+y)**2, x + y + z, y + z, x + z + y, m]) ([(x0, x + y), (x1, x0 + z)], [x0**2, x1, y + z, x1, Matrix([ [x0], [x1]])]) Note: the type and mutability of input matrices is retained. >>> isinstance(_[1][-1], SparseMatrix) True The user may disallow substitutions containing certain symbols: >>> cse([y**2*(x + 1), 3*y**2*(x + 1)], ignore=(y,)) ([(x0, x + 1)], [x0*y**2, 3*x0*y**2]) The default return value for the reduced expression(s) is a list, even if there is only one expression. The `list` flag preserves the type of the input in the output: >>> cse(x) ([], [x]) >>> cse(x, list=False) ([], x) """ if not list: return _cse_homogeneous(exprs, symbols=symbols, optimizations=optimizations, postprocess=postprocess, order=order, ignore=ignore) if isinstance(exprs, (int, float)): exprs = sympify(exprs) # Handle the case if just one expression was passed. if isinstance(exprs, (Basic, MatrixBase)): exprs = [exprs] copy = exprs temp = [] for e in exprs: if isinstance(e, (Matrix, ImmutableMatrix)): temp.append(Tuple(*e.flat())) elif isinstance(e, (SparseMatrix, ImmutableSparseMatrix)): temp.append(Tuple(*e.todok().items())) else: temp.append(e) exprs = temp del temp if optimizations is None: optimizations = [] elif optimizations == 'basic': optimizations = basic_optimizations # Preprocess the expressions to give us better optimization opportunities. reduced_exprs = [preprocess_for_cse(e, optimizations) for e in exprs] if symbols is None: symbols = numbered_symbols(cls=Symbol) else: # In case we get passed an iterable with an __iter__ method instead of # an actual iterator. symbols = iter(symbols) # Find other optimization opportunities. opt_subs = opt_cse(reduced_exprs, order) # Main CSE algorithm. replacements, reduced_exprs = tree_cse(reduced_exprs, symbols, opt_subs, order, ignore) # Postprocess the expressions to return the expressions to canonical form. exprs = copy for i, (sym, subtree) in enumerate(replacements): subtree = postprocess_for_cse(subtree, optimizations) replacements[i] = (sym, subtree) reduced_exprs = [postprocess_for_cse(e, optimizations) for e in reduced_exprs] # Get the matrices back for i, e in enumerate(exprs): if isinstance(e, (Matrix, ImmutableMatrix)): reduced_exprs[i] = Matrix(e.rows, e.cols, reduced_exprs[i]) if isinstance(e, ImmutableMatrix): reduced_exprs[i] = reduced_exprs[i].as_immutable() elif isinstance(e, (SparseMatrix, ImmutableSparseMatrix)): m = SparseMatrix(e.rows, e.cols, {}) for k, v in reduced_exprs[i]: m[k] = v if isinstance(e, ImmutableSparseMatrix): m = m.as_immutable() reduced_exprs[i] = m if postprocess is None: return replacements, reduced_exprs return postprocess(replacements, reduced_exprs) def _cse_homogeneous(exprs, **kwargs): """ Same as ``cse`` but the ``reduced_exprs`` are returned with the same type as ``exprs`` or a sympified version of the same. Parameters ========== exprs : an Expr, iterable of Expr or dictionary with Expr values the expressions in which repeated subexpressions will be identified kwargs : additional arguments for the ``cse`` function Returns ======= replacements : list of (Symbol, expression) pairs All of the common subexpressions that were replaced. Subexpressions earlier in this list might show up in subexpressions later in this list. reduced_exprs : list of SymPy expressions The reduced expressions with all of the replacements above. Examples ======== >>> from sympy.simplify.cse_main import cse >>> from sympy import cos, Tuple, Matrix >>> from sympy.abc import x >>> output = lambda x: type(cse(x, list=False)[1]) >>> output(1) <class 'sympy.core.numbers.One'> >>> output('cos(x)') <class 'str'> >>> output(cos(x)) cos >>> output(Tuple(1, x)) <class 'sympy.core.containers.Tuple'> >>> output(Matrix([[1,0], [0,1]])) <class 'sympy.matrices.dense.MutableDenseMatrix'> >>> output([1, x]) <class 'list'> >>> output((1, x)) <class 'tuple'> >>> output({1, x}) <class 'set'> """ if isinstance(exprs, str): replacements, reduced_exprs = _cse_homogeneous( sympify(exprs), **kwargs) return replacements, repr(reduced_exprs) if isinstance(exprs, (list, tuple, set)): replacements, reduced_exprs = cse(exprs, **kwargs) return replacements, type(exprs)(reduced_exprs) if isinstance(exprs, dict): keys = list(exprs.keys()) # In order to guarantee the order of the elements. replacements, values = cse([exprs[k] for k in keys], **kwargs) reduced_exprs = dict(zip(keys, values)) return replacements, reduced_exprs try: replacements, (reduced_exprs,) = cse(exprs, **kwargs) except TypeError: # For example 'mpf' objects return [], exprs else: return replacements, reduced_exprs
21a74b29aded6e24462031474dfaddb25c3dd19e33bee4af9aefa6802fce22b6
from sympy.core.numbers import Rational from sympy.core.singleton import S from sympy.functions.elementary.complexes import (conjugate, im, re, sign) from sympy.functions.elementary.exponential import (exp, log as ln) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (acos, cos, sin, atan2) from sympy.simplify.trigsimp import trigsimp from sympy.integrals.integrals import integrate from sympy.matrices.dense import MutableDenseMatrix as Matrix from sympy.core.sympify import sympify, _sympify from sympy.core.expr import Expr from sympy.core.logic import fuzzy_not, fuzzy_or from mpmath.libmp.libmpf import prec_to_dps class Quaternion(Expr): """Provides basic quaternion operations. Quaternion objects can be instantiated as Quaternion(a, b, c, d) as in (a + b*i + c*j + d*k). Examples ======== >>> from sympy import Quaternion >>> q = Quaternion(1, 2, 3, 4) >>> q 1 + 2*i + 3*j + 4*k Quaternions over complex fields can be defined as : >>> from sympy import Quaternion >>> from sympy import symbols, I >>> x = symbols('x') >>> q1 = Quaternion(x, x**3, x, x**2, real_field = False) >>> q2 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False) >>> q1 x + x**3*i + x*j + x**2*k >>> q2 (3 + 4*I) + (2 + 5*I)*i + 0*j + (7 + 8*I)*k References ========== .. [1] http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/ .. [2] https://en.wikipedia.org/wiki/Quaternion """ _op_priority = 11.0 is_commutative = False def __new__(cls, a=0, b=0, c=0, d=0, real_field=True): a, b, c, d = map(sympify, (a, b, c, d)) if any(i.is_commutative is False for i in [a, b, c, d]): raise ValueError("arguments have to be commutative") else: obj = Expr.__new__(cls, a, b, c, d) obj._a = a obj._b = b obj._c = c obj._d = d obj._real_field = real_field return obj @property def a(self): return self._a @property def b(self): return self._b @property def c(self): return self._c @property def d(self): return self._d @property def real_field(self): return self._real_field @classmethod def from_axis_angle(cls, vector, angle): """Returns a rotation quaternion given the axis and the angle of rotation. Parameters ========== vector : tuple of three numbers The vector representation of the given axis. angle : number The angle by which axis is rotated (in radians). Returns ======= Quaternion The normalized rotation quaternion calculated from the given axis and the angle of rotation. Examples ======== >>> from sympy import Quaternion >>> from sympy import pi, sqrt >>> q = Quaternion.from_axis_angle((sqrt(3)/3, sqrt(3)/3, sqrt(3)/3), 2*pi/3) >>> q 1/2 + 1/2*i + 1/2*j + 1/2*k """ (x, y, z) = vector norm = sqrt(x**2 + y**2 + z**2) (x, y, z) = (x / norm, y / norm, z / norm) s = sin(angle * S.Half) a = cos(angle * S.Half) b = x * s c = y * s d = z * s # note that this quaternion is already normalized by construction: # c^2 + (s*x)^2 + (s*y)^2 + (s*z)^2 = c^2 + s^2*(x^2 + y^2 + z^2) = c^2 + s^2 * 1 = c^2 + s^2 = 1 # so, what we return is a normalized quaternion return cls(a, b, c, d) @classmethod def from_rotation_matrix(cls, M): """Returns the equivalent quaternion of a matrix. The quaternion will be normalized only if the matrix is special orthogonal (orthogonal and det(M) = 1). Parameters ========== M : Matrix Input matrix to be converted to equivalent quaternion. M must be special orthogonal (orthogonal and det(M) = 1) for the quaternion to be normalized. Returns ======= Quaternion The quaternion equivalent to given matrix. Examples ======== >>> from sympy import Quaternion >>> from sympy import Matrix, symbols, cos, sin, trigsimp >>> x = symbols('x') >>> M = Matrix([[cos(x), -sin(x), 0], [sin(x), cos(x), 0], [0, 0, 1]]) >>> q = trigsimp(Quaternion.from_rotation_matrix(M)) >>> q sqrt(2)*sqrt(cos(x) + 1)/2 + 0*i + 0*j + sqrt(2 - 2*cos(x))*sign(sin(x))/2*k """ absQ = M.det()**Rational(1, 3) a = sqrt(absQ + M[0, 0] + M[1, 1] + M[2, 2]) / 2 b = sqrt(absQ + M[0, 0] - M[1, 1] - M[2, 2]) / 2 c = sqrt(absQ - M[0, 0] + M[1, 1] - M[2, 2]) / 2 d = sqrt(absQ - M[0, 0] - M[1, 1] + M[2, 2]) / 2 b = b * sign(M[2, 1] - M[1, 2]) c = c * sign(M[0, 2] - M[2, 0]) d = d * sign(M[1, 0] - M[0, 1]) return Quaternion(a, b, c, d) def __add__(self, other): return self.add(other) def __radd__(self, other): return self.add(other) def __sub__(self, other): return self.add(other*-1) def __mul__(self, other): return self._generic_mul(self, _sympify(other)) def __rmul__(self, other): return self._generic_mul(_sympify(other), self) def __pow__(self, p): return self.pow(p) def __neg__(self): return Quaternion(-self._a, -self._b, -self._c, -self.d) def __truediv__(self, other): return self * sympify(other)**-1 def __rtruediv__(self, other): return sympify(other) * self**-1 def _eval_Integral(self, *args): return self.integrate(*args) def diff(self, *symbols, **kwargs): kwargs.setdefault('evaluate', True) return self.func(*[a.diff(*symbols, **kwargs) for a in self.args]) def add(self, other): """Adds quaternions. Parameters ========== other : Quaternion The quaternion to add to current (self) quaternion. Returns ======= Quaternion The resultant quaternion after adding self to other Examples ======== >>> from sympy import Quaternion >>> from sympy import symbols >>> q1 = Quaternion(1, 2, 3, 4) >>> q2 = Quaternion(5, 6, 7, 8) >>> q1.add(q2) 6 + 8*i + 10*j + 12*k >>> q1 + 5 6 + 2*i + 3*j + 4*k >>> x = symbols('x', real = True) >>> q1.add(x) (x + 1) + 2*i + 3*j + 4*k Quaternions over complex fields : >>> from sympy import Quaternion >>> from sympy import I >>> q3 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False) >>> q3.add(2 + 3*I) (5 + 7*I) + (2 + 5*I)*i + 0*j + (7 + 8*I)*k """ q1 = self q2 = sympify(other) # If q2 is a number or a SymPy expression instead of a quaternion if not isinstance(q2, Quaternion): if q1.real_field and q2.is_complex: return Quaternion(re(q2) + q1.a, im(q2) + q1.b, q1.c, q1.d) elif q2.is_commutative: return Quaternion(q1.a + q2, q1.b, q1.c, q1.d) else: raise ValueError("Only commutative expressions can be added with a Quaternion.") return Quaternion(q1.a + q2.a, q1.b + q2.b, q1.c + q2.c, q1.d + q2.d) def mul(self, other): """Multiplies quaternions. Parameters ========== other : Quaternion or symbol The quaternion to multiply to current (self) quaternion. Returns ======= Quaternion The resultant quaternion after multiplying self with other Examples ======== >>> from sympy import Quaternion >>> from sympy import symbols >>> q1 = Quaternion(1, 2, 3, 4) >>> q2 = Quaternion(5, 6, 7, 8) >>> q1.mul(q2) (-60) + 12*i + 30*j + 24*k >>> q1.mul(2) 2 + 4*i + 6*j + 8*k >>> x = symbols('x', real = True) >>> q1.mul(x) x + 2*x*i + 3*x*j + 4*x*k Quaternions over complex fields : >>> from sympy import Quaternion >>> from sympy import I >>> q3 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False) >>> q3.mul(2 + 3*I) (2 + 3*I)*(3 + 4*I) + (2 + 3*I)*(2 + 5*I)*i + 0*j + (2 + 3*I)*(7 + 8*I)*k """ return self._generic_mul(self, _sympify(other)) @staticmethod def _generic_mul(q1, q2): """Generic multiplication. Parameters ========== q1 : Quaternion or symbol q2 : Quaternion or symbol It is important to note that if neither q1 nor q2 is a Quaternion, this function simply returns q1 * q2. Returns ======= Quaternion The resultant quaternion after multiplying q1 and q2 Examples ======== >>> from sympy import Quaternion >>> from sympy import Symbol, S >>> q1 = Quaternion(1, 2, 3, 4) >>> q2 = Quaternion(5, 6, 7, 8) >>> Quaternion._generic_mul(q1, q2) (-60) + 12*i + 30*j + 24*k >>> Quaternion._generic_mul(q1, S(2)) 2 + 4*i + 6*j + 8*k >>> x = Symbol('x', real = True) >>> Quaternion._generic_mul(q1, x) x + 2*x*i + 3*x*j + 4*x*k Quaternions over complex fields : >>> from sympy import I >>> q3 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False) >>> Quaternion._generic_mul(q3, 2 + 3*I) (2 + 3*I)*(3 + 4*I) + (2 + 3*I)*(2 + 5*I)*i + 0*j + (2 + 3*I)*(7 + 8*I)*k """ # None is a Quaternion: if not isinstance(q1, Quaternion) and not isinstance(q2, Quaternion): return q1 * q2 # If q1 is a number or a SymPy expression instead of a quaternion if not isinstance(q1, Quaternion): if q2.real_field and q1.is_complex: return Quaternion(re(q1), im(q1), 0, 0) * q2 elif q1.is_commutative: return Quaternion(q1 * q2.a, q1 * q2.b, q1 * q2.c, q1 * q2.d) else: raise ValueError("Only commutative expressions can be multiplied with a Quaternion.") # If q2 is a number or a SymPy expression instead of a quaternion if not isinstance(q2, Quaternion): if q1.real_field and q2.is_complex: return q1 * Quaternion(re(q2), im(q2), 0, 0) elif q2.is_commutative: return Quaternion(q2 * q1.a, q2 * q1.b, q2 * q1.c, q2 * q1.d) else: raise ValueError("Only commutative expressions can be multiplied with a Quaternion.") return Quaternion(-q1.b*q2.b - q1.c*q2.c - q1.d*q2.d + q1.a*q2.a, q1.b*q2.a + q1.c*q2.d - q1.d*q2.c + q1.a*q2.b, -q1.b*q2.d + q1.c*q2.a + q1.d*q2.b + q1.a*q2.c, q1.b*q2.c - q1.c*q2.b + q1.d*q2.a + q1.a * q2.d) def _eval_conjugate(self): """Returns the conjugate of the quaternion.""" q = self return Quaternion(q.a, -q.b, -q.c, -q.d) def norm(self): """Returns the norm of the quaternion.""" q = self # trigsimp is used to simplify sin(x)^2 + cos(x)^2 (these terms # arise when from_axis_angle is used). return sqrt(trigsimp(q.a**2 + q.b**2 + q.c**2 + q.d**2)) def normalize(self): """Returns the normalized form of the quaternion.""" q = self return q * (1/q.norm()) def inverse(self): """Returns the inverse of the quaternion.""" q = self if not q.norm(): raise ValueError("Cannot compute inverse for a quaternion with zero norm") return conjugate(q) * (1/q.norm()**2) def pow(self, p): """Finds the pth power of the quaternion. Parameters ========== p : int Power to be applied on quaternion. Returns ======= Quaternion Returns the p-th power of the current quaternion. Returns the inverse if p = -1. Examples ======== >>> from sympy import Quaternion >>> q = Quaternion(1, 2, 3, 4) >>> q.pow(4) 668 + (-224)*i + (-336)*j + (-448)*k """ p = sympify(p) q = self if p == -1: return q.inverse() res = 1 if not p.is_Integer: return NotImplemented if p < 0: q, p = q.inverse(), -p while p > 0: if p % 2 == 1: res = q * res p = p//2 q = q * q return res def exp(self): """Returns the exponential of q (e^q). Returns ======= Quaternion Exponential of q (e^q). Examples ======== >>> from sympy import Quaternion >>> q = Quaternion(1, 2, 3, 4) >>> q.exp() E*cos(sqrt(29)) + 2*sqrt(29)*E*sin(sqrt(29))/29*i + 3*sqrt(29)*E*sin(sqrt(29))/29*j + 4*sqrt(29)*E*sin(sqrt(29))/29*k """ # exp(q) = e^a(cos||v|| + v/||v||*sin||v||) q = self vector_norm = sqrt(q.b**2 + q.c**2 + q.d**2) a = exp(q.a) * cos(vector_norm) b = exp(q.a) * sin(vector_norm) * q.b / vector_norm c = exp(q.a) * sin(vector_norm) * q.c / vector_norm d = exp(q.a) * sin(vector_norm) * q.d / vector_norm return Quaternion(a, b, c, d) def _ln(self): """Returns the natural logarithm of the quaternion (_ln(q)). Examples ======== >>> from sympy import Quaternion >>> q = Quaternion(1, 2, 3, 4) >>> q._ln() log(sqrt(30)) + 2*sqrt(29)*acos(sqrt(30)/30)/29*i + 3*sqrt(29)*acos(sqrt(30)/30)/29*j + 4*sqrt(29)*acos(sqrt(30)/30)/29*k """ # _ln(q) = _ln||q|| + v/||v||*arccos(a/||q||) q = self vector_norm = sqrt(q.b**2 + q.c**2 + q.d**2) q_norm = q.norm() a = ln(q_norm) b = q.b * acos(q.a / q_norm) / vector_norm c = q.c * acos(q.a / q_norm) / vector_norm d = q.d * acos(q.a / q_norm) / vector_norm return Quaternion(a, b, c, d) def _eval_evalf(self, prec): """Returns the floating point approximations (decimal numbers) of the quaternion. Returns ======= Quaternion Floating point approximations of quaternion(self) Examples ======== >>> from sympy import Quaternion >>> from sympy import sqrt >>> q = Quaternion(1/sqrt(1), 1/sqrt(2), 1/sqrt(3), 1/sqrt(4)) >>> q.evalf() 1.00000000000000 + 0.707106781186547*i + 0.577350269189626*j + 0.500000000000000*k """ nprec = prec_to_dps(prec) return Quaternion(*[arg.evalf(n=nprec) for arg in self.args]) def pow_cos_sin(self, p): """Computes the pth power in the cos-sin form. Parameters ========== p : int Power to be applied on quaternion. Returns ======= Quaternion The p-th power in the cos-sin form. Examples ======== >>> from sympy import Quaternion >>> q = Quaternion(1, 2, 3, 4) >>> q.pow_cos_sin(4) 900*cos(4*acos(sqrt(30)/30)) + 1800*sqrt(29)*sin(4*acos(sqrt(30)/30))/29*i + 2700*sqrt(29)*sin(4*acos(sqrt(30)/30))/29*j + 3600*sqrt(29)*sin(4*acos(sqrt(30)/30))/29*k """ # q = ||q||*(cos(a) + u*sin(a)) # q^p = ||q||^p * (cos(p*a) + u*sin(p*a)) q = self (v, angle) = q.to_axis_angle() q2 = Quaternion.from_axis_angle(v, p * angle) return q2 * (q.norm()**p) def integrate(self, *args): """Computes integration of quaternion. Returns ======= Quaternion Integration of the quaternion(self) with the given variable. Examples ======== Indefinite Integral of quaternion : >>> from sympy import Quaternion >>> from sympy.abc import x >>> q = Quaternion(1, 2, 3, 4) >>> q.integrate(x) x + 2*x*i + 3*x*j + 4*x*k Definite integral of quaternion : >>> from sympy import Quaternion >>> from sympy.abc import x >>> q = Quaternion(1, 2, 3, 4) >>> q.integrate((x, 1, 5)) 4 + 8*i + 12*j + 16*k """ # TODO: is this expression correct? return Quaternion(integrate(self.a, *args), integrate(self.b, *args), integrate(self.c, *args), integrate(self.d, *args)) @staticmethod def rotate_point(pin, r): """Returns the coordinates of the point pin(a 3 tuple) after rotation. Parameters ========== pin : tuple A 3-element tuple of coordinates of a point which needs to be rotated. r : Quaternion or tuple Axis and angle of rotation. It's important to note that when r is a tuple, it must be of the form (axis, angle) Returns ======= tuple The coordinates of the point after rotation. Examples ======== >>> from sympy import Quaternion >>> from sympy import symbols, trigsimp, cos, sin >>> x = symbols('x') >>> q = Quaternion(cos(x/2), 0, 0, sin(x/2)) >>> trigsimp(Quaternion.rotate_point((1, 1, 1), q)) (sqrt(2)*cos(x + pi/4), sqrt(2)*sin(x + pi/4), 1) >>> (axis, angle) = q.to_axis_angle() >>> trigsimp(Quaternion.rotate_point((1, 1, 1), (axis, angle))) (sqrt(2)*cos(x + pi/4), sqrt(2)*sin(x + pi/4), 1) """ if isinstance(r, tuple): # if r is of the form (vector, angle) q = Quaternion.from_axis_angle(r[0], r[1]) else: # if r is a quaternion q = r.normalize() pout = q * Quaternion(0, pin[0], pin[1], pin[2]) * conjugate(q) return (pout.b, pout.c, pout.d) def to_axis_angle(self): """Returns the axis and angle of rotation of a quaternion Returns ======= tuple Tuple of (axis, angle) Examples ======== >>> from sympy import Quaternion >>> q = Quaternion(1, 1, 1, 1) >>> (axis, angle) = q.to_axis_angle() >>> axis (sqrt(3)/3, sqrt(3)/3, sqrt(3)/3) >>> angle 2*pi/3 """ q = self if q.a.is_negative: q = q * -1 q = q.normalize() angle = trigsimp(2 * acos(q.a)) # Since quaternion is normalised, q.a is less than 1. s = sqrt(1 - q.a*q.a) x = trigsimp(q.b / s) y = trigsimp(q.c / s) z = trigsimp(q.d / s) v = (x, y, z) t = (v, angle) return t def to_rotation_matrix(self, v=None): """Returns the equivalent rotation transformation matrix of the quaternion which represents rotation about the origin if v is not passed. Parameters ========== v : tuple or None Default value: None Returns ======= tuple Returns the equivalent rotation transformation matrix of the quaternion which represents rotation about the origin if v is not passed. Examples ======== >>> from sympy import Quaternion >>> from sympy import symbols, trigsimp, cos, sin >>> x = symbols('x') >>> q = Quaternion(cos(x/2), 0, 0, sin(x/2)) >>> trigsimp(q.to_rotation_matrix()) Matrix([ [cos(x), -sin(x), 0], [sin(x), cos(x), 0], [ 0, 0, 1]]) Generates a 4x4 transformation matrix (used for rotation about a point other than the origin) if the point(v) is passed as an argument. Examples ======== >>> from sympy import Quaternion >>> from sympy import symbols, trigsimp, cos, sin >>> x = symbols('x') >>> q = Quaternion(cos(x/2), 0, 0, sin(x/2)) >>> trigsimp(q.to_rotation_matrix((1, 1, 1))) Matrix([ [cos(x), -sin(x), 0, sin(x) - cos(x) + 1], [sin(x), cos(x), 0, -sin(x) - cos(x) + 1], [ 0, 0, 1, 0], [ 0, 0, 0, 1]]) """ q = self s = q.norm()**-2 m00 = 1 - 2*s*(q.c**2 + q.d**2) m01 = 2*s*(q.b*q.c - q.d*q.a) m02 = 2*s*(q.b*q.d + q.c*q.a) m10 = 2*s*(q.b*q.c + q.d*q.a) m11 = 1 - 2*s*(q.b**2 + q.d**2) m12 = 2*s*(q.c*q.d - q.b*q.a) m20 = 2*s*(q.b*q.d - q.c*q.a) m21 = 2*s*(q.c*q.d + q.b*q.a) m22 = 1 - 2*s*(q.b**2 + q.c**2) if not v: return Matrix([[m00, m01, m02], [m10, m11, m12], [m20, m21, m22]]) else: (x, y, z) = v m03 = x - x*m00 - y*m01 - z*m02 m13 = y - x*m10 - y*m11 - z*m12 m23 = z - x*m20 - y*m21 - z*m22 m30 = m31 = m32 = 0 m33 = 1 return Matrix([[m00, m01, m02, m03], [m10, m11, m12, m13], [m20, m21, m22, m23], [m30, m31, m32, m33]]) def scalar_part(self): r"""Returns scalar part($\mathbf{S}(q)$) of the quaternion q. Explanation =========== Given a quaternion $q = a + bi + cj + dk$, returns $\mathbf{S}(q) = a$. Examples ======== >>> from sympy.algebras.quaternion import Quaternion >>> q = Quaternion(4, 8, 13, 12) >>> q.scalar_part() 4 """ return self.a def vector_part(self): r""" Returns vector part($\mathbf{V}(q)$) of the quaternion q. Explanation =========== Given a quaternion $q = a + bi + cj + dk$, returns $\mathbf{V}(q) = bi + cj + dk$. Examples ======== >>> from sympy.algebras.quaternion import Quaternion >>> q = Quaternion(1, 1, 1, 1) >>> q.vector_part() 0 + 1*i + 1*j + 1*k >>> q = Quaternion(4, 8, 13, 12) >>> q.vector_part() 0 + 8*i + 13*j + 12*k """ return Quaternion(0, self.b, self.c, self.d) def axis(self): r""" Returns the axis($\mathbf{Ax}(q)$) of the quaternion. Explanation =========== Given a quaternion $q = a + bi + cj + dk$, returns $\mathbf{Ax}(q)$ i.e., the versor of the vector part of that quaternion equal to $\mathbf{U}[\mathbf{V}(q)]$. The axis is always an imaginary unit with square equal to $-1 + 0i + 0j + 0k$. Examples ======== >>> from sympy.algebras.quaternion import Quaternion >>> q = Quaternion(1, 1, 1, 1) >>> q.axis() 0 + sqrt(3)/3*i + sqrt(3)/3*j + sqrt(3)/3*k See Also ======== vector_part """ axis = self.vector_part().normalize() return Quaternion(0, axis.b, axis.c, axis.d) def is_pure(self): """ Returns true if the quaternion is pure, false if the quaternion is not pure or returns none if it is unknown. Explanation =========== A pure quaternion (also a vector quaternion) is a quaternion with scalar part equal to 0. Examples ======== >>> from sympy.algebras.quaternion import Quaternion >>> q = Quaternion(0, 8, 13, 12) >>> q.is_pure() True See Also ======== scalar_part """ return self.a.is_zero def is_zero_quaternion(self): """ Returns true if the quaternion is a zero quaternion or false if it is not a zero quaternion and None if the value is unknown. Explanation =========== A zero quaternion is a quaternion with both scalar part and vector part equal to 0. Examples ======== >>> from sympy.algebras.quaternion import Quaternion >>> q = Quaternion(1, 0, 0, 0) >>> q.is_zero_quaternion() False >>> q = Quaternion(0, 0, 0, 0) >>> q.is_zero_quaternion() True See Also ======== scalar_part vector_part """ return self.norm().is_zero def angle(self): r""" Returns the angle of the quaternion measured in the real-axis plane. Explanation =========== Given a quaternion $q = a + bi + cj + dk$ where a, b, c and d are real numbers, returns the angle of the quaternion given by .. math:: angle := atan2(\sqrt{b^2 + c^2 + d^2}, {a}) Examples ======== >>> from sympy.algebras.quaternion import Quaternion >>> q = Quaternion(1, 4, 4, 4) >>> q.angle() atan(4*sqrt(3)) """ return atan2(self.vector_part().norm(), self.scalar_part()) def arc_coplanar(self, other): """ Returns True if the transformation arcs represented by the input quaternions happen in the same plane. Explanation =========== Two quaternions are said to be coplanar (in this arc sense) when their axes are parallel. The plane of a quaternion is the one normal to its axis. Parameters ========== other : a Quaternion Returns ======= True : if the planes of the two quaternions are the same, apart from its orientation/sign. False : if the planes of the two quaternions are not the same, apart from its orientation/sign. None : if plane of either of the quaternion is unknown. Examples ======== >>> from sympy.algebras.quaternion import Quaternion >>> q1 = Quaternion(1, 4, 4, 4) >>> q2 = Quaternion(3, 8, 8, 8) >>> Quaternion.arc_coplanar(q1, q2) True >>> q1 = Quaternion(2, 8, 13, 12) >>> Quaternion.arc_coplanar(q1, q2) False See Also ======== vector_coplanar is_pure """ if (self.is_zero_quaternion()) or (other.is_zero_quaternion()): raise ValueError('Neither of the given quaternions can be 0') return fuzzy_or([(self.axis() - other.axis()).is_zero_quaternion(), (self.axis() + other.axis()).is_zero_quaternion()]) @classmethod def vector_coplanar(cls, q1, q2, q3): r""" Returns True if the axis of the pure quaternions seen as 3D vectors q1, q2, and q3 are coplanar. Explanation =========== Three pure quaternions are vector coplanar if the quaternions seen as 3D vectors are coplanar. Parameters ========== q1 : a pure Quaternion. q2 : a pure Quaternion. q3 : a pure Quaternion. Returns ======= True : if the axis of the pure quaternions seen as 3D vectors q1, q2, and q3 are coplanar. False : if the axis of the pure quaternions seen as 3D vectors q1, q2, and q3 are not coplanar. None : if the axis of the pure quaternions seen as 3D vectors q1, q2, and q3 are coplanar is unknown. Examples ======== >>> from sympy.algebras.quaternion import Quaternion >>> q1 = Quaternion(0, 4, 4, 4) >>> q2 = Quaternion(0, 8, 8, 8) >>> q3 = Quaternion(0, 24, 24, 24) >>> Quaternion.vector_coplanar(q1, q2, q3) True >>> q1 = Quaternion(0, 8, 16, 8) >>> q2 = Quaternion(0, 8, 3, 12) >>> Quaternion.vector_coplanar(q1, q2, q3) False See Also ======== axis is_pure """ if fuzzy_not(q1.is_pure()) or fuzzy_not(q2.is_pure()) or fuzzy_not(q3.is_pure()): raise ValueError('The given quaternions must be pure') M = Matrix([[q1.b, q1.c, q1.d], [q2.b, q2.c, q2.d], [q3.b, q3.c, q3.d]]).det() return M.is_zero def parallel(self, other): """ Returns True if the two pure quaternions seen as 3D vectors are parallel. Explanation =========== Two pure quaternions are called parallel when their vector product is commutative which implies that the quaternions seen as 3D vectors have same direction. Parameters ========== other : a Quaternion Returns ======= True : if the two pure quaternions seen as 3D vectors are parallel. False : if the two pure quaternions seen as 3D vectors are not parallel. None : if the two pure quaternions seen as 3D vectors are parallel is unknown. Examples ======== >>> from sympy.algebras.quaternion import Quaternion >>> q = Quaternion(0, 4, 4, 4) >>> q1 = Quaternion(0, 8, 8, 8) >>> q.parallel(q1) True >>> q1 = Quaternion(0, 8, 13, 12) >>> q.parallel(q1) False """ if fuzzy_not(self.is_pure()) or fuzzy_not(other.is_pure()): raise ValueError('The provided quaternions must be pure') return (self*other - other*self).is_zero_quaternion() def orthogonal(self, other): """ Returns the orthogonality of two quaternions. Explanation =========== Two pure quaternions are called orthogonal when their product is anti-commutative. Parameters ========== other : a Quaternion Returns ======= True : if the two pure quaternions seen as 3D vectors are orthogonal. False : if the two pure quaternions seen as 3D vectors are not orthogonal. None : if the two pure quaternions seen as 3D vectors are orthogonal is unknown. Examples ======== >>> from sympy.algebras.quaternion import Quaternion >>> q = Quaternion(0, 4, 4, 4) >>> q1 = Quaternion(0, 8, 8, 8) >>> q.orthogonal(q1) False >>> q1 = Quaternion(0, 2, 2, 0) >>> q = Quaternion(0, 2, -2, 0) >>> q.orthogonal(q1) True """ if fuzzy_not(self.is_pure()) or fuzzy_not(other.is_pure()): raise ValueError('The given quaternions must be pure') return (self*other + other*self).is_zero_quaternion() def index_vector(self): r""" Returns the index vector of the quaternion. Explanation =========== Index vector is given by $\mathbf{T}(q)$ multiplied by $\mathbf{Ax}(q)$ where $\mathbf{Ax}(q)$ is the axis of the quaternion q, and mod(q) is the $\mathbf{T}(q)$ (magnitude) of the quaternion. Returns ======= Quaternion: representing index vector of the provided quaternion. Examples ======== >>> from sympy.algebras.quaternion import Quaternion >>> q = Quaternion(2, 4, 2, 4) >>> q.index_vector() 0 + 4*sqrt(10)/3*i + 2*sqrt(10)/3*j + 4*sqrt(10)/3*k See Also ======== axis norm """ return self.norm() * self.axis() def mensor(self): """ Returns the natural logarithm of the norm(magnitude) of the quaternion. Examples ======== >>> from sympy.algebras.quaternion import Quaternion >>> q = Quaternion(2, 4, 2, 4) >>> q.mensor() log(2*sqrt(10)) >>> q.norm() 2*sqrt(10) See Also ======== norm """ return ln(self.norm())
e6164b03a923732e7101e6262796c825eb4fb9e1a0d359a577447a5fd6ce03b1
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 (sympy_deprecation_warning, SymPyDeprecationWarning, ignore_warnings) # 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 is deprecated. The Manifold object is now immutable. Instead use a separate list to keep track of the patches. """, []) 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_systms is deprecated. The Patch class is now immutable. Instead use a separate list to keep track of coordinate systems. """, []) 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: sympy_deprecation_warning( f""" The 'names' argument to CoordSystem is deprecated. Use 'symbols' instead. That is, replace CoordSystem(..., names={names}) with CoordSystem(..., symbols=[{', '.join(["Symbol(" + repr(n) + ", real=True)" for n in names])}]) """, deprecated_since_version="1.7", active_deprecations_target="deprecated-diffgeom-mutable", ) 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): sympy_deprecation_warning( f""" Passing a string as the coordinate symbol name to CoordSystem is deprecated. Pass a Symbol with the appropriate name and assumptions instead. That is, replace {s} with Symbol({s!r}, real=True). """, deprecated_since_version="1.7", active_deprecations_target="deprecated-diffgeom-mutable", ) 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( """ CoordSystem.transforms is deprecated. The CoordSystem class is now immutable. Use the 'relations' keyword argument to the CoordSystems() constructor to specify relations. """, {}) 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): sympy_deprecation_warning( """ The CoordSystem.connect_to() method is deprecated. Instead, generate a new instance of CoordSystem with the 'relations' keyword argument (CoordSystem classes are now immutable). """, deprecated_since_version="1.7", active_deprecations_target="deprecated-diffgeom-mutable", ) 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``.""" sympy_deprecation_warning( """ The CoordSystem.coord_tuple_transform_to() method is deprecated. Use the CoordSystem.transform() method instead. """, deprecated_since_version="1.7", active_deprecations_target="deprecated-diffgeom-mutable", ) coords = Matrix(coords) if self != to_sys: with ignore_warnings(SymPyDeprecationWarning): 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] 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, message, data): super().__init__(data) self.message = message def warn(self): sympy_deprecation_warning( self.message, deprecated_since_version="1.7", active_deprecations_target="deprecated-diffgeom-mutable", stacklevel=4 ) 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
d79cdde67895e1d68b41b155d2bdb7f99da42c945cf75c53c421650a15ee5ea2
""" The classes used here are for the internal use of assumptions system only and should not be used anywhere else as these do not possess the signatures common to SymPy objects. For general use of logic constructs please refer to sympy.logic classes And, Or, Not, etc. """ from itertools import combinations, product, zip_longest from sympy.assumptions.assume import AppliedPredicate, Predicate from sympy.core.relational import Eq, Ne, Gt, Lt, Ge, Le from sympy.core.singleton import S from sympy.logic.boolalg import Or, And, Not, Xnor from sympy.logic.boolalg import (Equivalent, ITE, Implies, Nand, Nor, Xor) class Literal: """ The smallest element of a CNF object. Parameters ========== lit : Boolean expression is_Not : bool Examples ======== >>> from sympy import Q >>> from sympy.assumptions.cnf import Literal >>> from sympy.abc import x >>> Literal(Q.even(x)) Literal(Q.even(x), False) >>> Literal(~Q.even(x)) Literal(Q.even(x), True) """ def __new__(cls, lit, is_Not=False): if isinstance(lit, Not): lit = lit.args[0] is_Not = True elif isinstance(lit, (AND, OR, Literal)): return ~lit if is_Not else lit obj = super().__new__(cls) obj.lit = lit obj.is_Not = is_Not return obj @property def arg(self): return self.lit def rcall(self, expr): if callable(self.lit): lit = self.lit(expr) else: try: lit = self.lit.apply(expr) except AttributeError: lit = self.lit.rcall(expr) return type(self)(lit, self.is_Not) def __invert__(self): is_Not = not self.is_Not return Literal(self.lit, is_Not) def __str__(self): return '{}({}, {})'.format(type(self).__name__, self.lit, self.is_Not) __repr__ = __str__ def __eq__(self, other): return self.arg == other.arg and self.is_Not == other.is_Not def __hash__(self): h = hash((type(self).__name__, self.arg, self.is_Not)) return h class OR: """ A low-level implementation for Or """ def __init__(self, *args): self._args = args @property def args(self): return sorted(self._args, key=str) def rcall(self, expr): return type(self)(*[arg.rcall(expr) for arg in self._args ]) def __invert__(self): return AND(*[~arg for arg in self._args]) def __hash__(self): return hash((type(self).__name__,) + tuple(self.args)) def __eq__(self, other): return self.args == other.args def __str__(self): s = '(' + ' | '.join([str(arg) for arg in self.args]) + ')' return s __repr__ = __str__ class AND: """ A low-level implementation for And """ def __init__(self, *args): self._args = args def __invert__(self): return OR(*[~arg for arg in self._args]) @property def args(self): return sorted(self._args, key=str) def rcall(self, expr): return type(self)(*[arg.rcall(expr) for arg in self._args ]) def __hash__(self): return hash((type(self).__name__,) + tuple(self.args)) def __eq__(self, other): return self.args == other.args def __str__(self): s = '('+' & '.join([str(arg) for arg in self.args])+')' return s __repr__ = __str__ def to_NNF(expr, composite_map=None): """ Generates the Negation Normal Form of any boolean expression in terms of AND, OR, and Literal objects. Examples ======== >>> from sympy import Q, Eq >>> from sympy.assumptions.cnf import to_NNF >>> from sympy.abc import x, y >>> expr = Q.even(x) & ~Q.positive(x) >>> to_NNF(expr) (Literal(Q.even(x), False) & Literal(Q.positive(x), True)) Supported boolean objects are converted to corresponding predicates. >>> to_NNF(Eq(x, y)) Literal(Q.eq(x, y), False) If ``composite_map`` argument is given, ``to_NNF`` decomposes the specified predicate into a combination of primitive predicates. >>> cmap = {Q.nonpositive: Q.negative | Q.zero} >>> to_NNF(Q.nonpositive, cmap) (Literal(Q.negative, False) | Literal(Q.zero, False)) >>> to_NNF(Q.nonpositive(x), cmap) (Literal(Q.negative(x), False) | Literal(Q.zero(x), False)) """ from sympy.assumptions.ask import Q if composite_map is None: composite_map = {} binrelpreds = {Eq: Q.eq, Ne: Q.ne, Gt: Q.gt, Lt: Q.lt, Ge: Q.ge, Le: Q.le} if type(expr) in binrelpreds: pred = binrelpreds[type(expr)] expr = pred(*expr.args) if isinstance(expr, Not): arg = expr.args[0] tmp = to_NNF(arg, composite_map) # Strategy: negate the NNF of expr return ~tmp if isinstance(expr, Or): return OR(*[to_NNF(x, composite_map) for x in Or.make_args(expr)]) if isinstance(expr, And): return AND(*[to_NNF(x, composite_map) for x in And.make_args(expr)]) if isinstance(expr, Nand): tmp = AND(*[to_NNF(x, composite_map) for x in expr.args]) return ~tmp if isinstance(expr, Nor): tmp = OR(*[to_NNF(x, composite_map) for x in expr.args]) return ~tmp if isinstance(expr, Xor): cnfs = [] for i in range(0, len(expr.args) + 1, 2): for neg in combinations(expr.args, i): clause = [~to_NNF(s, composite_map) if s in neg else to_NNF(s, composite_map) for s in expr.args] cnfs.append(OR(*clause)) return AND(*cnfs) if isinstance(expr, Xnor): cnfs = [] for i in range(0, len(expr.args) + 1, 2): for neg in combinations(expr.args, i): clause = [~to_NNF(s, composite_map) if s in neg else to_NNF(s, composite_map) for s in expr.args] cnfs.append(OR(*clause)) return ~AND(*cnfs) if isinstance(expr, Implies): L, R = to_NNF(expr.args[0], composite_map), to_NNF(expr.args[1], composite_map) return OR(~L, R) if isinstance(expr, Equivalent): cnfs = [] for a, b in zip_longest(expr.args, expr.args[1:], fillvalue=expr.args[0]): a = to_NNF(a, composite_map) b = to_NNF(b, composite_map) cnfs.append(OR(~a, b)) return AND(*cnfs) if isinstance(expr, ITE): L = to_NNF(expr.args[0], composite_map) M = to_NNF(expr.args[1], composite_map) R = to_NNF(expr.args[2], composite_map) return AND(OR(~L, M), OR(L, R)) if isinstance(expr, AppliedPredicate): pred, args = expr.function, expr.arguments newpred = composite_map.get(pred, None) if newpred is not None: return to_NNF(newpred.rcall(*args), composite_map) if isinstance(expr, Predicate): newpred = composite_map.get(expr, None) if newpred is not None: return to_NNF(newpred, composite_map) return Literal(expr) def distribute_AND_over_OR(expr): """ Distributes AND over OR in the NNF expression. Returns the result( Conjunctive Normal Form of expression) as a CNF object. """ if not isinstance(expr, (AND, OR)): tmp = set() tmp.add(frozenset((expr,))) return CNF(tmp) if isinstance(expr, OR): return CNF.all_or(*[distribute_AND_over_OR(arg) for arg in expr._args]) if isinstance(expr, AND): return CNF.all_and(*[distribute_AND_over_OR(arg) for arg in expr._args]) class CNF: """ Class to represent CNF of a Boolean expression. Consists of set of clauses, which themselves are stored as frozenset of Literal objects. Examples ======== >>> from sympy import Q >>> from sympy.assumptions.cnf import CNF >>> from sympy.abc import x >>> cnf = CNF.from_prop(Q.real(x) & ~Q.zero(x)) >>> cnf.clauses {frozenset({Literal(Q.zero(x), True)}), frozenset({Literal(Q.negative(x), False), Literal(Q.positive(x), False), Literal(Q.zero(x), False)})} """ def __init__(self, clauses=None): if not clauses: clauses = set() self.clauses = clauses def add(self, prop): clauses = CNF.to_CNF(prop).clauses self.add_clauses(clauses) def __str__(self): s = ' & '.join( ['(' + ' | '.join([str(lit) for lit in clause]) +')' for clause in self.clauses] ) return s def extend(self, props): for p in props: self.add(p) return self def copy(self): return CNF(set(self.clauses)) def add_clauses(self, clauses): self.clauses |= clauses @classmethod def from_prop(cls, prop): res = cls() res.add(prop) return res def __iand__(self, other): self.add_clauses(other.clauses) return self def all_predicates(self): predicates = set() for c in self.clauses: predicates |= {arg.lit for arg in c} return predicates def _or(self, cnf): clauses = set() for a, b in product(self.clauses, cnf.clauses): tmp = set(a) for t in b: tmp.add(t) clauses.add(frozenset(tmp)) return CNF(clauses) def _and(self, cnf): clauses = self.clauses.union(cnf.clauses) return CNF(clauses) def _not(self): clss = list(self.clauses) ll = set() for x in clss[-1]: ll.add(frozenset((~x,))) ll = CNF(ll) for rest in clss[:-1]: p = set() for x in rest: p.add(frozenset((~x,))) ll = ll._or(CNF(p)) return ll def rcall(self, expr): clause_list = list() for clause in self.clauses: lits = [arg.rcall(expr) for arg in clause] clause_list.append(OR(*lits)) expr = AND(*clause_list) return distribute_AND_over_OR(expr) @classmethod def all_or(cls, *cnfs): b = cnfs[0].copy() for rest in cnfs[1:]: b = b._or(rest) return b @classmethod def all_and(cls, *cnfs): b = cnfs[0].copy() for rest in cnfs[1:]: b = b._and(rest) return b @classmethod def to_CNF(cls, expr): from sympy.assumptions.facts import get_composite_predicates expr = to_NNF(expr, get_composite_predicates()) expr = distribute_AND_over_OR(expr) return expr @classmethod def CNF_to_cnf(cls, cnf): """ Converts CNF object to SymPy's boolean expression retaining the form of expression. """ def remove_literal(arg): return Not(arg.lit) if arg.is_Not else arg.lit return And(*(Or(*(remove_literal(arg) for arg in clause)) for clause in cnf.clauses)) class EncodedCNF: """ Class for encoding the CNF expression. """ def __init__(self, data=None, encoding=None): if not data and not encoding: data = [] encoding = {} self.data = data self.encoding = encoding self._symbols = list(encoding.keys()) def from_cnf(self, cnf): self._symbols = list(cnf.all_predicates()) n = len(self._symbols) self.encoding = dict(list(zip(self._symbols, list(range(1, n + 1))))) self.data = [self.encode(clause) for clause in cnf.clauses] @property def symbols(self): return self._symbols @property def variables(self): return range(1, len(self._symbols) + 1) def copy(self): new_data = [set(clause) for clause in self.data] return EncodedCNF(new_data, dict(self.encoding)) def add_prop(self, prop): cnf = CNF.from_prop(prop) self.add_from_cnf(cnf) def add_from_cnf(self, cnf): clauses = [self.encode(clause) for clause in cnf.clauses] self.data += clauses def encode_arg(self, arg): literal = arg.lit value = self.encoding.get(literal, None) if value is None: n = len(self._symbols) self._symbols.append(literal) value = self.encoding[literal] = n + 1 if arg.is_Not: return -value else: return value def encode(self, clause): return {self.encode_arg(arg) if not arg.lit == S.false else 0 for arg in clause}
731d00f2832dc09c962a73fd90ed8a58ac6996fa55c478203c6c0c26f6c7c26b
from sympy.core.add import Add from sympy.core.exprtools import factor_terms from sympy.core.function import expand_log, _mexpand 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.functions.elementary.exponential import (LambertW, exp, log) from sympy.functions.elementary.miscellaneous import root from sympy.polys.polyroots import roots from sympy.polys.polytools import Poly, factor from sympy.simplify.simplify import separatevars from sympy.simplify.radsimp import collect from sympy.simplify.simplify import powsimp from sympy.solvers.solvers import solve, _invert from sympy.utilities.iterables import uniq def _filtered_gens(poly, symbol): """process the generators of ``poly``, returning the set of generators that have ``symbol``. If there are two generators that are inverses of each other, prefer the one that has no denominator. Examples ======== >>> from sympy.solvers.bivariate import _filtered_gens >>> from sympy import Poly, exp >>> from sympy.abc import x >>> _filtered_gens(Poly(x + 1/x + exp(x)), x) {x, exp(x)} """ # TODO it would be good to pick the smallest divisible power # instead of the base for something like x**4 + x**2 --> # return x**2 not x gens = {g for g in poly.gens if symbol in g.free_symbols} for g in list(gens): ag = 1/g if g in gens and ag in gens: if ag.as_numer_denom()[1] is not S.One: g = ag gens.remove(g) return gens def _mostfunc(lhs, func, X=None): """Returns the term in lhs which contains the most of the func-type things e.g. log(log(x)) wins over log(x) if both terms appear. ``func`` can be a function (exp, log, etc...) or any other SymPy object, like Pow. If ``X`` is not ``None``, then the function returns the term composed with the most ``func`` having the specified variable. Examples ======== >>> from sympy.solvers.bivariate import _mostfunc >>> from sympy import exp >>> from sympy.abc import x, y >>> _mostfunc(exp(x) + exp(exp(x) + 2), exp) exp(exp(x) + 2) >>> _mostfunc(exp(x) + exp(exp(y) + 2), exp) exp(exp(y) + 2) >>> _mostfunc(exp(x) + exp(exp(y) + 2), exp, x) exp(x) >>> _mostfunc(x, exp, x) is None True >>> _mostfunc(exp(x) + exp(x*y), exp, x) exp(x) """ fterms = [tmp for tmp in lhs.atoms(func) if (not X or X.is_Symbol and X in tmp.free_symbols or not X.is_Symbol and tmp.has(X))] if len(fterms) == 1: return fterms[0] elif fterms: return max(list(ordered(fterms)), key=lambda x: x.count(func)) return None def _linab(arg, symbol): """Return ``a, b, X`` assuming ``arg`` can be written as ``a*X + b`` where ``X`` is a symbol-dependent factor and ``a`` and ``b`` are independent of ``symbol``. Examples ======== >>> from sympy.solvers.bivariate import _linab >>> from sympy.abc import x, y >>> from sympy import exp, S >>> _linab(S(2), x) (2, 0, 1) >>> _linab(2*x, x) (2, 0, x) >>> _linab(y + y*x + 2*x, x) (y + 2, y, x) >>> _linab(3 + 2*exp(x), x) (2, 3, exp(x)) """ arg = factor_terms(arg.expand()) ind, dep = arg.as_independent(symbol) if arg.is_Mul and dep.is_Add: a, b, x = _linab(dep, symbol) return ind*a, ind*b, x if not arg.is_Add: b = 0 a, x = ind, dep else: b = ind a, x = separatevars(dep).as_independent(symbol, as_Add=False) if x.could_extract_minus_sign(): a = -a x = -x return a, b, x def _lambert(eq, x): """ Given an expression assumed to be in the form ``F(X, a..f) = a*log(b*X + c) + d*X + f = 0`` where X = g(x) and x = g^-1(X), return the Lambert solution, ``x = g^-1(-c/b + (a/d)*W(d/(a*b)*exp(c*d/a/b)*exp(-f/a)))``. """ eq = _mexpand(expand_log(eq)) mainlog = _mostfunc(eq, log, x) if not mainlog: return [] # violated assumptions other = eq.subs(mainlog, 0) if isinstance(-other, log): eq = (eq - other).subs(mainlog, mainlog.args[0]) mainlog = mainlog.args[0] if not isinstance(mainlog, log): return [] # violated assumptions other = -(-other).args[0] eq += other if x not in other.free_symbols: return [] # violated assumptions d, f, X2 = _linab(other, x) logterm = collect(eq - other, mainlog) a = logterm.as_coefficient(mainlog) if a is None or x in a.free_symbols: return [] # violated assumptions logarg = mainlog.args[0] b, c, X1 = _linab(logarg, x) if X1 != X2: return [] # violated assumptions # invert the generator X1 so we have x(u) u = Dummy('rhs') xusolns = solve(X1 - u, x) # There are infinitely many branches for LambertW # but only branches for k = -1 and 0 might be real. The k = 0 # branch is real and the k = -1 branch is real if the LambertW argumen # in in range [-1/e, 0]. Since `solve` does not return infinite # solutions we will only include the -1 branch if it tests as real. # Otherwise, inclusion of any LambertW in the solution indicates to # the user that there are imaginary solutions corresponding to # different k values. lambert_real_branches = [-1, 0] sol = [] # solution of the given Lambert equation is like # sol = -c/b + (a/d)*LambertW(arg, k), # where arg = d/(a*b)*exp((c*d-b*f)/a/b) and k in lambert_real_branches. # Instead of considering the single arg, `d/(a*b)*exp((c*d-b*f)/a/b)`, # the individual `p` roots obtained when writing `exp((c*d-b*f)/a/b)` # as `exp(A/p) = exp(A)**(1/p)`, where `p` is an Integer, are used. # calculating args for LambertW num, den = ((c*d-b*f)/a/b).as_numer_denom() p, den = den.as_coeff_Mul() e = exp(num/den) t = Dummy('t') args = [d/(a*b)*t for t in roots(t**p - e, t).keys()] # calculating solutions from args for arg in args: for k in lambert_real_branches: w = LambertW(arg, k) if k and not w.is_real: continue rhs = -c/b + (a/d)*w sol.extend(xu.subs(u, rhs) for xu in xusolns) return sol def _solve_lambert(f, symbol, gens): """Return solution to ``f`` if it is a Lambert-type expression else raise NotImplementedError. For ``f(X, a..f) = a*log(b*X + c) + d*X - f = 0`` the solution for ``X`` is ``X = -c/b + (a/d)*W(d/(a*b)*exp(c*d/a/b)*exp(f/a))``. There are a variety of forms for `f(X, a..f)` as enumerated below: 1a1) if B**B = R for R not in [0, 1] (since those cases would already be solved before getting here) then log of both sides gives log(B) + log(log(B)) = log(log(R)) and X = log(B), a = 1, b = 1, c = 0, d = 1, f = log(log(R)) 1a2) if B*(b*log(B) + c)**a = R then log of both sides gives log(B) + a*log(b*log(B) + c) = log(R) and X = log(B), d=1, f=log(R) 1b) if a*log(b*B + c) + d*B = R and X = B, f = R 2a) if (b*B + c)*exp(d*B + g) = R then log of both sides gives log(b*B + c) + d*B + g = log(R) and X = B, a = 1, f = log(R) - g 2b) if g*exp(d*B + h) - b*B = c then the log form is log(g) + d*B + h - log(b*B + c) = 0 and X = B, a = -1, f = -h - log(g) 3) if d*p**(a*B + g) - b*B = c then the log form is log(d) + (a*B + g)*log(p) - log(b*B + c) = 0 and X = B, a = -1, d = a*log(p), f = -log(d) - g*log(p) """ def _solve_even_degree_expr(expr, t, symbol): """Return the unique solutions of equations derived from ``expr`` by replacing ``t`` with ``+/- symbol``. Parameters ========== expr : Expr The expression which includes a dummy variable t to be replaced with +symbol and -symbol. symbol : Symbol The symbol for which a solution is being sought. Returns ======= List of unique solution of the two equations generated by replacing ``t`` with positive and negative ``symbol``. Notes ===== If ``expr = 2*log(t) + x/2` then solutions for ``2*log(x) + x/2 = 0`` and ``2*log(-x) + x/2 = 0`` are returned by this function. Though this may seem counter-intuitive, one must note that the ``expr`` being solved here has been derived from a different expression. For an expression like ``eq = x**2*g(x) = 1``, if we take the log of both sides we obtain ``log(x**2) + log(g(x)) = 0``. If x is positive then this simplifies to ``2*log(x) + log(g(x)) = 0``; the Lambert-solving routines will return solutions for this, but we must also consider the solutions for ``2*log(-x) + log(g(x))`` since those must also be a solution of ``eq`` which has the same value when the ``x`` in ``x**2`` is negated. If `g(x)` does not have even powers of symbol then we do not want to replace the ``x`` there with ``-x``. So the role of the ``t`` in the expression received by this function is to mark where ``+/-x`` should be inserted before obtaining the Lambert solutions. """ nlhs, plhs = [ expr.xreplace({t: sgn*symbol}) for sgn in (-1, 1)] sols = _solve_lambert(nlhs, symbol, gens) if plhs != nlhs: sols.extend(_solve_lambert(plhs, symbol, gens)) # uniq is needed for a case like # 2*log(t) - log(-z**2) + log(z + log(x) + log(z)) # where subtituting t with +/-x gives all the same solution; # uniq, rather than list(set()), is used to maintain canonical # order return list(uniq(sols)) nrhs, lhs = f.as_independent(symbol, as_Add=True) rhs = -nrhs lamcheck = [tmp for tmp in gens if (tmp.func in [exp, log] or (tmp.is_Pow and symbol in tmp.exp.free_symbols))] if not lamcheck: raise NotImplementedError() if lhs.is_Add or lhs.is_Mul: # replacing all even_degrees of symbol with dummy variable t # since these will need special handling; non-Add/Mul do not # need this handling t = Dummy('t', **symbol.assumptions0) lhs = lhs.replace( lambda i: # find symbol**even i.is_Pow and i.base == symbol and i.exp.is_even, lambda i: # replace t**even t**i.exp) if lhs.is_Add and lhs.has(t): t_indep = lhs.subs(t, 0) t_term = lhs - t_indep _rhs = rhs - t_indep if not t_term.is_Add and _rhs and not ( t_term.has(S.ComplexInfinity, S.NaN)): eq = expand_log(log(t_term) - log(_rhs)) return _solve_even_degree_expr(eq, t, symbol) elif lhs.is_Mul and rhs: # this needs to happen whether t is present or not lhs = expand_log(log(lhs), force=True) rhs = log(rhs) if lhs.has(t) and lhs.is_Add: # it expanded from Mul to Add eq = lhs - rhs return _solve_even_degree_expr(eq, t, symbol) # restore symbol in lhs lhs = lhs.xreplace({t: symbol}) lhs = powsimp(factor(lhs, deep=True)) # make sure we have inverted as completely as possible r = Dummy() i, lhs = _invert(lhs - r, symbol) rhs = i.xreplace({r: rhs}) # For the first forms: # # 1a1) B**B = R will arrive here as B*log(B) = log(R) # lhs is Mul so take log of both sides: # log(B) + log(log(B)) = log(log(R)) # 1a2) B*(b*log(B) + c)**a = R will arrive unchanged so # lhs is Mul, so take log of both sides: # log(B) + a*log(b*log(B) + c) = log(R) # 1b) d*log(a*B + b) + c*B = R will arrive unchanged so # lhs is Add, so isolate c*B and expand log of both sides: # log(c) + log(B) = log(R - d*log(a*B + b)) soln = [] if not soln: mainlog = _mostfunc(lhs, log, symbol) if mainlog: if lhs.is_Mul and rhs != 0: soln = _lambert(log(lhs) - log(rhs), symbol) elif lhs.is_Add: other = lhs.subs(mainlog, 0) if other and not other.is_Add and [ tmp for tmp in other.atoms(Pow) if symbol in tmp.free_symbols]: if not rhs: diff = log(other) - log(other - lhs) else: diff = log(lhs - other) - log(rhs - other) soln = _lambert(expand_log(diff), symbol) else: #it's ready to go soln = _lambert(lhs - rhs, symbol) # For the next forms, # # collect on main exp # 2a) (b*B + c)*exp(d*B + g) = R # lhs is mul, so take log of both sides: # log(b*B + c) + d*B = log(R) - g # 2b) g*exp(d*B + h) - b*B = R # lhs is add, so add b*B to both sides, # take the log of both sides and rearrange to give # log(R + b*B) - d*B = log(g) + h if not soln: mainexp = _mostfunc(lhs, exp, symbol) if mainexp: lhs = collect(lhs, mainexp) if lhs.is_Mul and rhs != 0: soln = _lambert(expand_log(log(lhs) - log(rhs)), symbol) elif lhs.is_Add: # move all but mainexp-containing term to rhs other = lhs.subs(mainexp, 0) mainterm = lhs - other rhs = rhs - other if (mainterm.could_extract_minus_sign() and rhs.could_extract_minus_sign()): mainterm *= -1 rhs *= -1 diff = log(mainterm) - log(rhs) soln = _lambert(expand_log(diff), symbol) # For the last form: # # 3) d*p**(a*B + g) - b*B = c # collect on main pow, add b*B to both sides, # take log of both sides and rearrange to give # a*B*log(p) - log(b*B + c) = -log(d) - g*log(p) if not soln: mainpow = _mostfunc(lhs, Pow, symbol) if mainpow and symbol in mainpow.exp.free_symbols: lhs = collect(lhs, mainpow) if lhs.is_Mul and rhs != 0: # b*B = 0 soln = _lambert(expand_log(log(lhs) - log(rhs)), symbol) elif lhs.is_Add: # move all but mainpow-containing term to rhs other = lhs.subs(mainpow, 0) mainterm = lhs - other rhs = rhs - other diff = log(mainterm) - log(rhs) soln = _lambert(expand_log(diff), symbol) if not soln: raise NotImplementedError('%s does not appear to have a solution in ' 'terms of LambertW' % f) return list(ordered(soln)) def bivariate_type(f, x, y, *, first=True): """Given an expression, f, 3 tests will be done to see what type of composite bivariate it might be, options for u(x, y) are:: x*y x+y x*y+x x*y+y If it matches one of these types, ``u(x, y)``, ``P(u)`` and dummy variable ``u`` will be returned. Solving ``P(u)`` for ``u`` and equating the solutions to ``u(x, y)`` and then solving for ``x`` or ``y`` is equivalent to solving the original expression for ``x`` or ``y``. If ``x`` and ``y`` represent two functions in the same variable, e.g. ``x = g(t)`` and ``y = h(t)``, then if ``u(x, y) - p`` can be solved for ``t`` then these represent the solutions to ``P(u) = 0`` when ``p`` are the solutions of ``P(u) = 0``. Only positive values of ``u`` are considered. Examples ======== >>> from sympy import solve >>> from sympy.solvers.bivariate import bivariate_type >>> from sympy.abc import x, y >>> eq = (x**2 - 3).subs(x, x + y) >>> bivariate_type(eq, x, y) (x + y, _u**2 - 3, _u) >>> uxy, pu, u = _ >>> usol = solve(pu, u); usol [sqrt(3)] >>> [solve(uxy - s) for s in solve(pu, u)] [[{x: -y + sqrt(3)}]] >>> all(eq.subs(s).equals(0) for sol in _ for s in sol) True """ u = Dummy('u', positive=True) if first: p = Poly(f, x, y) f = p.as_expr() _x = Dummy() _y = Dummy() rv = bivariate_type(Poly(f.subs({x: _x, y: _y}), _x, _y), _x, _y, first=False) if rv: reps = {_x: x, _y: y} return rv[0].xreplace(reps), rv[1].xreplace(reps), rv[2] return p = f f = p.as_expr() # f(x*y) args = Add.make_args(p.as_expr()) new = [] for a in args: a = _mexpand(a.subs(x, u/y)) free = a.free_symbols if x in free or y in free: break new.append(a) else: return x*y, Add(*new), u def ok(f, v, c): new = _mexpand(f.subs(v, c)) free = new.free_symbols return None if (x in free or y in free) else new # f(a*x + b*y) new = [] d = p.degree(x) if p.degree(y) == d: a = root(p.coeff_monomial(x**d), d) b = root(p.coeff_monomial(y**d), d) new = ok(f, x, (u - b*y)/a) if new is not None: return a*x + b*y, new, u # f(a*x*y + b*y) new = [] d = p.degree(x) if p.degree(y) == d: for itry in range(2): a = root(p.coeff_monomial(x**d*y**d), d) b = root(p.coeff_monomial(y**d), d) new = ok(f, x, (u - b*y)/a/y) if new is not None: return a*x*y + b*y, new, u x, y = y, x
beefa9eef253f7152e05792df7ad1195e58faae551cfe0a24a783c9f03f40158
r""" This module is intended for solving recurrences or, in other words, difference equations. Currently supported are linear, inhomogeneous equations with polynomial or rational coefficients. The solutions are obtained among polynomials, rational functions, hypergeometric terms, or combinations of hypergeometric term which are pairwise dissimilar. ``rsolve_X`` functions were meant as a low level interface for ``rsolve`` which would use Mathematica's syntax. Given a recurrence relation: .. math:: a_{k}(n) y(n+k) + a_{k-1}(n) y(n+k-1) + ... + a_{0}(n) y(n) = f(n) where `k > 0` and `a_{i}(n)` are polynomials in `n`. To use ``rsolve_X`` we need to put all coefficients in to a list ``L`` of `k+1` elements the following way: ``L = [a_{0}(n), ..., a_{k-1}(n), a_{k}(n)]`` where ``L[i]``, for `i=0, \ldots, k`, maps to `a_{i}(n) y(n+i)` (`y(n+i)` is implicit). For example if we would like to compute `m`-th Bernoulli polynomial up to a constant (example was taken from rsolve_poly docstring), then we would use `b(n+1) - b(n) = m n^{m-1}` recurrence, which has solution `b(n) = B_m + C`. Then ``L = [-1, 1]`` and `f(n) = m n^(m-1)` and finally for `m=4`: >>> from sympy import Symbol, bernoulli, rsolve_poly >>> n = Symbol('n', integer=True) >>> rsolve_poly([-1, 1], 4*n**3, n) C0 + n**4 - 2*n**3 + n**2 >>> bernoulli(4, n) n**4 - 2*n**3 + n**2 - 1/30 For the sake of completeness, `f(n)` can be: [1] a polynomial -> rsolve_poly [2] a rational function -> rsolve_ratio [3] a hypergeometric function -> rsolve_hyper """ from collections import defaultdict from sympy.concrete import product from sympy.core.singleton import S from sympy.core.numbers import Rational, I from sympy.core.symbol import Symbol, Wild, Dummy from sympy.core.relational import Equality from sympy.core.add import Add from sympy.core.mul import Mul from sympy.core.sorting import default_sort_key from sympy.core.sympify import sympify from sympy.simplify import simplify, hypersimp, hypersimilar # type: ignore from sympy.solvers import solve, solve_undetermined_coeffs from sympy.polys import Poly, quo, gcd, lcm, roots, resultant from sympy.functions import binomial, factorial, FallingFactorial, RisingFactorial from sympy.matrices import Matrix, casoratian from sympy.utilities.iterables import numbered_symbols def rsolve_poly(coeffs, f, n, shift=0, **hints): r""" Given linear recurrence operator `\operatorname{L}` of order `k` with polynomial coefficients and inhomogeneous equation `\operatorname{L} y = f`, where `f` is a polynomial, we seek for all polynomial solutions over field `K` of characteristic zero. The algorithm performs two basic steps: (1) Compute degree `N` of the general polynomial solution. (2) Find all polynomials of degree `N` or less of `\operatorname{L} y = f`. There are two methods for computing the polynomial solutions. If the degree bound is relatively small, i.e. it's smaller than or equal to the order of the recurrence, then naive method of undetermined coefficients is being used. This gives system of algebraic equations with `N+1` unknowns. In the other case, the algorithm performs transformation of the initial equation to an equivalent one, for which the system of algebraic equations has only `r` indeterminates. This method is quite sophisticated (in comparison with the naive one) and was invented together by Abramov, Bronstein and Petkovsek. It is possible to generalize the algorithm implemented here to the case of linear q-difference and differential equations. Lets say that we would like to compute `m`-th Bernoulli polynomial up to a constant. For this we can use `b(n+1) - b(n) = m n^{m-1}` recurrence, which has solution `b(n) = B_m + C`. For example: >>> from sympy import Symbol, rsolve_poly >>> n = Symbol('n', integer=True) >>> rsolve_poly([-1, 1], 4*n**3, n) C0 + n**4 - 2*n**3 + n**2 References ========== .. [1] S. A. Abramov, M. Bronstein and M. Petkovsek, On polynomial solutions of linear operator equations, in: T. Levelt, ed., Proc. ISSAC '95, ACM Press, New York, 1995, 290-296. .. [2] M. Petkovsek, Hypergeometric solutions of linear recurrences with polynomial coefficients, J. Symbolic Computation, 14 (1992), 243-264. .. [3] M. Petkovsek, H. S. Wilf, D. Zeilberger, A = B, 1996. """ f = sympify(f) if not f.is_polynomial(n): return None homogeneous = f.is_zero r = len(coeffs) - 1 coeffs = [Poly(coeff, n) for coeff in coeffs] polys = [Poly(0, n)]*(r + 1) terms = [(S.Zero, S.NegativeInfinity)]*(r + 1) for i in range(r + 1): for j in range(i, r + 1): polys[i] += coeffs[j]*(binomial(j, i).as_poly(n)) if not polys[i].is_zero: (exp,), coeff = polys[i].LT() terms[i] = (coeff, exp) d = b = terms[0][1] for i in range(1, r + 1): if terms[i][1] > d: d = terms[i][1] if terms[i][1] - i > b: b = terms[i][1] - i d, b = int(d), int(b) x = Dummy('x') degree_poly = S.Zero for i in range(r + 1): if terms[i][1] - i == b: degree_poly += terms[i][0]*FallingFactorial(x, i) nni_roots = list(roots(degree_poly, x, filter='Z', predicate=lambda r: r >= 0).keys()) if nni_roots: N = [max(nni_roots)] else: N = [] if homogeneous: N += [-b - 1] else: N += [f.as_poly(n).degree() - b, -b - 1] N = int(max(N)) if N < 0: if homogeneous: if hints.get('symbols', False): return (S.Zero, []) else: return S.Zero else: return None if N <= r: C = [] y = E = S.Zero for i in range(N + 1): C.append(Symbol('C' + str(i + shift))) y += C[i] * n**i for i in range(r + 1): E += coeffs[i].as_expr()*y.subs(n, n + i) solutions = solve_undetermined_coeffs(E - f, C, n) if solutions is not None: C = [c for c in C if (c not in solutions)] result = y.subs(solutions) else: return None # TBD else: A = r U = N + A + b + 1 nni_roots = list(roots(polys[r], filter='Z', predicate=lambda r: r >= 0).keys()) if nni_roots != []: a = max(nni_roots) + 1 else: a = S.Zero def _zero_vector(k): return [S.Zero] * k def _one_vector(k): return [S.One] * k def _delta(p, k): B = S.One D = p.subs(n, a + k) for i in range(1, k + 1): B *= Rational(i - k - 1, i) D += B * p.subs(n, a + k - i) return D alpha = {} for i in range(-A, d + 1): I = _one_vector(d + 1) for k in range(1, d + 1): I[k] = I[k - 1] * (x + i - k + 1)/k alpha[i] = S.Zero for j in range(A + 1): for k in range(d + 1): B = binomial(k, i + j) D = _delta(polys[j].as_expr(), k) alpha[i] += I[k]*B*D V = Matrix(U, A, lambda i, j: int(i == j)) if homogeneous: for i in range(A, U): v = _zero_vector(A) for k in range(1, A + b + 1): if i - k < 0: break B = alpha[k - A].subs(x, i - k) for j in range(A): v[j] += B * V[i - k, j] denom = alpha[-A].subs(x, i) for j in range(A): V[i, j] = -v[j] / denom else: G = _zero_vector(U) for i in range(A, U): v = _zero_vector(A) g = S.Zero for k in range(1, A + b + 1): if i - k < 0: break B = alpha[k - A].subs(x, i - k) for j in range(A): v[j] += B * V[i - k, j] g += B * G[i - k] denom = alpha[-A].subs(x, i) for j in range(A): V[i, j] = -v[j] / denom G[i] = (_delta(f, i - A) - g) / denom P, Q = _one_vector(U), _zero_vector(A) for i in range(1, U): P[i] = (P[i - 1] * (n - a - i + 1)/i).expand() for i in range(A): Q[i] = Add(*[(v*p).expand() for v, p in zip(V[:, i], P)]) if not homogeneous: h = Add(*[(g*p).expand() for g, p in zip(G, P)]) C = [Symbol('C' + str(i + shift)) for i in range(A)] g = lambda i: Add(*[c*_delta(q, i) for c, q in zip(C, Q)]) if homogeneous: E = [g(i) for i in range(N + 1, U)] else: E = [g(i) + _delta(h, i) for i in range(N + 1, U)] if E != []: solutions = solve(E, *C) if not solutions: if homogeneous: if hints.get('symbols', False): return (S.Zero, []) else: return S.Zero else: return None else: solutions = {} if homogeneous: result = S.Zero else: result = h for c, q in list(zip(C, Q)): if c in solutions: s = solutions[c]*q C.remove(c) else: s = c*q result += s.expand() if hints.get('symbols', False): return (result, C) else: return result def rsolve_ratio(coeffs, f, n, **hints): r""" Given linear recurrence operator `\operatorname{L}` of order `k` with polynomial coefficients and inhomogeneous equation `\operatorname{L} y = f`, where `f` is a polynomial, we seek for all rational solutions over field `K` of characteristic zero. This procedure accepts only polynomials, however if you are interested in solving recurrence with rational coefficients then use ``rsolve`` which will pre-process the given equation and run this procedure with polynomial arguments. The algorithm performs two basic steps: (1) Compute polynomial `v(n)` which can be used as universal denominator of any rational solution of equation `\operatorname{L} y = f`. (2) Construct new linear difference equation by substitution `y(n) = u(n)/v(n)` and solve it for `u(n)` finding all its polynomial solutions. Return ``None`` if none were found. Algorithm implemented here is a revised version of the original Abramov's algorithm, developed in 1989. The new approach is much simpler to implement and has better overall efficiency. This method can be easily adapted to q-difference equations case. Besides finding rational solutions alone, this functions is an important part of Hyper algorithm were it is used to find particular solution of inhomogeneous part of a recurrence. Examples ======== >>> from sympy.abc import x >>> from sympy.solvers.recurr import rsolve_ratio >>> rsolve_ratio([-2*x**3 + x**2 + 2*x - 1, 2*x**3 + x**2 - 6*x, ... - 2*x**3 - 11*x**2 - 18*x - 9, 2*x**3 + 13*x**2 + 22*x + 8], 0, x) C2*(2*x - 3)/(2*(x**2 - 1)) References ========== .. [1] S. A. Abramov, Rational solutions of linear difference and q-difference equations with polynomial coefficients, in: T. Levelt, ed., Proc. ISSAC '95, ACM Press, New York, 1995, 285-289 See Also ======== rsolve_hyper """ f = sympify(f) if not f.is_polynomial(n): return None coeffs = list(map(sympify, coeffs)) r = len(coeffs) - 1 A, B = coeffs[r], coeffs[0] A = A.subs(n, n - r).expand() h = Dummy('h') res = resultant(A, B.subs(n, n + h), n) if not res.is_polynomial(h): p, q = res.as_numer_denom() res = quo(p, q, h) nni_roots = list(roots(res, h, filter='Z', predicate=lambda r: r >= 0).keys()) if not nni_roots: return rsolve_poly(coeffs, f, n, **hints) else: C, numers = S.One, [S.Zero]*(r + 1) for i in range(int(max(nni_roots)), -1, -1): d = gcd(A, B.subs(n, n + i), n) A = quo(A, d, n) B = quo(B, d.subs(n, n - i), n) C *= Mul(*[d.subs(n, n - j) for j in range(i + 1)]) denoms = [C.subs(n, n + i) for i in range(r + 1)] for i in range(r + 1): g = gcd(coeffs[i], denoms[i], n) numers[i] = quo(coeffs[i], g, n) denoms[i] = quo(denoms[i], g, n) for i in range(r + 1): numers[i] *= Mul(*(denoms[:i] + denoms[i + 1:])) result = rsolve_poly(numers, f * Mul(*denoms), n, **hints) if result is not None: if hints.get('symbols', False): return (simplify(result[0] / C), result[1]) else: return simplify(result / C) else: return None def rsolve_hyper(coeffs, f, n, **hints): r""" Given linear recurrence operator `\operatorname{L}` of order `k` with polynomial coefficients and inhomogeneous equation `\operatorname{L} y = f` we seek for all hypergeometric solutions over field `K` of characteristic zero. The inhomogeneous part can be either hypergeometric or a sum of a fixed number of pairwise dissimilar hypergeometric terms. The algorithm performs three basic steps: (1) Group together similar hypergeometric terms in the inhomogeneous part of `\operatorname{L} y = f`, and find particular solution using Abramov's algorithm. (2) Compute generating set of `\operatorname{L}` and find basis in it, so that all solutions are linearly independent. (3) Form final solution with the number of arbitrary constants equal to dimension of basis of `\operatorname{L}`. Term `a(n)` is hypergeometric if it is annihilated by first order linear difference equations with polynomial coefficients or, in simpler words, if consecutive term ratio is a rational function. The output of this procedure is a linear combination of fixed number of hypergeometric terms. However the underlying method can generate larger class of solutions - D'Alembertian terms. Note also that this method not only computes the kernel of the inhomogeneous equation, but also reduces in to a basis so that solutions generated by this procedure are linearly independent Examples ======== >>> from sympy.solvers import rsolve_hyper >>> from sympy.abc import x >>> rsolve_hyper([-1, -1, 1], 0, x) C0*(1/2 - sqrt(5)/2)**x + C1*(1/2 + sqrt(5)/2)**x >>> rsolve_hyper([-1, 1], 1 + x, x) C0 + x*(x + 1)/2 References ========== .. [1] M. Petkovsek, Hypergeometric solutions of linear recurrences with polynomial coefficients, J. Symbolic Computation, 14 (1992), 243-264. .. [2] M. Petkovsek, H. S. Wilf, D. Zeilberger, A = B, 1996. """ coeffs = list(map(sympify, coeffs)) f = sympify(f) r, kernel, symbols = len(coeffs) - 1, [], set() if not f.is_zero: if f.is_Add: similar = {} for g in f.expand().args: if not g.is_hypergeometric(n): return None for h in similar.keys(): if hypersimilar(g, h, n): similar[h] += g break else: similar[g] = S.Zero inhomogeneous = [g + h for g, h in similar.items()] elif f.is_hypergeometric(n): inhomogeneous = [f] else: return None for i, g in enumerate(inhomogeneous): coeff, polys = S.One, coeffs[:] denoms = [S.One]*(r + 1) s = hypersimp(g, n) for j in range(1, r + 1): coeff *= s.subs(n, n + j - 1) p, q = coeff.as_numer_denom() polys[j] *= p denoms[j] = q for j in range(r + 1): polys[j] *= Mul(*(denoms[:j] + denoms[j + 1:])) # FIXME: The call to rsolve_ratio below should suffice (rsolve_poly # call can be removed) but the XFAIL test_rsolve_ratio_missed must # be fixed first. R = rsolve_ratio(polys, Mul(*denoms), n, symbols=True) if R is not None: R, syms = R if syms: R = R.subs(zip(syms, [0]*len(syms))) else: R = rsolve_poly(polys, Mul(*denoms), n) if R: inhomogeneous[i] *= R else: return None result = Add(*inhomogeneous) result = simplify(result) else: result = S.Zero Z = Dummy('Z') p, q = coeffs[0], coeffs[r].subs(n, n - r + 1) p_factors = [z for z in roots(p, n).keys()] q_factors = [z for z in roots(q, n).keys()] factors = [(S.One, S.One)] for p in p_factors: for q in q_factors: if p.is_integer and q.is_integer and p <= q: continue else: factors += [(n - p, n - q)] p = [(n - p, S.One) for p in p_factors] q = [(S.One, n - q) for q in q_factors] factors = p + factors + q for A, B in factors: polys, degrees = [], [] D = A*B.subs(n, n + r - 1) for i in range(r + 1): a = Mul(*[A.subs(n, n + j) for j in range(i)]) b = Mul(*[B.subs(n, n + j) for j in range(i, r)]) poly = quo(coeffs[i]*a*b, D, n) polys.append(poly.as_poly(n)) if not poly.is_zero: degrees.append(polys[i].degree()) if degrees: d, poly = max(degrees), S.Zero else: return None for i in range(r + 1): coeff = polys[i].nth(d) if coeff is not S.Zero: poly += coeff * Z**i for z in roots(poly, Z).keys(): if z.is_zero: continue recurr_coeffs = [polys[i].as_expr()*z**i for i in range(r + 1)] if d == 0 and 0 != Add(*[recurr_coeffs[j]*j for j in range(1, r + 1)]): # faster inline check (than calling rsolve_poly) for a # constant solution to a constant coefficient recurrence. sol = [Symbol("C" + str(len(symbols)))] else: sol, syms = rsolve_poly(recurr_coeffs, 0, n, len(symbols), symbols=True) sol = sol.collect(syms) sol = [sol.coeff(s) for s in syms] for C in sol: ratio = z * A * C.subs(n, n + 1) / B / C ratio = simplify(ratio) # If there is a nonnegative root in the denominator of the ratio, # this indicates that the term y(n_root) is zero, and one should # start the product with the term y(n_root + 1). n0 = 0 for n_root in roots(ratio.as_numer_denom()[1], n).keys(): if n_root.has(I): return None elif (n0 < (n_root + 1)) == True: n0 = n_root + 1 K = product(ratio, (n, n0, n - 1)) if K.has(factorial, FallingFactorial, RisingFactorial): K = simplify(K) if casoratian(kernel + [K], n, zero=False) != 0: kernel.append(K) kernel.sort(key=default_sort_key) sk = list(zip(numbered_symbols('C'), kernel)) for C, ker in sk: result += C * ker if hints.get('symbols', False): # XXX: This returns the symbols in a non-deterministic order symbols |= {s for s, k in sk} return (result, list(symbols)) else: return result def rsolve(f, y, init=None): r""" Solve univariate recurrence with rational coefficients. Given `k`-th order linear recurrence `\operatorname{L} y = f`, or equivalently: .. math:: a_{k}(n) y(n+k) + a_{k-1}(n) y(n+k-1) + \cdots + a_{0}(n) y(n) = f(n) where `a_{i}(n)`, for `i=0, \ldots, k`, are polynomials or rational functions in `n`, and `f` is a hypergeometric function or a sum of a fixed number of pairwise dissimilar hypergeometric terms in `n`, finds all solutions or returns ``None``, if none were found. Initial conditions can be given as a dictionary in two forms: (1) ``{ n_0 : v_0, n_1 : v_1, ..., n_m : v_m}`` (2) ``{y(n_0) : v_0, y(n_1) : v_1, ..., y(n_m) : v_m}`` or as a list ``L`` of values: ``L = [v_0, v_1, ..., v_m]`` where ``L[i] = v_i``, for `i=0, \ldots, m`, maps to `y(n_i)`. Examples ======== Lets consider the following recurrence: .. math:: (n - 1) y(n + 2) - (n^2 + 3 n - 2) y(n + 1) + 2 n (n + 1) y(n) = 0 >>> from sympy import Function, rsolve >>> from sympy.abc import n >>> y = Function('y') >>> f = (n - 1)*y(n + 2) - (n**2 + 3*n - 2)*y(n + 1) + 2*n*(n + 1)*y(n) >>> rsolve(f, y(n)) 2**n*C0 + C1*factorial(n) >>> rsolve(f, y(n), {y(0):0, y(1):3}) 3*2**n - 3*factorial(n) See Also ======== rsolve_poly, rsolve_ratio, rsolve_hyper """ if isinstance(f, Equality): f = f.lhs - f.rhs n = y.args[0] k = Wild('k', exclude=(n,)) # Preprocess user input to allow things like # y(n) + a*(y(n + 1) + y(n - 1))/2 f = f.expand().collect(y.func(Wild('m', integer=True))) h_part = defaultdict(list) i_part = [] for g in Add.make_args(f): coeff, dep = g.as_coeff_mul(y.func) if not dep: i_part.append(coeff) continue for h in dep: if h.is_Function and h.func == y.func: result = h.args[0].match(n + k) if result is not None: h_part[int(result[k])].append(coeff) continue raise ValueError( "'%s(%s + k)' expected, got '%s'" % (y.func, n, h)) for k in h_part: h_part[k] = Add(*h_part[k]) h_part.default_factory = lambda: 0 i_part = Add(*i_part) for k, coeff in h_part.items(): h_part[k] = simplify(coeff) common = S.One if not i_part.is_zero and not i_part.is_hypergeometric(n) and \ not (i_part.is_Add and all(map(lambda x: x.is_hypergeometric(n), i_part.expand().args))): raise ValueError("The independent term should be a sum of hypergeometric functions, got '%s'" % i_part) for coeff in h_part.values(): if coeff.is_rational_function(n): if not coeff.is_polynomial(n): common = lcm(common, coeff.as_numer_denom()[1], n) else: raise ValueError( "Polynomial or rational function expected, got '%s'" % coeff) i_numer, i_denom = i_part.as_numer_denom() if i_denom.is_polynomial(n): common = lcm(common, i_denom, n) if common is not S.One: for k, coeff in h_part.items(): numer, denom = coeff.as_numer_denom() h_part[k] = numer*quo(common, denom, n) i_part = i_numer*quo(common, i_denom, n) K_min = min(h_part.keys()) if K_min < 0: K = abs(K_min) H_part = defaultdict(lambda: S.Zero) i_part = i_part.subs(n, n + K).expand() common = common.subs(n, n + K).expand() for k, coeff in h_part.items(): H_part[k + K] = coeff.subs(n, n + K).expand() else: H_part = h_part K_max = max(H_part.keys()) coeffs = [H_part[i] for i in range(K_max + 1)] result = rsolve_hyper(coeffs, -i_part, n, symbols=True) if result is None: return None solution, symbols = result if init in ({}, []): init = None if symbols and init is not None: if isinstance(init, list): init = {i: init[i] for i in range(len(init))} equations = [] for k, v in init.items(): try: i = int(k) except TypeError: if k.is_Function and k.func == y.func: i = int(k.args[0]) else: raise ValueError("Integer or term expected, got '%s'" % k) eq = solution.subs(n, i) - v if eq.has(S.NaN): eq = solution.limit(n, i) - v equations.append(eq) result = solve(equations, *symbols) if not result: return None else: solution = solution.subs(result) return solution
66603ccc548a39641bc06352f85df39b08d721e1c0d009e0e412d445f422de65
""" This module contains functions to: - solve a single equation for a single variable, in any domain either real or complex. - solve a single transcendental equation for a single variable in any domain either real or complex. (currently supports solving in real domain only) - solve a system of linear equations with N variables and M equations. - solve a system of Non Linear Equations with N variables and M equations """ from sympy.core.sympify import sympify from sympy.core import (S, Pow, Dummy, pi, Expr, Wild, Mul, Equality, Add) from sympy.core.containers import Tuple from sympy.core.function import (Lambda, expand_complex, AppliedUndef, expand_log, _mexpand, expand_trig, nfloat) from sympy.core.mod import Mod from sympy.core.numbers import igcd, I, Number, Rational, oo, ilcm from sympy.core.power import integer_log from sympy.core.relational import Eq, Ne, Relational from sympy.core.sorting import default_sort_key, ordered from sympy.core.symbol import Symbol, _uniquely_named_symbol from sympy.core.sympify import _sympify from sympy.core.traversal import iterfreeargs from sympy.polys.polyroots import UnsolvableFactorError from sympy.simplify.simplify import simplify, fraction, trigsimp, nsimplify from sympy.simplify import powdenest, logcombine from sympy.functions import (log, tan, cot, sin, cos, sec, csc, exp, acos, asin, acsc, asec, piecewise_fold, Piecewise) from sympy.functions.elementary.complexes import Abs, arg, re, im from sympy.functions.elementary.hyperbolic import HyperbolicFunction from sympy.functions.elementary.miscellaneous import real_root from sympy.functions.elementary.trigonometric import TrigonometricFunction from sympy.logic.boolalg import And, BooleanTrue from sympy.sets import (FiniteSet, imageset, Interval, Intersection, Union, ConditionSet, ImageSet, Complement, Contains) from sympy.sets.sets import Set, ProductSet from sympy.matrices import Matrix, MatrixBase from sympy.ntheory import totient from sympy.ntheory.factor_ import divisors from sympy.ntheory.residue_ntheory import discrete_log, nthroot_mod from sympy.polys import (roots, Poly, degree, together, PolynomialError, RootOf, factor, lcm, gcd) from sympy.polys.polyerrors import CoercionFailed from sympy.polys.polytools import invert, groebner, poly from sympy.polys.solvers import (sympy_eqs_to_ring, solve_lin_sys, PolyNonlinearError) from sympy.polys.matrices.linsolve import _linsolve from sympy.solvers.solvers import (checksol, denoms, unrad, _simple_dens, recast_to_symbols) from sympy.solvers.polysys import solve_poly_system from sympy.utilities import filldedent from sympy.utilities.iterables import (numbered_symbols, has_dups, is_sequence) from sympy.calculus.util import periodicity, continuous_domain, function_range from types import GeneratorType from collections import defaultdict class NonlinearError(ValueError): """Raised when unexpectedly encountering nonlinear equations""" pass _rc = Dummy("R", real=True), Dummy("C", complex=True) def _masked(f, *atoms): """Return ``f``, with all objects given by ``atoms`` replaced with Dummy symbols, ``d``, and the list of replacements, ``(d, e)``, where ``e`` is an object of type given by ``atoms`` in which any other instances of atoms have been recursively replaced with Dummy symbols, too. The tuples are ordered so that if they are applied in sequence, the origin ``f`` will be restored. Examples ======== >>> from sympy import cos >>> from sympy.abc import x >>> from sympy.solvers.solveset import _masked >>> f = cos(cos(x) + 1) >>> f, reps = _masked(cos(1 + cos(x)), cos) >>> f _a1 >>> reps [(_a1, cos(_a0 + 1)), (_a0, cos(x))] >>> for d, e in reps: ... f = f.xreplace({d: e}) >>> f cos(cos(x) + 1) """ sym = numbered_symbols('a', cls=Dummy, real=True) mask = [] for a in ordered(f.atoms(*atoms)): for i in mask: a = a.replace(*i) mask.append((a, next(sym))) for i, (o, n) in enumerate(mask): f = f.replace(o, n) mask[i] = (n, o) mask = list(reversed(mask)) return f, mask def _invert(f_x, y, x, domain=S.Complexes): r""" Reduce the complex valued equation $f(x) = y$ to a set of equations $$\left\{g(x) = h_1(y),\ g(x) = h_2(y),\ \dots,\ g(x) = h_n(y) \right\}$$ where $g(x)$ is a simpler function than $f(x)$. The return value is a tuple $(g(x), \mathrm{set}_h)$, where $g(x)$ is a function of $x$ and $\mathrm{set}_h$ is the set of function $\left\{h_1(y), h_2(y), \dots, h_n(y)\right\}$. Here, $y$ is not necessarily a symbol. $\mathrm{set}_h$ contains the functions, along with the information about the domain in which they are valid, through set operations. For instance, if :math:`y = |x| - n` is inverted in the real domain, then $\mathrm{set}_h$ is not simply $\{-n, n\}$ as the nature of `n` is unknown; rather, it is: $$ \left(\left[0, \infty\right) \cap \left\{n\right\}\right) \cup \left(\left(-\infty, 0\right] \cap \left\{- n\right\}\right)$$ By default, the complex domain is used which means that inverting even seemingly simple functions like $\exp(x)$ will give very different results from those obtained in the real domain. (In the case of $\exp(x)$, the inversion via $\log$ is multi-valued in the complex domain, having infinitely many branches.) If you are working with real values only (or you are not sure which function to use) you should probably set the domain to ``S.Reals`` (or use ``invert_real`` which does that automatically). Examples ======== >>> from sympy.solvers.solveset import invert_complex, invert_real >>> from sympy.abc import x, y >>> from sympy import exp When does exp(x) == y? >>> invert_complex(exp(x), y, x) (x, ImageSet(Lambda(_n, I*(2*_n*pi + arg(y)) + log(Abs(y))), Integers)) >>> invert_real(exp(x), y, x) (x, Intersection({log(y)}, Reals)) When does exp(x) == 1? >>> invert_complex(exp(x), 1, x) (x, ImageSet(Lambda(_n, 2*_n*I*pi), Integers)) >>> invert_real(exp(x), 1, x) (x, {0}) See Also ======== invert_real, invert_complex """ x = sympify(x) if not x.is_Symbol: raise ValueError("x must be a symbol") f_x = sympify(f_x) if x not in f_x.free_symbols: raise ValueError("Inverse of constant function doesn't exist") y = sympify(y) if x in y.free_symbols: raise ValueError("y should be independent of x ") if domain.is_subset(S.Reals): x1, s = _invert_real(f_x, FiniteSet(y), x) else: x1, s = _invert_complex(f_x, FiniteSet(y), x) if not isinstance(s, FiniteSet) or x1 != x: return x1, s # Avoid adding gratuitous intersections with S.Complexes. Actual # conditions should be handled by the respective inverters. if domain is S.Complexes: return x1, s else: return x1, s.intersection(domain) invert_complex = _invert def invert_real(f_x, y, x): """ Inverts a real-valued function. Same as :func:`invert_complex`, but sets the domain to ``S.Reals`` before inverting. """ return _invert(f_x, y, x, S.Reals) def _invert_real(f, g_ys, symbol): """Helper function for _invert.""" if f == symbol or g_ys is S.EmptySet: return (f, g_ys) n = Dummy('n', real=True) if isinstance(f, exp) or (f.is_Pow and f.base == S.Exp1): return _invert_real(f.exp, imageset(Lambda(n, log(n)), g_ys), symbol) if hasattr(f, 'inverse') and f.inverse() is not None and not isinstance(f, ( TrigonometricFunction, HyperbolicFunction, )): if len(f.args) > 1: raise ValueError("Only functions with one argument are supported.") return _invert_real(f.args[0], imageset(Lambda(n, f.inverse()(n)), g_ys), symbol) if isinstance(f, Abs): return _invert_abs(f.args[0], g_ys, symbol) if f.is_Add: # f = g + h g, h = f.as_independent(symbol) if g is not S.Zero: return _invert_real(h, imageset(Lambda(n, n - g), g_ys), symbol) if f.is_Mul: # f = g*h g, h = f.as_independent(symbol) if g is not S.One: return _invert_real(h, imageset(Lambda(n, n/g), g_ys), symbol) if f.is_Pow: base, expo = f.args base_has_sym = base.has(symbol) expo_has_sym = expo.has(symbol) if not expo_has_sym: if expo.is_rational: num, den = expo.as_numer_denom() if den % 2 == 0 and num % 2 == 1 and den.is_zero is False: # Here we have f(x)**(num/den) = y # where den is nonzero and even and y is an element # of the set g_ys. # den is even, so we are only interested in the cases # where both f(x) and y are positive. # Restricting y to be positive (using the set g_ys_pos) # means that y**(den/num) is always positive. # Therefore it isn't necessary to also constrain f(x) # to be positive because we are only going to # find solutions of f(x) = y**(d/n) # where the rhs is already required to be positive. root = Lambda(n, real_root(n, expo)) g_ys_pos = g_ys & Interval(0, oo) res = imageset(root, g_ys_pos) _inv, _set = _invert_real(base, res, symbol) return (_inv, _set) if den % 2 == 1: root = Lambda(n, real_root(n, expo)) res = imageset(root, g_ys) if num % 2 == 0: neg_res = imageset(Lambda(n, -n), res) return _invert_real(base, res + neg_res, symbol) if num % 2 == 1: return _invert_real(base, res, symbol) elif expo.is_irrational: root = Lambda(n, real_root(n, expo)) g_ys_pos = g_ys & Interval(0, oo) res = imageset(root, g_ys_pos) return _invert_real(base, res, symbol) else: # indeterminate exponent, e.g. Float or parity of # num, den of rational could not be determined pass # use default return if not base_has_sym: rhs = g_ys.args[0] if base.is_positive: return _invert_real(expo, imageset(Lambda(n, log(n, base, evaluate=False)), g_ys), symbol) elif base.is_negative: s, b = integer_log(rhs, base) if b: return _invert_real(expo, FiniteSet(s), symbol) else: return (expo, S.EmptySet) elif base.is_zero: one = Eq(rhs, 1) if one == S.true: # special case: 0**x - 1 return _invert_real(expo, FiniteSet(0), symbol) elif one == S.false: return (expo, S.EmptySet) if isinstance(f, TrigonometricFunction): if isinstance(g_ys, FiniteSet): def inv(trig): if isinstance(trig, (sin, csc)): F = asin if isinstance(trig, sin) else acsc return (lambda a: n*pi + S.NegativeOne**n*F(a),) if isinstance(trig, (cos, sec)): F = acos if isinstance(trig, cos) else asec return ( lambda a: 2*n*pi + F(a), lambda a: 2*n*pi - F(a),) if isinstance(trig, (tan, cot)): return (lambda a: n*pi + trig.inverse()(a),) n = Dummy('n', integer=True) invs = S.EmptySet for L in inv(f): invs += Union(*[imageset(Lambda(n, L(g)), S.Integers) for g in g_ys]) return _invert_real(f.args[0], invs, symbol) return (f, g_ys) def _invert_complex(f, g_ys, symbol): """Helper function for _invert.""" if f == symbol or g_ys is S.EmptySet: return (f, g_ys) n = Dummy('n') if f.is_Add: # f = g + h g, h = f.as_independent(symbol) if g is not S.Zero: return _invert_complex(h, imageset(Lambda(n, n - g), g_ys), symbol) if f.is_Mul: # f = g*h g, h = f.as_independent(symbol) if g is not S.One: if g in {S.NegativeInfinity, S.ComplexInfinity, S.Infinity}: return (h, S.EmptySet) return _invert_complex(h, imageset(Lambda(n, n/g), g_ys), symbol) if f.is_Pow: base, expo = f.args # special case: g**r = 0 # Could be improved like `_invert_real` to handle more general cases. if expo.is_Rational and g_ys == FiniteSet(0): if expo.is_positive: return _invert_complex(base, g_ys, symbol) if hasattr(f, 'inverse') and f.inverse() is not None and \ not isinstance(f, TrigonometricFunction) and \ not isinstance(f, HyperbolicFunction) and \ not isinstance(f, exp): if len(f.args) > 1: raise ValueError("Only functions with one argument are supported.") return _invert_complex(f.args[0], imageset(Lambda(n, f.inverse()(n)), g_ys), symbol) if isinstance(f, exp) or (f.is_Pow and f.base == S.Exp1): if isinstance(g_ys, ImageSet): # can solve upto `(d*exp(exp(...(exp(a*x + b))...) + c)` format. # Further can be improved to `(d*exp(exp(...(exp(a*x**n + b*x**(n-1) + ... + f))...) + c)`. g_ys_expr = g_ys.lamda.expr g_ys_vars = g_ys.lamda.variables k = Dummy('k{}'.format(len(g_ys_vars))) g_ys_vars_1 = (k,) + g_ys_vars exp_invs = Union(*[imageset(Lambda((g_ys_vars_1,), (I*(2*k*pi + arg(g_ys_expr)) + log(Abs(g_ys_expr)))), S.Integers**(len(g_ys_vars_1)))]) return _invert_complex(f.exp, exp_invs, symbol) elif isinstance(g_ys, FiniteSet): exp_invs = Union(*[imageset(Lambda(n, I*(2*n*pi + arg(g_y)) + log(Abs(g_y))), S.Integers) for g_y in g_ys if g_y != 0]) return _invert_complex(f.exp, exp_invs, symbol) return (f, g_ys) def _invert_abs(f, g_ys, symbol): """Helper function for inverting absolute value functions. Returns the complete result of inverting an absolute value function along with the conditions which must also be satisfied. If it is certain that all these conditions are met, a :class:`~.FiniteSet` of all possible solutions is returned. If any condition cannot be satisfied, an :class:`~.EmptySet` is returned. Otherwise, a :class:`~.ConditionSet` of the solutions, with all the required conditions specified, is returned. """ if not g_ys.is_FiniteSet: # this could be used for FiniteSet, but the # results are more compact if they aren't, e.g. # ConditionSet(x, Contains(n, Interval(0, oo)), {-n, n}) vs # Union(Intersection(Interval(0, oo), {n}), Intersection(Interval(-oo, 0), {-n})) # for the solution of abs(x) - n pos = Intersection(g_ys, Interval(0, S.Infinity)) parg = _invert_real(f, pos, symbol) narg = _invert_real(-f, pos, symbol) if parg[0] != narg[0]: raise NotImplementedError return parg[0], Union(narg[1], parg[1]) # check conditions: all these must be true. If any are unknown # then return them as conditions which must be satisfied unknown = [] for a in g_ys.args: ok = a.is_nonnegative if a.is_Number else a.is_positive if ok is None: unknown.append(a) elif not ok: return symbol, S.EmptySet if unknown: conditions = And(*[Contains(i, Interval(0, oo)) for i in unknown]) else: conditions = True n = Dummy('n', real=True) # this is slightly different than above: instead of solving # +/-f on positive values, here we solve for f on +/- g_ys g_x, values = _invert_real(f, Union( imageset(Lambda(n, n), g_ys), imageset(Lambda(n, -n), g_ys)), symbol) return g_x, ConditionSet(g_x, conditions, values) def domain_check(f, symbol, p): """Returns False if point p is infinite or any subexpression of f is infinite or becomes so after replacing symbol with p. If none of these conditions is met then True will be returned. Examples ======== >>> from sympy import Mul, oo >>> from sympy.abc import x >>> from sympy.solvers.solveset import domain_check >>> g = 1/(1 + (1/(x + 1))**2) >>> domain_check(g, x, -1) False >>> domain_check(x**2, x, 0) True >>> domain_check(1/x, x, oo) False * The function relies on the assumption that the original form of the equation has not been changed by automatic simplification. >>> domain_check(x/x, x, 0) # x/x is automatically simplified to 1 True * To deal with automatic evaluations use evaluate=False: >>> domain_check(Mul(x, 1/x, evaluate=False), x, 0) False """ f, p = sympify(f), sympify(p) if p.is_infinite: return False return _domain_check(f, symbol, p) def _domain_check(f, symbol, p): # helper for domain check if f.is_Atom and f.is_finite: return True elif f.subs(symbol, p).is_infinite: return False elif isinstance(f, Piecewise): # Check the cases of the Piecewise in turn. There might be invalid # expressions in later cases that don't apply e.g. # solveset(Piecewise((0, Eq(x, 0)), (1/x, True)), x) for expr, cond in f.args: condsubs = cond.subs(symbol, p) if condsubs is S.false: continue elif condsubs is S.true: return _domain_check(expr, symbol, p) else: # We don't know which case of the Piecewise holds. On this # basis we cannot decide whether any solution is in or out of # the domain. Ideally this function would allow returning a # symbolic condition for the validity of the solution that # could be handled in the calling code. In the mean time we'll # give this particular solution the benefit of the doubt and # let it pass. return True else: # TODO : We should not blindly recurse through all args of arbitrary expressions like this return all(_domain_check(g, symbol, p) for g in f.args) def _is_finite_with_finite_vars(f, domain=S.Complexes): """ Return True if the given expression is finite. For symbols that do not assign a value for `complex` and/or `real`, the domain will be used to assign a value; symbols that do not assign a value for `finite` will be made finite. All other assumptions are left unmodified. """ def assumptions(s): A = s.assumptions0 A.setdefault('finite', A.get('finite', True)) if domain.is_subset(S.Reals): # if this gets set it will make complex=True, too A.setdefault('real', True) else: # don't change 'real' because being complex implies # nothing about being real A.setdefault('complex', True) return A reps = {s: Dummy(**assumptions(s)) for s in f.free_symbols} return f.xreplace(reps).is_finite def _is_function_class_equation(func_class, f, symbol): """ Tests whether the equation is an equation of the given function class. The given equation belongs to the given function class if it is comprised of functions of the function class which are multiplied by or added to expressions independent of the symbol. In addition, the arguments of all such functions must be linear in the symbol as well. Examples ======== >>> from sympy.solvers.solveset import _is_function_class_equation >>> from sympy import tan, sin, tanh, sinh, exp >>> from sympy.abc import x >>> from sympy.functions.elementary.trigonometric import TrigonometricFunction >>> from sympy.functions.elementary.hyperbolic import HyperbolicFunction >>> _is_function_class_equation(TrigonometricFunction, exp(x) + tan(x), x) False >>> _is_function_class_equation(TrigonometricFunction, tan(x) + sin(x), x) True >>> _is_function_class_equation(TrigonometricFunction, tan(x**2), x) False >>> _is_function_class_equation(TrigonometricFunction, tan(x + 2), x) True >>> _is_function_class_equation(HyperbolicFunction, tanh(x) + sinh(x), x) True """ if f.is_Mul or f.is_Add: return all(_is_function_class_equation(func_class, arg, symbol) for arg in f.args) if f.is_Pow: if not f.exp.has(symbol): return _is_function_class_equation(func_class, f.base, symbol) else: return False if not f.has(symbol): return True if isinstance(f, func_class): try: g = Poly(f.args[0], symbol) return g.degree() <= 1 except PolynomialError: return False else: return False def _solve_as_rational(f, symbol, domain): """ solve rational functions""" f = together(_mexpand(f, recursive=True), deep=True) g, h = fraction(f) if not h.has(symbol): try: return _solve_as_poly(g, symbol, domain) except NotImplementedError: # The polynomial formed from g could end up having # coefficients in a ring over which finding roots # isn't implemented yet, e.g. ZZ[a] for some symbol a return ConditionSet(symbol, Eq(f, 0), domain) except CoercionFailed: # contained oo, zoo or nan return S.EmptySet else: valid_solns = _solveset(g, symbol, domain) invalid_solns = _solveset(h, symbol, domain) return valid_solns - invalid_solns class _SolveTrig1Error(Exception): """Raised when _solve_trig1 heuristics do not apply""" def _solve_trig(f, symbol, domain): """Function to call other helpers to solve trigonometric equations """ sol = None try: sol = _solve_trig1(f, symbol, domain) except _SolveTrig1Error: try: sol = _solve_trig2(f, symbol, domain) except ValueError: raise NotImplementedError(filldedent(''' Solution to this kind of trigonometric equations is yet to be implemented''')) return sol def _solve_trig1(f, symbol, domain): """Primary solver for trigonometric and hyperbolic equations Returns either the solution set as a ConditionSet (auto-evaluated to a union of ImageSets if no variables besides 'symbol' are involved) or raises _SolveTrig1Error if f == 0 cannot be solved. Notes ===== Algorithm: 1. Do a change of variable x -> mu*x in arguments to trigonometric and hyperbolic functions, in order to reduce them to small integers. (This step is crucial to keep the degrees of the polynomials of step 4 low.) 2. Rewrite trigonometric/hyperbolic functions as exponentials. 3. Proceed to a 2nd change of variable, replacing exp(I*x) or exp(x) by y. 4. Solve the resulting rational equation. 5. Use invert_complex or invert_real to return to the original variable. 6. If the coefficients of 'symbol' were symbolic in nature, add the necessary consistency conditions in a ConditionSet. """ # Prepare change of variable x = Dummy('x') if _is_function_class_equation(HyperbolicFunction, f, symbol): cov = exp(x) inverter = invert_real if domain.is_subset(S.Reals) else invert_complex else: cov = exp(I*x) inverter = invert_complex f = trigsimp(f) f_original = f trig_functions = f.atoms(TrigonometricFunction, HyperbolicFunction) trig_arguments = [e.args[0] for e in trig_functions] # trigsimp may have reduced the equation to an expression # that is independent of 'symbol' (e.g. cos**2+sin**2) if not any(a.has(symbol) for a in trig_arguments): return solveset(f_original, symbol, domain) denominators = [] numerators = [] for ar in trig_arguments: try: poly_ar = Poly(ar, symbol) except PolynomialError: raise _SolveTrig1Error("trig argument is not a polynomial") if poly_ar.degree() > 1: # degree >1 still bad raise _SolveTrig1Error("degree of variable must not exceed one") if poly_ar.degree() == 0: # degree 0, don't care continue c = poly_ar.all_coeffs()[0] # got the coefficient of 'symbol' numerators.append(fraction(c)[0]) denominators.append(fraction(c)[1]) mu = lcm(denominators)/gcd(numerators) f = f.subs(symbol, mu*x) f = f.rewrite(exp) f = together(f) g, h = fraction(f) y = Dummy('y') g, h = g.expand(), h.expand() g, h = g.subs(cov, y), h.subs(cov, y) if g.has(x) or h.has(x): raise _SolveTrig1Error("change of variable not possible") solns = solveset_complex(g, y) - solveset_complex(h, y) if isinstance(solns, ConditionSet): raise _SolveTrig1Error("polynomial has ConditionSet solution") if isinstance(solns, FiniteSet): if any(isinstance(s, RootOf) for s in solns): raise _SolveTrig1Error("polynomial results in RootOf object") # revert the change of variable cov = cov.subs(x, symbol/mu) result = Union(*[inverter(cov, s, symbol)[1] for s in solns]) # In case of symbolic coefficients, the solution set is only valid # if numerator and denominator of mu are non-zero. if mu.has(Symbol): syms = (mu).atoms(Symbol) munum, muden = fraction(mu) condnum = munum.as_independent(*syms, as_Add=False)[1] condden = muden.as_independent(*syms, as_Add=False)[1] cond = And(Ne(condnum, 0), Ne(condden, 0)) else: cond = True # Actual conditions are returned as part of the ConditionSet. Adding an # intersection with C would only complicate some solution sets due to # current limitations of intersection code. (e.g. #19154) if domain is S.Complexes: # This is a slight abuse of ConditionSet. Ideally this should # be some kind of "PiecewiseSet". (See #19507 discussion) return ConditionSet(symbol, cond, result) else: return ConditionSet(symbol, cond, Intersection(result, domain)) elif solns is S.EmptySet: return S.EmptySet else: raise _SolveTrig1Error("polynomial solutions must form FiniteSet") def _solve_trig2(f, symbol, domain): """Secondary helper to solve trigonometric equations, called when first helper fails """ f = trigsimp(f) f_original = f trig_functions = f.atoms(sin, cos, tan, sec, cot, csc) trig_arguments = [e.args[0] for e in trig_functions] denominators = [] numerators = [] # todo: This solver can be extended to hyperbolics if the # analogous change of variable to tanh (instead of tan) # is used. if not trig_functions: return ConditionSet(symbol, Eq(f_original, 0), domain) # todo: The pre-processing below (extraction of numerators, denominators, # gcd, lcm, mu, etc.) should be updated to the enhanced version in # _solve_trig1. (See #19507) for ar in trig_arguments: try: poly_ar = Poly(ar, symbol) except PolynomialError: raise ValueError("give up, we cannot solve if this is not a polynomial in x") if poly_ar.degree() > 1: # degree >1 still bad raise ValueError("degree of variable inside polynomial should not exceed one") if poly_ar.degree() == 0: # degree 0, don't care continue c = poly_ar.all_coeffs()[0] # got the coefficient of 'symbol' try: numerators.append(Rational(c).p) denominators.append(Rational(c).q) except TypeError: return ConditionSet(symbol, Eq(f_original, 0), domain) x = Dummy('x') # ilcm() and igcd() require more than one argument if len(numerators) > 1: mu = Rational(2)*ilcm(*denominators)/igcd(*numerators) else: assert len(numerators) == 1 mu = Rational(2)*denominators[0]/numerators[0] f = f.subs(symbol, mu*x) f = f.rewrite(tan) f = expand_trig(f) f = together(f) g, h = fraction(f) y = Dummy('y') g, h = g.expand(), h.expand() g, h = g.subs(tan(x), y), h.subs(tan(x), y) if g.has(x) or h.has(x): return ConditionSet(symbol, Eq(f_original, 0), domain) solns = solveset(g, y, S.Reals) - solveset(h, y, S.Reals) if isinstance(solns, FiniteSet): result = Union(*[invert_real(tan(symbol/mu), s, symbol)[1] for s in solns]) dsol = invert_real(tan(symbol/mu), oo, symbol)[1] if degree(h) > degree(g): # If degree(denom)>degree(num) then there result = Union(result, dsol) # would be another sol at Lim(denom-->oo) return Intersection(result, domain) elif solns is S.EmptySet: return S.EmptySet else: return ConditionSet(symbol, Eq(f_original, 0), S.Reals) def _solve_as_poly(f, symbol, domain=S.Complexes): """ Solve the equation using polynomial techniques if it already is a polynomial equation or, with a change of variables, can be made so. """ result = None if f.is_polynomial(symbol): solns = roots(f, symbol, cubics=True, quartics=True, quintics=True, domain='EX') num_roots = sum(solns.values()) if degree(f, symbol) <= num_roots: result = FiniteSet(*solns.keys()) else: poly = Poly(f, symbol) solns = poly.all_roots() if poly.degree() <= len(solns): result = FiniteSet(*solns) else: result = ConditionSet(symbol, Eq(f, 0), domain) else: poly = Poly(f) if poly is None: result = ConditionSet(symbol, Eq(f, 0), domain) gens = [g for g in poly.gens if g.has(symbol)] if len(gens) == 1: poly = Poly(poly, gens[0]) gen = poly.gen deg = poly.degree() poly = Poly(poly.as_expr(), poly.gen, composite=True) poly_solns = FiniteSet(*roots(poly, cubics=True, quartics=True, quintics=True).keys()) if len(poly_solns) < deg: result = ConditionSet(symbol, Eq(f, 0), domain) if gen != symbol: y = Dummy('y') inverter = invert_real if domain.is_subset(S.Reals) else invert_complex lhs, rhs_s = inverter(gen, y, symbol) if lhs == symbol: result = Union(*[rhs_s.subs(y, s) for s in poly_solns]) else: result = ConditionSet(symbol, Eq(f, 0), domain) else: result = ConditionSet(symbol, Eq(f, 0), domain) if result is not None: if isinstance(result, FiniteSet): # this is to simplify solutions like -sqrt(-I) to sqrt(2)/2 # - sqrt(2)*I/2. We are not expanding for solution with symbols # or undefined functions because that makes the solution more complicated. # For example, expand_complex(a) returns re(a) + I*im(a) if all(s.atoms(Symbol, AppliedUndef) == set() and not isinstance(s, RootOf) for s in result): s = Dummy('s') result = imageset(Lambda(s, expand_complex(s)), result) if isinstance(result, FiniteSet) and domain != S.Complexes: # Avoid adding gratuitous intersections with S.Complexes. Actual # conditions should be handled elsewhere. result = result.intersection(domain) return result else: return ConditionSet(symbol, Eq(f, 0), domain) def _solve_radical(f, unradf, symbol, solveset_solver): """ Helper function to solve equations with radicals """ res = unradf eq, cov = res if res else (f, []) if not cov: result = solveset_solver(eq, symbol) - \ Union(*[solveset_solver(g, symbol) for g in denoms(f, symbol)]) else: y, yeq = cov if not solveset_solver(y - I, y): yreal = Dummy('yreal', real=True) yeq = yeq.xreplace({y: yreal}) eq = eq.xreplace({y: yreal}) y = yreal g_y_s = solveset_solver(yeq, symbol) f_y_sols = solveset_solver(eq, y) result = Union(*[imageset(Lambda(y, g_y), f_y_sols) for g_y in g_y_s]) if not isinstance(result, FiniteSet): solution_set = result else: f_set = [] # solutions for FiniteSet c_set = [] # solutions for ConditionSet for s in result: if checksol(f, symbol, s): f_set.append(s) else: c_set.append(s) solution_set = FiniteSet(*f_set) + ConditionSet(symbol, Eq(f, 0), FiniteSet(*c_set)) return solution_set def _solve_abs(f, symbol, domain): """ Helper function to solve equation involving absolute value function """ if not domain.is_subset(S.Reals): raise ValueError(filldedent(''' Absolute values cannot be inverted in the complex domain.''')) p, q, r = Wild('p'), Wild('q'), Wild('r') pattern_match = f.match(p*Abs(q) + r) or {} f_p, f_q, f_r = [pattern_match.get(i, S.Zero) for i in (p, q, r)] if not (f_p.is_zero or f_q.is_zero): domain = continuous_domain(f_q, symbol, domain) from .inequalities import solve_univariate_inequality q_pos_cond = solve_univariate_inequality(f_q >= 0, symbol, relational=False, domain=domain, continuous=True) q_neg_cond = q_pos_cond.complement(domain) sols_q_pos = solveset_real(f_p*f_q + f_r, symbol).intersect(q_pos_cond) sols_q_neg = solveset_real(f_p*(-f_q) + f_r, symbol).intersect(q_neg_cond) return Union(sols_q_pos, sols_q_neg) else: return ConditionSet(symbol, Eq(f, 0), domain) def solve_decomposition(f, symbol, domain): """ Function to solve equations via the principle of "Decomposition and Rewriting". Examples ======== >>> from sympy import exp, sin, Symbol, pprint, S >>> from sympy.solvers.solveset import solve_decomposition as sd >>> x = Symbol('x') >>> f1 = exp(2*x) - 3*exp(x) + 2 >>> sd(f1, x, S.Reals) {0, log(2)} >>> f2 = sin(x)**2 + 2*sin(x) + 1 >>> pprint(sd(f2, x, S.Reals), use_unicode=False) 3*pi {2*n*pi + ---- | n in Integers} 2 >>> f3 = sin(x + 2) >>> pprint(sd(f3, x, S.Reals), use_unicode=False) {2*n*pi - 2 | n in Integers} U {2*n*pi - 2 + pi | n in Integers} """ from sympy.solvers.decompogen import decompogen # decompose the given function g_s = decompogen(f, symbol) # `y_s` represents the set of values for which the function `g` is to be # solved. # `solutions` represent the solutions of the equations `g = y_s` or # `g = 0` depending on the type of `y_s`. # As we are interested in solving the equation: f = 0 y_s = FiniteSet(0) for g in g_s: frange = function_range(g, symbol, domain) y_s = Intersection(frange, y_s) result = S.EmptySet if isinstance(y_s, FiniteSet): for y in y_s: solutions = solveset(Eq(g, y), symbol, domain) if not isinstance(solutions, ConditionSet): result += solutions else: if isinstance(y_s, ImageSet): iter_iset = (y_s,) elif isinstance(y_s, Union): iter_iset = y_s.args elif y_s is S.EmptySet: # y_s is not in the range of g in g_s, so no solution exists #in the given domain return S.EmptySet for iset in iter_iset: new_solutions = solveset(Eq(iset.lamda.expr, g), symbol, domain) dummy_var = tuple(iset.lamda.expr.free_symbols)[0] (base_set,) = iset.base_sets if isinstance(new_solutions, FiniteSet): new_exprs = new_solutions elif isinstance(new_solutions, Intersection): if isinstance(new_solutions.args[1], FiniteSet): new_exprs = new_solutions.args[1] for new_expr in new_exprs: result += ImageSet(Lambda(dummy_var, new_expr), base_set) if result is S.EmptySet: return ConditionSet(symbol, Eq(f, 0), domain) y_s = result return y_s def _solveset(f, symbol, domain, _check=False): """Helper for solveset to return a result from an expression that has already been sympify'ed and is known to contain the given symbol.""" # _check controls whether the answer is checked or not from sympy.simplify.simplify import signsimp if isinstance(f, BooleanTrue): return domain orig_f = f if f.is_Mul: coeff, f = f.as_independent(symbol, as_Add=False) if coeff in {S.ComplexInfinity, S.NegativeInfinity, S.Infinity}: f = together(orig_f) elif f.is_Add: a, h = f.as_independent(symbol) m, h = h.as_independent(symbol, as_Add=False) if m not in {S.ComplexInfinity, S.Zero, S.Infinity, S.NegativeInfinity}: f = a/m + h # XXX condition `m != 0` should be added to soln # assign the solvers to use solver = lambda f, x, domain=domain: _solveset(f, x, domain) inverter = lambda f, rhs, symbol: _invert(f, rhs, symbol, domain) result = S.EmptySet if f.expand().is_zero: return domain elif not f.has(symbol): return S.EmptySet elif f.is_Mul and all(_is_finite_with_finite_vars(m, domain) for m in f.args): # if f(x) and g(x) are both finite we can say that the solution of # f(x)*g(x) == 0 is same as Union(f(x) == 0, g(x) == 0) is not true in # general. g(x) can grow to infinitely large for the values where # f(x) == 0. To be sure that we are not silently allowing any # wrong solutions we are using this technique only if both f and g are # finite for a finite input. result = Union(*[solver(m, symbol) for m in f.args]) elif _is_function_class_equation(TrigonometricFunction, f, symbol) or \ _is_function_class_equation(HyperbolicFunction, f, symbol): result = _solve_trig(f, symbol, domain) elif isinstance(f, arg): a = f.args[0] result = Intersection(_solveset(re(a) > 0, symbol, domain), _solveset(im(a), symbol, domain)) elif f.is_Piecewise: expr_set_pairs = f.as_expr_set_pairs(domain) for (expr, in_set) in expr_set_pairs: if in_set.is_Relational: in_set = in_set.as_set() solns = solver(expr, symbol, in_set) result += solns elif isinstance(f, Eq): result = solver(Add(f.lhs, - f.rhs, evaluate=False), symbol, domain) elif f.is_Relational: from .inequalities import solve_univariate_inequality try: result = solve_univariate_inequality( f, symbol, domain=domain, relational=False) except NotImplementedError: result = ConditionSet(symbol, f, domain) return result elif _is_modular(f, symbol): result = _solve_modular(f, symbol, domain) else: lhs, rhs_s = inverter(f, 0, symbol) if lhs == symbol: # do some very minimal simplification since # repeated inversion may have left the result # in a state that other solvers (e.g. poly) # would have simplified; this is done here # rather than in the inverter since here it # is only done once whereas there it would # be repeated for each step of the inversion if isinstance(rhs_s, FiniteSet): rhs_s = FiniteSet(*[Mul(* signsimp(i).as_content_primitive()) for i in rhs_s]) result = rhs_s elif isinstance(rhs_s, FiniteSet): for equation in [lhs - rhs for rhs in rhs_s]: if equation == f: u = unrad(f, symbol) if u: result += _solve_radical(equation, u, symbol, solver) elif equation.has(Abs): result += _solve_abs(f, symbol, domain) else: result_rational = _solve_as_rational(equation, symbol, domain) if not isinstance(result_rational, ConditionSet): result += result_rational else: # may be a transcendental type equation t_result = _transolve(equation, symbol, domain) if isinstance(t_result, ConditionSet): # might need factoring; this is expensive so we # have delayed until now. To avoid recursion # errors look for a non-trivial factoring into # a product of symbol dependent terms; I think # that something that factors as a Pow would # have already been recognized by now. factored = equation.factor() if factored.is_Mul and equation != factored: _, dep = factored.as_independent(symbol) if not dep.is_Add: # non-trivial factoring of equation # but use form with constants # in case they need special handling t_results = [] for fac in Mul.make_args(factored): if fac.has(symbol): t_results.append(solver(fac, symbol)) t_result = Union(*t_results) result += t_result else: result += solver(equation, symbol) elif rhs_s is not S.EmptySet: result = ConditionSet(symbol, Eq(f, 0), domain) if isinstance(result, ConditionSet): if isinstance(f, Expr): num, den = f.as_numer_denom() if den.has(symbol): _result = _solveset(num, symbol, domain) if not isinstance(_result, ConditionSet): singularities = _solveset(den, symbol, domain) result = _result - singularities if _check: if isinstance(result, ConditionSet): # it wasn't solved or has enumerated all conditions # -- leave it alone return result # whittle away all but the symbol-containing core # to use this for testing if isinstance(orig_f, Expr): fx = orig_f.as_independent(symbol, as_Add=True)[1] fx = fx.as_independent(symbol, as_Add=False)[1] else: fx = orig_f if isinstance(result, FiniteSet): # check the result for invalid solutions result = FiniteSet(*[s for s in result if isinstance(s, RootOf) or domain_check(fx, symbol, s)]) return result def _is_modular(f, symbol): """ Helper function to check below mentioned types of modular equations. ``A - Mod(B, C) = 0`` A -> This can or cannot be a function of symbol. B -> This is surely a function of symbol. C -> It is an integer. Parameters ========== f : Expr The equation to be checked. symbol : Symbol The concerned variable for which the equation is to be checked. Examples ======== >>> from sympy import symbols, exp, Mod >>> from sympy.solvers.solveset import _is_modular as check >>> x, y = symbols('x y') >>> check(Mod(x, 3) - 1, x) True >>> check(Mod(x, 3) - 1, y) False >>> check(Mod(x, 3)**2 - 5, x) False >>> check(Mod(x, 3)**2 - y, x) False >>> check(exp(Mod(x, 3)) - 1, x) False >>> check(Mod(3, y) - 1, y) False """ if not f.has(Mod): return False # extract modterms from f. modterms = list(f.atoms(Mod)) return (len(modterms) == 1 and # only one Mod should be present modterms[0].args[0].has(symbol) and # B-> function of symbol modterms[0].args[1].is_integer and # C-> to be an integer. any(isinstance(term, Mod) for term in list(_term_factors(f))) # free from other funcs ) def _invert_modular(modterm, rhs, n, symbol): """ Helper function to invert modular equation. ``Mod(a, m) - rhs = 0`` Generally it is inverted as (a, ImageSet(Lambda(n, m*n + rhs), S.Integers)). More simplified form will be returned if possible. If it is not invertible then (modterm, rhs) is returned. The following cases arise while inverting equation ``Mod(a, m) - rhs = 0``: 1. If a is symbol then m*n + rhs is the required solution. 2. If a is an instance of ``Add`` then we try to find two symbol independent parts of a and the symbol independent part gets tranferred to the other side and again the ``_invert_modular`` is called on the symbol dependent part. 3. If a is an instance of ``Mul`` then same as we done in ``Add`` we separate out the symbol dependent and symbol independent parts and transfer the symbol independent part to the rhs with the help of invert and again the ``_invert_modular`` is called on the symbol dependent part. 4. If a is an instance of ``Pow`` then two cases arise as following: - If a is of type (symbol_indep)**(symbol_dep) then the remainder is evaluated with the help of discrete_log function and then the least period is being found out with the help of totient function. period*n + remainder is the required solution in this case. For reference: (https://en.wikipedia.org/wiki/Euler's_theorem) - If a is of type (symbol_dep)**(symbol_indep) then we try to find all primitive solutions list with the help of nthroot_mod function. m*n + rem is the general solution where rem belongs to solutions list from nthroot_mod function. Parameters ========== modterm, rhs : Expr The modular equation to be inverted, ``modterm - rhs = 0`` symbol : Symbol The variable in the equation to be inverted. n : Dummy Dummy variable for output g_n. Returns ======= A tuple (f_x, g_n) is being returned where f_x is modular independent function of symbol and g_n being set of values f_x can have. Examples ======== >>> from sympy import symbols, exp, Mod, Dummy, S >>> from sympy.solvers.solveset import _invert_modular as invert_modular >>> x, y = symbols('x y') >>> n = Dummy('n') >>> invert_modular(Mod(exp(x), 7), S(5), n, x) (Mod(exp(x), 7), 5) >>> invert_modular(Mod(x, 7), S(5), n, x) (x, ImageSet(Lambda(_n, 7*_n + 5), Integers)) >>> invert_modular(Mod(3*x + 8, 7), S(5), n, x) (x, ImageSet(Lambda(_n, 7*_n + 6), Integers)) >>> invert_modular(Mod(x**4, 7), S(5), n, x) (x, EmptySet) >>> invert_modular(Mod(2**(x**2 + x + 1), 7), S(2), n, x) (x**2 + x + 1, ImageSet(Lambda(_n, 3*_n + 1), Naturals0)) """ a, m = modterm.args if rhs.is_real is False or any(term.is_real is False for term in list(_term_factors(a))): # Check for complex arguments return modterm, rhs if abs(rhs) >= abs(m): # if rhs has value greater than value of m. return symbol, S.EmptySet if a == symbol: return symbol, ImageSet(Lambda(n, m*n + rhs), S.Integers) if a.is_Add: # g + h = a g, h = a.as_independent(symbol) if g is not S.Zero: x_indep_term = rhs - Mod(g, m) return _invert_modular(Mod(h, m), Mod(x_indep_term, m), n, symbol) if a.is_Mul: # g*h = a g, h = a.as_independent(symbol) if g is not S.One: x_indep_term = rhs*invert(g, m) return _invert_modular(Mod(h, m), Mod(x_indep_term, m), n, symbol) if a.is_Pow: # base**expo = a base, expo = a.args if expo.has(symbol) and not base.has(symbol): # remainder -> solution independent of n of equation. # m, rhs are made coprime by dividing igcd(m, rhs) try: remainder = discrete_log(m / igcd(m, rhs), rhs, a.base) except ValueError: # log does not exist return modterm, rhs # period -> coefficient of n in the solution and also referred as # the least period of expo in which it is repeats itself. # (a**(totient(m)) - 1) divides m. Here is link of theorem: # (https://en.wikipedia.org/wiki/Euler's_theorem) period = totient(m) for p in divisors(period): # there might a lesser period exist than totient(m). if pow(a.base, p, m / igcd(m, a.base)) == 1: period = p break # recursion is not applied here since _invert_modular is currently # not smart enough to handle infinite rhs as here expo has infinite # rhs = ImageSet(Lambda(n, period*n + remainder), S.Naturals0). return expo, ImageSet(Lambda(n, period*n + remainder), S.Naturals0) elif base.has(symbol) and not expo.has(symbol): try: remainder_list = nthroot_mod(rhs, expo, m, all_roots=True) if remainder_list == []: return symbol, S.EmptySet except (ValueError, NotImplementedError): return modterm, rhs g_n = S.EmptySet for rem in remainder_list: g_n += ImageSet(Lambda(n, m*n + rem), S.Integers) return base, g_n return modterm, rhs def _solve_modular(f, symbol, domain): r""" Helper function for solving modular equations of type ``A - Mod(B, C) = 0``, where A can or cannot be a function of symbol, B is surely a function of symbol and C is an integer. Currently ``_solve_modular`` is only able to solve cases where A is not a function of symbol. Parameters ========== f : Expr The modular equation to be solved, ``f = 0`` symbol : Symbol The variable in the equation to be solved. domain : Set A set over which the equation is solved. It has to be a subset of Integers. Returns ======= A set of integer solutions satisfying the given modular equation. A ``ConditionSet`` if the equation is unsolvable. Examples ======== >>> from sympy.solvers.solveset import _solve_modular as solve_modulo >>> from sympy import S, Symbol, sin, Intersection, Interval, Mod >>> x = Symbol('x') >>> solve_modulo(Mod(5*x - 8, 7) - 3, x, S.Integers) ImageSet(Lambda(_n, 7*_n + 5), Integers) >>> solve_modulo(Mod(5*x - 8, 7) - 3, x, S.Reals) # domain should be subset of integers. ConditionSet(x, Eq(Mod(5*x + 6, 7) - 3, 0), Reals) >>> solve_modulo(-7 + Mod(x, 5), x, S.Integers) EmptySet >>> solve_modulo(Mod(12**x, 21) - 18, x, S.Integers) ImageSet(Lambda(_n, 6*_n + 2), Naturals0) >>> solve_modulo(Mod(sin(x), 7) - 3, x, S.Integers) # not solvable ConditionSet(x, Eq(Mod(sin(x), 7) - 3, 0), Integers) >>> solve_modulo(3 - Mod(x, 5), x, Intersection(S.Integers, Interval(0, 100))) Intersection(ImageSet(Lambda(_n, 5*_n + 3), Integers), Range(0, 101, 1)) """ # extract modterm and g_y from f unsolved_result = ConditionSet(symbol, Eq(f, 0), domain) modterm = list(f.atoms(Mod))[0] rhs = -S.One*(f.subs(modterm, S.Zero)) if f.as_coefficients_dict()[modterm].is_negative: # checks if coefficient of modterm is negative in main equation. rhs *= -S.One if not domain.is_subset(S.Integers): return unsolved_result if rhs.has(symbol): # TODO Case: A-> function of symbol, can be extended here # in future. return unsolved_result n = Dummy('n', integer=True) f_x, g_n = _invert_modular(modterm, rhs, n, symbol) if f_x == modterm and g_n == rhs: return unsolved_result if f_x == symbol: if domain is not S.Integers: return domain.intersect(g_n) return g_n if isinstance(g_n, ImageSet): lamda_expr = g_n.lamda.expr lamda_vars = g_n.lamda.variables base_sets = g_n.base_sets sol_set = _solveset(f_x - lamda_expr, symbol, S.Integers) if isinstance(sol_set, FiniteSet): tmp_sol = S.EmptySet for sol in sol_set: tmp_sol += ImageSet(Lambda(lamda_vars, sol), *base_sets) sol_set = tmp_sol else: sol_set = ImageSet(Lambda(lamda_vars, sol_set), *base_sets) return domain.intersect(sol_set) return unsolved_result def _term_factors(f): """ Iterator to get the factors of all terms present in the given equation. Parameters ========== f : Expr Equation that needs to be addressed Returns ======= Factors of all terms present in the equation. Examples ======== >>> from sympy import symbols >>> from sympy.solvers.solveset import _term_factors >>> x = symbols('x') >>> list(_term_factors(-2 - x**2 + x*(x + 1))) [-2, -1, x**2, x, x + 1] """ for add_arg in Add.make_args(f): yield from Mul.make_args(add_arg) def _solve_exponential(lhs, rhs, symbol, domain): r""" Helper function for solving (supported) exponential equations. Exponential equations are the sum of (currently) at most two terms with one or both of them having a power with a symbol-dependent exponent. For example .. math:: 5^{2x + 3} - 5^{3x - 1} .. math:: 4^{5 - 9x} - e^{2 - x} Parameters ========== lhs, rhs : Expr The exponential equation to be solved, `lhs = rhs` symbol : Symbol The variable in which the equation is solved domain : Set A set over which the equation is solved. Returns ======= A set of solutions satisfying the given equation. A ``ConditionSet`` if the equation is unsolvable or if the assumptions are not properly defined, in that case a different style of ``ConditionSet`` is returned having the solution(s) of the equation with the desired assumptions. Examples ======== >>> from sympy.solvers.solveset import _solve_exponential as solve_expo >>> from sympy import symbols, S >>> x = symbols('x', real=True) >>> a, b = symbols('a b') >>> solve_expo(2**x + 3**x - 5**x, 0, x, S.Reals) # not solvable ConditionSet(x, Eq(2**x + 3**x - 5**x, 0), Reals) >>> solve_expo(a**x - b**x, 0, x, S.Reals) # solvable but incorrect assumptions ConditionSet(x, (a > 0) & (b > 0), {0}) >>> solve_expo(3**(2*x) - 2**(x + 3), 0, x, S.Reals) {-3*log(2)/(-2*log(3) + log(2))} >>> solve_expo(2**x - 4**x, 0, x, S.Reals) {0} * Proof of correctness of the method The logarithm function is the inverse of the exponential function. The defining relation between exponentiation and logarithm is: .. math:: {\log_b x} = y \enspace if \enspace b^y = x Therefore if we are given an equation with exponent terms, we can convert every term to its corresponding logarithmic form. This is achieved by taking logarithms and expanding the equation using logarithmic identities so that it can easily be handled by ``solveset``. For example: .. math:: 3^{2x} = 2^{x + 3} Taking log both sides will reduce the equation to .. math:: (2x)\log(3) = (x + 3)\log(2) This form can be easily handed by ``solveset``. """ unsolved_result = ConditionSet(symbol, Eq(lhs - rhs, 0), domain) newlhs = powdenest(lhs) if lhs != newlhs: # it may also be advantageous to factor the new expr neweq = factor(newlhs - rhs) if neweq != (lhs - rhs): return _solveset(neweq, symbol, domain) # try again with _solveset if not (isinstance(lhs, Add) and len(lhs.args) == 2): # solving for the sum of more than two powers is possible # but not yet implemented return unsolved_result if rhs != 0: return unsolved_result a, b = list(ordered(lhs.args)) a_term = a.as_independent(symbol)[1] b_term = b.as_independent(symbol)[1] a_base, a_exp = a_term.as_base_exp() b_base, b_exp = b_term.as_base_exp() if domain.is_subset(S.Reals): conditions = And( a_base > 0, b_base > 0, Eq(im(a_exp), 0), Eq(im(b_exp), 0)) else: conditions = And( Ne(a_base, 0), Ne(b_base, 0)) L, R = map(lambda i: expand_log(log(i), force=True), (a, -b)) solutions = _solveset(L - R, symbol, domain) return ConditionSet(symbol, conditions, solutions) def _is_exponential(f, symbol): r""" Return ``True`` if one or more terms contain ``symbol`` only in exponents, else ``False``. Parameters ========== f : Expr The equation to be checked symbol : Symbol The variable in which the equation is checked Examples ======== >>> from sympy import symbols, cos, exp >>> from sympy.solvers.solveset import _is_exponential as check >>> x, y = symbols('x y') >>> check(y, y) False >>> check(x**y - 1, y) True >>> check(x**y*2**y - 1, y) True >>> check(exp(x + 3) + 3**x, x) True >>> check(cos(2**x), x) False * Philosophy behind the helper The function extracts each term of the equation and checks if it is of exponential form w.r.t ``symbol``. """ rv = False for expr_arg in _term_factors(f): if symbol not in expr_arg.free_symbols: continue if (isinstance(expr_arg, Pow) and symbol not in expr_arg.base.free_symbols or isinstance(expr_arg, exp)): rv = True # symbol in exponent else: return False # dependent on symbol in non-exponential way return rv def _solve_logarithm(lhs, rhs, symbol, domain): r""" Helper to solve logarithmic equations which are reducible to a single instance of `\log`. Logarithmic equations are (currently) the equations that contains `\log` terms which can be reduced to a single `\log` term or a constant using various logarithmic identities. For example: .. math:: \log(x) + \log(x - 4) can be reduced to: .. math:: \log(x(x - 4)) Parameters ========== lhs, rhs : Expr The logarithmic equation to be solved, `lhs = rhs` symbol : Symbol The variable in which the equation is solved domain : Set A set over which the equation is solved. Returns ======= A set of solutions satisfying the given equation. A ``ConditionSet`` if the equation is unsolvable. Examples ======== >>> from sympy import symbols, log, S >>> from sympy.solvers.solveset import _solve_logarithm as solve_log >>> x = symbols('x') >>> f = log(x - 3) + log(x + 3) >>> solve_log(f, 0, x, S.Reals) {-sqrt(10), sqrt(10)} * Proof of correctness A logarithm is another way to write exponent and is defined by .. math:: {\log_b x} = y \enspace if \enspace b^y = x When one side of the equation contains a single logarithm, the equation can be solved by rewriting the equation as an equivalent exponential equation as defined above. But if one side contains more than one logarithm, we need to use the properties of logarithm to condense it into a single logarithm. Take for example .. math:: \log(2x) - 15 = 0 contains single logarithm, therefore we can directly rewrite it to exponential form as .. math:: x = \frac{e^{15}}{2} But if the equation has more than one logarithm as .. math:: \log(x - 3) + \log(x + 3) = 0 we use logarithmic identities to convert it into a reduced form Using, .. math:: \log(a) + \log(b) = \log(ab) the equation becomes, .. math:: \log((x - 3)(x + 3)) This equation contains one logarithm and can be solved by rewriting to exponents. """ new_lhs = logcombine(lhs, force=True) new_f = new_lhs - rhs return _solveset(new_f, symbol, domain) def _is_logarithmic(f, symbol): r""" Return ``True`` if the equation is in the form `a\log(f(x)) + b\log(g(x)) + ... + c` else ``False``. Parameters ========== f : Expr The equation to be checked symbol : Symbol The variable in which the equation is checked Returns ======= ``True`` if the equation is logarithmic otherwise ``False``. Examples ======== >>> from sympy import symbols, tan, log >>> from sympy.solvers.solveset import _is_logarithmic as check >>> x, y = symbols('x y') >>> check(log(x + 2) - log(x + 3), x) True >>> check(tan(log(2*x)), x) False >>> check(x*log(x), x) False >>> check(x + log(x), x) False >>> check(y + log(x), x) True * Philosophy behind the helper The function extracts each term and checks whether it is logarithmic w.r.t ``symbol``. """ rv = False for term in Add.make_args(f): saw_log = False for term_arg in Mul.make_args(term): if symbol not in term_arg.free_symbols: continue if isinstance(term_arg, log): if saw_log: return False # more than one log in term saw_log = True else: return False # dependent on symbol in non-log way if saw_log: rv = True return rv def _is_lambert(f, symbol): r""" If this returns ``False`` then the Lambert solver (``_solve_lambert``) will not be called. Explanation =========== Quick check for cases that the Lambert solver might be able to handle. 1. Equations containing more than two operands and `symbol`s involving any of `Pow`, `exp`, `HyperbolicFunction`,`TrigonometricFunction`, `log` terms. 2. In `Pow`, `exp` the exponent should have `symbol` whereas for `HyperbolicFunction`,`TrigonometricFunction`, `log` should contain `symbol`. 3. For `HyperbolicFunction`,`TrigonometricFunction` the number of trigonometric functions in equation should be less than number of symbols. (since `A*cos(x) + B*sin(x) - c` is not the Lambert type). Some forms of lambert equations are: 1. X**X = C 2. X*(B*log(X) + D)**A = C 3. A*log(B*X + A) + d*X = C 4. (B*X + A)*exp(d*X + g) = C 5. g*exp(B*X + h) - B*X = C 6. A*D**(E*X + g) - B*X = C 7. A*cos(X) + B*sin(X) - D*X = C 8. A*cosh(X) + B*sinh(X) - D*X = C Where X is any variable, A, B, C, D, E are any constants, g, h are linear functions or log terms. Parameters ========== f : Expr The equation to be checked symbol : Symbol The variable in which the equation is checked Returns ======= If this returns ``False`` then the Lambert solver (``_solve_lambert``) will not be called. Examples ======== >>> from sympy.solvers.solveset import _is_lambert >>> from sympy import symbols, cosh, sinh, log >>> x = symbols('x') >>> _is_lambert(3*log(x) - x*log(3), x) True >>> _is_lambert(log(log(x - 3)) + log(x-3), x) True >>> _is_lambert(cosh(x) - sinh(x), x) False >>> _is_lambert((x**2 - 2*x + 1).subs(x, (log(x) + 3*x)**2 - 1), x) True See Also ======== _solve_lambert """ term_factors = list(_term_factors(f.expand())) # total number of symbols in equation no_of_symbols = len([arg for arg in term_factors if arg.has(symbol)]) # total number of trigonometric terms in equation no_of_trig = len([arg for arg in term_factors \ if arg.has(HyperbolicFunction, TrigonometricFunction)]) if f.is_Add and no_of_symbols >= 2: # `log`, `HyperbolicFunction`, `TrigonometricFunction` should have symbols # and no_of_trig < no_of_symbols lambert_funcs = (log, HyperbolicFunction, TrigonometricFunction) if any(isinstance(arg, lambert_funcs)\ for arg in term_factors if arg.has(symbol)): if no_of_trig < no_of_symbols: return True # here, `Pow`, `exp` exponent should have symbols elif any(isinstance(arg, (Pow, exp)) \ for arg in term_factors if (arg.as_base_exp()[1]).has(symbol)): return True return False def _transolve(f, symbol, domain): r""" Function to solve transcendental equations. It is a helper to ``solveset`` and should be used internally. ``_transolve`` currently supports the following class of equations: - Exponential equations - Logarithmic equations Parameters ========== f : Any transcendental equation that needs to be solved. This needs to be an expression, which is assumed to be equal to ``0``. symbol : The variable for which the equation is solved. This needs to be of class ``Symbol``. domain : A set over which the equation is solved. This needs to be of class ``Set``. Returns ======= Set A set of values for ``symbol`` for which ``f`` is equal to zero. An ``EmptySet`` is returned if ``f`` does not have solutions in respective domain. A ``ConditionSet`` is returned as unsolved object if algorithms to evaluate complete solution are not yet implemented. How to use ``_transolve`` ========================= ``_transolve`` should not be used as an independent function, because it assumes that the equation (``f``) and the ``symbol`` comes from ``solveset`` and might have undergone a few modification(s). To use ``_transolve`` as an independent function the equation (``f``) and the ``symbol`` should be passed as they would have been by ``solveset``. Examples ======== >>> from sympy.solvers.solveset import _transolve as transolve >>> from sympy.solvers.solvers import _tsolve as tsolve >>> from sympy import symbols, S, pprint >>> x = symbols('x', real=True) # assumption added >>> transolve(5**(x - 3) - 3**(2*x + 1), x, S.Reals) {-(log(3) + 3*log(5))/(-log(5) + 2*log(3))} How ``_transolve`` works ======================== ``_transolve`` uses two types of helper functions to solve equations of a particular class: Identifying helpers: To determine whether a given equation belongs to a certain class of equation or not. Returns either ``True`` or ``False``. Solving helpers: Once an equation is identified, a corresponding helper either solves the equation or returns a form of the equation that ``solveset`` might better be able to handle. * Philosophy behind the module The purpose of ``_transolve`` is to take equations which are not already polynomial in their generator(s) and to either recast them as such through a valid transformation or to solve them outright. A pair of helper functions for each class of supported transcendental functions are employed for this purpose. One identifies the transcendental form of an equation and the other either solves it or recasts it into a tractable form that can be solved by ``solveset``. For example, an equation in the form `ab^{f(x)} - cd^{g(x)} = 0` can be transformed to `\log(a) + f(x)\log(b) - \log(c) - g(x)\log(d) = 0` (under certain assumptions) and this can be solved with ``solveset`` if `f(x)` and `g(x)` are in polynomial form. How ``_transolve`` is better than ``_tsolve`` ============================================= 1) Better output ``_transolve`` provides expressions in a more simplified form. Consider a simple exponential equation >>> f = 3**(2*x) - 2**(x + 3) >>> pprint(transolve(f, x, S.Reals), use_unicode=False) -3*log(2) {------------------} -2*log(3) + log(2) >>> pprint(tsolve(f, x), use_unicode=False) / 3 \ | --------| | log(2/9)| [-log\2 /] 2) Extensible The API of ``_transolve`` is designed such that it is easily extensible, i.e. the code that solves a given class of equations is encapsulated in a helper and not mixed in with the code of ``_transolve`` itself. 3) Modular ``_transolve`` is designed to be modular i.e, for every class of equation a separate helper for identification and solving is implemented. This makes it easy to change or modify any of the method implemented directly in the helpers without interfering with the actual structure of the API. 4) Faster Computation Solving equation via ``_transolve`` is much faster as compared to ``_tsolve``. In ``solve``, attempts are made computing every possibility to get the solutions. This series of attempts makes solving a bit slow. In ``_transolve``, computation begins only after a particular type of equation is identified. How to add new class of equations ================================= Adding a new class of equation solver is a three-step procedure: - Identify the type of the equations Determine the type of the class of equations to which they belong: it could be of ``Add``, ``Pow``, etc. types. Separate internal functions are used for each type. Write identification and solving helpers and use them from within the routine for the given type of equation (after adding it, if necessary). Something like: .. code-block:: python def add_type(lhs, rhs, x): .... if _is_exponential(lhs, x): new_eq = _solve_exponential(lhs, rhs, x) .... rhs, lhs = eq.as_independent(x) if lhs.is_Add: result = add_type(lhs, rhs, x) - Define the identification helper. - Define the solving helper. Apart from this, a few other things needs to be taken care while adding an equation solver: - Naming conventions: Name of the identification helper should be as ``_is_class`` where class will be the name or abbreviation of the class of equation. The solving helper will be named as ``_solve_class``. For example: for exponential equations it becomes ``_is_exponential`` and ``_solve_expo``. - The identifying helpers should take two input parameters, the equation to be checked and the variable for which a solution is being sought, while solving helpers would require an additional domain parameter. - Be sure to consider corner cases. - Add tests for each helper. - Add a docstring to your helper that describes the method implemented. The documentation of the helpers should identify: - the purpose of the helper, - the method used to identify and solve the equation, - a proof of correctness - the return values of the helpers """ def add_type(lhs, rhs, symbol, domain): """ Helper for ``_transolve`` to handle equations of ``Add`` type, i.e. equations taking the form as ``a*f(x) + b*g(x) + .... = c``. For example: 4**x + 8**x = 0 """ result = ConditionSet(symbol, Eq(lhs - rhs, 0), domain) # check if it is exponential type equation if _is_exponential(lhs, symbol): result = _solve_exponential(lhs, rhs, symbol, domain) # check if it is logarithmic type equation elif _is_logarithmic(lhs, symbol): result = _solve_logarithm(lhs, rhs, symbol, domain) return result result = ConditionSet(symbol, Eq(f, 0), domain) # invert_complex handles the call to the desired inverter based # on the domain specified. lhs, rhs_s = invert_complex(f, 0, symbol, domain) if isinstance(rhs_s, FiniteSet): assert (len(rhs_s.args)) == 1 rhs = rhs_s.args[0] if lhs.is_Add: result = add_type(lhs, rhs, symbol, domain) else: result = rhs_s return result def solveset(f, symbol=None, domain=S.Complexes): r"""Solves a given inequality or equation with set as output Parameters ========== f : Expr or a relational. The target equation or inequality symbol : Symbol The variable for which the equation is solved domain : Set The domain over which the equation is solved Returns ======= Set A set of values for `symbol` for which `f` is True or is equal to zero. An :class:`~.EmptySet` is returned if `f` is False or nonzero. A :class:`~.ConditionSet` is returned as unsolved object if algorithms to evaluate complete solution are not yet implemented. ``solveset`` claims to be complete in the solution set that it returns. Raises ====== NotImplementedError The algorithms to solve inequalities in complex domain are not yet implemented. ValueError The input is not valid. RuntimeError It is a bug, please report to the github issue tracker. Notes ===== Python interprets 0 and 1 as False and True, respectively, but in this function they refer to solutions of an expression. So 0 and 1 return the domain and EmptySet, respectively, while True and False return the opposite (as they are assumed to be solutions of relational expressions). See Also ======== solveset_real: solver for real domain solveset_complex: solver for complex domain Examples ======== >>> from sympy import exp, sin, Symbol, pprint, S, Eq >>> from sympy.solvers.solveset import solveset, solveset_real * The default domain is complex. Not specifying a domain will lead to the solving of the equation in the complex domain (and this is not affected by the assumptions on the symbol): >>> x = Symbol('x') >>> pprint(solveset(exp(x) - 1, x), use_unicode=False) {2*n*I*pi | n in Integers} >>> x = Symbol('x', real=True) >>> pprint(solveset(exp(x) - 1, x), use_unicode=False) {2*n*I*pi | n in Integers} * If you want to use ``solveset`` to solve the equation in the real domain, provide a real domain. (Using ``solveset_real`` does this automatically.) >>> R = S.Reals >>> x = Symbol('x') >>> solveset(exp(x) - 1, x, R) {0} >>> solveset_real(exp(x) - 1, x) {0} The solution is unaffected by assumptions on the symbol: >>> p = Symbol('p', positive=True) >>> pprint(solveset(p**2 - 4)) {-2, 2} When a :class:`~.ConditionSet` is returned, symbols with assumptions that would alter the set are replaced with more generic symbols: >>> i = Symbol('i', imaginary=True) >>> solveset(Eq(i**2 + i*sin(i), 1), i, domain=S.Reals) ConditionSet(_R, Eq(_R**2 + _R*sin(_R) - 1, 0), Reals) * Inequalities can be solved over the real domain only. Use of a complex domain leads to a NotImplementedError. >>> solveset(exp(x) > 1, x, R) Interval.open(0, oo) """ f = sympify(f) symbol = sympify(symbol) if f is S.true: return domain if f is S.false: return S.EmptySet if not isinstance(f, (Expr, Relational, Number)): raise ValueError("%s is not a valid SymPy expression" % f) if not isinstance(symbol, (Expr, Relational)) and symbol is not None: raise ValueError("%s is not a valid SymPy symbol" % (symbol,)) if not isinstance(domain, Set): raise ValueError("%s is not a valid domain" %(domain)) free_symbols = f.free_symbols if f.has(Piecewise): f = piecewise_fold(f) if symbol is None and not free_symbols: b = Eq(f, 0) if b is S.true: return domain elif b is S.false: return S.EmptySet else: raise NotImplementedError(filldedent(''' relationship between value and 0 is unknown: %s''' % b)) if symbol is None: if len(free_symbols) == 1: symbol = free_symbols.pop() elif free_symbols: raise ValueError(filldedent(''' The independent variable must be specified for a multivariate equation.''')) elif not isinstance(symbol, Symbol): f, s, swap = recast_to_symbols([f], [symbol]) # the xreplace will be needed if a ConditionSet is returned return solveset(f[0], s[0], domain).xreplace(swap) # solveset should ignore assumptions on symbols if symbol not in _rc: x = _rc[0] if domain.is_subset(S.Reals) else _rc[1] rv = solveset(f.xreplace({symbol: x}), x, domain) # try to use the original symbol if possible try: _rv = rv.xreplace({x: symbol}) except TypeError: _rv = rv if rv.dummy_eq(_rv): rv = _rv return rv # Abs has its own handling method which avoids the # rewriting property that the first piece of abs(x) # is for x >= 0 and the 2nd piece for x < 0 -- solutions # can look better if the 2nd condition is x <= 0. Since # the solution is a set, duplication of results is not # an issue, e.g. {y, -y} when y is 0 will be {0} f, mask = _masked(f, Abs) f = f.rewrite(Piecewise) # everything that's not an Abs for d, e in mask: # everything *in* an Abs e = e.func(e.args[0].rewrite(Piecewise)) f = f.xreplace({d: e}) f = piecewise_fold(f) return _solveset(f, symbol, domain, _check=True) def solveset_real(f, symbol): return solveset(f, symbol, S.Reals) def solveset_complex(f, symbol): return solveset(f, symbol, S.Complexes) def _solveset_multi(eqs, syms, domains): '''Basic implementation of a multivariate solveset. For internal use (not ready for public consumption)''' rep = {} for sym, dom in zip(syms, domains): if dom is S.Reals: rep[sym] = Symbol(sym.name, real=True) eqs = [eq.subs(rep) for eq in eqs] syms = [sym.subs(rep) for sym in syms] syms = tuple(syms) if len(eqs) == 0: return ProductSet(*domains) if len(syms) == 1: sym = syms[0] domain = domains[0] solsets = [solveset(eq, sym, domain) for eq in eqs] solset = Intersection(*solsets) return ImageSet(Lambda((sym,), (sym,)), solset).doit() eqs = sorted(eqs, key=lambda eq: len(eq.free_symbols & set(syms))) for n, eq in enumerate(eqs): sols = [] all_handled = True for sym in syms: if sym not in eq.free_symbols: continue sol = solveset(eq, sym, domains[syms.index(sym)]) if isinstance(sol, FiniteSet): i = syms.index(sym) symsp = syms[:i] + syms[i+1:] domainsp = domains[:i] + domains[i+1:] eqsp = eqs[:n] + eqs[n+1:] for s in sol: eqsp_sub = [eq.subs(sym, s) for eq in eqsp] sol_others = _solveset_multi(eqsp_sub, symsp, domainsp) fun = Lambda((symsp,), symsp[:i] + (s,) + symsp[i:]) sols.append(ImageSet(fun, sol_others).doit()) else: all_handled = False if all_handled: return Union(*sols) def solvify(f, symbol, domain): """Solves an equation using solveset and returns the solution in accordance with the `solve` output API. Returns ======= We classify the output based on the type of solution returned by `solveset`. Solution | Output ---------------------------------------- FiniteSet | list ImageSet, | list (if `f` is periodic) Union | Union | list (with FiniteSet) EmptySet | empty list Others | None Raises ====== NotImplementedError A ConditionSet is the input. Examples ======== >>> from sympy.solvers.solveset import solvify >>> from sympy.abc import x >>> from sympy import S, tan, sin, exp >>> solvify(x**2 - 9, x, S.Reals) [-3, 3] >>> solvify(sin(x) - 1, x, S.Reals) [pi/2] >>> solvify(tan(x), x, S.Reals) [0] >>> solvify(exp(x) - 1, x, S.Complexes) >>> solvify(exp(x) - 1, x, S.Reals) [0] """ solution_set = solveset(f, symbol, domain) result = None if solution_set is S.EmptySet: result = [] elif isinstance(solution_set, ConditionSet): raise NotImplementedError('solveset is unable to solve this equation.') elif isinstance(solution_set, FiniteSet): result = list(solution_set) else: period = periodicity(f, symbol) if period is not None: solutions = S.EmptySet iter_solutions = () if isinstance(solution_set, ImageSet): iter_solutions = (solution_set,) elif isinstance(solution_set, Union): if all(isinstance(i, ImageSet) for i in solution_set.args): iter_solutions = solution_set.args for solution in iter_solutions: solutions += solution.intersect(Interval(0, period, False, True)) if isinstance(solutions, FiniteSet): result = list(solutions) else: solution = solution_set.intersect(domain) if isinstance(solution, Union): # concerned about only FiniteSet with Union but not about ImageSet # if required could be extend if any(isinstance(i, FiniteSet) for i in solution.args): result = [sol for soln in solution.args \ for sol in soln.args if isinstance(soln,FiniteSet)] else: return None elif isinstance(solution, FiniteSet): result += solution return result ############################################################################### ################################ LINSOLVE ##################################### ############################################################################### def linear_coeffs(eq, *syms, **_kw): """Return a list whose elements are the coefficients of the corresponding symbols in the sum of terms in ``eq``. The additive constant is returned as the last element of the list. Raises ====== NonlinearError The equation contains a nonlinear term Examples ======== >>> from sympy.solvers.solveset import linear_coeffs >>> from sympy.abc import x, y, z >>> linear_coeffs(3*x + 2*y - 1, x, y) [3, 2, -1] It is not necessary to expand the expression: >>> linear_coeffs(x + y*(z*(x*3 + 2) + 3), x) [3*y*z + 1, y*(2*z + 3)] But if there are nonlinear or cross terms -- even if they would cancel after simplification -- an error is raised so the situation does not pass silently past the caller's attention: >>> eq = 1/x*(x - 1) + 1/x >>> linear_coeffs(eq.expand(), x) [0, 1] >>> linear_coeffs(eq, x) Traceback (most recent call last): ... NonlinearError: nonlinear term encountered: 1/x >>> linear_coeffs(x*(y + 1) - x*y, x, y) Traceback (most recent call last): ... NonlinearError: nonlinear term encountered: x*(y + 1) """ d = defaultdict(list) eq = _sympify(eq) symset = set(syms) if len(symset) != len(syms): raise ValueError('duplicate symbols given') has = set(iterfreeargs(eq)) & symset if not has: return [S.Zero]*len(syms) + [eq] c, terms = eq.as_coeff_add(*has) d[0].extend(Add.make_args(c)) for t in terms: m, f = t.as_coeff_mul(*has) if len(f) != 1: break f = f[0] if f in symset: d[f].append(m) elif f.is_Add: d1 = linear_coeffs(f, *has, **{'dict': True}) d[0].append(m*d1.pop(0)) for xf, vf in d1.items(): d[xf].append(m*vf) else: break else: for k, v in d.items(): d[k] = Add(*v) if not _kw: return [d.get(s, S.Zero) for s in syms]+ [d[0]] return d # default is still list but this won't matter raise NonlinearError('nonlinear term encountered: %s' % t) def linear_eq_to_matrix(equations, *symbols): r""" Converts a given System of Equations into Matrix form. Here `equations` must be a linear system of equations in `symbols`. Element ``M[i, j]`` corresponds to the coefficient of the jth symbol in the ith equation. The Matrix form corresponds to the augmented matrix form. For example: .. math:: 4x + 2y + 3z = 1 .. math:: 3x + y + z = -6 .. math:: 2x + 4y + 9z = 2 This system will return $A$ and $b$ as: $$ A = \left[\begin{array}{ccc} 4 & 2 & 3 \\ 3 & 1 & 1 \\ 2 & 4 & 9 \end{array}\right] \ \ b = \left[\begin{array}{c} 1 \\ -6 \\ 2 \end{array}\right] $$ The only simplification performed is to convert ``Eq(a, b)`` $\Rightarrow a - b$. Raises ====== NonlinearError The equations contain a nonlinear term. ValueError The symbols are not given or are not unique. Examples ======== >>> from sympy import linear_eq_to_matrix, symbols >>> c, x, y, z = symbols('c, x, y, z') The coefficients (numerical or symbolic) of the symbols will be returned as matrices: >>> eqns = [c*x + z - 1 - c, y + z, x - y] >>> A, b = linear_eq_to_matrix(eqns, [x, y, z]) >>> A Matrix([ [c, 0, 1], [0, 1, 1], [1, -1, 0]]) >>> b Matrix([ [c + 1], [ 0], [ 0]]) This routine does not simplify expressions and will raise an error if nonlinearity is encountered: >>> eqns = [ ... (x**2 - 3*x)/(x - 3) - 3, ... y**2 - 3*y - y*(y - 4) + x - 4] >>> linear_eq_to_matrix(eqns, [x, y]) Traceback (most recent call last): ... NonlinearError: The term (x**2 - 3*x)/(x - 3) is nonlinear in {x, y} Simplifying these equations will discard the removable singularity in the first, reveal the linear structure of the second: >>> [e.simplify() for e in eqns] [x - 3, x + y - 4] Any such simplification needed to eliminate nonlinear terms must be done before calling this routine. """ if not symbols: raise ValueError(filldedent(''' Symbols must be given, for which coefficients are to be found. ''')) if hasattr(symbols[0], '__iter__'): symbols = symbols[0] for i in symbols: if not isinstance(i, Symbol): raise ValueError(filldedent(''' Expecting a Symbol but got %s ''' % i)) if has_dups(symbols): raise ValueError('Symbols must be unique') equations = sympify(equations) if isinstance(equations, MatrixBase): equations = list(equations) elif isinstance(equations, (Expr, Eq)): equations = [equations] elif not is_sequence(equations): raise ValueError(filldedent(''' Equation(s) must be given as a sequence, Expr, Eq or Matrix. ''')) A, b = [], [] for i, f in enumerate(equations): if isinstance(f, Equality): f = f.rewrite(Add, evaluate=False) coeff_list = linear_coeffs(f, *symbols) b.append(-coeff_list.pop()) A.append(coeff_list) A, b = map(Matrix, (A, b)) return A, b def linsolve(system, *symbols): r""" Solve system of $N$ linear equations with $M$ variables; both underdetermined and overdetermined systems are supported. The possible number of solutions is zero, one or infinite. Zero solutions throws a ValueError, whereas infinite solutions are represented parametrically in terms of the given symbols. For unique solution a :class:`~.FiniteSet` of ordered tuples is returned. All standard input formats are supported: For the given set of equations, the respective input types are given below: .. math:: 3x + 2y - z = 1 .. math:: 2x - 2y + 4z = -2 .. math:: 2x - y + 2z = 0 * Augmented matrix form, ``system`` given below: $$ \text{system} = \left[{array}{cccc} 3 & 2 & -1 & 1\\ 2 & -2 & 4 & -2\\ 2 & -1 & 2 & 0 \end{array}\right] $$ :: system = Matrix([[3, 2, -1, 1], [2, -2, 4, -2], [2, -1, 2, 0]]) * List of equations form :: system = [3x + 2y - z - 1, 2x - 2y + 4z + 2, 2x - y + 2z] * Input $A$ and $b$ in matrix form (from $Ax = b$) are given as: $$ A = \left[\begin{array}{ccc} 3 & 2 & -1 \\ 2 & -2 & 4 \\ 2 & -1 & 2 \end{array}\right] \ \ b = \left[\begin{array}{c} 1 \\ -2 \\ 0 \end{array}\right] $$ :: A = Matrix([[3, 2, -1], [2, -2, 4], [2, -1, 2]]) b = Matrix([[1], [-2], [0]]) system = (A, b) Symbols can always be passed but are actually only needed when 1) a system of equations is being passed and 2) the system is passed as an underdetermined matrix and one wants to control the name of the free variables in the result. An error is raised if no symbols are used for case 1, but if no symbols are provided for case 2, internally generated symbols will be provided. When providing symbols for case 2, there should be at least as many symbols are there are columns in matrix A. The algorithm used here is Gauss-Jordan elimination, which results, after elimination, in a row echelon form matrix. Returns ======= A FiniteSet containing an ordered tuple of values for the unknowns for which the `system` has a solution. (Wrapping the tuple in FiniteSet is used to maintain a consistent output format throughout solveset.) Returns EmptySet, if the linear system is inconsistent. Raises ====== ValueError The input is not valid. The symbols are not given. Examples ======== >>> from sympy import Matrix, linsolve, symbols >>> x, y, z = symbols("x, y, z") >>> A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 10]]) >>> b = Matrix([3, 6, 9]) >>> A Matrix([ [1, 2, 3], [4, 5, 6], [7, 8, 10]]) >>> b Matrix([ [3], [6], [9]]) >>> linsolve((A, b), [x, y, z]) {(-1, 2, 0)} * Parametric Solution: In case the system is underdetermined, the function will return a parametric solution in terms of the given symbols. Those that are free will be returned unchanged. e.g. in the system below, `z` is returned as the solution for variable z; it can take on any value. >>> A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> b = Matrix([3, 6, 9]) >>> linsolve((A, b), x, y, z) {(z - 1, 2 - 2*z, z)} If no symbols are given, internally generated symbols will be used. The ``tau0`` in the third position indicates (as before) that the third variable -- whatever it is named -- can take on any value: >>> linsolve((A, b)) {(tau0 - 1, 2 - 2*tau0, tau0)} * List of equations as input >>> Eqns = [3*x + 2*y - z - 1, 2*x - 2*y + 4*z + 2, - x + y/2 - z] >>> linsolve(Eqns, x, y, z) {(1, -2, -2)} * Augmented matrix as input >>> aug = Matrix([[2, 1, 3, 1], [2, 6, 8, 3], [6, 8, 18, 5]]) >>> aug Matrix([ [2, 1, 3, 1], [2, 6, 8, 3], [6, 8, 18, 5]]) >>> linsolve(aug, x, y, z) {(3/10, 2/5, 0)} * Solve for symbolic coefficients >>> a, b, c, d, e, f = symbols('a, b, c, d, e, f') >>> eqns = [a*x + b*y - c, d*x + e*y - f] >>> linsolve(eqns, x, y) {((-b*f + c*e)/(a*e - b*d), (a*f - c*d)/(a*e - b*d))} * A degenerate system returns solution as set of given symbols. >>> system = Matrix(([0, 0, 0], [0, 0, 0], [0, 0, 0])) >>> linsolve(system, x, y) {(x, y)} * For an empty system linsolve returns empty set >>> linsolve([], x) EmptySet * An error is raised if, after expansion, any nonlinearity is detected: >>> linsolve([x*(1/x - 1), (y - 1)**2 - y**2 + 1], x, y) {(1, 1)} >>> linsolve([x**2 - 1], x) Traceback (most recent call last): ... NonlinearError: nonlinear term encountered: x**2 """ if not system: return S.EmptySet # If second argument is an iterable if symbols and hasattr(symbols[0], '__iter__'): symbols = symbols[0] sym_gen = isinstance(symbols, GeneratorType) b = None # if we don't get b the input was bad # unpack system if hasattr(system, '__iter__'): # 1). (A, b) if len(system) == 2 and isinstance(system[0], MatrixBase): A, b = system # 2). (eq1, eq2, ...) if not isinstance(system[0], MatrixBase): if sym_gen or not symbols: raise ValueError(filldedent(''' When passing a system of equations, the explicit symbols for which a solution is being sought must be given as a sequence, too. ''')) # # Pass to the sparse solver implemented in polys. It is important # that we do not attempt to convert the equations to a matrix # because that would be very inefficient for large sparse systems # of equations. # eqs = system eqs = [sympify(eq) for eq in eqs] try: sol = _linsolve(eqs, symbols) except PolyNonlinearError as exc: # e.g. cos(x) contains an element of the set of generators raise NonlinearError(str(exc)) if sol is None: return S.EmptySet sol = FiniteSet(Tuple(*(sol.get(sym, sym) for sym in symbols))) return sol elif isinstance(system, MatrixBase) and not ( symbols and not isinstance(symbols, GeneratorType) and isinstance(symbols[0], MatrixBase)): # 3). A augmented with b A, b = system[:, :-1], system[:, -1:] if b is None: raise ValueError("Invalid arguments") if sym_gen: symbols = [next(symbols) for i in range(A.cols)] if any(set(symbols) & (A.free_symbols | b.free_symbols)): raise ValueError(filldedent(''' At least one of the symbols provided already appears in the system to be solved. One way to avoid this is to use Dummy symbols in the generator, e.g. numbered_symbols('%s', cls=Dummy) ''' % symbols[0].name.rstrip('1234567890'))) if not symbols: symbols = [Dummy() for _ in range(A.cols)] name = _uniquely_named_symbol('tau', (A, b), compare=lambda i: str(i).rstrip('1234567890')).name gen = numbered_symbols(name) else: gen = None # This is just a wrapper for solve_lin_sys eqs = [] rows = A.tolist() for rowi, bi in zip(rows, b): terms = [elem * sym for elem, sym in zip(rowi, symbols) if elem] terms.append(-bi) eqs.append(Add(*terms)) eqs, ring = sympy_eqs_to_ring(eqs, symbols) sol = solve_lin_sys(eqs, ring, _raw=False) if sol is None: return S.EmptySet #sol = {sym:val for sym, val in sol.items() if sym != val} sol = FiniteSet(Tuple(*(sol.get(sym, sym) for sym in symbols))) if gen is not None: solsym = sol.free_symbols rep = {sym: next(gen) for sym in symbols if sym in solsym} sol = sol.subs(rep) return sol ############################################################################## # ------------------------------nonlinsolve ---------------------------------# ############################################################################## def _return_conditionset(eqs, symbols): # return conditionset eqs = (Eq(lhs, 0) for lhs in eqs) condition_set = ConditionSet( Tuple(*symbols), And(*eqs), S.Complexes**len(symbols)) return condition_set def substitution(system, symbols, result=[{}], known_symbols=[], exclude=[], all_symbols=None): r""" Solves the `system` using substitution method. It is used in :func:`~.nonlinsolve`. This will be called from :func:`~.nonlinsolve` when any equation(s) is non polynomial equation. Parameters ========== system : list of equations The target system of equations symbols : list of symbols to be solved. The variable(s) for which the system is solved known_symbols : list of solved symbols Values are known for these variable(s) result : An empty list or list of dict If No symbol values is known then empty list otherwise symbol as keys and corresponding value in dict. exclude : Set of expression. Mostly denominator expression(s) of the equations of the system. Final solution should not satisfy these expressions. all_symbols : known_symbols + symbols(unsolved). Returns ======= A FiniteSet of ordered tuple of values of `all_symbols` for which the `system` has solution. Order of values in the tuple is same as symbols present in the parameter `all_symbols`. If parameter `all_symbols` is None then same as symbols present in the parameter `symbols`. Please note that general FiniteSet is unordered, the solution returned here is not simply a FiniteSet of solutions, rather it is a FiniteSet of ordered tuple, i.e. the first & only argument to FiniteSet is a tuple of solutions, which is ordered, & hence the returned solution is ordered. Also note that solution could also have been returned as an ordered tuple, FiniteSet is just a wrapper `{}` around the tuple. It has no other significance except for the fact it is just used to maintain a consistent output format throughout the solveset. Raises ====== ValueError The input is not valid. The symbols are not given. AttributeError The input symbols are not :class:`~.Symbol` type. Examples ======== >>> from sympy import symbols, substitution >>> x, y = symbols('x, y', real=True) >>> substitution([x + y], [x], [{y: 1}], [y], set([]), [x, y]) {(-1, 1)} * When you want a soln not satisfying $x + 1 = 0$ >>> substitution([x + y], [x], [{y: 1}], [y], set([x + 1]), [y, x]) EmptySet >>> substitution([x + y], [x], [{y: 1}], [y], set([x - 1]), [y, x]) {(1, -1)} >>> substitution([x + y - 1, y - x**2 + 5], [x, y]) {(-3, 4), (2, -1)} * Returns both real and complex solution >>> x, y, z = symbols('x, y, z') >>> from sympy import exp, sin >>> substitution([exp(x) - sin(y), y**2 - 4], [x, y]) {(ImageSet(Lambda(_n, I*(2*_n*pi + pi) + log(sin(2))), Integers), -2), (ImageSet(Lambda(_n, 2*_n*I*pi + log(sin(2))), Integers), 2)} >>> eqs = [z**2 + exp(2*x) - sin(y), -3 + exp(-y)] >>> substitution(eqs, [y, z]) {(-log(3), -sqrt(-exp(2*x) - sin(log(3)))), (-log(3), sqrt(-exp(2*x) - sin(log(3)))), (ImageSet(Lambda(_n, 2*_n*I*pi - log(3)), Integers), ImageSet(Lambda(_n, -sqrt(-exp(2*x) + sin(2*_n*I*pi - log(3)))), Integers)), (ImageSet(Lambda(_n, 2*_n*I*pi - log(3)), Integers), ImageSet(Lambda(_n, sqrt(-exp(2*x) + sin(2*_n*I*pi - log(3)))), Integers))} """ if not system: return S.EmptySet if not symbols: msg = ('Symbols must be given, for which solution of the ' 'system is to be found.') raise ValueError(filldedent(msg)) if not is_sequence(symbols): msg = ('symbols should be given as a sequence, e.g. a list.' 'Not type %s: %s') raise TypeError(filldedent(msg % (type(symbols), symbols))) if not getattr(symbols[0], 'is_Symbol', False): msg = ('Iterable of symbols must be given as ' 'second argument, not type %s: %s') raise ValueError(filldedent(msg % (type(symbols[0]), symbols[0]))) # By default `all_symbols` will be same as `symbols` if all_symbols is None: all_symbols = symbols old_result = result # storing complements and intersection for particular symbol complements = {} intersections = {} # when total_solveset_call equals total_conditionset # it means that solveset failed to solve all eqs. total_conditionset = -1 total_solveset_call = -1 def _unsolved_syms(eq, sort=False): """Returns the unsolved symbol present in the equation `eq`. """ free = eq.free_symbols unsolved = (free - set(known_symbols)) & set(all_symbols) if sort: unsolved = list(unsolved) unsolved.sort(key=default_sort_key) return unsolved # end of _unsolved_syms() # sort such that equation with the fewest potential symbols is first. # means eq with less number of variable first in the list. eqs_in_better_order = list( ordered(system, lambda _: len(_unsolved_syms(_)))) def add_intersection_complement(result, intersection_dict, complement_dict): # If solveset has returned some intersection/complement # for any symbol, it will be added in the final solution. final_result = [] for res in result: res_copy = res for key_res, value_res in res.items(): intersect_set, complement_set = None, None for key_sym, value_sym in intersection_dict.items(): if key_sym == key_res: intersect_set = value_sym for key_sym, value_sym in complement_dict.items(): if key_sym == key_res: complement_set = value_sym if intersect_set or complement_set: new_value = FiniteSet(value_res) if intersect_set and intersect_set != S.Complexes: new_value = Intersection(new_value, intersect_set) if complement_set: new_value = Complement(new_value, complement_set) if new_value is S.EmptySet: res_copy = None break elif new_value.is_FiniteSet and len(new_value) == 1: res_copy[key_res] = set(new_value).pop() else: res_copy[key_res] = new_value if res_copy is not None: final_result.append(res_copy) return final_result # end of def add_intersection_complement() def _extract_main_soln(sym, sol, soln_imageset): """Separate the Complements, Intersections, ImageSet lambda expr and its base_set. This function returns the unmasks sol from different classes of sets and also returns the appended ImageSet elements in a soln_imageset (dict: where key as unmasked element and value as ImageSet). """ # if there is union, then need to check # Complement, Intersection, Imageset. # Order should not be changed. if isinstance(sol, ConditionSet): # extracts any solution in ConditionSet sol = sol.base_set if isinstance(sol, Complement): # extract solution and complement complements[sym] = sol.args[1] sol = sol.args[0] # complement will be added at the end # using `add_intersection_complement` method # if there is union of Imageset or other in soln. # no testcase is written for this if block if isinstance(sol, Union): sol_args = sol.args sol = S.EmptySet # We need in sequence so append finteset elements # and then imageset or other. for sol_arg2 in sol_args: if isinstance(sol_arg2, FiniteSet): sol += sol_arg2 else: # ImageSet, Intersection, complement then # append them directly sol += FiniteSet(sol_arg2) if isinstance(sol, Intersection): # Interval/Set will be at 0th index always if sol.args[0] not in (S.Reals, S.Complexes): # Sometimes solveset returns soln with intersection # S.Reals or S.Complexes. We don't consider that # intersection. intersections[sym] = sol.args[0] sol = sol.args[1] # after intersection and complement Imageset should # be checked. if isinstance(sol, ImageSet): soln_imagest = sol expr2 = sol.lamda.expr sol = FiniteSet(expr2) soln_imageset[expr2] = soln_imagest if not isinstance(sol, FiniteSet): sol = FiniteSet(sol) return sol, soln_imageset # end of def _extract_main_soln() # helper function for _append_new_soln def _check_exclude(rnew, imgset_yes): rnew_ = rnew if imgset_yes: # replace all dummy variables (Imageset lambda variables) # with zero before `checksol`. Considering fundamental soln # for `checksol`. rnew_copy = rnew.copy() dummy_n = imgset_yes[0] for key_res, value_res in rnew_copy.items(): rnew_copy[key_res] = value_res.subs(dummy_n, 0) rnew_ = rnew_copy # satisfy_exclude == true if it satisfies the expr of `exclude` list. try: # something like : `Mod(-log(3), 2*I*pi)` can't be # simplified right now, so `checksol` returns `TypeError`. # when this issue is fixed this try block should be # removed. Mod(-log(3), 2*I*pi) == -log(3) satisfy_exclude = any( checksol(d, rnew_) for d in exclude) except TypeError: satisfy_exclude = None return satisfy_exclude # end of def _check_exclude() # helper function for _append_new_soln def _restore_imgset(rnew, original_imageset, newresult): restore_sym = set(rnew.keys()) & \ set(original_imageset.keys()) for key_sym in restore_sym: img = original_imageset[key_sym] rnew[key_sym] = img if rnew not in newresult: newresult.append(rnew) # end of def _restore_imgset() def _append_eq(eq, result, res, delete_soln, n=None): u = Dummy('u') if n: eq = eq.subs(n, 0) satisfy = eq if eq in (True, False) else checksol(u, u, eq, minimal=True) if satisfy is False: delete_soln = True res = {} else: result.append(res) return result, res, delete_soln def _append_new_soln(rnew, sym, sol, imgset_yes, soln_imageset, original_imageset, newresult, eq=None): """If `rnew` (A dict <symbol: soln>) contains valid soln append it to `newresult` list. `imgset_yes` is (base, dummy_var) if there was imageset in previously calculated result(otherwise empty tuple). `original_imageset` is dict of imageset expr and imageset from this result. `soln_imageset` dict of imageset expr and imageset of new soln. """ satisfy_exclude = _check_exclude(rnew, imgset_yes) delete_soln = False # soln should not satisfy expr present in `exclude` list. if not satisfy_exclude: local_n = None # if it is imageset if imgset_yes: local_n = imgset_yes[0] base = imgset_yes[1] if sym and sol: # when `sym` and `sol` is `None` means no new # soln. In that case we will append rnew directly after # substituting original imagesets in rnew values if present # (second last line of this function using _restore_imgset) dummy_list = list(sol.atoms(Dummy)) # use one dummy `n` which is in # previous imageset local_n_list = [ local_n for i in range( 0, len(dummy_list))] dummy_zip = zip(dummy_list, local_n_list) lam = Lambda(local_n, sol.subs(dummy_zip)) rnew[sym] = ImageSet(lam, base) if eq is not None: newresult, rnew, delete_soln = _append_eq( eq, newresult, rnew, delete_soln, local_n) elif eq is not None: newresult, rnew, delete_soln = _append_eq( eq, newresult, rnew, delete_soln) elif sol in soln_imageset.keys(): rnew[sym] = soln_imageset[sol] # restore original imageset _restore_imgset(rnew, original_imageset, newresult) else: newresult.append(rnew) elif satisfy_exclude: delete_soln = True rnew = {} _restore_imgset(rnew, original_imageset, newresult) return newresult, delete_soln # end of def _append_new_soln() def _new_order_result(result, eq): # separate first, second priority. `res` that makes `eq` value equals # to zero, should be used first then other result(second priority). # If it is not done then we may miss some soln. first_priority = [] second_priority = [] for res in result: if not any(isinstance(val, ImageSet) for val in res.values()): if eq.subs(res) == 0: first_priority.append(res) else: second_priority.append(res) if first_priority or second_priority: return first_priority + second_priority return result def _solve_using_known_values(result, solver): """Solves the system using already known solution (result contains the dict <symbol: value>). solver is :func:`~.solveset_complex` or :func:`~.solveset_real`. """ # stores imageset <expr: imageset(Lambda(n, expr), base)>. soln_imageset = {} total_solvest_call = 0 total_conditionst = 0 # sort such that equation with the fewest potential symbols is first. # means eq with less variable first for index, eq in enumerate(eqs_in_better_order): newresult = [] original_imageset = {} # if imageset expr is used to solve other symbol imgset_yes = False result = _new_order_result(result, eq) for res in result: got_symbol = set() # symbols solved in one iteration # find the imageset and use its expr. for key_res, value_res in res.items(): if isinstance(value_res, ImageSet): res[key_res] = value_res.lamda.expr original_imageset[key_res] = value_res dummy_n = value_res.lamda.expr.atoms(Dummy).pop() (base,) = value_res.base_sets imgset_yes = (dummy_n, base) # update eq with everything that is known so far eq2 = eq.subs(res).expand() unsolved_syms = _unsolved_syms(eq2, sort=True) if not unsolved_syms: if res: newresult, delete_res = _append_new_soln( res, None, None, imgset_yes, soln_imageset, original_imageset, newresult, eq2) if delete_res: # `delete_res` is true, means substituting `res` in # eq2 doesn't return `zero` or deleting the `res` # (a soln) since it staisfies expr of `exclude` # list. result.remove(res) continue # skip as it's independent of desired symbols depen1, depen2 = (eq2.rewrite(Add)).as_independent(*unsolved_syms) if (depen1.has(Abs) or depen2.has(Abs)) and solver == solveset_complex: # Absolute values cannot be inverted in the # complex domain continue soln_imageset = {} for sym in unsolved_syms: not_solvable = False try: soln = solver(eq2, sym) total_solvest_call += 1 soln_new = S.EmptySet if isinstance(soln, Complement): # separate solution and complement complements[sym] = soln.args[1] soln = soln.args[0] # complement will be added at the end if isinstance(soln, Intersection): # Interval will be at 0th index always if soln.args[0] != Interval(-oo, oo): # sometimes solveset returns soln # with intersection S.Reals, to confirm that # soln is in domain=S.Reals intersections[sym] = soln.args[0] soln_new += soln.args[1] soln = soln_new if soln_new else soln if index > 0 and solver == solveset_real: # one symbol's real soln, another symbol may have # corresponding complex soln. if not isinstance(soln, (ImageSet, ConditionSet)): soln += solveset_complex(eq2, sym) # might give ValueError with Abs except (NotImplementedError, ValueError): # If solveset is not able to solve equation `eq2`. Next # time we may get soln using next equation `eq2` continue if isinstance(soln, ConditionSet): if soln.base_set in (S.Reals, S.Complexes): soln = S.EmptySet # don't do `continue` we may get soln # in terms of other symbol(s) not_solvable = True total_conditionst += 1 else: soln = soln.base_set if soln is not S.EmptySet: soln, soln_imageset = _extract_main_soln( sym, soln, soln_imageset) for sol in soln: # sol is not a `Union` since we checked it # before this loop sol, soln_imageset = _extract_main_soln( sym, sol, soln_imageset) sol = set(sol).pop() free = sol.free_symbols if got_symbol and any( ss in free for ss in got_symbol ): # sol depends on previously solved symbols # then continue continue rnew = res.copy() # put each solution in res and append the new result # in the new result list (solution for symbol `s`) # along with old results. for k, v in res.items(): if isinstance(v, Expr) and isinstance(sol, Expr): # if any unsolved symbol is present # Then subs known value rnew[k] = v.subs(sym, sol) # and add this new solution if sol in soln_imageset.keys(): # replace all lambda variables with 0. imgst = soln_imageset[sol] rnew[sym] = imgst.lamda( *[0 for i in range(0, len( imgst.lamda.variables))]) else: rnew[sym] = sol newresult, delete_res = _append_new_soln( rnew, sym, sol, imgset_yes, soln_imageset, original_imageset, newresult) if delete_res: # deleting the `res` (a soln) since it staisfies # eq of `exclude` list result.remove(res) # solution got for sym if not not_solvable: got_symbol.add(sym) # next time use this new soln if newresult: result = newresult return result, total_solvest_call, total_conditionst # end def _solve_using_know_values() new_result_real, solve_call1, cnd_call1 = _solve_using_known_values( old_result, solveset_real) new_result_complex, solve_call2, cnd_call2 = _solve_using_known_values( old_result, solveset_complex) # If total_solveset_call is equal to total_conditionset # then solveset failed to solve all of the equations. # In this case we return a ConditionSet here. total_conditionset += (cnd_call1 + cnd_call2) total_solveset_call += (solve_call1 + solve_call2) if total_conditionset == total_solveset_call and total_solveset_call != -1: return _return_conditionset(eqs_in_better_order, all_symbols) # don't keep duplicate solutions filtered_complex = [] for i in list(new_result_complex): for j in list(new_result_real): if i.keys() != j.keys(): continue if all(a.dummy_eq(b) for a, b in zip(i.values(), j.values()) \ if not (isinstance(a, int) and isinstance(b, int))): break else: filtered_complex.append(i) # overall result result = new_result_real + filtered_complex result_all_variables = [] result_infinite = [] for res in result: if not res: # means {None : None} continue # If length < len(all_symbols) means infinite soln. # Some or all the soln is dependent on 1 symbol. # eg. {x: y+2} then final soln {x: y+2, y: y} if len(res) < len(all_symbols): solved_symbols = res.keys() unsolved = list(filter( lambda x: x not in solved_symbols, all_symbols)) for unsolved_sym in unsolved: res[unsolved_sym] = unsolved_sym result_infinite.append(res) if res not in result_all_variables: result_all_variables.append(res) if result_infinite: # we have general soln # eg : [{x: -1, y : 1}, {x : -y, y: y}] then # return [{x : -y, y : y}] result_all_variables = result_infinite if intersections or complements: result_all_variables = add_intersection_complement( result_all_variables, intersections, complements) # convert to ordered tuple result = S.EmptySet for r in result_all_variables: temp = [r[symb] for symb in all_symbols] result += FiniteSet(tuple(temp)) return result # end of def substitution() def _solveset_work(system, symbols): soln = solveset(system[0], symbols[0]) if isinstance(soln, FiniteSet): _soln = FiniteSet(*[tuple((s,)) for s in soln]) return _soln else: return FiniteSet(tuple(FiniteSet(soln))) def _handle_positive_dimensional(polys, symbols, denominators): from sympy.polys.polytools import groebner # substitution method where new system is groebner basis of the system _symbols = list(symbols) _symbols.sort(key=default_sort_key) basis = groebner(polys, _symbols, polys=True) new_system = [] for poly_eq in basis: new_system.append(poly_eq.as_expr()) result = [{}] result = substitution( new_system, symbols, result, [], denominators) return result # end of def _handle_positive_dimensional() def _handle_zero_dimensional(polys, symbols, system): # solve 0 dimensional poly system using `solve_poly_system` result = solve_poly_system(polys, *symbols) # May be some extra soln is added because # we used `unrad` in `_separate_poly_nonpoly`, so # need to check and remove if it is not a soln. result_update = S.EmptySet for res in result: dict_sym_value = dict(list(zip(symbols, res))) if all(checksol(eq, dict_sym_value) for eq in system): result_update += FiniteSet(res) return result_update # end of def _handle_zero_dimensional() def _separate_poly_nonpoly(system, symbols): polys = [] polys_expr = [] nonpolys = [] # unrad_changed stores a list of expressions containing # radicals that were processed using unrad # this is useful if solutions need to be checked later. unrad_changed = [] denominators = set() poly = None for eq in system: # Store denom expressions that contain symbols denominators.update(_simple_dens(eq, symbols)) # Convert equality to expression if isinstance(eq, Equality): eq = eq.rewrite(Add) # try to remove sqrt and rational power without_radicals = unrad(simplify(eq), *symbols) if without_radicals: unrad_changed.append(eq) eq_unrad, cov = without_radicals if not cov: eq = eq_unrad if isinstance(eq, Expr): eq = eq.as_numer_denom()[0] poly = eq.as_poly(*symbols, extension=True) elif simplify(eq).is_number: continue if poly is not None: polys.append(poly) polys_expr.append(poly.as_expr()) else: nonpolys.append(eq) return polys, polys_expr, nonpolys, denominators, unrad_changed # end of def _separate_poly_nonpoly() def _handle_poly(polys, symbols): # _handle_poly(polys, symbols) -> (poly_sol, poly_eqs) # # We will return possible solution information to nonlinsolve as well as a # new system of polynomial equations to be solved if we cannot solve # everything directly here. The new system of polynomial equations will be # a lex-order Groebner basis for the original system. The lex basis # hopefully separate some of the variables and equations and give something # easier for substitution to work with. # The format for representing solution sets in nonlinsolve and substitution # is a list of dicts. These are the special cases: no_information = [{}] # No equations solved yet no_solutions = [] # The system is inconsistent and has no solutions. # If there is no need to attempt further solution of these equations then # we return no equations: no_equations = [] inexact = any(not p.domain.is_Exact for p in polys) if inexact: # The use of Groebner over RR is likely to result incorrectly in an # inconsistent Groebner basis. So, convert any float coefficients to # Rational before computing the Groebner basis. polys = [poly(nsimplify(p, rational=True)) for p in polys] # Compute a Groebner basis in grevlex order wrt the ordering given. We will # try to convert this to lex order later. Usually it seems to be more # efficient to compute a lex order basis by computing a grevlex basis and # converting to lex with fglm. basis = groebner(polys, symbols, order='grevlex', polys=False) # # No solutions (inconsistent equations)? # if 1 in basis: # No solutions: poly_sol = no_solutions poly_eqs = no_equations # # Finite number of solutions (zero-dimensional case) # elif basis.is_zero_dimensional: # Convert Groebner basis to lex ordering basis = basis.fglm('lex') # Convert polynomial coefficients back to float before calling # solve_poly_system if inexact: basis = [nfloat(p) for p in basis] # Solve the zero-dimensional case using solve_poly_system if possible. # If some polynomials have factors that cannot be solved in radicals # then this will fail. Using solve_poly_system(..., strict=True) # ensures that we either get a complete solution set in radicals or # UnsolvableFactorError will be raised. try: result = solve_poly_system(basis, *symbols, strict=True) except UnsolvableFactorError: # Failure... not fully solvable in radicals. Return the lex-order # basis for substitution to handle. poly_sol = no_information poly_eqs = list(basis) else: # Success! We have a finite solution set and solve_poly_system has # succeeded in finding all solutions. Return the solutions and also # an empty list of remaining equations to be solved. poly_sol = [dict(zip(symbols, res)) for res in result] poly_eqs = no_equations # # Infinite families of solutions (positive-dimensional case) # else: # In this case the grevlex basis cannot be converted to lex using the # fglm method and also solve_poly_system cannot solve the equations. We # would like to return a lex basis but since we can't use fglm we # compute the lex basis directly here. The time required to recompute # the basis is generally significantly less than the time required by # substitution to solve the new system. poly_sol = no_information poly_eqs = list(groebner(polys, symbols, order='lex', polys=False)) if inexact: poly_eqs = [nfloat(p) for p in poly_eqs] return poly_sol, poly_eqs def nonlinsolve(system, *symbols): r""" Solve system of $N$ nonlinear equations with $M$ variables, which means both under and overdetermined systems are supported. Positive dimensional system is also supported (A system with infinitely many solutions is said to be positive-dimensional). In a positive dimensional system the solution will be dependent on at least one symbol. Returns both real solution and complex solution (if they exist). Parameters ========== system : list of equations The target system of equations symbols : list of Symbols symbols should be given as a sequence eg. list Returns ======= A :class:`~.FiniteSet` of ordered tuple of values of `symbols` for which the `system` has solution. Order of values in the tuple is same as symbols present in the parameter `symbols`. Please note that general :class:`~.FiniteSet` is unordered, the solution returned here is not simply a :class:`~.FiniteSet` of solutions, rather it is a :class:`~.FiniteSet` of ordered tuple, i.e. the first and only argument to :class:`~.FiniteSet` is a tuple of solutions, which is ordered, and, hence ,the returned solution is ordered. Also note that solution could also have been returned as an ordered tuple, FiniteSet is just a wrapper ``{}`` around the tuple. It has no other significance except for the fact it is just used to maintain a consistent output format throughout the solveset. For the given set of equations, the respective input types are given below: .. math:: xy - 1 = 0 .. math:: 4x^2 + y^2 - 5 = 0 :: system = [x*y - 1, 4*x**2 + y**2 - 5] symbols = [x, y] Raises ====== ValueError The input is not valid. The symbols are not given. AttributeError The input symbols are not `Symbol` type. Examples ======== >>> from sympy import symbols, nonlinsolve >>> x, y, z = symbols('x, y, z', real=True) >>> nonlinsolve([x*y - 1, 4*x**2 + y**2 - 5], [x, y]) {(-1, -1), (-1/2, -2), (1/2, 2), (1, 1)} 1. Positive dimensional system and complements: >>> from sympy import pprint >>> from sympy.polys.polytools import is_zero_dimensional >>> a, b, c, d = symbols('a, b, c, d', extended_real=True) >>> eq1 = a + b + c + d >>> eq2 = a*b + b*c + c*d + d*a >>> eq3 = a*b*c + b*c*d + c*d*a + d*a*b >>> eq4 = a*b*c*d - 1 >>> system = [eq1, eq2, eq3, eq4] >>> is_zero_dimensional(system) False >>> pprint(nonlinsolve(system, [a, b, c, d]), use_unicode=False) -1 1 1 -1 {(---, -d, -, {d} \ {0}), (-, -d, ---, {d} \ {0})} d d d d >>> nonlinsolve([(x+y)**2 - 4, x + y - 2], [x, y]) {(2 - y, y)} 2. If some of the equations are non-polynomial then `nonlinsolve` will call the ``substitution`` function and return real and complex solutions, if present. >>> from sympy import exp, sin >>> nonlinsolve([exp(x) - sin(y), y**2 - 4], [x, y]) {(ImageSet(Lambda(_n, I*(2*_n*pi + pi) + log(sin(2))), Integers), -2), (ImageSet(Lambda(_n, 2*_n*I*pi + log(sin(2))), Integers), 2)} 3. If system is non-linear polynomial and zero-dimensional then it returns both solution (real and complex solutions, if present) using :func:`~.solve_poly_system`: >>> from sympy import sqrt >>> nonlinsolve([x**2 - 2*y**2 -2, x*y - 2], [x, y]) {(-2, -1), (2, 1), (-sqrt(2)*I, sqrt(2)*I), (sqrt(2)*I, -sqrt(2)*I)} 4. ``nonlinsolve`` can solve some linear (zero or positive dimensional) system (because it uses the :func:`sympy.polys.polytools.groebner` function to get the groebner basis and then uses the ``substitution`` function basis as the new `system`). But it is not recommended to solve linear system using ``nonlinsolve``, because :func:`~.linsolve` is better for general linear systems. >>> nonlinsolve([x + 2*y -z - 3, x - y - 4*z + 9, y + z - 4], [x, y, z]) {(3*z - 5, 4 - z, z)} 5. System having polynomial equations and only real solution is solved using :func:`~.solve_poly_system`: >>> e1 = sqrt(x**2 + y**2) - 10 >>> e2 = sqrt(y**2 + (-x + 10)**2) - 3 >>> nonlinsolve((e1, e2), (x, y)) {(191/20, -3*sqrt(391)/20), (191/20, 3*sqrt(391)/20)} >>> nonlinsolve([x**2 + 2/y - 2, x + y - 3], [x, y]) {(1, 2), (1 - sqrt(5), 2 + sqrt(5)), (1 + sqrt(5), 2 - sqrt(5))} >>> nonlinsolve([x**2 + 2/y - 2, x + y - 3], [y, x]) {(2, 1), (2 - sqrt(5), 1 + sqrt(5)), (2 + sqrt(5), 1 - sqrt(5))} 6. It is better to use symbols instead of trigonometric functions or :class:`~.Function`. For example, replace $\sin(x)$ with a symbol, replace $f(x)$ with a symbol and so on. Get a solution from ``nonlinsolve`` and then use :func:`~.solveset` to get the value of $x$. How nonlinsolve is better than old solver ``_solve_system`` : ============================================================= 1. A positive dimensional system solver: nonlinsolve can return solution for positive dimensional system. It finds the Groebner Basis of the positive dimensional system(calling it as basis) then we can start solving equation(having least number of variable first in the basis) using solveset and substituting that solved solutions into other equation(of basis) to get solution in terms of minimum variables. Here the important thing is how we are substituting the known values and in which equations. 2. Real and complex solutions: nonlinsolve returns both real and complex solution. If all the equations in the system are polynomial then using :func:`~.solve_poly_system` both real and complex solution is returned. If all the equations in the system are not polynomial equation then goes to ``substitution`` method with this polynomial and non polynomial equation(s), to solve for unsolved variables. Here to solve for particular variable solveset_real and solveset_complex is used. For both real and complex solution ``_solve_using_known_values`` is used inside ``substitution`` (``substitution`` will be called when any non-polynomial equation is present). If a solution is valid its general solution is added to the final result. 3. :class:`~.Complement` and :class:`~.Intersection` will be added: nonlinsolve maintains dict for complements and intersections. If solveset find complements or/and intersections with any interval or set during the execution of ``substitution`` function, then complement or/and intersection for that variable is added before returning final solution. """ if not system: return S.EmptySet if not symbols: msg = ('Symbols must be given, for which solution of the ' 'system is to be found.') raise ValueError(filldedent(msg)) if hasattr(symbols[0], '__iter__'): symbols = symbols[0] if not is_sequence(symbols) or not symbols: msg = ('Symbols must be given, for which solution of the ' 'system is to be found.') raise IndexError(filldedent(msg)) symbols = list(map(_sympify, symbols)) system, symbols, swap = recast_to_symbols(system, symbols) if swap: soln = nonlinsolve(system, symbols) return FiniteSet(*[tuple(i.xreplace(swap) for i in s) for s in soln]) if len(system) == 1 and len(symbols) == 1: return _solveset_work(system, symbols) # main code of def nonlinsolve() starts from here polys, polys_expr, nonpolys, denominators, unrad_changed = \ _separate_poly_nonpoly(system, symbols) poly_eqs = [] poly_sol = [{}] if polys: poly_sol, poly_eqs = _handle_poly(polys, symbols) if poly_sol and poly_sol[0]: poly_syms = set().union(*(eq.free_symbols for eq in polys)) unrad_syms = set().union(*(eq.free_symbols for eq in unrad_changed)) if unrad_syms == poly_syms and unrad_changed: # if all the symbols have been solved by _handle_poly # and unrad has been used then check solutions poly_sol = [sol for sol in poly_sol if checksol(unrad_changed, sol)] # Collect together the unsolved polynomials with the non-polynomial # equations. remaining = poly_eqs + nonpolys # to_tuple converts a solution dictionary to a tuple containing the # value for each symbol to_tuple = lambda sol: tuple(sol[s] for s in symbols) if not remaining: # If there is nothing left to solve then return the solution from # solve_poly_system directly. return FiniteSet(*map(to_tuple, poly_sol)) else: # Here we handle: # # 1. The Groebner basis if solve_poly_system failed. # 2. The Groebner basis in the positive-dimensional case. # 3. Any non-polynomial equations # # If solve_poly_system did succeed then we pass those solutions in as # preliminary results. subs_res = substitution(remaining, symbols, result=poly_sol, exclude=denominators) if not isinstance(subs_res, FiniteSet): return subs_res # check solutions produced by substitution. Currently, checking is done for # only those solutions which have non-Set variable values. if unrad_changed: result = [dict(zip(symbols, sol)) for sol in subs_res.args] correct_sols = [sol for sol in result if any(isinstance(v, Set) for v in sol) or checksol(unrad_changed, sol) != False] return FiniteSet(*map(to_tuple, correct_sols)) else: return subs_res
15116711b0fb64939ccbcfaad4b67936f611b7816ee00bdfe577ba5e4ea95a8a
""" This module contains pdsolve() and different helper functions that it uses. It is heavily inspired by the ode module and hence the basic infrastructure remains the same. **Functions in this module** These are the user functions in this module: - pdsolve() - Solves PDE's - classify_pde() - Classifies PDEs into possible hints for dsolve(). - pde_separate() - Separate variables in partial differential equation either by additive or multiplicative separation approach. These are the helper functions in this module: - pde_separate_add() - Helper function for searching additive separable solutions. - pde_separate_mul() - Helper function for searching multiplicative separable solutions. **Currently implemented solver methods** The following methods are implemented for solving partial differential equations. See the docstrings of the various pde_hint() functions for more information on each (run help(pde)): - 1st order linear homogeneous partial differential equations with constant coefficients. - 1st order linear general partial differential equations with constant coefficients. - 1st order linear partial differential equations with variable coefficients. """ from functools import reduce from itertools import combinations_with_replacement from sympy.simplify import simplify # type: ignore from sympy.core import Add, S from sympy.core.function import Function, expand, AppliedUndef, Subs from sympy.core.relational import Equality, Eq from sympy.core.symbol import Symbol, Wild, symbols from sympy.functions import exp from sympy.integrals.integrals import Integral, integrate from sympy.utilities.iterables import has_dups, is_sequence from sympy.utilities.misc import filldedent from sympy.solvers.deutils import _preprocess, ode_order, _desolve from sympy.solvers.solvers import solve from sympy.simplify.radsimp import collect import operator allhints = ( "1st_linear_constant_coeff_homogeneous", "1st_linear_constant_coeff", "1st_linear_constant_coeff_Integral", "1st_linear_variable_coeff" ) def pdsolve(eq, func=None, hint='default', dict=False, solvefun=None, **kwargs): """ Solves any (supported) kind of partial differential equation. **Usage** pdsolve(eq, f(x,y), hint) -> Solve partial differential equation eq for function f(x,y), using method hint. **Details** ``eq`` can be any supported partial differential equation (see the pde docstring for supported methods). This can either be an Equality, or an expression, which is assumed to be equal to 0. ``f(x,y)`` is a function of two variables whose derivatives in that variable make up the partial differential equation. In many cases it is not necessary to provide this; it will be autodetected (and an error raised if it could not be detected). ``hint`` is the solving method that you want pdsolve to use. Use classify_pde(eq, f(x,y)) to get all of the possible hints for a PDE. The default hint, 'default', will use whatever hint is returned first by classify_pde(). See Hints below for more options that you can use for hint. ``solvefun`` is the convention used for arbitrary functions returned by the PDE solver. If not set by the user, it is set by default to be F. **Hints** Aside from the various solving methods, there are also some meta-hints that you can pass to pdsolve(): "default": This uses whatever hint is returned first by classify_pde(). This is the default argument to pdsolve(). "all": To make pdsolve apply all relevant classification hints, use pdsolve(PDE, func, hint="all"). This will return a dictionary of hint:solution terms. If a hint causes pdsolve to raise the NotImplementedError, value of that hint's key will be the exception object raised. The dictionary will also include some special keys: - order: The order of the PDE. See also ode_order() in deutils.py - default: The solution that would be returned by default. This is the one produced by the hint that appears first in the tuple returned by classify_pde(). "all_Integral": This is the same as "all", except if a hint also has a corresponding "_Integral" hint, it only returns the "_Integral" hint. This is useful if "all" causes pdsolve() to hang because of a difficult or impossible integral. This meta-hint will also be much faster than "all", because integrate() is an expensive routine. See also the classify_pde() docstring for more info on hints, and the pde docstring for a list of all supported hints. **Tips** - You can declare the derivative of an unknown function this way: >>> from sympy import Function, Derivative >>> from sympy.abc import x, y # x and y are the independent variables >>> f = Function("f")(x, y) # f is a function of x and y >>> # fx will be the partial derivative of f with respect to x >>> fx = Derivative(f, x) >>> # fy will be the partial derivative of f with respect to y >>> fy = Derivative(f, y) - See test_pde.py for many tests, which serves also as a set of examples for how to use pdsolve(). - pdsolve always returns an Equality class (except for the case when the hint is "all" or "all_Integral"). Note that it is not possible to get an explicit solution for f(x, y) as in the case of ODE's - Do help(pde.pde_hintname) to get help more information on a specific hint Examples ======== >>> from sympy.solvers.pde import pdsolve >>> from sympy import Function, Eq >>> from sympy.abc import x, y >>> f = Function('f') >>> u = f(x, y) >>> ux = u.diff(x) >>> uy = u.diff(y) >>> eq = Eq(1 + (2*(ux/u)) + (3*(uy/u)), 0) >>> pdsolve(eq) Eq(f(x, y), F(3*x - 2*y)*exp(-2*x/13 - 3*y/13)) """ if not solvefun: solvefun = Function('F') # See the docstring of _desolve for more details. hints = _desolve(eq, func=func, hint=hint, simplify=True, type='pde', **kwargs) eq = hints.pop('eq', False) all_ = hints.pop('all', False) if all_: # TODO : 'best' hint should be implemented when adequate # number of hints are added. pdedict = {} failed_hints = {} gethints = classify_pde(eq, dict=True) pdedict.update({'order': gethints['order'], 'default': gethints['default']}) for hint in hints: try: rv = _helper_simplify(eq, hint, hints[hint]['func'], hints[hint]['order'], hints[hint][hint], solvefun) except NotImplementedError as detail: failed_hints[hint] = detail else: pdedict[hint] = rv pdedict.update(failed_hints) return pdedict else: return _helper_simplify(eq, hints['hint'], hints['func'], hints['order'], hints[hints['hint']], solvefun) def _helper_simplify(eq, hint, func, order, match, solvefun): """Helper function of pdsolve that calls the respective pde functions to solve for the partial differential equations. This minimizes the computation in calling _desolve multiple times. """ if hint.endswith("_Integral"): solvefunc = globals()[ "pde_" + hint[:-len("_Integral")]] else: solvefunc = globals()["pde_" + hint] return _handle_Integral(solvefunc(eq, func, order, match, solvefun), func, order, hint) def _handle_Integral(expr, func, order, hint): r""" Converts a solution with integrals in it into an actual solution. Simplifies the integral mainly using doit() """ if hint.endswith("_Integral"): return expr elif hint == "1st_linear_constant_coeff": return simplify(expr.doit()) else: return expr def classify_pde(eq, func=None, dict=False, *, prep=True, **kwargs): """ Returns a tuple of possible pdsolve() classifications for a PDE. The tuple is ordered so that first item is the classification that pdsolve() uses to solve the PDE by default. In general, classifications near the beginning of the list will produce better solutions faster than those near the end, though there are always exceptions. To make pdsolve use a different classification, use pdsolve(PDE, func, hint=<classification>). See also the pdsolve() docstring for different meta-hints you can use. If ``dict`` is true, classify_pde() will return a dictionary of hint:match expression terms. This is intended for internal use by pdsolve(). Note that because dictionaries are ordered arbitrarily, this will most likely not be in the same order as the tuple. You can get help on different hints by doing help(pde.pde_hintname), where hintname is the name of the hint without "_Integral". See sympy.pde.allhints or the sympy.pde docstring for a list of all supported hints that can be returned from classify_pde. Examples ======== >>> from sympy.solvers.pde import classify_pde >>> from sympy import Function, Eq >>> from sympy.abc import x, y >>> f = Function('f') >>> u = f(x, y) >>> ux = u.diff(x) >>> uy = u.diff(y) >>> eq = Eq(1 + (2*(ux/u)) + (3*(uy/u)), 0) >>> classify_pde(eq) ('1st_linear_constant_coeff_homogeneous',) """ if func and len(func.args) != 2: raise NotImplementedError("Right now only partial " "differential equations of two variables are supported") if prep or func is None: prep, func_ = _preprocess(eq, func) if func is None: func = func_ if isinstance(eq, Equality): if eq.rhs != 0: return classify_pde(eq.lhs - eq.rhs, func) eq = eq.lhs f = func.func x = func.args[0] y = func.args[1] fx = f(x,y).diff(x) fy = f(x,y).diff(y) # TODO : For now pde.py uses support offered by the ode_order function # to find the order with respect to a multi-variable function. An # improvement could be to classify the order of the PDE on the basis of # individual variables. order = ode_order(eq, f(x,y)) # hint:matchdict or hint:(tuple of matchdicts) # Also will contain "default":<default hint> and "order":order items. matching_hints = {'order': order} if not order: if dict: matching_hints["default"] = None return matching_hints else: return () eq = expand(eq) a = Wild('a', exclude = [f(x,y)]) b = Wild('b', exclude = [f(x,y), fx, fy, x, y]) c = Wild('c', exclude = [f(x,y), fx, fy, x, y]) d = Wild('d', exclude = [f(x,y), fx, fy, x, y]) e = Wild('e', exclude = [f(x,y), fx, fy]) n = Wild('n', exclude = [x, y]) # Try removing the smallest power of f(x,y) # from the highest partial derivatives of f(x,y) reduced_eq = None if eq.is_Add: var = set(combinations_with_replacement((x,y), order)) dummyvar = var.copy() power = None for i in var: coeff = eq.coeff(f(x,y).diff(*i)) if coeff != 1: match = coeff.match(a*f(x,y)**n) if match and match[a]: power = match[n] dummyvar.remove(i) break dummyvar.remove(i) for i in dummyvar: coeff = eq.coeff(f(x,y).diff(*i)) if coeff != 1: match = coeff.match(a*f(x,y)**n) if match and match[a] and match[n] < power: power = match[n] if power: den = f(x,y)**power reduced_eq = Add(*[arg/den for arg in eq.args]) if not reduced_eq: reduced_eq = eq if order == 1: reduced_eq = collect(reduced_eq, f(x, y)) r = reduced_eq.match(b*fx + c*fy + d*f(x,y) + e) if r: if not r[e]: ## Linear first-order homogeneous partial-differential ## equation with constant coefficients r.update({'b': b, 'c': c, 'd': d}) matching_hints["1st_linear_constant_coeff_homogeneous"] = r else: if r[b]**2 + r[c]**2 != 0: ## Linear first-order general partial-differential ## equation with constant coefficients r.update({'b': b, 'c': c, 'd': d, 'e': e}) matching_hints["1st_linear_constant_coeff"] = r matching_hints[ "1st_linear_constant_coeff_Integral"] = r else: b = Wild('b', exclude=[f(x, y), fx, fy]) c = Wild('c', exclude=[f(x, y), fx, fy]) d = Wild('d', exclude=[f(x, y), fx, fy]) r = reduced_eq.match(b*fx + c*fy + d*f(x,y) + e) if r: r.update({'b': b, 'c': c, 'd': d, 'e': e}) matching_hints["1st_linear_variable_coeff"] = r # Order keys based on allhints. retlist = [i for i in allhints if i in matching_hints] if dict: # Dictionaries are ordered arbitrarily, so make note of which # hint would come first for pdsolve(). Use an ordered dict in Py 3. matching_hints["default"] = None matching_hints["ordered_hints"] = tuple(retlist) for i in allhints: if i in matching_hints: matching_hints["default"] = i break return matching_hints else: return tuple(retlist) def checkpdesol(pde, sol, func=None, solve_for_func=True): """ Checks if the given solution satisfies the partial differential equation. pde is the partial differential equation which can be given in the form of an equation or an expression. sol is the solution for which the pde is to be checked. This can also be given in an equation or an expression form. If the function is not provided, the helper function _preprocess from deutils is used to identify the function. If a sequence of solutions is passed, the same sort of container will be used to return the result for each solution. The following methods are currently being implemented to check if the solution satisfies the PDE: 1. Directly substitute the solution in the PDE and check. If the solution has not been solved for f, then it will solve for f provided solve_for_func has not been set to False. If the solution satisfies the PDE, then a tuple (True, 0) is returned. Otherwise a tuple (False, expr) where expr is the value obtained after substituting the solution in the PDE. However if a known solution returns False, it may be due to the inability of doit() to simplify it to zero. Examples ======== >>> from sympy import Function, symbols >>> from sympy.solvers.pde import checkpdesol, pdsolve >>> x, y = symbols('x y') >>> f = Function('f') >>> eq = 2*f(x,y) + 3*f(x,y).diff(x) + 4*f(x,y).diff(y) >>> sol = pdsolve(eq) >>> assert checkpdesol(eq, sol)[0] >>> eq = x*f(x,y) + f(x,y).diff(x) >>> checkpdesol(eq, sol) (False, (x*F(4*x - 3*y) - 6*F(4*x - 3*y)/25 + 4*Subs(Derivative(F(_xi_1), _xi_1), _xi_1, 4*x - 3*y))*exp(-6*x/25 - 8*y/25)) """ # Converting the pde into an equation if not isinstance(pde, Equality): pde = Eq(pde, 0) # If no function is given, try finding the function present. if func is None: try: _, func = _preprocess(pde.lhs) except ValueError: funcs = [s.atoms(AppliedUndef) for s in ( sol if is_sequence(sol, set) else [sol])] funcs = set().union(funcs) if len(funcs) != 1: raise ValueError( 'must pass func arg to checkpdesol for this case.') func = funcs.pop() # If the given solution is in the form of a list or a set # then return a list or set of tuples. if is_sequence(sol, set): return type(sol)([checkpdesol( pde, i, func=func, solve_for_func=solve_for_func) for i in sol]) # Convert solution into an equation if not isinstance(sol, Equality): sol = Eq(func, sol) elif sol.rhs == func: sol = sol.reversed # Try solving for the function solved = sol.lhs == func and not sol.rhs.has(func) if solve_for_func and not solved: solved = solve(sol, func) if solved: if len(solved) == 1: return checkpdesol(pde, Eq(func, solved[0]), func=func, solve_for_func=False) else: return checkpdesol(pde, [Eq(func, t) for t in solved], func=func, solve_for_func=False) # try direct substitution of the solution into the PDE and simplify if sol.lhs == func: pde = pde.lhs - pde.rhs s = simplify(pde.subs(func, sol.rhs).doit()) return s is S.Zero, s raise NotImplementedError(filldedent(''' Unable to test if %s is a solution to %s.''' % (sol, pde))) def pde_1st_linear_constant_coeff_homogeneous(eq, func, order, match, solvefun): r""" Solves a first order linear homogeneous partial differential equation with constant coefficients. The general form of this partial differential equation is .. math:: a \frac{\partial f(x,y)}{\partial x} + b \frac{\partial f(x,y)}{\partial y} + c f(x,y) = 0 where `a`, `b` and `c` are constants. The general solution is of the form: .. math:: f(x, y) = F(- a y + b x ) e^{- \frac{c (a x + b y)}{a^2 + b^2}} and can be found in SymPy with ``pdsolve``:: >>> from sympy.solvers import pdsolve >>> from sympy.abc import x, y, a, b, c >>> from sympy import Function, pprint >>> f = Function('f') >>> u = f(x,y) >>> ux = u.diff(x) >>> uy = u.diff(y) >>> genform = a*ux + b*uy + c*u >>> pprint(genform) d d a*--(f(x, y)) + b*--(f(x, y)) + c*f(x, y) dx dy >>> pprint(pdsolve(genform)) -c*(a*x + b*y) --------------- 2 2 a + b f(x, y) = F(-a*y + b*x)*e Examples ======== >>> from sympy import pdsolve >>> from sympy import Function, pprint >>> from sympy.abc import x,y >>> f = Function('f') >>> pdsolve(f(x,y) + f(x,y).diff(x) + f(x,y).diff(y)) Eq(f(x, y), F(x - y)*exp(-x/2 - y/2)) >>> pprint(pdsolve(f(x,y) + f(x,y).diff(x) + f(x,y).diff(y))) x y - - - - 2 2 f(x, y) = F(x - y)*e References ========== - Viktor Grigoryan, "Partial Differential Equations" Math 124A - Fall 2010, pp.7 """ # TODO : For now homogeneous first order linear PDE's having # two variables are implemented. Once there is support for # solving systems of ODE's, this can be extended to n variables. f = func.func x = func.args[0] y = func.args[1] b = match[match['b']] c = match[match['c']] d = match[match['d']] return Eq(f(x,y), exp(-S(d)/(b**2 + c**2)*(b*x + c*y))*solvefun(c*x - b*y)) def pde_1st_linear_constant_coeff(eq, func, order, match, solvefun): r""" Solves a first order linear partial differential equation with constant coefficients. The general form of this partial differential equation is .. math:: a \frac{\partial f(x,y)}{\partial x} + b \frac{\partial f(x,y)}{\partial y} + c f(x,y) = G(x,y) where `a`, `b` and `c` are constants and `G(x, y)` can be an arbitrary function in `x` and `y`. The general solution of the PDE is: .. math:: f(x, y) = \left. \left[F(\eta) + \frac{1}{a^2 + b^2} \int\limits^{a x + b y} G\left(\frac{a \xi + b \eta}{a^2 + b^2}, \frac{- a \eta + b \xi}{a^2 + b^2} \right) e^{\frac{c \xi}{a^2 + b^2}}\, d\xi\right] e^{- \frac{c \xi}{a^2 + b^2}} \right|_{\substack{\eta=- a y + b x\\ \xi=a x + b y }}\, , where `F(\eta)` is an arbitrary single-valued function. The solution can be found in SymPy with ``pdsolve``:: >>> from sympy.solvers import pdsolve >>> from sympy.abc import x, y, a, b, c >>> from sympy import Function, pprint >>> f = Function('f') >>> G = Function('G') >>> u = f(x,y) >>> ux = u.diff(x) >>> uy = u.diff(y) >>> genform = a*ux + b*uy + c*u - G(x,y) >>> pprint(genform) d d a*--(f(x, y)) + b*--(f(x, y)) + c*f(x, y) - G(x, y) dx dy >>> pprint(pdsolve(genform, hint='1st_linear_constant_coeff_Integral')) // a*x + b*y \ || / | || | | || | c*xi | || | ------- | || | 2 2 | || | /a*xi + b*eta -a*eta + b*xi\ a + b | || | G|------------, -------------|*e d(xi)| || | | 2 2 2 2 | | || | \ a + b a + b / | || | | || / | || | f(x, y) = ||F(eta) + -------------------------------------------------------|* || 2 2 | \\ a + b / <BLANKLINE> \| || || || || || || || || -c*xi || -------|| 2 2|| a + b || e || || /|eta=-a*y + b*x, xi=a*x + b*y Examples ======== >>> from sympy.solvers.pde import pdsolve >>> from sympy import Function, pprint, exp >>> from sympy.abc import x,y >>> f = Function('f') >>> eq = -2*f(x,y).diff(x) + 4*f(x,y).diff(y) + 5*f(x,y) - exp(x + 3*y) >>> pdsolve(eq) Eq(f(x, y), (F(4*x + 2*y)*exp(x/2) + exp(x + 4*y)/15)*exp(-y)) References ========== - Viktor Grigoryan, "Partial Differential Equations" Math 124A - Fall 2010, pp.7 """ # TODO : For now homogeneous first order linear PDE's having # two variables are implemented. Once there is support for # solving systems of ODE's, this can be extended to n variables. xi, eta = symbols("xi eta") f = func.func x = func.args[0] y = func.args[1] b = match[match['b']] c = match[match['c']] d = match[match['d']] e = -match[match['e']] expterm = exp(-S(d)/(b**2 + c**2)*xi) functerm = solvefun(eta) solvedict = solve((b*x + c*y - xi, c*x - b*y - eta), x, y) # Integral should remain as it is in terms of xi, # doit() should be done in _handle_Integral. genterm = (1/S(b**2 + c**2))*Integral( (1/expterm*e).subs(solvedict), (xi, b*x + c*y)) return Eq(f(x,y), Subs(expterm*(functerm + genterm), (eta, xi), (c*x - b*y, b*x + c*y))) def pde_1st_linear_variable_coeff(eq, func, order, match, solvefun): r""" Solves a first order linear partial differential equation with variable coefficients. The general form of this partial differential equation is .. math:: a(x, y) \frac{\partial f(x, y)}{\partial x} + b(x, y) \frac{\partial f(x, y)}{\partial y} + c(x, y) f(x, y) = G(x, y) where `a(x, y)`, `b(x, y)`, `c(x, y)` and `G(x, y)` are arbitrary functions in `x` and `y`. This PDE is converted into an ODE by making the following transformation: 1. `\xi` as `x` 2. `\eta` as the constant in the solution to the differential equation `\frac{dy}{dx} = -\frac{b}{a}` Making the previous substitutions reduces it to the linear ODE .. math:: a(\xi, \eta)\frac{du}{d\xi} + c(\xi, \eta)u - G(\xi, \eta) = 0 which can be solved using ``dsolve``. >>> from sympy.abc import x, y >>> from sympy import Function, pprint >>> a, b, c, G, f= [Function(i) for i in ['a', 'b', 'c', 'G', 'f']] >>> u = f(x,y) >>> ux = u.diff(x) >>> uy = u.diff(y) >>> genform = a(x, y)*u + b(x, y)*ux + c(x, y)*uy - G(x,y) >>> pprint(genform) d d -G(x, y) + a(x, y)*f(x, y) + b(x, y)*--(f(x, y)) + c(x, y)*--(f(x, y)) dx dy Examples ======== >>> from sympy.solvers.pde import pdsolve >>> from sympy import Function, pprint >>> from sympy.abc import x,y >>> f = Function('f') >>> eq = x*(u.diff(x)) - y*(u.diff(y)) + y**2*u - y**2 >>> pdsolve(eq) Eq(f(x, y), F(x*y)*exp(y**2/2) + 1) References ========== - Viktor Grigoryan, "Partial Differential Equations" Math 124A - Fall 2010, pp.7 """ from sympy.solvers.ode import dsolve xi, eta = symbols("xi eta") f = func.func x = func.args[0] y = func.args[1] b = match[match['b']] c = match[match['c']] d = match[match['d']] e = -match[match['e']] if not d: # To deal with cases like b*ux = e or c*uy = e if not (b and c): if c: try: tsol = integrate(e/c, y) except NotImplementedError: raise NotImplementedError("Unable to find a solution" " due to inability of integrate") else: return Eq(f(x,y), solvefun(x) + tsol) if b: try: tsol = integrate(e/b, x) except NotImplementedError: raise NotImplementedError("Unable to find a solution" " due to inability of integrate") else: return Eq(f(x,y), solvefun(y) + tsol) if not c: # To deal with cases when c is 0, a simpler method is used. # The PDE reduces to b*(u.diff(x)) + d*u = e, which is a linear ODE in x plode = f(x).diff(x)*b + d*f(x) - e sol = dsolve(plode, f(x)) syms = sol.free_symbols - plode.free_symbols - {x, y} rhs = _simplify_variable_coeff(sol.rhs, syms, solvefun, y) return Eq(f(x, y), rhs) if not b: # To deal with cases when b is 0, a simpler method is used. # The PDE reduces to c*(u.diff(y)) + d*u = e, which is a linear ODE in y plode = f(y).diff(y)*c + d*f(y) - e sol = dsolve(plode, f(y)) syms = sol.free_symbols - plode.free_symbols - {x, y} rhs = _simplify_variable_coeff(sol.rhs, syms, solvefun, x) return Eq(f(x, y), rhs) dummy = Function('d') h = (c/b).subs(y, dummy(x)) sol = dsolve(dummy(x).diff(x) - h, dummy(x)) if isinstance(sol, list): sol = sol[0] solsym = sol.free_symbols - h.free_symbols - {x, y} if len(solsym) == 1: solsym = solsym.pop() etat = (solve(sol, solsym)[0]).subs(dummy(x), y) ysub = solve(eta - etat, y)[0] deq = (b*(f(x).diff(x)) + d*f(x) - e).subs(y, ysub) final = (dsolve(deq, f(x), hint='1st_linear')).rhs if isinstance(final, list): final = final[0] finsyms = final.free_symbols - deq.free_symbols - {x, y} rhs = _simplify_variable_coeff(final, finsyms, solvefun, etat) return Eq(f(x, y), rhs) else: raise NotImplementedError("Cannot solve the partial differential equation due" " to inability of constantsimp") def _simplify_variable_coeff(sol, syms, func, funcarg): r""" Helper function to replace constants by functions in 1st_linear_variable_coeff """ eta = Symbol("eta") if len(syms) == 1: sym = syms.pop() final = sol.subs(sym, func(funcarg)) else: for key, sym in enumerate(syms): final = sol.subs(sym, func(funcarg)) return simplify(final.subs(eta, funcarg)) def pde_separate(eq, fun, sep, strategy='mul'): """Separate variables in partial differential equation either by additive or multiplicative separation approach. It tries to rewrite an equation so that one of the specified variables occurs on a different side of the equation than the others. :param eq: Partial differential equation :param fun: Original function F(x, y, z) :param sep: List of separated functions [X(x), u(y, z)] :param strategy: Separation strategy. You can choose between additive separation ('add') and multiplicative separation ('mul') which is default. Examples ======== >>> from sympy import E, Eq, Function, pde_separate, Derivative as D >>> from sympy.abc import x, t >>> u, X, T = map(Function, 'uXT') >>> eq = Eq(D(u(x, t), x), E**(u(x, t))*D(u(x, t), t)) >>> pde_separate(eq, u(x, t), [X(x), T(t)], strategy='add') [exp(-X(x))*Derivative(X(x), x), exp(T(t))*Derivative(T(t), t)] >>> eq = Eq(D(u(x, t), x, 2), D(u(x, t), t, 2)) >>> pde_separate(eq, u(x, t), [X(x), T(t)], strategy='mul') [Derivative(X(x), (x, 2))/X(x), Derivative(T(t), (t, 2))/T(t)] See Also ======== pde_separate_add, pde_separate_mul """ do_add = False if strategy == 'add': do_add = True elif strategy == 'mul': do_add = False else: raise ValueError('Unknown strategy: %s' % strategy) if isinstance(eq, Equality): if eq.rhs != 0: return pde_separate(Eq(eq.lhs - eq.rhs, 0), fun, sep, strategy) else: return pde_separate(Eq(eq, 0), fun, sep, strategy) if eq.rhs != 0: raise ValueError("Value should be 0") # Handle arguments orig_args = list(fun.args) subs_args = [arg for s in sep for arg in s.args] if do_add: functions = reduce(operator.add, sep) else: functions = reduce(operator.mul, sep) # Check whether variables match if len(subs_args) != len(orig_args): raise ValueError("Variable counts do not match") # Check for duplicate arguments like [X(x), u(x, y)] if has_dups(subs_args): raise ValueError("Duplicate substitution arguments detected") # Check whether the variables match if set(orig_args) != set(subs_args): raise ValueError("Arguments do not match") # Substitute original function with separated... result = eq.lhs.subs(fun, functions).doit() # Divide by terms when doing multiplicative separation if not do_add: eq = 0 for i in result.args: eq += i/functions result = eq svar = subs_args[0] dvar = subs_args[1:] return _separate(result, svar, dvar) def pde_separate_add(eq, fun, sep): """ Helper function for searching additive separable solutions. Consider an equation of two independent variables x, y and a dependent variable w, we look for the product of two functions depending on different arguments: `w(x, y, z) = X(x) + y(y, z)` Examples ======== >>> from sympy import E, Eq, Function, pde_separate_add, Derivative as D >>> from sympy.abc import x, t >>> u, X, T = map(Function, 'uXT') >>> eq = Eq(D(u(x, t), x), E**(u(x, t))*D(u(x, t), t)) >>> pde_separate_add(eq, u(x, t), [X(x), T(t)]) [exp(-X(x))*Derivative(X(x), x), exp(T(t))*Derivative(T(t), t)] """ return pde_separate(eq, fun, sep, strategy='add') def pde_separate_mul(eq, fun, sep): """ Helper function for searching multiplicative separable solutions. Consider an equation of two independent variables x, y and a dependent variable w, we look for the product of two functions depending on different arguments: `w(x, y, z) = X(x)*u(y, z)` Examples ======== >>> from sympy import Function, Eq, pde_separate_mul, Derivative as D >>> from sympy.abc import x, y >>> u, X, Y = map(Function, 'uXY') >>> eq = Eq(D(u(x, y), x, 2), D(u(x, y), y, 2)) >>> pde_separate_mul(eq, u(x, y), [X(x), Y(y)]) [Derivative(X(x), (x, 2))/X(x), Derivative(Y(y), (y, 2))/Y(y)] """ return pde_separate(eq, fun, sep, strategy='mul') def _separate(eq, dep, others): """Separate expression into two parts based on dependencies of variables.""" # FIRST PASS # Extract derivatives depending our separable variable... terms = set() for term in eq.args: if term.is_Mul: for i in term.args: if i.is_Derivative and not i.has(*others): terms.add(term) continue elif term.is_Derivative and not term.has(*others): terms.add(term) # Find the factor that we need to divide by div = set() for term in terms: ext, sep = term.expand().as_independent(dep) # Failed? if sep.has(*others): return None div.add(ext) # FIXME: Find lcm() of all the divisors and divide with it, instead of # current hack :( # https://github.com/sympy/sympy/issues/4597 if len(div) > 0: # double sum required or some tests will fail eq = Add(*[simplify(Add(*[term/i for i in div])) for term in eq.args]) # SECOND PASS - separate the derivatives div = set() lhs = rhs = 0 for term in eq.args: # Check, whether we have already term with independent variable... if not term.has(*others): lhs += term continue # ...otherwise, try to separate temp, sep = term.expand().as_independent(dep) # Failed? if sep.has(*others): return None # Extract the divisors div.add(sep) rhs -= term.expand() # Do the division fulldiv = reduce(operator.add, div) lhs = simplify(lhs/fulldiv).expand() rhs = simplify(rhs/fulldiv).expand() # ...and check whether we were successful :) if lhs.has(*others) or rhs.has(dep): return None return [lhs, rhs]
e9d088a19a97f26173efb4a94f50ce33f239caf770535b543274db036be360c1
"""Utility functions for classifying and solving ordinary and partial differential equations. Contains ======== _preprocess ode_order _desolve """ from sympy.core import Pow from sympy.core.function import Derivative, AppliedUndef from sympy.core.relational import Equality from sympy.core.symbol import Wild def _preprocess(expr, func=None, hint='_Integral'): """Prepare expr for solving by making sure that differentiation is done so that only func remains in unevaluated derivatives and (if hint does not end with _Integral) that doit is applied to all other derivatives. If hint is None, do not do any differentiation. (Currently this may cause some simple differential equations to fail.) In case func is None, an attempt will be made to autodetect the function to be solved for. >>> from sympy.solvers.deutils import _preprocess >>> from sympy import Derivative, Function >>> from sympy.abc import x, y, z >>> f, g = map(Function, 'fg') If f(x)**p == 0 and p>0 then we can solve for f(x)=0 >>> _preprocess((f(x).diff(x)-4)**5, f(x)) (Derivative(f(x), x) - 4, f(x)) Apply doit to derivatives that contain more than the function of interest: >>> _preprocess(Derivative(f(x) + x, x)) (Derivative(f(x), x) + 1, f(x)) Do others if the differentiation variable(s) intersect with those of the function of interest or contain the function of interest: >>> _preprocess(Derivative(g(x), y, z), f(y)) (0, f(y)) >>> _preprocess(Derivative(f(y), z), f(y)) (0, f(y)) Do others if the hint does not end in '_Integral' (the default assumes that it does): >>> _preprocess(Derivative(g(x), y), f(x)) (Derivative(g(x), y), f(x)) >>> _preprocess(Derivative(f(x), y), f(x), hint='') (0, f(x)) Do not do any derivatives if hint is None: >>> eq = Derivative(f(x) + 1, x) + Derivative(f(x), y) >>> _preprocess(eq, f(x), hint=None) (Derivative(f(x) + 1, x) + Derivative(f(x), y), f(x)) If it's not clear what the function of interest is, it must be given: >>> eq = Derivative(f(x) + g(x), x) >>> _preprocess(eq, g(x)) (Derivative(f(x), x) + Derivative(g(x), x), g(x)) >>> try: _preprocess(eq) ... except ValueError: print("A ValueError was raised.") A ValueError was raised. """ if isinstance(expr, Pow): # if f(x)**p=0 then f(x)=0 (p>0) if (expr.exp).is_positive: expr = expr.base derivs = expr.atoms(Derivative) if not func: funcs = set().union(*[d.atoms(AppliedUndef) for d in derivs]) if len(funcs) != 1: raise ValueError('The function cannot be ' 'automatically detected for %s.' % expr) func = funcs.pop() fvars = set(func.args) if hint is None: return expr, func reps = [(d, d.doit()) for d in derivs if not hint.endswith('_Integral') or d.has(func) or set(d.variables) & fvars] eq = expr.subs(reps) return eq, func def ode_order(expr, func): """ Returns the order of a given differential equation with respect to func. This function is implemented recursively. Examples ======== >>> from sympy import Function >>> from sympy.solvers.deutils import ode_order >>> from sympy.abc import x >>> f, g = map(Function, ['f', 'g']) >>> ode_order(f(x).diff(x, 2) + f(x).diff(x)**2 + ... f(x).diff(x), f(x)) 2 >>> ode_order(f(x).diff(x, 2) + g(x).diff(x, 3), f(x)) 2 >>> ode_order(f(x).diff(x, 2) + g(x).diff(x, 3), g(x)) 3 """ a = Wild('a', exclude=[func]) if expr.match(a): return 0 if isinstance(expr, Derivative): if expr.args[0] == func: return len(expr.variables) else: args = expr.args[0].args rv = len(expr.variables) if args: rv += max(ode_order(_, func) for _ in args) return rv else: return max(ode_order(_, func) for _ in expr.args) if expr.args else 0 def _desolve(eq, func=None, hint="default", ics=None, simplify=True, *, prep=True, **kwargs): """This is a helper function to dsolve and pdsolve in the ode and pde modules. If the hint provided to the function is "default", then a dict with the following keys are returned 'func' - It provides the function for which the differential equation has to be solved. This is useful when the expression has more than one function in it. 'default' - The default key as returned by classifier functions in ode and pde.py 'hint' - The hint given by the user for which the differential equation is to be solved. If the hint given by the user is 'default', then the value of 'hint' and 'default' is the same. 'order' - The order of the function as returned by ode_order 'match' - It returns the match as given by the classifier functions, for the default hint. If the hint provided to the function is not "default" and is not in ('all', 'all_Integral', 'best'), then a dict with the above mentioned keys is returned along with the keys which are returned when dict in classify_ode or classify_pde is set True If the hint given is in ('all', 'all_Integral', 'best'), then this function returns a nested dict, with the keys, being the set of classified hints returned by classifier functions, and the values being the dict of form as mentioned above. Key 'eq' is a common key to all the above mentioned hints which returns an expression if eq given by user is an Equality. See Also ======== classify_ode(ode.py) classify_pde(pde.py) """ if isinstance(eq, Equality): eq = eq.lhs - eq.rhs # preprocess the equation and find func if not given if prep or func is None: eq, func = _preprocess(eq, func) prep = False # type is an argument passed by the solve functions in ode and pde.py # that identifies whether the function caller is an ordinary # or partial differential equation. Accordingly corresponding # changes are made in the function. type = kwargs.get('type', None) xi = kwargs.get('xi') eta = kwargs.get('eta') x0 = kwargs.get('x0', 0) terms = kwargs.get('n') if type == 'ode': from sympy.solvers.ode import classify_ode, allhints classifier = classify_ode string = 'ODE ' dummy = '' elif type == 'pde': from sympy.solvers.pde import classify_pde, allhints classifier = classify_pde string = 'PDE ' dummy = 'p' # Magic that should only be used internally. Prevents classify_ode from # being called more than it needs to be by passing its results through # recursive calls. if kwargs.get('classify', True): hints = classifier(eq, func, dict=True, ics=ics, xi=xi, eta=eta, n=terms, x0=x0, hint=hint, prep=prep) else: # Here is what all this means: # # hint: The hint method given to _desolve() by the user. # hints: The dictionary of hints that match the DE, along with other # information (including the internal pass-through magic). # default: The default hint to return, the first hint from allhints # that matches the hint; obtained from classify_ode(). # match: Dictionary containing the match dictionary for each hint # (the parts of the DE for solving). When going through the # hints in "all", this holds the match string for the current # hint. # order: The order of the DE, as determined by ode_order(). hints = kwargs.get('hint', {'default': hint, hint: kwargs['match'], 'order': kwargs['order']}) if not hints['default']: # classify_ode will set hints['default'] to None if no hints match. if hint not in allhints and hint != 'default': raise ValueError("Hint not recognized: " + hint) elif hint not in hints['ordered_hints'] and hint != 'default': raise ValueError(string + str(eq) + " does not match hint " + hint) # If dsolve can't solve the purely algebraic equation then dsolve will raise # ValueError elif hints['order'] == 0: raise ValueError( str(eq) + " is not a solvable differential equation in " + str(func)) else: raise NotImplementedError(dummy + "solve" + ": Cannot solve " + str(eq)) if hint == 'default': return _desolve(eq, func, ics=ics, hint=hints['default'], simplify=simplify, prep=prep, x0=x0, classify=False, order=hints['order'], match=hints[hints['default']], xi=xi, eta=eta, n=terms, type=type) elif hint in ('all', 'all_Integral', 'best'): retdict = {} gethints = set(hints) - {'order', 'default', 'ordered_hints'} if hint == 'all_Integral': for i in hints: if i.endswith('_Integral'): gethints.remove(i[:-len('_Integral')]) # special cases for k in ["1st_homogeneous_coeff_best", "1st_power_series", "lie_group", "2nd_power_series_ordinary", "2nd_power_series_regular"]: if k in gethints: gethints.remove(k) for i in gethints: sol = _desolve(eq, func, ics=ics, hint=i, x0=x0, simplify=simplify, prep=prep, classify=False, n=terms, order=hints['order'], match=hints[i], type=type) retdict[i] = sol retdict['all'] = True retdict['eq'] = eq return retdict elif hint not in allhints: # and hint not in ('default', 'ordered_hints'): raise ValueError("Hint not recognized: " + hint) elif hint not in hints: raise ValueError(string + str(eq) + " does not match hint " + hint) else: # Key added to identify the hint needed to solve the equation hints['hint'] = hint hints.update({'func': func, 'eq': eq}) return hints
46300ad7a8f1ae51221dd1ca1aacf9e1c743e97ece49fa9f772ecc86c85c19fd
"""Solvers of systems of polynomial equations. """ import itertools from sympy.core import S from sympy.core.sorting import default_sort_key from sympy.polys import Poly, groebner, roots from sympy.polys.polytools import parallel_poly_from_expr from sympy.polys.polyerrors import (ComputationFailed, PolificationFailed, CoercionFailed) from sympy.simplify import rcollect from sympy.utilities import postfixes from sympy.utilities.misc import filldedent class SolveFailed(Exception): """Raised when solver's conditions were not met. """ def solve_poly_system(seq, *gens, strict=False, **args): """ Solve a system of polynomial equations. Parameters ========== seq: a list/tuple/set Listing all the equations that are needed to be solved gens: generators generators of the equations in seq for which we want the solutions strict: a boolean (default is False) if strict is True, NotImplementedError will be raised if the solution is known to be incomplete (which can occur if not all solutions are expressible in radicals) args: Keyword arguments Special options for solving the equations. Returns ======= List[Tuple] A List of tuples. Solutions for symbols that satisfy the equations listed in seq Examples ======== >>> from sympy import solve_poly_system >>> from sympy.abc import x, y >>> solve_poly_system([x*y - 2*y, 2*y**2 - x**2], x, y) [(0, 0), (2, -sqrt(2)), (2, sqrt(2))] >>> solve_poly_system([x**5 - x + y**3, y**2 - 1], x, y, strict=True) Traceback (most recent call last): ... UnsolvableFactorError """ try: polys, opt = parallel_poly_from_expr(seq, *gens, **args) except PolificationFailed as exc: raise ComputationFailed('solve_poly_system', len(seq), exc) if len(polys) == len(opt.gens) == 2: f, g = polys if all(i <= 2 for i in f.degree_list() + g.degree_list()): try: return solve_biquadratic(f, g, opt) except SolveFailed: pass return solve_generic(polys, opt, strict=strict) def solve_biquadratic(f, g, opt): """Solve a system of two bivariate quadratic polynomial equations. Parameters ========== f: a single Expr or Poly First equation g: a single Expr or Poly Second Equation opt: an Options object For specifying keyword arguments and generators Returns ======= List[Tuple] A List of tuples. Solutions for symbols that satisfy the equations listed in seq. Examples ======== >>> from sympy import Options, Poly >>> from sympy.abc import x, y >>> from sympy.solvers.polysys import solve_biquadratic >>> NewOption = Options((x, y), {'domain': 'ZZ'}) >>> a = Poly(y**2 - 4 + x, y, x, domain='ZZ') >>> b = Poly(y*2 + 3*x - 7, y, x, domain='ZZ') >>> solve_biquadratic(a, b, NewOption) [(1/3, 3), (41/27, 11/9)] >>> a = Poly(y + x**2 - 3, y, x, domain='ZZ') >>> b = Poly(-y + x - 4, y, x, domain='ZZ') >>> solve_biquadratic(a, b, NewOption) [(7/2 - sqrt(29)/2, -sqrt(29)/2 - 1/2), (sqrt(29)/2 + 7/2, -1/2 + \ sqrt(29)/2)] """ G = groebner([f, g]) if len(G) == 1 and G[0].is_ground: return None if len(G) != 2: raise SolveFailed x, y = opt.gens p, q = G if not p.gcd(q).is_ground: # not 0-dimensional raise SolveFailed p = Poly(p, x, expand=False) p_roots = [rcollect(expr, y) for expr in roots(p).keys()] q = q.ltrim(-1) q_roots = list(roots(q).keys()) solutions = [(p_root.subs(y, q_root), q_root) for q_root, p_root in itertools.product(q_roots, p_roots)] return sorted(solutions, key=default_sort_key) def solve_generic(polys, opt, strict=False): """ Solve a generic system of polynomial equations. Returns all possible solutions over C[x_1, x_2, ..., x_m] of a set F = { f_1, f_2, ..., f_n } of polynomial equations, using Groebner basis approach. For now only zero-dimensional systems are supported, which means F can have at most a finite number of solutions. The algorithm works by the fact that, supposing G is the basis of F with respect to an elimination order (here lexicographic order is used), G and F generate the same ideal, they have the same set of solutions. By the elimination property, if G is a reduced, zero-dimensional Groebner basis, then there exists an univariate polynomial in G (in its last variable). This can be solved by computing its roots. Substituting all computed roots for the last (eliminated) variable in other elements of G, new polynomial system is generated. Applying the above procedure recursively, a finite number of solutions can be found. The ability of finding all solutions by this procedure depends on the root finding algorithms. If no solutions were found, it means only that roots() failed, but the system is solvable. To overcome this difficulty use numerical algorithms instead. Parameters ========== polys: a list/tuple/set Listing all the polynomial equations that are needed to be solved opt: an Options object For specifying keyword arguments and generators strict: a boolean If strict is True, NotImplementedError will be raised if the solution is known to be incomplete Returns ======= List[Tuple] A List of tuples. Solutions for symbols that satisfy the equations listed in seq References ========== .. [Buchberger01] B. Buchberger, Groebner Bases: A Short Introduction for Systems Theorists, In: R. Moreno-Diaz, B. Buchberger, J.L. Freire, Proceedings of EUROCAST'01, February, 2001 .. [Cox97] D. Cox, J. Little, D. O'Shea, Ideals, Varieties and Algorithms, Springer, Second Edition, 1997, pp. 112 Raises ======== NotImplementedError If the system is not zero-dimensional. (does not have a finite number of solutions) UnsolvableFactorError If ``strict`` is True and not all solution components are expressible in radicals Examples ======== >>> from sympy import Poly, Options >>> from sympy.solvers.polysys import solve_generic >>> from sympy.abc import x, y >>> NewOption = Options((x, y), {'domain': 'ZZ'}) >>> a = Poly(x - y + 5, x, y, domain='ZZ') >>> b = Poly(x + y - 3, x, y, domain='ZZ') >>> solve_generic([a, b], NewOption) [(-1, 4)] >>> a = Poly(x - 2*y + 5, x, y, domain='ZZ') >>> b = Poly(2*x - y - 3, x, y, domain='ZZ') >>> solve_generic([a, b], NewOption) [(11/3, 13/3)] >>> a = Poly(x**2 + y, x, y, domain='ZZ') >>> b = Poly(x + y*4, x, y, domain='ZZ') >>> solve_generic([a, b], NewOption) [(0, 0), (1/4, -1/16)] >>> a = Poly(x**5 - x + y**3, x, y, domain='ZZ') >>> b = Poly(y**2 - 1, x, y, domain='ZZ') >>> solve_generic([a, b], NewOption, strict=True) Traceback (most recent call last): ... UnsolvableFactorError """ def _is_univariate(f): """Returns True if 'f' is univariate in its last variable. """ for monom in f.monoms(): if any(monom[:-1]): return False return True def _subs_root(f, gen, zero): """Replace generator with a root so that the result is nice. """ p = f.as_expr({gen: zero}) if f.degree(gen) >= 2: p = p.expand(deep=False) return p def _solve_reduced_system(system, gens, entry=False): """Recursively solves reduced polynomial systems. """ if len(system) == len(gens) == 1: # the below line will produce UnsolvableFactorError if # strict=True and the produced by roots is incomplete zeros = list(roots(system[0], gens[-1], strict=strict).keys()) return [(zero,) for zero in zeros] basis = groebner(system, gens, polys=True) if len(basis) == 1 and basis[0].is_ground: if not entry: return [] else: return None univariate = list(filter(_is_univariate, basis)) if len(basis) < len(gens): raise NotImplementedError(filldedent(''' only zero-dimensional systems supported (finite number of solutions) ''')) if len(univariate) == 1: f = univariate.pop() else: raise NotImplementedError(filldedent(''' only zero-dimensional systems supported (finite number of solutions) ''')) gens = f.gens gen = gens[-1] # the below line will produce UnsolvableFactorError if # strict=True and the produced by roots is incomplete zeros = list(roots(f.ltrim(gen), strict=strict).keys()) if not zeros: return [] if len(basis) == 1: return [(zero,) for zero in zeros] solutions = [] for zero in zeros: new_system = [] new_gens = gens[:-1] for b in basis[:-1]: eq = _subs_root(b, gen, zero) if eq is not S.Zero: new_system.append(eq) for solution in _solve_reduced_system(new_system, new_gens): solutions.append(solution + (zero,)) if solutions and len(solutions[0]) != len(gens): raise NotImplementedError(filldedent(''' only zero-dimensional systems supported (finite number of solutions) ''')) return solutions try: result = _solve_reduced_system(polys, opt.gens, entry=True) except CoercionFailed: raise NotImplementedError if result is not None: return sorted(result, key=default_sort_key) else: return None def solve_triangulated(polys, *gens, **args): """ Solve a polynomial system using Gianni-Kalkbrenner algorithm. The algorithm proceeds by computing one Groebner basis in the ground domain and then by iteratively computing polynomial factorizations in appropriately constructed algebraic extensions of the ground domain. Parameters ========== polys: a list/tuple/set Listing all the equations that are needed to be solved gens: generators generators of the equations in polys for which we want the solutions args: Keyword arguments Special options for solving the equations Returns ======= List[Tuple] A List of tuples. Solutions for symbols that satisfy the equations listed in polys Examples ======== >>> from sympy import solve_triangulated >>> from sympy.abc import x, y, z >>> F = [x**2 + y + z - 1, x + y**2 + z - 1, x + y + z**2 - 1] >>> solve_triangulated(F, x, y, z) [(0, 0, 1), (0, 1, 0), (1, 0, 0)] References ========== 1. Patrizia Gianni, Teo Mora, Algebraic Solution of System of Polynomial Equations using Groebner Bases, AAECC-5 on Applied Algebra, Algebraic Algorithms and Error-Correcting Codes, LNCS 356 247--257, 1989 """ G = groebner(polys, gens, polys=True) G = list(reversed(G)) domain = args.get('domain') if domain is not None: for i, g in enumerate(G): G[i] = g.set_domain(domain) f, G = G[0].ltrim(-1), G[1:] dom = f.get_domain() zeros = f.ground_roots() solutions = set() for zero in zeros: solutions.add(((zero,), dom)) var_seq = reversed(gens[:-1]) vars_seq = postfixes(gens[1:]) for var, vars in zip(var_seq, vars_seq): _solutions = set() for values, dom in solutions: H, mapping = [], list(zip(vars, values)) for g in G: _vars = (var,) + vars if g.has_only_gens(*_vars) and g.degree(var) != 0: h = g.ltrim(var).eval(dict(mapping)) if g.degree(var) == h.degree(): H.append(h) p = min(H, key=lambda h: h.degree()) zeros = p.ground_roots() for zero in zeros: if not zero.is_Rational: dom_zero = dom.algebraic_field(zero) else: dom_zero = dom _solutions.add(((zero,) + values, dom_zero)) solutions = _solutions solutions = list(solutions) for i, (solution, _) in enumerate(solutions): solutions[i] = solution return sorted(solutions, key=default_sort_key)
9e88ba4cb81d06b3619b03e574148549041ad079fa9cfb4adcbc036cece8f3a9
"""Tools for solving inequalities and systems of inequalities. """ import itertools from sympy.calculus.util import (continuous_domain, periodicity, function_range) from sympy.core import Symbol, Dummy, sympify from sympy.core.exprtools import factor_terms from sympy.core.relational import Relational, Eq, Ge, Lt from sympy.sets.sets import Interval, FiniteSet, Union, Intersection from sympy.core.singleton import S from sympy.core.function import expand_mul from sympy.functions.elementary.complexes import im, Abs from sympy.logic import And from sympy.polys import Poly, PolynomialError, parallel_poly_from_expr from sympy.polys.polyutils import _nsort from sympy.solvers.solveset import solvify, solveset from sympy.utilities.iterables import sift, iterable from sympy.utilities.misc import filldedent def solve_poly_inequality(poly, rel): """Solve a polynomial inequality with rational coefficients. Examples ======== >>> from sympy import solve_poly_inequality, Poly >>> from sympy.abc import x >>> solve_poly_inequality(Poly(x, x, domain='ZZ'), '==') [{0}] >>> solve_poly_inequality(Poly(x**2 - 1, x, domain='ZZ'), '!=') [Interval.open(-oo, -1), Interval.open(-1, 1), Interval.open(1, oo)] >>> solve_poly_inequality(Poly(x**2 - 1, x, domain='ZZ'), '==') [{-1}, {1}] See Also ======== solve_poly_inequalities """ if not isinstance(poly, Poly): raise ValueError( 'For efficiency reasons, `poly` should be a Poly instance') if poly.as_expr().is_number: t = Relational(poly.as_expr(), 0, rel) if t is S.true: return [S.Reals] elif t is S.false: return [S.EmptySet] else: raise NotImplementedError( "could not determine truth value of %s" % t) reals, intervals = poly.real_roots(multiple=False), [] if rel == '==': for root, _ in reals: interval = Interval(root, root) intervals.append(interval) elif rel == '!=': left = S.NegativeInfinity for right, _ in reals + [(S.Infinity, 1)]: interval = Interval(left, right, True, True) intervals.append(interval) left = right else: if poly.LC() > 0: sign = +1 else: sign = -1 eq_sign, equal = None, False if rel == '>': eq_sign = +1 elif rel == '<': eq_sign = -1 elif rel == '>=': eq_sign, equal = +1, True elif rel == '<=': eq_sign, equal = -1, True else: raise ValueError("'%s' is not a valid relation" % rel) right, right_open = S.Infinity, True for left, multiplicity in reversed(reals): if multiplicity % 2: if sign == eq_sign: intervals.insert( 0, Interval(left, right, not equal, right_open)) sign, right, right_open = -sign, left, not equal else: if sign == eq_sign and not equal: intervals.insert( 0, Interval(left, right, True, right_open)) right, right_open = left, True elif sign != eq_sign and equal: intervals.insert(0, Interval(left, left)) if sign == eq_sign: intervals.insert( 0, Interval(S.NegativeInfinity, right, True, right_open)) return intervals def solve_poly_inequalities(polys): """Solve polynomial inequalities with rational coefficients. Examples ======== >>> from sympy import Poly >>> from sympy.solvers.inequalities import solve_poly_inequalities >>> from sympy.abc import x >>> solve_poly_inequalities((( ... Poly(x**2 - 3), ">"), ( ... Poly(-x**2 + 1), ">"))) Union(Interval.open(-oo, -sqrt(3)), Interval.open(-1, 1), Interval.open(sqrt(3), oo)) """ return Union(*[s for p in polys for s in solve_poly_inequality(*p)]) def solve_rational_inequalities(eqs): """Solve a system of rational inequalities with rational coefficients. Examples ======== >>> from sympy.abc import x >>> from sympy import solve_rational_inequalities, Poly >>> solve_rational_inequalities([[ ... ((Poly(-x + 1), Poly(1, x)), '>='), ... ((Poly(-x + 1), Poly(1, x)), '<=')]]) {1} >>> solve_rational_inequalities([[ ... ((Poly(x), Poly(1, x)), '!='), ... ((Poly(-x + 1), Poly(1, x)), '>=')]]) Union(Interval.open(-oo, 0), Interval.Lopen(0, 1)) See Also ======== solve_poly_inequality """ result = S.EmptySet for _eqs in eqs: if not _eqs: continue global_intervals = [Interval(S.NegativeInfinity, S.Infinity)] for (numer, denom), rel in _eqs: numer_intervals = solve_poly_inequality(numer*denom, rel) denom_intervals = solve_poly_inequality(denom, '==') intervals = [] for numer_interval, global_interval in itertools.product( numer_intervals, global_intervals): interval = numer_interval.intersect(global_interval) if interval is not S.EmptySet: intervals.append(interval) global_intervals = intervals intervals = [] for global_interval in global_intervals: for denom_interval in denom_intervals: global_interval -= denom_interval if global_interval is not S.EmptySet: intervals.append(global_interval) global_intervals = intervals if not global_intervals: break for interval in global_intervals: result = result.union(interval) return result def reduce_rational_inequalities(exprs, gen, relational=True): """Reduce a system of rational inequalities with rational coefficients. Examples ======== >>> from sympy import Symbol >>> from sympy.solvers.inequalities import reduce_rational_inequalities >>> x = Symbol('x', real=True) >>> reduce_rational_inequalities([[x**2 <= 0]], x) Eq(x, 0) >>> reduce_rational_inequalities([[x + 2 > 0]], x) -2 < x >>> reduce_rational_inequalities([[(x + 2, ">")]], x) -2 < x >>> reduce_rational_inequalities([[x + 2]], x) Eq(x, -2) This function find the non-infinite solution set so if the unknown symbol is declared as extended real rather than real then the result may include finiteness conditions: >>> y = Symbol('y', extended_real=True) >>> reduce_rational_inequalities([[y + 2 > 0]], y) (-2 < y) & (y < oo) """ exact = True eqs = [] solution = S.Reals if exprs else S.EmptySet for _exprs in exprs: _eqs = [] for expr in _exprs: if isinstance(expr, tuple): expr, rel = expr else: if expr.is_Relational: expr, rel = expr.lhs - expr.rhs, expr.rel_op else: expr, rel = expr, '==' if expr is S.true: numer, denom, rel = S.Zero, S.One, '==' elif expr is S.false: numer, denom, rel = S.One, S.One, '==' else: numer, denom = expr.together().as_numer_denom() try: (numer, denom), opt = parallel_poly_from_expr( (numer, denom), gen) except PolynomialError: raise PolynomialError(filldedent(''' only polynomials and rational functions are supported in this context. ''')) if not opt.domain.is_Exact: numer, denom, exact = numer.to_exact(), denom.to_exact(), False domain = opt.domain.get_exact() if not (domain.is_ZZ or domain.is_QQ): expr = numer/denom expr = Relational(expr, 0, rel) solution &= solve_univariate_inequality(expr, gen, relational=False) else: _eqs.append(((numer, denom), rel)) if _eqs: eqs.append(_eqs) if eqs: solution &= solve_rational_inequalities(eqs) exclude = solve_rational_inequalities([[((d, d.one), '==') for i in eqs for ((n, d), _) in i if d.has(gen)]]) solution -= exclude if not exact and solution: solution = solution.evalf() if relational: solution = solution.as_relational(gen) return solution def reduce_abs_inequality(expr, rel, gen): """Reduce an inequality with nested absolute values. Examples ======== >>> from sympy import reduce_abs_inequality, Abs, Symbol >>> x = Symbol('x', real=True) >>> reduce_abs_inequality(Abs(x - 5) - 3, '<', x) (2 < x) & (x < 8) >>> reduce_abs_inequality(Abs(x + 2)*3 - 13, '<', x) (-19/3 < x) & (x < 7/3) See Also ======== reduce_abs_inequalities """ if gen.is_extended_real is False: raise TypeError(filldedent(''' Cannot solve inequalities with absolute values containing non-real variables. ''')) def _bottom_up_scan(expr): exprs = [] if expr.is_Add or expr.is_Mul: op = expr.func for arg in expr.args: _exprs = _bottom_up_scan(arg) if not exprs: exprs = _exprs else: exprs = [(op(expr, _expr), conds + _conds) for (expr, conds), (_expr, _conds) in itertools.product(exprs, _exprs)] elif expr.is_Pow: n = expr.exp if not n.is_Integer: raise ValueError("Only Integer Powers are allowed on Abs.") exprs.extend((expr**n, conds) for expr, conds in _bottom_up_scan(expr.base)) elif isinstance(expr, Abs): _exprs = _bottom_up_scan(expr.args[0]) for expr, conds in _exprs: exprs.append(( expr, conds + [Ge(expr, 0)])) exprs.append((-expr, conds + [Lt(expr, 0)])) else: exprs = [(expr, [])] return exprs mapping = {'<': '>', '<=': '>='} inequalities = [] for expr, conds in _bottom_up_scan(expr): if rel not in mapping.keys(): expr = Relational( expr, 0, rel) else: expr = Relational(-expr, 0, mapping[rel]) inequalities.append([expr] + conds) return reduce_rational_inequalities(inequalities, gen) def reduce_abs_inequalities(exprs, gen): """Reduce a system of inequalities with nested absolute values. Examples ======== >>> from sympy import reduce_abs_inequalities, Abs, Symbol >>> x = Symbol('x', extended_real=True) >>> reduce_abs_inequalities([(Abs(3*x - 5) - 7, '<'), ... (Abs(x + 25) - 13, '>')], x) (-2/3 < x) & (x < 4) & (((-oo < x) & (x < -38)) | ((-12 < x) & (x < oo))) >>> reduce_abs_inequalities([(Abs(x - 4) + Abs(3*x - 5) - 7, '<')], x) (1/2 < x) & (x < 4) See Also ======== reduce_abs_inequality """ return And(*[ reduce_abs_inequality(expr, rel, gen) for expr, rel in exprs ]) def solve_univariate_inequality(expr, gen, relational=True, domain=S.Reals, continuous=False): """Solves a real univariate inequality. Parameters ========== expr : Relational The target inequality gen : Symbol The variable for which the inequality is solved relational : bool A Relational type output is expected or not domain : Set The domain over which the equation is solved continuous: bool True if expr is known to be continuous over the given domain (and so continuous_domain() does not need to be called on it) Raises ====== NotImplementedError The solution of the inequality cannot be determined due to limitation in :func:`sympy.solvers.solveset.solvify`. Notes ===== Currently, we cannot solve all the inequalities due to limitations in :func:`sympy.solvers.solveset.solvify`. Also, the solution returned for trigonometric inequalities are restricted in its periodic interval. See Also ======== sympy.solvers.solveset.solvify: solver returning solveset solutions with solve's output API Examples ======== >>> from sympy import solve_univariate_inequality, Symbol, sin, Interval, S >>> x = Symbol('x') >>> solve_univariate_inequality(x**2 >= 4, x) ((2 <= x) & (x < oo)) | ((-oo < x) & (x <= -2)) >>> solve_univariate_inequality(x**2 >= 4, x, relational=False) Union(Interval(-oo, -2), Interval(2, oo)) >>> domain = Interval(0, S.Infinity) >>> solve_univariate_inequality(x**2 >= 4, x, False, domain) Interval(2, oo) >>> solve_univariate_inequality(sin(x) > 0, x, relational=False) Interval.open(0, pi) """ from sympy.solvers.solvers import denoms if domain.is_subset(S.Reals) is False: raise NotImplementedError(filldedent(''' Inequalities in the complex domain are not supported. Try the real domain by setting domain=S.Reals''')) elif domain is not S.Reals: rv = solve_univariate_inequality( expr, gen, relational=False, continuous=continuous).intersection(domain) if relational: rv = rv.as_relational(gen) return rv else: pass # continue with attempt to solve in Real domain # This keeps the function independent of the assumptions about `gen`. # `solveset` makes sure this function is called only when the domain is # real. _gen = gen _domain = domain if gen.is_extended_real is False: rv = S.EmptySet return rv if not relational else rv.as_relational(_gen) elif gen.is_extended_real is None: gen = Dummy('gen', extended_real=True) try: expr = expr.xreplace({_gen: gen}) except TypeError: raise TypeError(filldedent(''' When gen is real, the relational has a complex part which leads to an invalid comparison like I < 0. ''')) rv = None if expr is S.true: rv = domain elif expr is S.false: rv = S.EmptySet else: e = expr.lhs - expr.rhs period = periodicity(e, gen) if period == S.Zero: e = expand_mul(e) const = expr.func(e, 0) if const is S.true: rv = domain elif const is S.false: rv = S.EmptySet elif period is not None: frange = function_range(e, gen, domain) rel = expr.rel_op if rel in ('<', '<='): if expr.func(frange.sup, 0): rv = domain elif not expr.func(frange.inf, 0): rv = S.EmptySet elif rel in ('>', '>='): if expr.func(frange.inf, 0): rv = domain elif not expr.func(frange.sup, 0): rv = S.EmptySet inf, sup = domain.inf, domain.sup if sup - inf is S.Infinity: domain = Interval(0, period, False, True).intersect(_domain) _domain = domain if rv is None: n, d = e.as_numer_denom() try: if gen not in n.free_symbols and len(e.free_symbols) > 1: raise ValueError # this might raise ValueError on its own # or it might give None... solns = solvify(e, gen, domain) if solns is None: # in which case we raise ValueError raise ValueError except (ValueError, NotImplementedError): # replace gen with generic x since it's # univariate anyway raise NotImplementedError(filldedent(''' The inequality, %s, cannot be solved using solve_univariate_inequality. ''' % expr.subs(gen, Symbol('x')))) expanded_e = expand_mul(e) def valid(x): # this is used to see if gen=x satisfies the # relational by substituting it into the # expanded form and testing against 0, e.g. # if expr = x*(x + 1) < 2 then e = x*(x + 1) - 2 # and expanded_e = x**2 + x - 2; the test is # whether a given value of x satisfies # x**2 + x - 2 < 0 # # expanded_e, expr and gen used from enclosing scope v = expanded_e.subs(gen, expand_mul(x)) try: r = expr.func(v, 0) except TypeError: r = S.false if r in (S.true, S.false): return r if v.is_extended_real is False: return S.false else: v = v.n(2) if v.is_comparable: return expr.func(v, 0) # not comparable or couldn't be evaluated raise NotImplementedError( 'relationship did not evaluate: %s' % r) singularities = [] for d in denoms(expr, gen): singularities.extend(solvify(d, gen, domain)) if not continuous: domain = continuous_domain(expanded_e, gen, domain) include_x = '=' in expr.rel_op and expr.rel_op != '!=' try: discontinuities = set(domain.boundary - FiniteSet(domain.inf, domain.sup)) # remove points that are not between inf and sup of domain critical_points = FiniteSet(*(solns + singularities + list( discontinuities))).intersection( Interval(domain.inf, domain.sup, domain.inf not in domain, domain.sup not in domain)) if all(r.is_number for r in critical_points): reals = _nsort(critical_points, separated=True)[0] else: sifted = sift(critical_points, lambda x: x.is_extended_real) if sifted[None]: # there were some roots that weren't known # to be real raise NotImplementedError try: reals = sifted[True] if len(reals) > 1: reals = list(sorted(reals)) except TypeError: raise NotImplementedError except NotImplementedError: raise NotImplementedError('sorting of these roots is not supported') # If expr contains imaginary coefficients, only take real # values of x for which the imaginary part is 0 make_real = S.Reals if im(expanded_e) != S.Zero: check = True im_sol = FiniteSet() try: a = solveset(im(expanded_e), gen, domain) if not isinstance(a, Interval): for z in a: if z not in singularities and valid(z) and z.is_extended_real: im_sol += FiniteSet(z) else: start, end = a.inf, a.sup for z in _nsort(critical_points + FiniteSet(end)): valid_start = valid(start) if start != end: valid_z = valid(z) pt = _pt(start, z) if pt not in singularities and pt.is_extended_real and valid(pt): if valid_start and valid_z: im_sol += Interval(start, z) elif valid_start: im_sol += Interval.Ropen(start, z) elif valid_z: im_sol += Interval.Lopen(start, z) else: im_sol += Interval.open(start, z) start = z for s in singularities: im_sol -= FiniteSet(s) except (TypeError): im_sol = S.Reals check = False if im_sol is S.EmptySet: raise ValueError(filldedent(''' %s contains imaginary parts which cannot be made 0 for any value of %s satisfying the inequality, leading to relations like I < 0. ''' % (expr.subs(gen, _gen), _gen))) make_real = make_real.intersect(im_sol) sol_sets = [S.EmptySet] start = domain.inf if start in domain and valid(start) and start.is_finite: sol_sets.append(FiniteSet(start)) for x in reals: end = x if valid(_pt(start, end)): sol_sets.append(Interval(start, end, True, True)) if x in singularities: singularities.remove(x) else: if x in discontinuities: discontinuities.remove(x) _valid = valid(x) else: # it's a solution _valid = include_x if _valid: sol_sets.append(FiniteSet(x)) start = end end = domain.sup if end in domain and valid(end) and end.is_finite: sol_sets.append(FiniteSet(end)) if valid(_pt(start, end)): sol_sets.append(Interval.open(start, end)) if im(expanded_e) != S.Zero and check: rv = (make_real).intersect(_domain) else: rv = Intersection( (Union(*sol_sets)), make_real, _domain).subs(gen, _gen) return rv if not relational else rv.as_relational(_gen) def _pt(start, end): """Return a point between start and end""" if not start.is_infinite and not end.is_infinite: pt = (start + end)/2 elif start.is_infinite and end.is_infinite: pt = S.Zero else: if (start.is_infinite and start.is_extended_positive is None or end.is_infinite and end.is_extended_positive is None): raise ValueError('cannot proceed with unsigned infinite values') if (end.is_infinite and end.is_extended_negative or start.is_infinite and start.is_extended_positive): start, end = end, start # if possible, use a multiple of self which has # better behavior when checking assumptions than # an expression obtained by adding or subtracting 1 if end.is_infinite: if start.is_extended_positive: pt = start*2 elif start.is_extended_negative: pt = start*S.Half else: pt = start + 1 elif start.is_infinite: if end.is_extended_positive: pt = end*S.Half elif end.is_extended_negative: pt = end*2 else: pt = end - 1 return pt def _solve_inequality(ie, s, linear=False): """Return the inequality with s isolated on the left, if possible. If the relationship is non-linear, a solution involving And or Or may be returned. False or True are returned if the relationship is never True or always True, respectively. If `linear` is True (default is False) an `s`-dependent expression will be isolated on the left, if possible but it will not be solved for `s` unless the expression is linear in `s`. Furthermore, only "safe" operations which do not change the sense of the relationship are applied: no division by an unsigned value is attempted unless the relationship involves Eq or Ne and no division by a value not known to be nonzero is ever attempted. Examples ======== >>> from sympy import Eq, Symbol >>> from sympy.solvers.inequalities import _solve_inequality as f >>> from sympy.abc import x, y For linear expressions, the symbol can be isolated: >>> f(x - 2 < 0, x) x < 2 >>> f(-x - 6 < x, x) x > -3 Sometimes nonlinear relationships will be False >>> f(x**2 + 4 < 0, x) False Or they may involve more than one region of values: >>> f(x**2 - 4 < 0, x) (-2 < x) & (x < 2) To restrict the solution to a relational, set linear=True and only the x-dependent portion will be isolated on the left: >>> f(x**2 - 4 < 0, x, linear=True) x**2 < 4 Division of only nonzero quantities is allowed, so x cannot be isolated by dividing by y: >>> y.is_nonzero is None # it is unknown whether it is 0 or not True >>> f(x*y < 1, x) x*y < 1 And while an equality (or inequality) still holds after dividing by a non-zero quantity >>> nz = Symbol('nz', nonzero=True) >>> f(Eq(x*nz, 1), x) Eq(x, 1/nz) the sign must be known for other inequalities involving > or <: >>> f(x*nz <= 1, x) nz*x <= 1 >>> p = Symbol('p', positive=True) >>> f(x*p <= 1, x) x <= 1/p When there are denominators in the original expression that are removed by expansion, conditions for them will be returned as part of the result: >>> f(x < x*(2/x - 1), x) (x < 1) & Ne(x, 0) """ from sympy.solvers.solvers import denoms if s not in ie.free_symbols: return ie if ie.rhs == s: ie = ie.reversed if ie.lhs == s and s not in ie.rhs.free_symbols: return ie def classify(ie, s, i): # return True or False if ie evaluates when substituting s with # i else None (if unevaluated) or NaN (when there is an error # in evaluating) try: v = ie.subs(s, i) if v is S.NaN: return v elif v not in (True, False): return return v except TypeError: return S.NaN rv = None oo = S.Infinity expr = ie.lhs - ie.rhs try: p = Poly(expr, s) if p.degree() == 0: rv = ie.func(p.as_expr(), 0) elif not linear and p.degree() > 1: # handle in except clause raise NotImplementedError except (PolynomialError, NotImplementedError): if not linear: try: rv = reduce_rational_inequalities([[ie]], s) except PolynomialError: rv = solve_univariate_inequality(ie, s) # remove restrictions wrt +/-oo that may have been # applied when using sets to simplify the relationship okoo = classify(ie, s, oo) if okoo is S.true and classify(rv, s, oo) is S.false: rv = rv.subs(s < oo, True) oknoo = classify(ie, s, -oo) if (oknoo is S.true and classify(rv, s, -oo) is S.false): rv = rv.subs(-oo < s, True) rv = rv.subs(s > -oo, True) if rv is S.true: rv = (s <= oo) if okoo is S.true else (s < oo) if oknoo is not S.true: rv = And(-oo < s, rv) else: p = Poly(expr) conds = [] if rv is None: e = p.as_expr() # this is in expanded form # Do a safe inversion of e, moving non-s terms # to the rhs and dividing by a nonzero factor if # the relational is Eq/Ne; for other relationals # the sign must also be positive or negative rhs = 0 b, ax = e.as_independent(s, as_Add=True) e -= b rhs -= b ef = factor_terms(e) a, e = ef.as_independent(s, as_Add=False) if (a.is_zero != False or # don't divide by potential 0 a.is_negative == a.is_positive is None and # if sign is not known then ie.rel_op not in ('!=', '==')): # reject if not Eq/Ne e = ef a = S.One rhs /= a if a.is_positive: rv = ie.func(e, rhs) else: rv = ie.reversed.func(e, rhs) # return conditions under which the value is # valid, too. beginning_denoms = denoms(ie.lhs) | denoms(ie.rhs) current_denoms = denoms(rv) for d in beginning_denoms - current_denoms: c = _solve_inequality(Eq(d, 0), s, linear=linear) if isinstance(c, Eq) and c.lhs == s: if classify(rv, s, c.rhs) is S.true: # rv is permitting this value but it shouldn't conds.append(~c) for i in (-oo, oo): if (classify(rv, s, i) is S.true and classify(ie, s, i) is not S.true): conds.append(s < i if i is oo else i < s) conds.append(rv) return And(*conds) def _reduce_inequalities(inequalities, symbols): # helper for reduce_inequalities poly_part, abs_part = {}, {} other = [] for inequality in inequalities: expr, rel = inequality.lhs, inequality.rel_op # rhs is 0 # check for gens using atoms which is more strict than free_symbols to # guard against EX domain which won't be handled by # reduce_rational_inequalities gens = expr.atoms(Symbol) if len(gens) == 1: gen = gens.pop() else: common = expr.free_symbols & symbols if len(common) == 1: gen = common.pop() other.append(_solve_inequality(Relational(expr, 0, rel), gen)) continue else: raise NotImplementedError(filldedent(''' inequality has more than one symbol of interest. ''')) if expr.is_polynomial(gen): poly_part.setdefault(gen, []).append((expr, rel)) else: components = expr.find(lambda u: u.has(gen) and ( u.is_Function or u.is_Pow and not u.exp.is_Integer)) if components and all(isinstance(i, Abs) for i in components): abs_part.setdefault(gen, []).append((expr, rel)) else: other.append(_solve_inequality(Relational(expr, 0, rel), gen)) poly_reduced = [reduce_rational_inequalities([exprs], gen) for gen, exprs in poly_part.items()] abs_reduced = [reduce_abs_inequalities(exprs, gen) for gen, exprs in abs_part.items()] return And(*(poly_reduced + abs_reduced + other)) def reduce_inequalities(inequalities, symbols=[]): """Reduce a system of inequalities with rational coefficients. Examples ======== >>> from sympy.abc import x, y >>> from sympy import reduce_inequalities >>> reduce_inequalities(0 <= x + 3, []) (-3 <= x) & (x < oo) >>> reduce_inequalities(0 <= x + y*2 - 1, [x]) (x < oo) & (x >= 1 - 2*y) """ if not iterable(inequalities): inequalities = [inequalities] inequalities = [sympify(i) for i in inequalities] gens = set().union(*[i.free_symbols for i in inequalities]) if not iterable(symbols): symbols = [symbols] symbols = (set(symbols) or gens) & gens if any(i.is_extended_real is False for i in symbols): raise TypeError(filldedent(''' inequalities cannot contain symbols that are not real. ''')) # make vanilla symbol real recast = {i: Dummy(i.name, extended_real=True) for i in gens if i.is_extended_real is None} inequalities = [i.xreplace(recast) for i in inequalities] symbols = {i.xreplace(recast) for i in symbols} # prefilter keep = [] for i in inequalities: if isinstance(i, Relational): i = i.func(i.lhs.as_expr() - i.rhs.as_expr(), 0) elif i not in (True, False): i = Eq(i, 0) if i == True: continue elif i == False: return S.false if i.lhs.is_number: raise NotImplementedError( "could not determine truth value of %s" % i) keep.append(i) inequalities = keep del keep # solve system rv = _reduce_inequalities(inequalities, symbols) # restore original symbols and return return rv.xreplace({v: k for k, v in recast.items()})
421379f956893d7db8ac1f0704d69d575406aeace54ec671905ea27b07766bb4
""" This module contain solvers for all kinds of equations: - algebraic or transcendental, use solve() - recurrence, use rsolve() - differential, use dsolve() - nonlinear (numerically), use nsolve() (you will need a good starting point) """ from sympy.core import (S, Add, Symbol, Dummy, Expr, Mul) from sympy.core.assumptions import check_assumptions from sympy.core.exprtools import factor_terms from sympy.core.function import (expand_mul, expand_log, Derivative, AppliedUndef, UndefinedFunction, nfloat, Function, expand_power_exp, _mexpand, expand, expand_func) from sympy.core.logic import fuzzy_not from sympy.core.numbers import ilcm, Float, Rational, _illegal from sympy.core.power import integer_log, Pow from sympy.core.relational import Relational, Eq, Ne from sympy.core.sorting import ordered, default_sort_key from sympy.core.sympify import sympify, _sympify from sympy.core.traversal import preorder_traversal from sympy.logic.boolalg import And, Or, BooleanAtom from sympy.functions import (log, exp, LambertW, cos, sin, tan, acos, asin, atan, Abs, re, im, arg, sqrt, atan2) from sympy.functions.combinatorial.factorials import binomial from sympy.functions.elementary.hyperbolic import HyperbolicFunction from sympy.functions.elementary.piecewise import piecewise_fold, Piecewise from sympy.functions.elementary.trigonometric import TrigonometricFunction from sympy.integrals.integrals import Integral from sympy.ntheory.factor_ import divisors from sympy.simplify import (simplify, collect, powsimp, posify, # type: ignore powdenest, nsimplify, denom, logcombine, sqrtdenest, fraction, separatevars) from sympy.simplify.sqrtdenest import sqrt_depth from sympy.simplify.fu import TR1, TR2i from sympy.matrices.common import NonInvertibleMatrixError from sympy.matrices import Matrix, zeros from sympy.polys import roots, cancel, factor, Poly from sympy.polys.polyerrors import GeneratorsNeeded, PolynomialError from sympy.polys.solvers import sympy_eqs_to_ring, solve_lin_sys from sympy.utilities.lambdify import lambdify from sympy.utilities.misc import filldedent, debug from sympy.utilities.iterables import (connected_components, generate_bell, uniq, iterable, is_sequence, subsets, flatten) from sympy.utilities.decorator import conserve_mpmath_dps from mpmath import findroot from sympy.solvers.polysys import solve_poly_system from types import GeneratorType from collections import defaultdict from itertools import combinations, product import warnings def recast_to_symbols(eqs, symbols): """ Return (e, s, d) where e and s are versions of *eqs* and *symbols* in which any non-Symbol objects in *symbols* have been replaced with generic Dummy symbols and d is a dictionary that can be used to restore the original expressions. Examples ======== >>> from sympy.solvers.solvers import recast_to_symbols >>> from sympy import symbols, Function >>> x, y = symbols('x y') >>> fx = Function('f')(x) >>> eqs, syms = [fx + 1, x, y], [fx, y] >>> e, s, d = recast_to_symbols(eqs, syms); (e, s, d) ([_X0 + 1, x, y], [_X0, y], {_X0: f(x)}) The original equations and symbols can be restored using d: >>> assert [i.xreplace(d) for i in eqs] == eqs >>> assert [d.get(i, i) for i in s] == syms """ if not iterable(eqs) and iterable(symbols): raise ValueError('Both eqs and symbols must be iterable') orig = list(symbols) symbols = list(ordered(symbols)) swap_sym = {} i = 0 for j, s in enumerate(symbols): if not isinstance(s, Symbol) and s not in swap_sym: swap_sym[s] = Dummy('X%d' % i) i += 1 new_f = [] for i in eqs: isubs = getattr(i, 'subs', None) if isubs is not None: new_f.append(isubs(swap_sym)) else: new_f.append(i) restore = {v: k for k, v in swap_sym.items()} return new_f, [swap_sym.get(i, i) for i in orig], restore def _ispow(e): """Return True if e is a Pow or is exp.""" return isinstance(e, Expr) and (e.is_Pow or isinstance(e, exp)) def _simple_dens(f, symbols): # when checking if a denominator is zero, we can just check the # base of powers with nonzero exponents since if the base is zero # the power will be zero, too. To keep it simple and fast, we # limit simplification to exponents that are Numbers dens = set() for d in denoms(f, symbols): if d.is_Pow and d.exp.is_Number: if d.exp.is_zero: continue # foo**0 is never 0 d = d.base dens.add(d) return dens def denoms(eq, *symbols): """ Return (recursively) set of all denominators that appear in *eq* that contain any symbol in *symbols*; if *symbols* are not provided then all denominators will be returned. Examples ======== >>> from sympy.solvers.solvers import denoms >>> from sympy.abc import x, y, z >>> denoms(x/y) {y} >>> denoms(x/(y*z)) {y, z} >>> denoms(3/x + y/z) {x, z} >>> denoms(x/2 + y/z) {2, z} If *symbols* are provided then only denominators containing those symbols will be returned: >>> denoms(1/x + 1/y + 1/z, y, z) {y, z} """ pot = preorder_traversal(eq) dens = set() for p in pot: # Here p might be Tuple or Relational # Expr subtrees (e.g. lhs and rhs) will be traversed after by pot if not isinstance(p, Expr): continue den = denom(p) if den is S.One: continue for d in Mul.make_args(den): dens.add(d) if not symbols: return dens elif len(symbols) == 1: if iterable(symbols[0]): symbols = symbols[0] return {d for d in dens if any(s in d.free_symbols for s in symbols)} def checksol(f, symbol, sol=None, **flags): """ Checks whether sol is a solution of equation f == 0. Explanation =========== Input can be either a single symbol and corresponding value or a dictionary of symbols and values. When given as a dictionary and flag ``simplify=True``, the values in the dictionary will be simplified. *f* can be a single equation or an iterable of equations. A solution must satisfy all equations in *f* to be considered valid; if a solution does not satisfy any equation, False is returned; if one or more checks are inconclusive (and none are False) then None is returned. Examples ======== >>> from sympy import checksol, symbols >>> x, y = symbols('x,y') >>> checksol(x**4 - 1, x, 1) True >>> checksol(x**4 - 1, x, 0) False >>> checksol(x**2 + y**2 - 5**2, {x: 3, y: 4}) True To check if an expression is zero using ``checksol()``, pass it as *f* and send an empty dictionary for *symbol*: >>> checksol(x**2 + x - x*(x + 1), {}) True None is returned if ``checksol()`` could not conclude. flags: 'numerical=True (default)' do a fast numerical check if ``f`` has only one symbol. 'minimal=True (default is False)' a very fast, minimal testing. 'warn=True (default is False)' show a warning if checksol() could not conclude. 'simplify=True (default)' simplify solution before substituting into function and simplify the function before trying specific simplifications 'force=True (default is False)' make positive all symbols without assumptions regarding sign. """ from sympy.physics.units import Unit minimal = flags.get('minimal', False) if sol is not None: sol = {symbol: sol} elif isinstance(symbol, dict): sol = symbol else: msg = 'Expecting (sym, val) or ({sym: val}, None) but got (%s, %s)' raise ValueError(msg % (symbol, sol)) if iterable(f): if not f: raise ValueError('no functions to check') rv = True for fi in f: check = checksol(fi, sol, **flags) if check: continue if check is False: return False rv = None # don't return, wait to see if there's a False return rv f = _sympify(f) if f.is_number: return f.is_zero if isinstance(f, Poly): f = f.as_expr() elif isinstance(f, (Eq, Ne)): if f.rhs in (S.true, S.false): f = f.reversed B, E = f.args if isinstance(B, BooleanAtom): f = f.subs(sol) if not f.is_Boolean: return else: f = f.rewrite(Add, evaluate=False) if isinstance(f, BooleanAtom): return bool(f) elif not f.is_Relational and not f: return True illegal = set(_illegal) if any(sympify(v).atoms() & illegal for k, v in sol.items()): return False was = f attempt = -1 numerical = flags.get('numerical', True) while 1: attempt += 1 if attempt == 0: val = f.subs(sol) if isinstance(val, Mul): val = val.as_independent(Unit)[0] if val.atoms() & illegal: return False elif attempt == 1: if not val.is_number: if not val.is_constant(*list(sol.keys()), simplify=not minimal): return False # there are free symbols -- simple expansion might work _, val = val.as_content_primitive() val = _mexpand(val.as_numer_denom()[0], recursive=True) elif attempt == 2: if minimal: return if flags.get('simplify', True): for k in sol: sol[k] = simplify(sol[k]) # start over without the failed expanded form, possibly # with a simplified solution val = simplify(f.subs(sol)) if flags.get('force', True): val, reps = posify(val) # expansion may work now, so try again and check exval = _mexpand(val, recursive=True) if exval.is_number: # we can decide now val = exval else: # if there are no radicals and no functions then this can't be # zero anymore -- can it? pot = preorder_traversal(expand_mul(val)) seen = set() saw_pow_func = False for p in pot: if p in seen: continue seen.add(p) if p.is_Pow and not p.exp.is_Integer: saw_pow_func = True elif p.is_Function: saw_pow_func = True elif isinstance(p, UndefinedFunction): saw_pow_func = True if saw_pow_func: break if saw_pow_func is False: return False if flags.get('force', True): # don't do a zero check with the positive assumptions in place val = val.subs(reps) nz = fuzzy_not(val.is_zero) if nz is not None: # issue 5673: nz may be True even when False # so these are just hacks to keep a false positive # from being returned # HACK 1: LambertW (issue 5673) if val.is_number and val.has(LambertW): # don't eval this to verify solution since if we got here, # numerical must be False return None # add other HACKs here if necessary, otherwise we assume # the nz value is correct return not nz break if numerical and val.is_number: return (abs(val.n(18).n(12, chop=True)) < 1e-9) is S.true if val == was: continue elif val.is_Rational: return val == 0 was = val if flags.get('warn', False): warnings.warn("\n\tWarning: could not verify solution %s." % sol) # returns None if it can't conclude # TODO: improve solution testing def solve(f, *symbols, **flags): r""" Algebraically solves equations and systems of equations. Explanation =========== Currently supported: - polynomial - transcendental - piecewise combinations of the above - systems of linear and polynomial equations - systems containing relational expressions Examples ======== The output varies according to the input and can be seen by example: >>> from sympy import solve, Poly, Eq, Function, exp >>> from sympy.abc import x, y, z, a, b >>> f = Function('f') Boolean or univariate Relational: >>> solve(x < 3) (-oo < x) & (x < 3) To always get a list of solution mappings, use flag dict=True: >>> solve(x - 3, dict=True) [{x: 3}] >>> sol = solve([x - 3, y - 1], dict=True) >>> sol [{x: 3, y: 1}] >>> sol[0][x] 3 >>> sol[0][y] 1 To get a list of *symbols* and set of solution(s) use flag set=True: >>> solve([x**2 - 3, y - 1], set=True) ([x, y], {(-sqrt(3), 1), (sqrt(3), 1)}) Single expression and single symbol that is in the expression: >>> solve(x - y, x) [y] >>> solve(x - 3, x) [3] >>> solve(Eq(x, 3), x) [3] >>> solve(Poly(x - 3), x) [3] >>> solve(x**2 - y**2, x, set=True) ([x], {(-y,), (y,)}) >>> solve(x**4 - 1, x, set=True) ([x], {(-1,), (1,), (-I,), (I,)}) Single expression with no symbol that is in the expression: >>> solve(3, x) [] >>> solve(x - 3, y) [] Single expression with no symbol given. In this case, all free *symbols* will be selected as potential *symbols* to solve for. If the equation is univariate then a list of solutions is returned; otherwise - as is the case when *symbols* are given as an iterable of length greater than 1 - a list of mappings will be returned: >>> solve(x - 3) [3] >>> solve(x**2 - y**2) [{x: -y}, {x: y}] >>> solve(z**2*x**2 - z**2*y**2) [{x: -y}, {x: y}, {z: 0}] >>> solve(z**2*x - z**2*y**2) [{x: y**2}, {z: 0}] When an object other than a Symbol is given as a symbol, it is isolated algebraically and an implicit solution may be obtained. This is mostly provided as a convenience to save you from replacing the object with a Symbol and solving for that Symbol. It will only work if the specified object can be replaced with a Symbol using the subs method: >>> solve(f(x) - x, f(x)) [x] >>> solve(f(x).diff(x) - f(x) - x, f(x).diff(x)) [x + f(x)] >>> solve(f(x).diff(x) - f(x) - x, f(x)) [-x + Derivative(f(x), x)] >>> solve(x + exp(x)**2, exp(x), set=True) ([exp(x)], {(-sqrt(-x),), (sqrt(-x),)}) >>> from sympy import Indexed, IndexedBase, Tuple, sqrt >>> A = IndexedBase('A') >>> eqs = Tuple(A[1] + A[2] - 3, A[1] - A[2] + 1) >>> solve(eqs, eqs.atoms(Indexed)) {A[1]: 1, A[2]: 2} * To solve for a symbol implicitly, use implicit=True: >>> solve(x + exp(x), x) [-LambertW(1)] >>> solve(x + exp(x), x, implicit=True) [-exp(x)] * It is possible to solve for anything that can be targeted with subs: >>> solve(x + 2 + sqrt(3), x + 2) [-sqrt(3)] >>> solve((x + 2 + sqrt(3), x + 4 + y), y, x + 2) {y: -2 + sqrt(3), x + 2: -sqrt(3)} * Nothing heroic is done in this implicit solving so you may end up with a symbol still in the solution: >>> eqs = (x*y + 3*y + sqrt(3), x + 4 + y) >>> solve(eqs, y, x + 2) {y: -sqrt(3)/(x + 3), x + 2: -2*x/(x + 3) - 6/(x + 3) + sqrt(3)/(x + 3)} >>> solve(eqs, y*x, x) {x: -y - 4, x*y: -3*y - sqrt(3)} * If you attempt to solve for a number remember that the number you have obtained does not necessarily mean that the value is equivalent to the expression obtained: >>> solve(sqrt(2) - 1, 1) [sqrt(2)] >>> solve(x - y + 1, 1) # /!\ -1 is targeted, too [x/(y - 1)] >>> [_.subs(z, -1) for _ in solve((x - y + 1).subs(-1, z), 1)] [-x + y] * To solve for a function within a derivative, use ``dsolve``. Single expression and more than one symbol: * When there is a linear solution: >>> solve(x - y**2, x, y) [(y**2, y)] >>> solve(x**2 - y, x, y) [(x, x**2)] >>> solve(x**2 - y, x, y, dict=True) [{y: x**2}] * When undetermined coefficients are identified: * That are linear: >>> solve((a + b)*x - b + 2, a, b) {a: -2, b: 2} * That are nonlinear: >>> solve((a + b)*x - b**2 + 2, a, b, set=True) ([a, b], {(-sqrt(2), sqrt(2)), (sqrt(2), -sqrt(2))}) * If there is no linear solution, then the first successful attempt for a nonlinear solution will be returned: >>> solve(x**2 - y**2, x, y, dict=True) [{x: -y}, {x: y}] >>> solve(x**2 - y**2/exp(x), x, y, dict=True) [{x: 2*LambertW(-y/2)}, {x: 2*LambertW(y/2)}] >>> solve(x**2 - y**2/exp(x), y, x) [(-x*sqrt(exp(x)), x), (x*sqrt(exp(x)), x)] Iterable of one or more of the above: * Involving relationals or bools: >>> solve([x < 3, x - 2]) Eq(x, 2) >>> solve([x > 3, x - 2]) False * When the system is linear: * With a solution: >>> solve([x - 3], x) {x: 3} >>> solve((x + 5*y - 2, -3*x + 6*y - 15), x, y) {x: -3, y: 1} >>> solve((x + 5*y - 2, -3*x + 6*y - 15), x, y, z) {x: -3, y: 1} >>> solve((x + 5*y - 2, -3*x + 6*y - z), z, x, y) {x: 2 - 5*y, z: 21*y - 6} * Without a solution: >>> solve([x + 3, x - 3]) [] * When the system is not linear: >>> solve([x**2 + y -2, y**2 - 4], x, y, set=True) ([x, y], {(-2, -2), (0, 2), (2, -2)}) * If no *symbols* are given, all free *symbols* will be selected and a list of mappings returned: >>> solve([x - 2, x**2 + y]) [{x: 2, y: -4}] >>> solve([x - 2, x**2 + f(x)], {f(x), x}) [{x: 2, f(x): -4}] * If any equation does not depend on the symbol(s) given, it will be eliminated from the equation set and an answer may be given implicitly in terms of variables that were not of interest: >>> solve([x - y, y - 3], x) {x: y} **Additional Examples** ``solve()`` with check=True (default) will run through the symbol tags to elimate unwanted solutions. If no assumptions are included, all possible solutions will be returned: >>> from sympy import Symbol, solve >>> x = Symbol("x") >>> solve(x**2 - 1) [-1, 1] By using the positive tag, only one solution will be returned: >>> pos = Symbol("pos", positive=True) >>> solve(pos**2 - 1) [1] Assumptions are not checked when ``solve()`` input involves relationals or bools. When the solutions are checked, those that make any denominator zero are automatically excluded. If you do not want to exclude such solutions, then use the check=False option: >>> from sympy import sin, limit >>> solve(sin(x)/x) # 0 is excluded [pi] If check=False, then a solution to the numerator being zero is found: x = 0. In this case, this is a spurious solution since $\sin(x)/x$ has the well known limit (without dicontinuity) of 1 at x = 0: >>> solve(sin(x)/x, check=False) [0, pi] In the following case, however, the limit exists and is equal to the value of x = 0 that is excluded when check=True: >>> eq = x**2*(1/x - z**2/x) >>> solve(eq, x) [] >>> solve(eq, x, check=False) [0] >>> limit(eq, x, 0, '-') 0 >>> limit(eq, x, 0, '+') 0 **Disabling High-Order Explicit Solutions** When solving polynomial expressions, you might not want explicit solutions (which can be quite long). If the expression is univariate, ``CRootOf`` instances will be returned instead: >>> solve(x**3 - x + 1) [-1/((-1/2 - sqrt(3)*I/2)*(3*sqrt(69)/2 + 27/2)**(1/3)) - (-1/2 - sqrt(3)*I/2)*(3*sqrt(69)/2 + 27/2)**(1/3)/3, -(-1/2 + sqrt(3)*I/2)*(3*sqrt(69)/2 + 27/2)**(1/3)/3 - 1/((-1/2 + sqrt(3)*I/2)*(3*sqrt(69)/2 + 27/2)**(1/3)), -(3*sqrt(69)/2 + 27/2)**(1/3)/3 - 1/(3*sqrt(69)/2 + 27/2)**(1/3)] >>> solve(x**3 - x + 1, cubics=False) [CRootOf(x**3 - x + 1, 0), CRootOf(x**3 - x + 1, 1), CRootOf(x**3 - x + 1, 2)] If the expression is multivariate, no solution might be returned: >>> solve(x**3 - x + a, x, cubics=False) [] Sometimes solutions will be obtained even when a flag is False because the expression could be factored. In the following example, the equation can be factored as the product of a linear and a quadratic factor so explicit solutions (which did not require solving a cubic expression) are obtained: >>> eq = x**3 + 3*x**2 + x - 1 >>> solve(eq, cubics=False) [-1, -1 + sqrt(2), -sqrt(2) - 1] **Solving Equations Involving Radicals** Because of SymPy's use of the principle root, some solutions to radical equations will be missed unless check=False: >>> from sympy import root >>> eq = root(x**3 - 3*x**2, 3) + 1 - x >>> solve(eq) [] >>> solve(eq, check=False) [1/3] In the above example, there is only a single solution to the equation. Other expressions will yield spurious roots which must be checked manually; roots which give a negative argument to odd-powered radicals will also need special checking: >>> from sympy import real_root, S >>> eq = root(x, 3) - root(x, 5) + S(1)/7 >>> solve(eq) # this gives 2 solutions but misses a 3rd [CRootOf(7*x**5 - 7*x**3 + 1, 1)**15, CRootOf(7*x**5 - 7*x**3 + 1, 2)**15] >>> sol = solve(eq, check=False) >>> [abs(eq.subs(x,i).n(2)) for i in sol] [0.48, 0.e-110, 0.e-110, 0.052, 0.052] The first solution is negative so ``real_root`` must be used to see that it satisfies the expression: >>> abs(real_root(eq.subs(x, sol[0])).n(2)) 0.e-110 If the roots of the equation are not real then more care will be necessary to find the roots, especially for higher order equations. Consider the following expression: >>> expr = root(x, 3) - root(x, 5) We will construct a known value for this expression at x = 3 by selecting the 1-th root for each radical: >>> expr1 = root(x, 3, 1) - root(x, 5, 1) >>> v = expr1.subs(x, -3) The ``solve`` function is unable to find any exact roots to this equation: >>> eq = Eq(expr, v); eq1 = Eq(expr1, v) >>> solve(eq, check=False), solve(eq1, check=False) ([], []) The function ``unrad``, however, can be used to get a form of the equation for which numerical roots can be found: >>> from sympy.solvers.solvers import unrad >>> from sympy import nroots >>> e, (p, cov) = unrad(eq) >>> pvals = nroots(e) >>> inversion = solve(cov, x)[0] >>> xvals = [inversion.subs(p, i) for i in pvals] Although ``eq`` or ``eq1`` could have been used to find ``xvals``, the solution can only be verified with ``expr1``: >>> z = expr - v >>> [xi.n(chop=1e-9) for xi in xvals if abs(z.subs(x, xi).n()) < 1e-9] [] >>> z1 = expr1 - v >>> [xi.n(chop=1e-9) for xi in xvals if abs(z1.subs(x, xi).n()) < 1e-9] [-3.0] Parameters ========== f : - a single Expr or Poly that must be zero - an Equality - a Relational expression - a Boolean - iterable of one or more of the above symbols : (object(s) to solve for) specified as - none given (other non-numeric objects will be used) - single symbol - denested list of symbols (e.g., ``solve(f, x, y)``) - ordered iterable of symbols (e.g., ``solve(f, [x, y])``) flags : dict=True (default is False) Return list (perhaps empty) of solution mappings. set=True (default is False) Return list of symbols and set of tuple(s) of solution(s). exclude=[] (default) Do not try to solve for any of the free symbols in exclude; if expressions are given, the free symbols in them will be extracted automatically. check=True (default) If False, do not do any testing of solutions. This can be useful if you want to include solutions that make any denominator zero. numerical=True (default) Do a fast numerical check if *f* has only one symbol. minimal=True (default is False) A very fast, minimal testing. warn=True (default is False) Show a warning if ``checksol()`` could not conclude. simplify=True (default) Simplify all but polynomials of order 3 or greater before returning them and (if check is not False) use the general simplify function on the solutions and the expression obtained when they are substituted into the function which should be zero. force=True (default is False) Make positive all symbols without assumptions regarding sign. rational=True (default) Recast Floats as Rational; if this option is not used, the system containing Floats may fail to solve because of issues with polys. If rational=None, Floats will be recast as rationals but the answer will be recast as Floats. If the flag is False then nothing will be done to the Floats. manual=True (default is False) Do not use the polys/matrix method to solve a system of equations, solve them one at a time as you might "manually." implicit=True (default is False) Allows ``solve`` to return a solution for a pattern in terms of other functions that contain that pattern; this is only needed if the pattern is inside of some invertible function like cos, exp, ect. particular=True (default is False) Instructs ``solve`` to try to find a particular solution to a linear system with as many zeros as possible; this is very expensive. quick=True (default is False; ``particular`` must be True) Selects a fast heuristic to find a solution with many zeros whereas a value of False uses the very slow method guaranteed to find the largest number of zeros possible. cubics=True (default) Return explicit solutions when cubic expressions are encountered. When False, quartics and quintics are disabled, too. quartics=True (default) Return explicit solutions when quartic expressions are encountered. When False, quintics are disabled, too. quintics=True (default) Return explicit solutions (if possible) when quintic expressions are encountered. See Also ======== rsolve: For solving recurrence relationships dsolve: For solving differential equations """ from .inequalities import reduce_inequalities # set solver types explicitly; as soon as one is False # all the rest will be False ########################################################################### hints = ('cubics', 'quartics', 'quintics') default = True for k in hints: default = flags.setdefault(k, bool(flags.get(k, default))) # keeping track of how f was passed since if it is a list # a dictionary of results will be returned. ########################################################################### def _sympified_list(w): return list(map(sympify, w if iterable(w) else [w])) bare_f = not iterable(f) # check flag usage for particular/quick which should only be used # with systems of equations if flags.get('quick', None) is not None: if not flags.get('particular', None): raise ValueError('when using `quick`, `particular` should be True') if flags.get('particular', False) and bare_f: raise ValueError(filldedent(""" The 'particular/quick' flag is usually used with systems of equations. Either pass your equation in a list or consider using a solver like `diophantine` if you are looking for a solution in integers.""")) ordered_symbols = (symbols and symbols[0] and (isinstance(symbols[0], Symbol) or is_sequence(symbols[0], include=GeneratorType))) f, symbols = (_sympified_list(w) for w in [f, symbols]) if isinstance(f, list): f = [s for s in f if s is not S.true and s is not True] implicit = flags.get('implicit', False) # preprocess symbol(s) ########################################################################### if not symbols: # get symbols from equations symbols = set().union(*[fi.free_symbols for fi in f]) if len(symbols) < len(f): for fi in f: pot = preorder_traversal(fi) for p in pot: if isinstance(p, AppliedUndef): flags['dict'] = True # better show symbols symbols.add(p) pot.skip() # don't go any deeper symbols = list(symbols) ordered_symbols = False elif len(symbols) == 1 and iterable(symbols[0]): symbols = symbols[0] # remove symbols the user is not interested in exclude = flags.pop('exclude', set()) if exclude: if isinstance(exclude, Expr): exclude = [exclude] exclude = set().union(*[e.free_symbols for e in sympify(exclude)]) symbols = [s for s in symbols if s not in exclude] # preprocess equation(s) ########################################################################### for i, fi in enumerate(f): if isinstance(fi, (Eq, Ne)): if 'ImmutableDenseMatrix' in [type(a).__name__ for a in fi.args]: fi = fi.lhs - fi.rhs else: L, R = fi.args if isinstance(R, BooleanAtom): L, R = R, L if isinstance(L, BooleanAtom): if isinstance(fi, Ne): L = ~L if R.is_Relational: fi = ~R if L is S.false else R elif R.is_Symbol: return L elif R.is_Boolean and (~R).is_Symbol: return ~L else: raise NotImplementedError(filldedent(''' Unanticipated argument of Eq when other arg is True or False. ''')) else: fi = fi.rewrite(Add, evaluate=False) f[i] = fi if fi.is_Relational: return reduce_inequalities(f, symbols=symbols) if isinstance(fi, Poly): f[i] = fi.as_expr() # rewrite hyperbolics in terms of exp if they have symbols of # interest f[i] = f[i].replace(lambda w: isinstance(w, HyperbolicFunction) and \ w.has_free(*symbols), lambda w: w.rewrite(exp)) # if we have a Matrix, we need to iterate over its elements again if f[i].is_Matrix: bare_f = False f.extend(list(f[i])) f[i] = S.Zero # if we can split it into real and imaginary parts then do so freei = f[i].free_symbols if freei and all(s.is_extended_real or s.is_imaginary for s in freei): fr, fi = f[i].as_real_imag() # accept as long as new re, im, arg or atan2 are not introduced had = f[i].atoms(re, im, arg, atan2) if fr and fi and fr != fi and not any( i.atoms(re, im, arg, atan2) - had for i in (fr, fi)): if bare_f: bare_f = False f[i: i + 1] = [fr, fi] # real/imag handling ----------------------------- if any(isinstance(fi, (bool, BooleanAtom)) for fi in f): if flags.get('set', False): return [], set() return [] for i, fi in enumerate(f): # Abs while True: was = fi fi = fi.replace(Abs, lambda arg: separatevars(Abs(arg)).rewrite(Piecewise) if arg.has(*symbols) else Abs(arg)) if was == fi: break for e in fi.find(Abs): if e.has(*symbols): raise NotImplementedError('solving %s when the argument ' 'is not real or imaginary.' % e) # arg fi = fi.replace(arg, lambda a: arg(a).rewrite(atan2).rewrite(atan)) # save changes f[i] = fi # see if re(s) or im(s) appear freim = [fi for fi in f if fi.has(re, im)] if freim: irf = [] for s in symbols: if s.is_real or s.is_imaginary: continue # neither re(x) nor im(x) will appear # if re(s) or im(s) appear, the auxiliary equation must be present if any(fi.has(re(s), im(s)) for fi in freim): irf.append((s, re(s) + S.ImaginaryUnit*im(s))) if irf: for s, rhs in irf: f = [fi.xreplace({s: rhs}) for fi in f] + [s - rhs] symbols.extend([re(s), im(s)]) if bare_f: bare_f = False flags['dict'] = True # end of real/imag handling ----------------------------- symbols = list(uniq(symbols)) if not ordered_symbols: # we do this to make the results returned canonical in case f # contains a system of nonlinear equations; all other cases should # be unambiguous symbols = sorted(symbols, key=default_sort_key) # we can solve for non-symbol entities by replacing them with Dummy symbols f, symbols, swap_sym = recast_to_symbols(f, symbols) # this is needed in the next two events symset = set(symbols) # get rid of equations that have no symbols of interest; we don't # try to solve them because the user didn't ask and they might be # hard to solve; this means that solutions may be given in terms # of the eliminated equations e.g. solve((x-y, y-3), x) -> {x: y} newf = [] for fi in f: # let the solver handle equations that.. # - have no symbols but are expressions # - have symbols of interest # - have no symbols of interest but are constant # but when an expression is not constant and has no symbols of # interest, it can't change what we obtain for a solution from # the remaining equations so we don't include it; and if it's # zero it can be removed and if it's not zero, there is no # solution for the equation set as a whole # # The reason for doing this filtering is to allow an answer # to be obtained to queries like solve((x - y, y), x); without # this mod the return value is [] ok = False if fi.free_symbols & symset: ok = True else: if fi.is_number: if fi.is_Number: if fi.is_zero: continue return [] ok = True else: if fi.is_constant(): ok = True if ok: newf.append(fi) if not newf: return [] f = newf del newf # mask off any Object that we aren't going to invert: Derivative, # Integral, etc... so that solving for anything that they contain will # give an implicit solution seen = set() non_inverts = set() for fi in f: pot = preorder_traversal(fi) for p in pot: if not isinstance(p, Expr) or isinstance(p, Piecewise): pass elif (isinstance(p, bool) or not p.args or p in symset or p.is_Add or p.is_Mul or p.is_Pow and not implicit or p.is_Function and not implicit) and p.func not in (re, im): continue elif p not in seen: seen.add(p) if p.free_symbols & symset: non_inverts.add(p) else: continue pot.skip() del seen non_inverts = dict(list(zip(non_inverts, [Dummy() for _ in non_inverts]))) f = [fi.subs(non_inverts) for fi in f] # Both xreplace and subs are needed below: xreplace to force substitution # inside Derivative, subs to handle non-straightforward substitutions non_inverts = [(v, k.xreplace(swap_sym).subs(swap_sym)) for k, v in non_inverts.items()] # rationalize Floats floats = False if flags.get('rational', True) is not False: for i, fi in enumerate(f): if fi.has(Float): floats = True f[i] = nsimplify(fi, rational=True) # capture any denominators before rewriting since # they may disappear after the rewrite, e.g. issue 14779 flags['_denominators'] = _simple_dens(f[0], symbols) # Any embedded piecewise functions need to be brought out to the # top level so that the appropriate strategy gets selected. # However, this is necessary only if one of the piecewise # functions depends on one of the symbols we are solving for. def _has_piecewise(e): if e.is_Piecewise: return e.has(*symbols) return any(_has_piecewise(a) for a in e.args) for i, fi in enumerate(f): if _has_piecewise(fi): f[i] = piecewise_fold(fi) # # try to get a solution ########################################################################### if bare_f: solution = _solve(f[0], *symbols, **flags) else: solution = _solve_system(f, symbols, **flags) # # postprocessing ########################################################################### # Restore masked-off objects if non_inverts: def _do_dict(solution): return {k: v.subs(non_inverts) for k, v in solution.items()} for i in range(1): if isinstance(solution, dict): solution = _do_dict(solution) break elif solution and isinstance(solution, list): if isinstance(solution[0], dict): solution = [_do_dict(s) for s in solution] break elif isinstance(solution[0], tuple): solution = [tuple([v.subs(non_inverts) for v in s]) for s in solution] break else: solution = [v.subs(non_inverts) for v in solution] break elif not solution: break else: raise NotImplementedError(filldedent(''' no handling of %s was implemented''' % solution)) # Restore original "symbols" if a dictionary is returned. # This is not necessary for # - the single univariate equation case # since the symbol will have been removed from the solution; # - the nonlinear poly_system since that only supports zero-dimensional # systems and those results come back as a list # # ** unless there were Derivatives with the symbols, but those were handled # above. if swap_sym: symbols = [swap_sym.get(k, k) for k in symbols] if isinstance(solution, dict): solution = {swap_sym.get(k, k): v.subs(swap_sym) for k, v in solution.items()} elif solution and isinstance(solution, list) and isinstance(solution[0], dict): for i, sol in enumerate(solution): solution[i] = {swap_sym.get(k, k): v.subs(swap_sym) for k, v in sol.items()} # undo the dictionary solutions returned when the system was only partially # solved with poly-system if all symbols are present if ( not flags.get('dict', False) and solution and ordered_symbols and not isinstance(solution, dict) and all(isinstance(sol, dict) for sol in solution) ): solution = [tuple([r.get(s, s) for s in symbols]) for r in solution] # Get assumptions about symbols, to filter solutions. # Note that if assumptions about a solution can't be verified, it is still # returned. check = flags.get('check', True) # restore floats if floats and solution and flags.get('rational', None) is None: solution = nfloat(solution, exponent=False) if check and solution: # assumption checking warn = flags.get('warn', False) got_None = [] # solutions for which one or more symbols gave None no_False = [] # solutions for which no symbols gave False if isinstance(solution, tuple): # this has already been checked and is in as_set form return solution elif isinstance(solution, list): if isinstance(solution[0], tuple): for sol in solution: for symb, val in zip(symbols, sol): test = check_assumptions(val, **symb.assumptions0) if test is False: break if test is None: got_None.append(sol) else: no_False.append(sol) elif isinstance(solution[0], dict): for sol in solution: a_None = False for symb, val in sol.items(): test = check_assumptions(val, **symb.assumptions0) if test: continue if test is False: break a_None = True else: no_False.append(sol) if a_None: got_None.append(sol) else: # list of expressions for sol in solution: test = check_assumptions(sol, **symbols[0].assumptions0) if test is False: continue no_False.append(sol) if test is None: got_None.append(sol) elif isinstance(solution, dict): a_None = False for symb, val in solution.items(): test = check_assumptions(val, **symb.assumptions0) if test: continue if test is False: no_False = None break a_None = True else: no_False = solution if a_None: got_None.append(solution) elif isinstance(solution, (Relational, And, Or)): if len(symbols) != 1: raise ValueError("Length should be 1") if warn and symbols[0].assumptions0: warnings.warn(filldedent(""" \tWarning: assumptions about variable '%s' are not handled currently.""" % symbols[0])) # TODO: check also variable assumptions for inequalities else: raise TypeError('Unrecognized solution') # improve the checker solution = no_False if warn and got_None: warnings.warn(filldedent(""" \tWarning: assumptions concerning following solution(s) cannot be checked:""" + '\n\t' + ', '.join(str(s) for s in got_None))) # # done ########################################################################### as_dict = flags.get('dict', False) as_set = flags.get('set', False) if not as_set and isinstance(solution, list): # Make sure that a list of solutions is ordered in a canonical way. solution.sort(key=default_sort_key) if not as_dict and not as_set: return solution or [] # return a list of mappings or [] if not solution: solution = [] else: if isinstance(solution, dict): solution = [solution] elif iterable(solution[0]): solution = [dict(list(zip(symbols, s))) for s in solution] elif isinstance(solution[0], dict): solution = [{k: s[k] for k in ordered(s)} for s in solution] else: if len(symbols) != 1: raise ValueError("Length should be 1") solution = [{symbols[0]: s} for s in solution] if as_dict: return solution assert as_set # each dict does not necessarily have the same keys so unify them k = list(ordered(set(flatten(tuple(i.keys()) for i in solution)))) return k, {tuple([s.get(ki, ki) for ki in k]) for s in solution} def _solve(f, *symbols, **flags): """ Return a checked solution for *f* in terms of one or more of the symbols. A list should be returned except for the case when a linear undetermined-coefficients equation is encountered (in which case a dictionary is returned). If no method is implemented to solve the equation, a NotImplementedError will be raised. In the case that conversion of an expression to a Poly gives None a ValueError will be raised. """ not_impl_msg = "No algorithms are implemented to solve equation %s" if len(symbols) != 1: soln = None free = f.free_symbols ex = free - set(symbols) if len(ex) != 1: ind, dep = f.as_independent(*symbols) ex = ind.free_symbols & dep.free_symbols if len(ex) == 1: ex = ex.pop() try: # soln may come back as dict, list of dicts or tuples, or # tuple of symbol list and set of solution tuples soln = solve_undetermined_coeffs(f, symbols, ex, **flags) except NotImplementedError: pass if soln: if flags.get('simplify', True): if isinstance(soln, dict): for k in soln: soln[k] = simplify(soln[k]) elif isinstance(soln, list): if isinstance(soln[0], dict): for d in soln: for k in d: d[k] = simplify(d[k]) elif isinstance(soln[0], tuple): soln = [tuple(simplify(i) for i in j) for j in soln] else: raise TypeError('unrecognized args in list') elif isinstance(soln, tuple): sym, sols = soln soln = sym, {tuple(simplify(i) for i in j) for j in sols} else: raise TypeError('unrecognized solution type') return soln # look for solutions for desired symbols that are independent # of symbols already solved for, e.g. if we solve for x = y # then no symbol having x in its solution will be returned. # First solve for linear symbols (since that is easier and limits # solution size) and then proceed with symbols appearing # in a non-linear fashion. Ideally, if one is solving a single # expression for several symbols, they would have to be # appear in factors of an expression, but we do not here # attempt factorization. XXX perhaps handling a Mul # should come first in this routine whether there is # one or several symbols. nonlin_s = [] got_s = set() rhs_s = set() result = [] for s in symbols: xi, v = solve_linear(f, symbols=[s]) if xi == s: # no need to check but we should simplify if desired if flags.get('simplify', True): v = simplify(v) vfree = v.free_symbols if vfree & got_s: # was linear, but has redundant relationship # e.g. x - y = 0 has y == x is redundant for x == y # so ignore continue rhs_s |= vfree got_s.add(xi) result.append({xi: v}) elif xi: # there might be a non-linear solution if xi is not 0 nonlin_s.append(s) if not nonlin_s: return result for s in nonlin_s: try: soln = _solve(f, s, **flags) for sol in soln: if sol.free_symbols & got_s: # depends on previously solved symbols: ignore continue got_s.add(s) result.append({s: sol}) except NotImplementedError: continue if got_s: return result else: raise NotImplementedError(not_impl_msg % f) # solve f for a single variable symbol = symbols[0] # expand binomials only if it has the unknown symbol f = f.replace(lambda e: isinstance(e, binomial) and e.has(symbol), lambda e: expand_func(e)) # checking will be done unless it is turned off before making a # recursive call; the variables `checkdens` and `check` are # captured here (for reference below) in case flag value changes flags['check'] = checkdens = check = flags.pop('check', True) # build up solutions if f is a Mul if f.is_Mul: result = set() for m in f.args: if m in {S.NegativeInfinity, S.ComplexInfinity, S.Infinity}: result = set() break soln = _solve(m, symbol, **flags) result.update(set(soln)) result = list(result) if check: # all solutions have been checked but now we must # check that the solutions do not set denominators # in any factor to zero dens = flags.get('_denominators', _simple_dens(f, symbols)) result = [s for s in result if not any(checksol(den, {symbol: s}, **flags) for den in dens)] # set flags for quick exit at end; solutions for each # factor were already checked and simplified check = False flags['simplify'] = False elif f.is_Piecewise: result = set() for i, (expr, cond) in enumerate(f.args): if expr.is_zero: raise NotImplementedError( 'solve cannot represent interval solutions') candidates = _solve(expr, symbol, **flags) # the explicit condition for this expr is the current cond # and none of the previous conditions args = [~c for _, c in f.args[:i]] + [cond] cond = And(*args) for candidate in candidates: if candidate in result: # an unconditional value was already there continue try: v = cond.subs(symbol, candidate) _eval_simplify = getattr(v, '_eval_simplify', None) if _eval_simplify is not None: # unconditionally take the simpification of v v = _eval_simplify(ratio=2, measure=lambda x: 1) except TypeError: # incompatible type with condition(s) continue if v == False: continue if v == True: result.add(candidate) else: result.add(Piecewise( (candidate, v), (S.NaN, True))) # set flags for quick exit at end; solutions for each # piece were already checked and simplified check = False flags['simplify'] = False else: # first see if it really depends on symbol and whether there # is only a linear solution f_num, sol = solve_linear(f, symbols=symbols) if f_num.is_zero or sol is S.NaN: return [] elif f_num.is_Symbol: # no need to check but simplify if desired if flags.get('simplify', True): sol = simplify(sol) return [sol] poly = None # check for a single Add generator if not f_num.is_Add: add_args = [i for i in f_num.atoms(Add) if symbol in i.free_symbols] if len(add_args) == 1: gen = add_args[0] spart = gen.as_independent(symbol)[1].as_base_exp()[0] if spart == symbol: try: poly = Poly(f_num, spart) except PolynomialError: pass result = False # no solution was obtained msg = '' # there is no failure message # Poly is generally robust enough to convert anything to # a polynomial and tell us the different generators that it # contains, so we will inspect the generators identified by # polys to figure out what to do. # try to identify a single generator that will allow us to solve this # as a polynomial, followed (perhaps) by a change of variables if the # generator is not a symbol try: if poly is None: poly = Poly(f_num) if poly is None: raise ValueError('could not convert %s to Poly' % f_num) except GeneratorsNeeded: simplified_f = simplify(f_num) if simplified_f != f_num: return _solve(simplified_f, symbol, **flags) raise ValueError('expression appears to be a constant') gens = [g for g in poly.gens if g.has(symbol)] def _as_base_q(x): """Return (b**e, q) for x = b**(p*e/q) where p/q is the leading Rational of the exponent of x, e.g. exp(-2*x/3) -> (exp(x), 3) """ b, e = x.as_base_exp() if e.is_Rational: return b, e.q if not e.is_Mul: return x, 1 c, ee = e.as_coeff_Mul() if c.is_Rational and c is not S.One: # c could be a Float return b**ee, c.q return x, 1 if len(gens) > 1: # If there is more than one generator, it could be that the # generators have the same base but different powers, e.g. # >>> Poly(exp(x) + 1/exp(x)) # Poly(exp(-x) + exp(x), exp(-x), exp(x), domain='ZZ') # # If unrad was not disabled then there should be no rational # exponents appearing as in # >>> Poly(sqrt(x) + sqrt(sqrt(x))) # Poly(sqrt(x) + x**(1/4), sqrt(x), x**(1/4), domain='ZZ') bases, qs = list(zip(*[_as_base_q(g) for g in gens])) bases = set(bases) if len(bases) > 1 or not all(q == 1 for q in qs): funcs = {b for b in bases if b.is_Function} trig = {_ for _ in funcs if isinstance(_, TrigonometricFunction)} other = funcs - trig if not other and len(funcs.intersection(trig)) > 1: newf = None if f_num.is_Add and len(f_num.args) == 2: # check for sin(x)**p = cos(x)**p _args = f_num.args t = a, b = [i.atoms(Function).intersection( trig) for i in _args] if all(len(i) == 1 for i in t): a, b = [i.pop() for i in t] if isinstance(a, cos): a, b = b, a _args = _args[::-1] if isinstance(a, sin) and isinstance(b, cos ) and a.args[0] == b.args[0]: # sin(x) + cos(x) = 0 -> tan(x) + 1 = 0 newf, _d = (TR2i(_args[0]/_args[1]) + 1 ).as_numer_denom() if not _d.is_Number: newf = None if newf is None: newf = TR1(f_num).rewrite(tan) if newf != f_num: # don't check the rewritten form --check # solutions in the un-rewritten form below flags['check'] = False result = _solve(newf, symbol, **flags) flags['check'] = check # just a simple case - see if replacement of single function # clears all symbol-dependent functions, e.g. # log(x) - log(log(x) - 1) - 3 can be solved even though it has # two generators. if result is False and funcs: funcs = list(ordered(funcs)) # put shallowest function first f1 = funcs[0] t = Dummy('t') # perform the substitution ftry = f_num.subs(f1, t) # if no Functions left, we can proceed with usual solve if not ftry.has(symbol): cv_sols = _solve(ftry, t, **flags) cv_inv = _solve(t - f1, symbol, **flags)[0] sols = list() for sol in cv_sols: sols.append(cv_inv.subs(t, sol)) result = list(ordered(sols)) if result is False: msg = 'multiple generators %s' % gens else: # e.g. case where gens are exp(x), exp(-x) u = bases.pop() t = Dummy('t') inv = _solve(u - t, symbol, **flags) if isinstance(u, (Pow, exp)): # this will be resolved by factor in _tsolve but we might # as well try a simple expansion here to get things in # order so something like the following will work now without # having to factor: # # >>> eq = (exp(I*(-x-2))+exp(I*(x+2))) # >>> eq.subs(exp(x),y) # fails # exp(I*(-x - 2)) + exp(I*(x + 2)) # >>> eq.expand().subs(exp(x),y) # works # y**I*exp(2*I) + y**(-I)*exp(-2*I) def _expand(p): b, e = p.as_base_exp() e = expand_mul(e) return expand_power_exp(b**e) ftry = f_num.replace( lambda w: w.is_Pow or isinstance(w, exp), _expand).subs(u, t) if not ftry.has(symbol): soln = _solve(ftry, t, **flags) sols = list() for sol in soln: for i in inv: sols.append(i.subs(t, sol)) result = list(ordered(sols)) elif len(gens) == 1: # There is only one generator that we are interested in, but # there may have been more than one generator identified by # polys (e.g. for symbols other than the one we are interested # in) so recast the poly in terms of our generator of interest. # Also use composite=True with f_num since Poly won't update # poly as documented in issue 8810. poly = Poly(f_num, gens[0], composite=True) # if we aren't on the tsolve-pass, use roots if not flags.pop('tsolve', False): soln = None deg = poly.degree() flags['tsolve'] = True hints = ('cubics', 'quartics', 'quintics') solvers = {h: flags.get(h) for h in hints} soln = roots(poly, **solvers) if sum(soln.values()) < deg: # e.g. roots(32*x**5 + 400*x**4 + 2032*x**3 + # 5000*x**2 + 6250*x + 3189) -> {} # so all_roots is used and RootOf instances are # returned *unless* the system is multivariate # or high-order EX domain. try: soln = poly.all_roots() except NotImplementedError: if not flags.get('incomplete', True): raise NotImplementedError( filldedent(''' Neither high-order multivariate polynomials nor sorting of EX-domain polynomials is supported. If you want to see any results, pass keyword incomplete=True to solve; to see numerical values of roots for univariate expressions, use nroots. ''')) else: pass else: soln = list(soln.keys()) if soln is not None: u = poly.gen if u != symbol: try: t = Dummy('t') iv = _solve(u - t, symbol, **flags) soln = list(ordered({i.subs(t, s) for i in iv for s in soln})) except NotImplementedError: # perhaps _tsolve can handle f_num soln = None else: check = False # only dens need to be checked if soln is not None: if len(soln) > 2: # if the flag wasn't set then unset it since high-order # results are quite long. Perhaps one could base this # decision on a certain critical length of the # roots. In addition, wester test M2 has an expression # whose roots can be shown to be real with the # unsimplified form of the solution whereas only one of # the simplified forms appears to be real. flags['simplify'] = flags.get('simplify', False) result = soln # fallback if above fails # ----------------------- if result is False: # try unrad if flags.pop('_unrad', True): try: u = unrad(f_num, symbol) except (ValueError, NotImplementedError): u = False if u: eq, cov = u if cov: isym, ieq = cov inv = _solve(ieq, symbol, **flags)[0] rv = {inv.subs(isym, xi) for xi in _solve(eq, isym, **flags)} else: try: rv = set(_solve(eq, symbol, **flags)) except NotImplementedError: rv = None if rv is not None: result = list(ordered(rv)) # if the flag wasn't set then unset it since unrad results # can be quite long or of very high order flags['simplify'] = flags.get('simplify', False) else: pass # for coverage # try _tsolve if result is False: flags.pop('tsolve', None) # allow tsolve to be used on next pass try: soln = _tsolve(f_num, symbol, **flags) if soln is not None: result = soln except PolynomialError: pass # ----------- end of fallback ---------------------------- if result is False: raise NotImplementedError('\n'.join([msg, not_impl_msg % f])) if flags.get('simplify', True): result = list(map(simplify, result)) # we just simplified the solution so we now set the flag to # False so the simplification doesn't happen again in checksol() flags['simplify'] = False if checkdens: # reject any result that makes any denom. affirmatively 0; # if in doubt, keep it dens = _simple_dens(f, symbols) result = [s for s in result if not any(checksol(d, {symbol: s}, **flags) for d in dens)] if check: # keep only results if the check is not False result = [r for r in result if checksol(f_num, {symbol: r}, **flags) is not False] return result def _solve_system(exprs, symbols, **flags): if not exprs: return [] if flags.pop('_split', True): # Split the system into connected components V = exprs symsset = set(symbols) exprsyms = {e: e.free_symbols & symsset for e in exprs} E = [] sym_indices = {sym: i for i, sym in enumerate(symbols)} for n, e1 in enumerate(exprs): for e2 in exprs[:n]: # Equations are connected if they share a symbol if exprsyms[e1] & exprsyms[e2]: E.append((e1, e2)) G = V, E subexprs = connected_components(G) if len(subexprs) > 1: subsols = [] for subexpr in subexprs: subsyms = set() for e in subexpr: subsyms |= exprsyms[e] subsyms = list(sorted(subsyms, key = lambda x: sym_indices[x])) flags['_split'] = False # skip split step subsol = _solve_system(subexpr, subsyms, **flags) if not isinstance(subsol, list): subsol = [subsol] subsols.append(subsol) # Full solution is cartesion product of subsystems sols = [] for soldicts in product(*subsols): sols.append(dict(item for sd in soldicts for item in sd.items())) # Return a list with one dict as just the dict if len(sols) == 1: return sols[0] return sols polys = [] dens = set() failed = [] result = False linear = False manual = flags.get('manual', False) checkdens = check = flags.get('check', True) for j, g in enumerate(exprs): dens.update(_simple_dens(g, symbols)) i, d = _invert(g, *symbols) g = d - i g = g.as_numer_denom()[0] if manual: failed.append(g) continue poly = g.as_poly(*symbols, extension=True) if poly is not None: polys.append(poly) else: failed.append(g) if not polys: solved_syms = [] else: if all(p.is_linear for p in polys): n, m = len(polys), len(symbols) matrix = zeros(n, m + 1) for i, poly in enumerate(polys): for monom, coeff in poly.terms(): try: j = monom.index(1) matrix[i, j] = coeff except ValueError: matrix[i, m] = -coeff # returns a dictionary ({symbols: values}) or None if flags.pop('particular', False): result = minsolve_linear_system(matrix, *symbols, **flags) else: result = solve_linear_system(matrix, *symbols, **flags) if failed: if result: solved_syms = list(result.keys()) else: solved_syms = [] else: linear = True else: if len(symbols) > len(polys): free = set().union(*[p.free_symbols for p in polys]) free = list(ordered(free.intersection(symbols))) got_s = set() result = [] for syms in subsets(free, len(polys)): try: # returns [] or list of tuples of solutions for syms res = solve_poly_system(polys, *syms) if res: for r in res: skip = False for r1 in r: if got_s and any(ss in r1.free_symbols for ss in got_s): # sol depends on previously # solved symbols: discard it skip = True if not skip: got_s.update(syms) result.extend([dict(list(zip(syms, r)))]) except NotImplementedError: pass if got_s: solved_syms = list(got_s) else: raise NotImplementedError('no valid subset found') else: try: result = solve_poly_system(polys, *symbols) if result: solved_syms = symbols # we don't know here if the symbols provided # were given or not, so let solve resolve that. # A list of dictionaries is going to always be # returned from here. result = [dict(list(zip(solved_syms, r))) for r in result] except NotImplementedError: failed.extend([g.as_expr() for g in polys]) solved_syms = [] result = None if result: if isinstance(result, dict): result = [result] else: result = [{}] if failed: # For each failed equation, see if we can solve for one of the # remaining symbols from that equation. If so, we update the # solution set and continue with the next failed equation, # repeating until we are done or we get an equation that can't # be solved. def _ok_syms(e, sort=False): rv = e.free_symbols & legal # Solve first for symbols that have lower degree in the equation. # Ideally we want to solve firstly for symbols that appear linearly # with rational coefficients e.g. if e = x*y + z then we should # solve for z first. def key(sym): ep = e.as_poly(sym) if ep is None: complexity = (S.Infinity, S.Infinity, S.Infinity) else: coeff_syms = ep.LC().free_symbols complexity = (ep.degree(), len(coeff_syms & rv), len(coeff_syms)) return complexity + (default_sort_key(sym),) if sort: rv = sorted(rv, key=key) return rv legal = set(symbols) # what we are interested in # sort so equation with the fewest potential symbols is first u = Dummy() # used in solution checking for eq in ordered(failed, lambda _: len(_ok_syms(_))): newresult = [] bad_results = [] got_s = set() hit = False for r in result: # update eq with everything that is known so far eq2 = eq.subs(r) # if check is True then we see if it satisfies this # equation, otherwise we just accept it if check and r: b = checksol(u, u, eq2, minimal=True) if b is not None: # this solution is sufficient to know whether # it is valid or not so we either accept or # reject it, then continue if b: newresult.append(r) else: bad_results.append(r) continue # search for a symbol amongst those available that # can be solved for ok_syms = _ok_syms(eq2, sort=True) if not ok_syms: if r: newresult.append(r) break # skip as it's independent of desired symbols for s in ok_syms: try: soln = _solve(eq2, s, **flags) except NotImplementedError: continue # put each solution in r and append the now-expanded # result in the new result list; use copy since the # solution for s is being added in-place for sol in soln: if got_s and any(ss in sol.free_symbols for ss in got_s): # sol depends on previously solved symbols: discard it continue rnew = r.copy() for k, v in r.items(): rnew[k] = v.subs(s, sol) # and add this new solution rnew[s] = sol # check that it is independent of previous solutions iset = set(rnew.items()) for i in newresult: if len(i) < len(iset) and not set(i.items()) - iset: # this is a superset of a known solution that # is smaller break else: # keep it newresult.append(rnew) hit = True got_s.add(s) if not hit: raise NotImplementedError('could not solve %s' % eq2) else: result = newresult for b in bad_results: if b in result: result.remove(b) default_simplify = bool(failed) # rely on system-solvers to simplify if flags.get('simplify', default_simplify): for r in result: for k in r: r[k] = simplify(r[k]) flags['simplify'] = False # don't need to do so in checksol now if checkdens: result = [r for r in result if not any(checksol(d, r, **flags) for d in dens)] if check and not linear: result = [r for r in result if not any(checksol(e, r, **flags) is False for e in exprs)] result = [r for r in result if r] if linear and result: result = result[0] return result def solve_linear(lhs, rhs=0, symbols=[], exclude=[]): r""" Return a tuple derived from ``f = lhs - rhs`` that is one of the following: ``(0, 1)``, ``(0, 0)``, ``(symbol, solution)``, ``(n, d)``. Explanation =========== ``(0, 1)`` meaning that ``f`` is independent of the symbols in *symbols* that are not in *exclude*. ``(0, 0)`` meaning that there is no solution to the equation amongst the symbols given. If the first element of the tuple is not zero, then the function is guaranteed to be dependent on a symbol in *symbols*. ``(symbol, solution)`` where symbol appears linearly in the numerator of ``f``, is in *symbols* (if given), and is not in *exclude* (if given). No simplification is done to ``f`` other than a ``mul=True`` expansion, so the solution will correspond strictly to a unique solution. ``(n, d)`` where ``n`` and ``d`` are the numerator and denominator of ``f`` when the numerator was not linear in any symbol of interest; ``n`` will never be a symbol unless a solution for that symbol was found (in which case the second element is the solution, not the denominator). Examples ======== >>> from sympy import cancel, Pow ``f`` is independent of the symbols in *symbols* that are not in *exclude*: >>> from sympy import cos, sin, solve_linear >>> from sympy.abc import x, y, z >>> eq = y*cos(x)**2 + y*sin(x)**2 - y # = y*(1 - 1) = 0 >>> solve_linear(eq) (0, 1) >>> eq = cos(x)**2 + sin(x)**2 # = 1 >>> solve_linear(eq) (0, 1) >>> solve_linear(x, exclude=[x]) (0, 1) The variable ``x`` appears as a linear variable in each of the following: >>> solve_linear(x + y**2) (x, -y**2) >>> solve_linear(1/x - y**2) (x, y**(-2)) When not linear in ``x`` or ``y`` then the numerator and denominator are returned: >>> solve_linear(x**2/y**2 - 3) (x**2 - 3*y**2, y**2) If the numerator of the expression is a symbol, then ``(0, 0)`` is returned if the solution for that symbol would have set any denominator to 0: >>> eq = 1/(1/x - 2) >>> eq.as_numer_denom() (x, 1 - 2*x) >>> solve_linear(eq) (0, 0) But automatic rewriting may cause a symbol in the denominator to appear in the numerator so a solution will be returned: >>> (1/x)**-1 x >>> solve_linear((1/x)**-1) (x, 0) Use an unevaluated expression to avoid this: >>> solve_linear(Pow(1/x, -1, evaluate=False)) (0, 0) If ``x`` is allowed to cancel in the following expression, then it appears to be linear in ``x``, but this sort of cancellation is not done by ``solve_linear`` so the solution will always satisfy the original expression without causing a division by zero error. >>> eq = x**2*(1/x - z**2/x) >>> solve_linear(cancel(eq)) (x, 0) >>> solve_linear(eq) (x**2*(1 - z**2), x) A list of symbols for which a solution is desired may be given: >>> solve_linear(x + y + z, symbols=[y]) (y, -x - z) A list of symbols to ignore may also be given: >>> solve_linear(x + y + z, exclude=[x]) (y, -x - z) (A solution for ``y`` is obtained because it is the first variable from the canonically sorted list of symbols that had a linear solution.) """ if isinstance(lhs, Eq): if rhs: raise ValueError(filldedent(''' If lhs is an Equality, rhs must be 0 but was %s''' % rhs)) rhs = lhs.rhs lhs = lhs.lhs dens = None eq = lhs - rhs n, d = eq.as_numer_denom() if not n: return S.Zero, S.One free = n.free_symbols if not symbols: symbols = free else: bad = [s for s in symbols if not s.is_Symbol] if bad: if len(bad) == 1: bad = bad[0] if len(symbols) == 1: eg = 'solve(%s, %s)' % (eq, symbols[0]) else: eg = 'solve(%s, *%s)' % (eq, list(symbols)) raise ValueError(filldedent(''' solve_linear only handles symbols, not %s. To isolate non-symbols use solve, e.g. >>> %s <<<. ''' % (bad, eg))) symbols = free.intersection(symbols) symbols = symbols.difference(exclude) if not symbols: return S.Zero, S.One # derivatives are easy to do but tricky to analyze to see if they # are going to disallow a linear solution, so for simplicity we # just evaluate the ones that have the symbols of interest derivs = defaultdict(list) for der in n.atoms(Derivative): csym = der.free_symbols & symbols for c in csym: derivs[c].append(der) all_zero = True for xi in sorted(symbols, key=default_sort_key): # canonical order # if there are derivatives in this var, calculate them now if isinstance(derivs[xi], list): derivs[xi] = {der: der.doit() for der in derivs[xi]} newn = n.subs(derivs[xi]) dnewn_dxi = newn.diff(xi) # dnewn_dxi can be nonzero if it survives differentation by any # of its free symbols free = dnewn_dxi.free_symbols if dnewn_dxi and (not free or any(dnewn_dxi.diff(s) for s in free) or free == symbols): all_zero = False if dnewn_dxi is S.NaN: break if xi not in dnewn_dxi.free_symbols: vi = -1/dnewn_dxi*(newn.subs(xi, 0)) if dens is None: dens = _simple_dens(eq, symbols) if not any(checksol(di, {xi: vi}, minimal=True) is True for di in dens): # simplify any trivial integral irep = [(i, i.doit()) for i in vi.atoms(Integral) if i.function.is_number] # do a slight bit of simplification vi = expand_mul(vi.subs(irep)) return xi, vi if all_zero: return S.Zero, S.One if n.is_Symbol: # no solution for this symbol was found return S.Zero, S.Zero return n, d def minsolve_linear_system(system, *symbols, **flags): r""" Find a particular solution to a linear system. Explanation =========== In particular, try to find a solution with the minimal possible number of non-zero variables using a naive algorithm with exponential complexity. If ``quick=True``, a heuristic is used. """ quick = flags.get('quick', False) # Check if there are any non-zero solutions at all s0 = solve_linear_system(system, *symbols, **flags) if not s0 or all(v == 0 for v in s0.values()): return s0 if quick: # We just solve the system and try to heuristically find a nice # solution. s = solve_linear_system(system, *symbols) def update(determined, solution): delete = [] for k, v in solution.items(): solution[k] = v.subs(determined) if not solution[k].free_symbols: delete.append(k) determined[k] = solution[k] for k in delete: del solution[k] determined = {} update(determined, s) while s: # NOTE sort by default_sort_key to get deterministic result k = max((k for k in s.values()), key=lambda x: (len(x.free_symbols), default_sort_key(x))) kfree = k.free_symbols x = next(reversed(list(ordered(kfree)))) if len(kfree) != 1: determined[x] = S.Zero else: val = _solve(k, x, check=False)[0] if val == 0 and all(v.subs(x, val) == 0 for v in s.values()): determined[x] = S.One else: determined[x] = val update(determined, s) return determined else: # We try to select n variables which we want to be non-zero. # All others will be assumed zero. We try to solve the modified system. # If there is a non-trivial solution, just set the free variables to # one. If we do this for increasing n, trying all combinations of # variables, we will find an optimal solution. # We speed up slightly by starting at one less than the number of # variables the quick method manages. N = len(symbols) bestsol = minsolve_linear_system(system, *symbols, quick=True) n0 = len([x for x in bestsol.values() if x != 0]) for n in range(n0 - 1, 1, -1): debug('minsolve: %s' % n) thissol = None for nonzeros in combinations(list(range(N)), n): subm = Matrix([system.col(i).T for i in nonzeros] + [system.col(-1).T]).T s = solve_linear_system(subm, *[symbols[i] for i in nonzeros]) if s and not all(v == 0 for v in s.values()): subs = [(symbols[v], S.One) for v in nonzeros] for k, v in s.items(): s[k] = v.subs(subs) for sym in symbols: if sym not in s: if symbols.index(sym) in nonzeros: s[sym] = S.One else: s[sym] = S.Zero thissol = s break if thissol is None: break bestsol = thissol return bestsol def solve_linear_system(system, *symbols, **flags): r""" Solve system of $N$ linear equations with $M$ variables, which means both under- and overdetermined systems are supported. Explanation =========== The possible number of solutions is zero, one, or infinite. Respectively, this procedure will return None or a dictionary with solutions. In the case of underdetermined systems, all arbitrary parameters are skipped. This may cause a situation in which an empty dictionary is returned. In that case, all symbols can be assigned arbitrary values. Input to this function is a $N\times M + 1$ matrix, which means it has to be in augmented form. If you prefer to enter $N$ equations and $M$ unknowns then use ``solve(Neqs, *Msymbols)`` instead. Note: a local copy of the matrix is made by this routine so the matrix that is passed will not be modified. The algorithm used here is fraction-free Gaussian elimination, which results, after elimination, in an upper-triangular matrix. Then solutions are found using back-substitution. This approach is more efficient and compact than the Gauss-Jordan method. Examples ======== >>> from sympy import Matrix, solve_linear_system >>> from sympy.abc import x, y Solve the following system:: x + 4 y == 2 -2 x + y == 14 >>> system = Matrix(( (1, 4, 2), (-2, 1, 14))) >>> solve_linear_system(system, x, y) {x: -6, y: 2} A degenerate system returns an empty dictionary: >>> system = Matrix(( (0,0,0), (0,0,0) )) >>> solve_linear_system(system, x, y) {} """ assert system.shape[1] == len(symbols) + 1 # This is just a wrapper for solve_lin_sys eqs = list(system * Matrix(symbols + (-1,))) eqs, ring = sympy_eqs_to_ring(eqs, symbols) sol = solve_lin_sys(eqs, ring, _raw=False) if sol is not None: sol = {sym:val for sym, val in sol.items() if sym != val} return sol def solve_undetermined_coeffs(equ, coeffs, sym, **flags): r""" Solve equation of a type $p(x; a_1, \ldots, a_k) = q(x)$ where both $p$ and $q$ are univariate polynomials that depend on $k$ parameters. Explanation =========== The result of this function is a dictionary with symbolic values of those parameters with respect to coefficients in $q$. This function accepts both equations class instances and ordinary SymPy expressions. Specification of parameters and variables is obligatory for efficiency and simplicity reasons. Examples ======== >>> from sympy import Eq, solve_undetermined_coeffs >>> from sympy.abc import a, b, c, x >>> solve_undetermined_coeffs(Eq(2*a*x + a+b, x), [a, b], x) {a: 1/2, b: -1/2} >>> solve_undetermined_coeffs(Eq(a*c*x + a+b, x), [a, b], x) {a: 1/c, b: -1/c} """ if isinstance(equ, Eq): # got equation, so move all the # terms to the left hand side equ = equ.lhs - equ.rhs equ = cancel(equ).as_numer_denom()[0] system = list(collect(equ.expand(), sym, evaluate=False).values()) if not any(equ.has(sym) for equ in system): # consecutive powers in the input expressions have # been successfully collected, so solve remaining # system using Gaussian elimination algorithm return solve(system, *coeffs, **flags) else: return None # no solutions def solve_linear_system_LU(matrix, syms): """ Solves the augmented matrix system using ``LUsolve`` and returns a dictionary in which solutions are keyed to the symbols of *syms* as ordered. Explanation =========== The matrix must be invertible. Examples ======== >>> from sympy import Matrix, solve_linear_system_LU >>> from sympy.abc import x, y, z >>> solve_linear_system_LU(Matrix([ ... [1, 2, 0, 1], ... [3, 2, 2, 1], ... [2, 0, 0, 1]]), [x, y, z]) {x: 1/2, y: 1/4, z: -1/2} See Also ======== LUsolve """ if matrix.rows != matrix.cols - 1: raise ValueError("Rows should be equal to columns - 1") A = matrix[:matrix.rows, :matrix.rows] b = matrix[:, matrix.cols - 1:] soln = A.LUsolve(b) solutions = {} for i in range(soln.rows): solutions[syms[i]] = soln[i, 0] return solutions def det_perm(M): """ Return the determinant of *M* by using permutations to select factors. Explanation =========== For sizes larger than 8 the number of permutations becomes prohibitively large, or if there are no symbols in the matrix, it is better to use the standard determinant routines (e.g., ``M.det()``.) See Also ======== det_minor det_quick """ args = [] s = True n = M.rows list_ = M.flat() for perm in generate_bell(n): fac = [] idx = 0 for j in perm: fac.append(list_[idx + j]) idx += n term = Mul(*fac) # disaster with unevaluated Mul -- takes forever for n=7 args.append(term if s else -term) s = not s return Add(*args) def det_minor(M): """ Return the ``det(M)`` computed from minors without introducing new nesting in products. See Also ======== det_perm det_quick """ n = M.rows if n == 2: return M[0, 0]*M[1, 1] - M[1, 0]*M[0, 1] else: return sum([(1, -1)[i % 2]*Add(*[M[0, i]*d for d in Add.make_args(det_minor(M.minor_submatrix(0, i)))]) if M[0, i] else S.Zero for i in range(n)]) def det_quick(M, method=None): """ Return ``det(M)`` assuming that either there are lots of zeros or the size of the matrix is small. If this assumption is not met, then the normal Matrix.det function will be used with method = ``method``. See Also ======== det_minor det_perm """ if any(i.has(Symbol) for i in M): if M.rows < 8 and all(i.has(Symbol) for i in M): return det_perm(M) return det_minor(M) else: return M.det(method=method) if method else M.det() def inv_quick(M): """Return the inverse of ``M``, assuming that either there are lots of zeros or the size of the matrix is small. """ if not all(i.is_Number for i in M): if not any(i.is_Number for i in M): det = lambda _: det_perm(_) else: det = lambda _: det_minor(_) else: return M.inv() n = M.rows d = det(M) if d == S.Zero: raise NonInvertibleMatrixError("Matrix det == 0; not invertible") ret = zeros(n) s1 = -1 for i in range(n): s = s1 = -s1 for j in range(n): di = det(M.minor_submatrix(i, j)) ret[j, i] = s*di/d s = -s return ret # these are functions that have multiple inverse values per period multi_inverses = { sin: lambda x: (asin(x), S.Pi - asin(x)), cos: lambda x: (acos(x), 2*S.Pi - acos(x)), } def _tsolve(eq, sym, **flags): """ Helper for ``_solve`` that solves a transcendental equation with respect to the given symbol. Various equations containing powers and logarithms, can be solved. There is currently no guarantee that all solutions will be returned or that a real solution will be favored over a complex one. Either a list of potential solutions will be returned or None will be returned (in the case that no method was known to get a solution for the equation). All other errors (like the inability to cast an expression as a Poly) are unhandled. Examples ======== >>> from sympy import log >>> from sympy.solvers.solvers import _tsolve as tsolve >>> from sympy.abc import x >>> tsolve(3**(2*x + 5) - 4, x) [-5/2 + log(2)/log(3), (-5*log(3)/2 + log(2) + I*pi)/log(3)] >>> tsolve(log(x) + 2*x, x) [LambertW(2)/2] """ if 'tsolve_saw' not in flags: flags['tsolve_saw'] = [] if eq in flags['tsolve_saw']: return None else: flags['tsolve_saw'].append(eq) rhs, lhs = _invert(eq, sym) if lhs == sym: return [rhs] try: if lhs.is_Add: # it's time to try factoring; powdenest is used # to try get powers in standard form for better factoring f = factor(powdenest(lhs - rhs)) if f.is_Mul: return _solve(f, sym, **flags) if rhs: f = logcombine(lhs, force=flags.get('force', True)) if f.count(log) != lhs.count(log): if isinstance(f, log): return _solve(f.args[0] - exp(rhs), sym, **flags) return _tsolve(f - rhs, sym, **flags) elif lhs.is_Pow: if lhs.exp.is_Integer: if lhs - rhs != eq: return _solve(lhs - rhs, sym, **flags) if sym not in lhs.exp.free_symbols: return _solve(lhs.base - rhs**(1/lhs.exp), sym, **flags) # _tsolve calls this with Dummy before passing the actual number in. if any(t.is_Dummy for t in rhs.free_symbols): raise NotImplementedError # _tsolve will call here again... # a ** g(x) == 0 if not rhs: # f(x)**g(x) only has solutions where f(x) == 0 and g(x) != 0 at # the same place sol_base = _solve(lhs.base, sym, **flags) return [s for s in sol_base if lhs.exp.subs(sym, s) != 0] # a ** g(x) == b if not lhs.base.has(sym): if lhs.base == 0: return _solve(lhs.exp, sym, **flags) if rhs != 0 else [] # Gets most solutions... if lhs.base == rhs.as_base_exp()[0]: # handles case when bases are equal sol = _solve(lhs.exp - rhs.as_base_exp()[1], sym, **flags) else: # handles cases when bases are not equal and exp # may or may not be equal sol = _solve(exp(log(lhs.base)*lhs.exp)-exp(log(rhs)), sym, **flags) # Check for duplicate solutions def equal(expr1, expr2): _ = Dummy() eq = checksol(expr1 - _, _, expr2) if eq is None: if nsimplify(expr1) != nsimplify(expr2): return False # they might be coincidentally the same # so check more rigorously eq = expr1.equals(expr2) return eq # Guess a rational exponent e_rat = nsimplify(log(abs(rhs))/log(abs(lhs.base))) e_rat = simplify(posify(e_rat)[0]) n, d = fraction(e_rat) if expand(lhs.base**n - rhs**d) == 0: sol = [s for s in sol if not equal(lhs.exp.subs(sym, s), e_rat)] sol.extend(_solve(lhs.exp - e_rat, sym, **flags)) return list(ordered(set(sol))) # f(x) ** g(x) == c else: sol = [] logform = lhs.exp*log(lhs.base) - log(rhs) if logform != lhs - rhs: try: sol.extend(_solve(logform, sym, **flags)) except NotImplementedError: pass # Collect possible solutions and check with substitution later. check = [] if rhs == 1: # f(x) ** g(x) = 1 -- g(x)=0 or f(x)=+-1 check.extend(_solve(lhs.exp, sym, **flags)) check.extend(_solve(lhs.base - 1, sym, **flags)) check.extend(_solve(lhs.base + 1, sym, **flags)) elif rhs.is_Rational: for d in (i for i in divisors(abs(rhs.p)) if i != 1): e, t = integer_log(rhs.p, d) if not t: continue # rhs.p != d**b for s in divisors(abs(rhs.q)): if s**e== rhs.q: r = Rational(d, s) check.extend(_solve(lhs.base - r, sym, **flags)) check.extend(_solve(lhs.base + r, sym, **flags)) check.extend(_solve(lhs.exp - e, sym, **flags)) elif rhs.is_irrational: b_l, e_l = lhs.base.as_base_exp() n, d = (e_l*lhs.exp).as_numer_denom() b, e = sqrtdenest(rhs).as_base_exp() check = [sqrtdenest(i) for i in (_solve(lhs.base - b, sym, **flags))] check.extend([sqrtdenest(i) for i in (_solve(lhs.exp - e, sym, **flags))]) if e_l*d != 1: check.extend(_solve(b_l**n - rhs**(e_l*d), sym, **flags)) for s in check: ok = checksol(eq, sym, s) if ok is None: ok = eq.subs(sym, s).equals(0) if ok: sol.append(s) return list(ordered(set(sol))) elif lhs.is_Function and len(lhs.args) == 1: if lhs.func in multi_inverses: # sin(x) = 1/3 -> x - asin(1/3) & x - (pi - asin(1/3)) soln = [] for i in multi_inverses[type(lhs)](rhs): soln.extend(_solve(lhs.args[0] - i, sym, **flags)) return list(ordered(soln)) elif lhs.func == LambertW: return _solve(lhs.args[0] - rhs*exp(rhs), sym, **flags) rewrite = lhs.rewrite(exp) if rewrite != lhs: return _solve(rewrite - rhs, sym, **flags) except NotImplementedError: pass # maybe it is a lambert pattern if flags.pop('bivariate', True): # lambert forms may need some help being recognized, e.g. changing # 2**(3*x) + x**3*log(2)**3 + 3*x**2*log(2)**2 + 3*x*log(2) + 1 # to 2**(3*x) + (x*log(2) + 1)**3 # make generator in log have exponent of 1 logs = eq.atoms(log) spow = min( {i.exp for j in logs for i in j.atoms(Pow) if i.base == sym} or {1}) if spow != 1: p = sym**spow u = Dummy('bivariate-cov') ueq = eq.subs(p, u) if not ueq.has_free(sym): sol = solve(ueq, u, **flags) inv = solve(p - u, sym) rv = [] for i in inv: rv.extend([i.subs(u, s) for s in sol]) return rv g = _filtered_gens(eq.as_poly(), sym) up_or_log = set() for gi in g: if isinstance(gi, (exp, log)) or (gi.is_Pow and gi.base == S.Exp1): up_or_log.add(gi) elif gi.is_Pow: gisimp = powdenest(expand_power_exp(gi)) if gisimp.is_Pow and sym in gisimp.exp.free_symbols: up_or_log.add(gi) eq_down = expand_log(expand_power_exp(eq)).subs( dict(list(zip(up_or_log, [0]*len(up_or_log))))) eq = expand_power_exp(factor(eq_down, deep=True) + (eq - eq_down)) rhs, lhs = _invert(eq, sym) if lhs.has(sym): try: poly = lhs.as_poly() g = _filtered_gens(poly, sym) _eq = lhs - rhs sols = _solve_lambert(_eq, sym, g) # use a simplified form if it satisfies eq # and has fewer operations for n, s in enumerate(sols): ns = nsimplify(s) if ns != s and ns.count_ops() <= s.count_ops(): ok = checksol(_eq, sym, ns) if ok is None: ok = _eq.subs(sym, ns).equals(0) if ok: sols[n] = ns return sols except NotImplementedError: # maybe it's a convoluted function if len(g) == 2: try: gpu = bivariate_type(lhs - rhs, *g) if gpu is None: raise NotImplementedError g, p, u = gpu flags['bivariate'] = False inversion = _tsolve(g - u, sym, **flags) if inversion: sol = _solve(p, u, **flags) return list(ordered({i.subs(u, s) for i in inversion for s in sol})) except NotImplementedError: pass else: pass if flags.pop('force', True): flags['force'] = False pos, reps = posify(lhs - rhs) if rhs == S.ComplexInfinity: return [] for u, s in reps.items(): if s == sym: break else: u = sym if pos.has(u): try: soln = _solve(pos, u, **flags) return list(ordered([s.subs(reps) for s in soln])) except NotImplementedError: pass else: pass # here for coverage return # here for coverage # TODO: option for calculating J numerically @conserve_mpmath_dps def nsolve(*args, dict=False, **kwargs): r""" Solve a nonlinear equation system numerically: ``nsolve(f, [args,] x0, modules=['mpmath'], **kwargs)``. Explanation =========== ``f`` is a vector function of symbolic expressions representing the system. *args* are the variables. If there is only one variable, this argument can be omitted. ``x0`` is a starting vector close to a solution. Use the modules keyword to specify which modules should be used to evaluate the function and the Jacobian matrix. Make sure to use a module that supports matrices. For more information on the syntax, please see the docstring of ``lambdify``. If the keyword arguments contain ``dict=True`` (default is False) ``nsolve`` will return a list (perhaps empty) of solution mappings. This might be especially useful if you want to use ``nsolve`` as a fallback to solve since using the dict argument for both methods produces return values of consistent type structure. Please note: to keep this consistent with ``solve``, the solution will be returned in a list even though ``nsolve`` (currently at least) only finds one solution at a time. Overdetermined systems are supported. Examples ======== >>> from sympy import Symbol, nsolve >>> import mpmath >>> mpmath.mp.dps = 15 >>> x1 = Symbol('x1') >>> x2 = Symbol('x2') >>> f1 = 3 * x1**2 - 2 * x2**2 - 1 >>> f2 = x1**2 - 2 * x1 + x2**2 + 2 * x2 - 8 >>> print(nsolve((f1, f2), (x1, x2), (-1, 1))) Matrix([[-1.19287309935246], [1.27844411169911]]) For one-dimensional functions the syntax is simplified: >>> from sympy import sin, nsolve >>> from sympy.abc import x >>> nsolve(sin(x), x, 2) 3.14159265358979 >>> nsolve(sin(x), 2) 3.14159265358979 To solve with higher precision than the default, use the prec argument: >>> from sympy import cos >>> nsolve(cos(x) - x, 1) 0.739085133215161 >>> nsolve(cos(x) - x, 1, prec=50) 0.73908513321516064165531208767387340401341175890076 >>> cos(_) 0.73908513321516064165531208767387340401341175890076 To solve for complex roots of real functions, a nonreal initial point must be specified: >>> from sympy import I >>> nsolve(x**2 + 2, I) 1.4142135623731*I ``mpmath.findroot`` is used and you can find their more extensive documentation, especially concerning keyword parameters and available solvers. Note, however, that functions which are very steep near the root, the verification of the solution may fail. In this case you should use the flag ``verify=False`` and independently verify the solution. >>> from sympy import cos, cosh >>> f = cos(x)*cosh(x) - 1 >>> nsolve(f, 3.14*100) Traceback (most recent call last): ... ValueError: Could not find root within given tolerance. (1.39267e+230 > 2.1684e-19) >>> ans = nsolve(f, 3.14*100, verify=False); ans 312.588469032184 >>> f.subs(x, ans).n(2) 2.1e+121 >>> (f/f.diff(x)).subs(x, ans).n(2) 7.4e-15 One might safely skip the verification if bounds of the root are known and a bisection method is used: >>> bounds = lambda i: (3.14*i, 3.14*(i + 1)) >>> nsolve(f, bounds(100), solver='bisect', verify=False) 315.730061685774 Alternatively, a function may be better behaved when the denominator is ignored. Since this is not always the case, however, the decision of what function to use is left to the discretion of the user. >>> eq = x**2/(1 - x)/(1 - 2*x)**2 - 100 >>> nsolve(eq, 0.46) Traceback (most recent call last): ... ValueError: Could not find root within given tolerance. (10000 > 2.1684e-19) Try another starting point or tweak arguments. >>> nsolve(eq.as_numer_denom()[0], 0.46) 0.46792545969349058 """ # there are several other SymPy functions that use method= so # guard against that here if 'method' in kwargs: raise ValueError(filldedent(''' Keyword "method" should not be used in this context. When using some mpmath solvers directly, the keyword "method" is used, but when using nsolve (and findroot) the keyword to use is "solver".''')) if 'prec' in kwargs: import mpmath mpmath.mp.dps = kwargs.pop('prec') # keyword argument to return result as a dictionary as_dict = dict from builtins import dict # to unhide the builtin # interpret arguments if len(args) == 3: f = args[0] fargs = args[1] x0 = args[2] if iterable(fargs) and iterable(x0): if len(x0) != len(fargs): raise TypeError('nsolve expected exactly %i guess vectors, got %i' % (len(fargs), len(x0))) elif len(args) == 2: f = args[0] fargs = None x0 = args[1] if iterable(f): raise TypeError('nsolve expected 3 arguments, got 2') elif len(args) < 2: raise TypeError('nsolve expected at least 2 arguments, got %i' % len(args)) else: raise TypeError('nsolve expected at most 3 arguments, got %i' % len(args)) modules = kwargs.get('modules', ['mpmath']) if iterable(f): f = list(f) for i, fi in enumerate(f): if isinstance(fi, Eq): f[i] = fi.lhs - fi.rhs f = Matrix(f).T if iterable(x0): x0 = list(x0) if not isinstance(f, Matrix): # assume it's a SymPy expression if isinstance(f, Eq): f = f.lhs - f.rhs syms = f.free_symbols if fargs is None: fargs = syms.copy().pop() if not (len(syms) == 1 and (fargs in syms or fargs[0] in syms)): raise ValueError(filldedent(''' expected a one-dimensional and numerical function''')) # the function is much better behaved if there is no denominator # but sending the numerator is left to the user since sometimes # the function is better behaved when the denominator is present # e.g., issue 11768 f = lambdify(fargs, f, modules) x = sympify(findroot(f, x0, **kwargs)) if as_dict: return [{fargs: x}] return x if len(fargs) > f.cols: raise NotImplementedError(filldedent(''' need at least as many equations as variables''')) verbose = kwargs.get('verbose', False) if verbose: print('f(x):') print(f) # derive Jacobian J = f.jacobian(fargs) if verbose: print('J(x):') print(J) # create functions f = lambdify(fargs, f.T, modules) J = lambdify(fargs, J, modules) # solve the system numerically x = findroot(f, x0, J=J, **kwargs) if as_dict: return [dict(zip(fargs, [sympify(xi) for xi in x]))] return Matrix(x) def _invert(eq, *symbols, **kwargs): """ Return tuple (i, d) where ``i`` is independent of *symbols* and ``d`` contains symbols. Explanation =========== ``i`` and ``d`` are obtained after recursively using algebraic inversion until an uninvertible ``d`` remains. If there are no free symbols then ``d`` will be zero. Some (but not necessarily all) solutions to the expression ``i - d`` will be related to the solutions of the original expression. Examples ======== >>> from sympy.solvers.solvers import _invert as invert >>> from sympy import sqrt, cos >>> from sympy.abc import x, y >>> invert(x - 3) (3, x) >>> invert(3) (3, 0) >>> invert(2*cos(x) - 1) (1/2, cos(x)) >>> invert(sqrt(x) - 3) (3, sqrt(x)) >>> invert(sqrt(x) + y, x) (-y, sqrt(x)) >>> invert(sqrt(x) + y, y) (-sqrt(x), y) >>> invert(sqrt(x) + y, x, y) (0, sqrt(x) + y) If there is more than one symbol in a power's base and the exponent is not an Integer, then the principal root will be used for the inversion: >>> invert(sqrt(x + y) - 2) (4, x + y) >>> invert(sqrt(x + y) - 2) (4, x + y) If the exponent is an Integer, setting ``integer_power`` to True will force the principal root to be selected: >>> invert(x**2 - 4, integer_power=True) (2, x) """ eq = sympify(eq) if eq.args: # make sure we are working with flat eq eq = eq.func(*eq.args) free = eq.free_symbols if not symbols: symbols = free if not free & set(symbols): return eq, S.Zero dointpow = bool(kwargs.get('integer_power', False)) lhs = eq rhs = S.Zero while True: was = lhs while True: indep, dep = lhs.as_independent(*symbols) # dep + indep == rhs if lhs.is_Add: # this indicates we have done it all if indep.is_zero: break lhs = dep rhs -= indep # dep * indep == rhs else: # this indicates we have done it all if indep is S.One: break lhs = dep rhs /= indep # collect like-terms in symbols if lhs.is_Add: terms = {} for a in lhs.args: i, d = a.as_independent(*symbols) terms.setdefault(d, []).append(i) if any(len(v) > 1 for v in terms.values()): args = [] for d, i in terms.items(): if len(i) > 1: args.append(Add(*i)*d) else: args.append(i[0]*d) lhs = Add(*args) # if it's a two-term Add with rhs = 0 and two powers we can get the # dependent terms together, e.g. 3*f(x) + 2*g(x) -> f(x)/g(x) = -2/3 if lhs.is_Add and not rhs and len(lhs.args) == 2 and \ not lhs.is_polynomial(*symbols): a, b = ordered(lhs.args) ai, ad = a.as_independent(*symbols) bi, bd = b.as_independent(*symbols) if any(_ispow(i) for i in (ad, bd)): a_base, a_exp = ad.as_base_exp() b_base, b_exp = bd.as_base_exp() if a_base == b_base: # a = -b lhs = powsimp(powdenest(ad/bd)) rhs = -bi/ai else: rat = ad/bd _lhs = powsimp(ad/bd) if _lhs != rat: lhs = _lhs rhs = -bi/ai elif ai == -bi: if isinstance(ad, Function) and ad.func == bd.func: if len(ad.args) == len(bd.args) == 1: lhs = ad.args[0] - bd.args[0] elif len(ad.args) == len(bd.args): # should be able to solve # f(x, y) - f(2 - x, 0) == 0 -> x == 1 raise NotImplementedError( 'equal function with more than 1 argument') else: raise ValueError( 'function with different numbers of args') elif lhs.is_Mul and any(_ispow(a) for a in lhs.args): lhs = powsimp(powdenest(lhs)) if lhs.is_Function: if hasattr(lhs, 'inverse') and lhs.inverse() is not None and len(lhs.args) == 1: # -1 # f(x) = g -> x = f (g) # # /!\ inverse should not be defined if there are multiple values # for the function -- these are handled in _tsolve # rhs = lhs.inverse()(rhs) lhs = lhs.args[0] elif isinstance(lhs, atan2): y, x = lhs.args lhs = 2*atan(y/(sqrt(x**2 + y**2) + x)) elif lhs.func == rhs.func: if len(lhs.args) == len(rhs.args) == 1: lhs = lhs.args[0] rhs = rhs.args[0] elif len(lhs.args) == len(rhs.args): # should be able to solve # f(x, y) == f(2, 3) -> x == 2 # f(x, x + y) == f(2, 3) -> x == 2 raise NotImplementedError( 'equal function with more than 1 argument') else: raise ValueError( 'function with different numbers of args') if rhs and lhs.is_Pow and lhs.exp.is_Integer and lhs.exp < 0: lhs = 1/lhs rhs = 1/rhs # base**a = b -> base = b**(1/a) if # a is an Integer and dointpow=True (this gives real branch of root) # a is not an Integer and the equation is multivariate and the # base has more than 1 symbol in it # The rationale for this is that right now the multi-system solvers # doesn't try to resolve generators to see, for example, if the whole # system is written in terms of sqrt(x + y) so it will just fail, so we # do that step here. if lhs.is_Pow and ( lhs.exp.is_Integer and dointpow or not lhs.exp.is_Integer and len(symbols) > 1 and len(lhs.base.free_symbols & set(symbols)) > 1): rhs = rhs**(1/lhs.exp) lhs = lhs.base if lhs == was: break return rhs, lhs def unrad(eq, *syms, **flags): """ Remove radicals with symbolic arguments and return (eq, cov), None, or raise an error. Explanation =========== None is returned if there are no radicals to remove. NotImplementedError is raised if there are radicals and they cannot be removed or if the relationship between the original symbols and the change of variable needed to rewrite the system as a polynomial cannot be solved. Otherwise the tuple, ``(eq, cov)``, is returned where: *eq*, ``cov`` *eq* is an equation without radicals (in the symbol(s) of interest) whose solutions are a superset of the solutions to the original expression. *eq* might be rewritten in terms of a new variable; the relationship to the original variables is given by ``cov`` which is a list containing ``v`` and ``v**p - b`` where ``p`` is the power needed to clear the radical and ``b`` is the radical now expressed as a polynomial in the symbols of interest. For example, for sqrt(2 - x) the tuple would be ``(c, c**2 - 2 + x)``. The solutions of *eq* will contain solutions to the original equation (if there are any). *syms* An iterable of symbols which, if provided, will limit the focus of radical removal: only radicals with one or more of the symbols of interest will be cleared. All free symbols are used if *syms* is not set. *flags* are used internally for communication during recursive calls. Two options are also recognized: ``take``, when defined, is interpreted as a single-argument function that returns True if a given Pow should be handled. Radicals can be removed from an expression if: * All bases of the radicals are the same; a change of variables is done in this case. * If all radicals appear in one term of the expression. * There are only four terms with sqrt() factors or there are less than four terms having sqrt() factors. * There are only two terms with radicals. Examples ======== >>> from sympy.solvers.solvers import unrad >>> from sympy.abc import x >>> from sympy import sqrt, Rational, root >>> unrad(sqrt(x)*x**Rational(1, 3) + 2) (x**5 - 64, []) >>> unrad(sqrt(x) + root(x + 1, 3)) (-x**3 + x**2 + 2*x + 1, []) >>> eq = sqrt(x) + root(x, 3) - 2 >>> unrad(eq) (_p**3 + _p**2 - 2, [_p, _p**6 - x]) """ uflags = dict(check=False, simplify=False) def _cov(p, e): if cov: # XXX - uncovered oldp, olde = cov if Poly(e, p).degree(p) in (1, 2): cov[:] = [p, olde.subs(oldp, _solve(e, p, **uflags)[0])] else: raise NotImplementedError else: cov[:] = [p, e] def _canonical(eq, cov): if cov: # change symbol to vanilla so no solutions are eliminated p, e = cov rep = {p: Dummy(p.name)} eq = eq.xreplace(rep) cov = [p.xreplace(rep), e.xreplace(rep)] # remove constants and powers of factors since these don't change # the location of the root; XXX should factor or factor_terms be used? eq = factor_terms(_mexpand(eq.as_numer_denom()[0], recursive=True), clear=True) if eq.is_Mul: args = [] for f in eq.args: if f.is_number: continue if f.is_Pow: args.append(f.base) else: args.append(f) eq = Mul(*args) # leave as Mul for more efficient solving # make the sign canonical margs = list(Mul.make_args(eq)) changed = False for i, m in enumerate(margs): if m.could_extract_minus_sign(): margs[i] = -m changed = True if changed: eq = Mul(*margs, evaluate=False) return eq, cov def _Q(pow): # return leading Rational of denominator of Pow's exponent c = pow.as_base_exp()[1].as_coeff_Mul()[0] if not c.is_Rational: return S.One return c.q # define the _take method that will determine whether a term is of interest def _take(d): # return True if coefficient of any factor's exponent's den is not 1 for pow in Mul.make_args(d): if not pow.is_Pow: continue if _Q(pow) == 1: continue if pow.free_symbols & syms: return True return False _take = flags.setdefault('_take', _take) if isinstance(eq, Eq): eq = eq.lhs - eq.rhs # XXX legacy Eq as Eqn support elif not isinstance(eq, Expr): return cov, nwas, rpt = [flags.setdefault(k, v) for k, v in sorted(dict(cov=[], n=None, rpt=0).items())] # preconditioning eq = powdenest(factor_terms(eq, radical=True, clear=True)) eq = eq.as_numer_denom()[0] eq = _mexpand(eq, recursive=True) if eq.is_number: return # see if there are radicals in symbols of interest syms = set(syms) or eq.free_symbols # _take uses this poly = eq.as_poly() gens = [g for g in poly.gens if _take(g)] if not gens: return # recast poly in terms of eigen-gens poly = eq.as_poly(*gens) # not a polynomial e.g. 1 + sqrt(x)*exp(sqrt(x)) with gen sqrt(x) if poly is None: return # - an exponent has a symbol of interest (don't handle) if any(g.exp.has(*syms) for g in gens): return def _rads_bases_lcm(poly): # if all the bases are the same or all the radicals are in one # term, `lcm` will be the lcm of the denominators of the # exponents of the radicals lcm = 1 rads = set() bases = set() for g in poly.gens: q = _Q(g) if q != 1: rads.add(g) lcm = ilcm(lcm, q) bases.add(g.base) return rads, bases, lcm rads, bases, lcm = _rads_bases_lcm(poly) covsym = Dummy('p', nonnegative=True) # only keep in syms symbols that actually appear in radicals; # and update gens newsyms = set() for r in rads: newsyms.update(syms & r.free_symbols) if newsyms != syms: syms = newsyms # get terms together that have common generators drad = dict(list(zip(rads, list(range(len(rads)))))) rterms = {(): []} args = Add.make_args(poly.as_expr()) for t in args: if _take(t): common = set(t.as_poly().gens).intersection(rads) key = tuple(sorted([drad[i] for i in common])) else: key = () rterms.setdefault(key, []).append(t) others = Add(*rterms.pop(())) rterms = [Add(*rterms[k]) for k in rterms.keys()] # the output will depend on the order terms are processed, so # make it canonical quickly rterms = list(reversed(list(ordered(rterms)))) ok = False # we don't have a solution yet depth = sqrt_depth(eq) if len(rterms) == 1 and not (rterms[0].is_Add and lcm > 2): eq = rterms[0]**lcm - ((-others)**lcm) ok = True else: if len(rterms) == 1 and rterms[0].is_Add: rterms = list(rterms[0].args) if len(bases) == 1: b = bases.pop() if len(syms) > 1: x = b.free_symbols else: x = syms x = list(ordered(x))[0] try: inv = _solve(covsym**lcm - b, x, **uflags) if not inv: raise NotImplementedError eq = poly.as_expr().subs(b, covsym**lcm).subs(x, inv[0]) _cov(covsym, covsym**lcm - b) return _canonical(eq, cov) except NotImplementedError: pass if len(rterms) == 2: if not others: eq = rterms[0]**lcm - (-rterms[1])**lcm ok = True elif not log(lcm, 2).is_Integer: # the lcm-is-power-of-two case is handled below r0, r1 = rterms if flags.get('_reverse', False): r1, r0 = r0, r1 i0 = _rads0, _bases0, lcm0 = _rads_bases_lcm(r0.as_poly()) i1 = _rads1, _bases1, lcm1 = _rads_bases_lcm(r1.as_poly()) for reverse in range(2): if reverse: i0, i1 = i1, i0 r0, r1 = r1, r0 _rads1, _, lcm1 = i1 _rads1 = Mul(*_rads1) t1 = _rads1**lcm1 c = covsym**lcm1 - t1 for x in syms: try: sol = _solve(c, x, **uflags) if not sol: raise NotImplementedError neweq = r0.subs(x, sol[0]) + covsym*r1/_rads1 + \ others tmp = unrad(neweq, covsym) if tmp: eq, newcov = tmp if newcov: newp, newc = newcov _cov(newp, c.subs(covsym, _solve(newc, covsym, **uflags)[0])) else: _cov(covsym, c) else: eq = neweq _cov(covsym, c) ok = True break except NotImplementedError: if reverse: raise NotImplementedError( 'no successful change of variable found') else: pass if ok: break elif len(rterms) == 3: # two cube roots and another with order less than 5 # (so an analytical solution can be found) or a base # that matches one of the cube root bases info = [_rads_bases_lcm(i.as_poly()) for i in rterms] RAD = 0 BASES = 1 LCM = 2 if info[0][LCM] != 3: info.append(info.pop(0)) rterms.append(rterms.pop(0)) elif info[1][LCM] != 3: info.append(info.pop(1)) rterms.append(rterms.pop(1)) if info[0][LCM] == info[1][LCM] == 3: if info[1][BASES] != info[2][BASES]: info[0], info[1] = info[1], info[0] rterms[0], rterms[1] = rterms[1], rterms[0] if info[1][BASES] == info[2][BASES]: eq = rterms[0]**3 + (rterms[1] + rterms[2] + others)**3 ok = True elif info[2][LCM] < 5: # a*root(A, 3) + b*root(B, 3) + others = c a, b, c, d, A, B = [Dummy(i) for i in 'abcdAB'] # zz represents the unraded expression into which the # specifics for this case are substituted zz = (c - d)*(A**3*a**9 + 3*A**2*B*a**6*b**3 - 3*A**2*a**6*c**3 + 9*A**2*a**6*c**2*d - 9*A**2*a**6*c*d**2 + 3*A**2*a**6*d**3 + 3*A*B**2*a**3*b**6 + 21*A*B*a**3*b**3*c**3 - 63*A*B*a**3*b**3*c**2*d + 63*A*B*a**3*b**3*c*d**2 - 21*A*B*a**3*b**3*d**3 + 3*A*a**3*c**6 - 18*A*a**3*c**5*d + 45*A*a**3*c**4*d**2 - 60*A*a**3*c**3*d**3 + 45*A*a**3*c**2*d**4 - 18*A*a**3*c*d**5 + 3*A*a**3*d**6 + B**3*b**9 - 3*B**2*b**6*c**3 + 9*B**2*b**6*c**2*d - 9*B**2*b**6*c*d**2 + 3*B**2*b**6*d**3 + 3*B*b**3*c**6 - 18*B*b**3*c**5*d + 45*B*b**3*c**4*d**2 - 60*B*b**3*c**3*d**3 + 45*B*b**3*c**2*d**4 - 18*B*b**3*c*d**5 + 3*B*b**3*d**6 - c**9 + 9*c**8*d - 36*c**7*d**2 + 84*c**6*d**3 - 126*c**5*d**4 + 126*c**4*d**5 - 84*c**3*d**6 + 36*c**2*d**7 - 9*c*d**8 + d**9) def _t(i): b = Mul(*info[i][RAD]) return cancel(rterms[i]/b), Mul(*info[i][BASES]) aa, AA = _t(0) bb, BB = _t(1) cc = -rterms[2] dd = others eq = zz.xreplace(dict(zip( (a, A, b, B, c, d), (aa, AA, bb, BB, cc, dd)))) ok = True # handle power-of-2 cases if not ok: if log(lcm, 2).is_Integer and (not others and len(rterms) == 4 or len(rterms) < 4): def _norm2(a, b): return a**2 + b**2 + 2*a*b if len(rterms) == 4: # (r0+r1)**2 - (r2+r3)**2 r0, r1, r2, r3 = rterms eq = _norm2(r0, r1) - _norm2(r2, r3) ok = True elif len(rterms) == 3: # (r1+r2)**2 - (r0+others)**2 r0, r1, r2 = rterms eq = _norm2(r1, r2) - _norm2(r0, others) ok = True elif len(rterms) == 2: # r0**2 - (r1+others)**2 r0, r1 = rterms eq = r0**2 - _norm2(r1, others) ok = True new_depth = sqrt_depth(eq) if ok else depth rpt += 1 # XXX how many repeats with others unchanging is enough? if not ok or ( nwas is not None and len(rterms) == nwas and new_depth is not None and new_depth == depth and rpt > 3): raise NotImplementedError('Cannot remove all radicals') flags.update(dict(cov=cov, n=len(rterms), rpt=rpt)) neq = unrad(eq, *syms, **flags) if neq: eq, cov = neq eq, cov = _canonical(eq, cov) return eq, cov # Delayed imports from sympy.solvers.bivariate import ( bivariate_type, _solve_lambert, _filtered_gens)
1b059ce22a65a04ee8812f4b4ce9248ec8a3d666cf310c5b576fe9bcdae261b1
from .cartan_type import CartanType from sympy.core.basic import Atom class RootSystem(Atom): """Represent the root system of a simple Lie algebra Every simple Lie algebra has a unique root system. To find the root system, we first consider the Cartan subalgebra of g, which is the maximal abelian subalgebra, and consider the adjoint action of g on this subalgebra. There is a root system associated with this action. Now, a root system over a vector space V is a set of finite vectors Phi (called roots), which satisfy: 1. The roots span V 2. The only scalar multiples of x in Phi are x and -x 3. For every x in Phi, the set Phi is closed under reflection through the hyperplane perpendicular to x. 4. If x and y are roots in Phi, then the projection of y onto the line through x is a half-integral multiple of x. Now, there is a subset of Phi, which we will call Delta, such that: 1. Delta is a basis of V 2. Each root x in Phi can be written x = sum k_y y for y in Delta The elements of Delta are called the simple roots. Therefore, we see that the simple roots span the root space of a given simple Lie algebra. References ========== .. [1] https://en.wikipedia.org/wiki/Root_system .. [2] Lie Algebras and Representation Theory - Humphreys """ def __new__(cls, cartantype): """Create a new RootSystem object This method assigns an attribute called cartan_type to each instance of a RootSystem object. When an instance of RootSystem is called, it needs an argument, which should be an instance of a simple Lie algebra. We then take the CartanType of this argument and set it as the cartan_type attribute of the RootSystem instance. """ obj = Atom.__new__(cls) obj.cartan_type = CartanType(cartantype) return obj def simple_roots(self): """Generate the simple roots of the Lie algebra The rank of the Lie algebra determines the number of simple roots that it has. This method obtains the rank of the Lie algebra, and then uses the simple_root method from the Lie algebra classes to generate all the simple roots. Examples ======== >>> from sympy.liealgebras.root_system import RootSystem >>> c = RootSystem("A3") >>> roots = c.simple_roots() >>> roots {1: [1, -1, 0, 0], 2: [0, 1, -1, 0], 3: [0, 0, 1, -1]} """ n = self.cartan_type.rank() roots = {} for i in range(1, n+1): root = self.cartan_type.simple_root(i) roots[i] = root return roots def all_roots(self): """Generate all the roots of a given root system The result is a dictionary where the keys are integer numbers. It generates the roots by getting the dictionary of all positive roots from the bases classes, and then taking each root, and multiplying it by -1 and adding it to the dictionary. In this way all the negative roots are generated. """ alpha = self.cartan_type.positive_roots() keys = list(alpha.keys()) k = max(keys) for val in keys: k += 1 root = alpha[val] newroot = [-x for x in root] alpha[k] = newroot return alpha def root_space(self): """Return the span of the simple roots The root space is the vector space spanned by the simple roots, i.e. it is a vector space with a distinguished basis, the simple roots. This method returns a string that represents the root space as the span of the simple roots, alpha[1],...., alpha[n]. Examples ======== >>> from sympy.liealgebras.root_system import RootSystem >>> c = RootSystem("A3") >>> c.root_space() 'alpha[1] + alpha[2] + alpha[3]' """ n = self.cartan_type.rank() rs = " + ".join("alpha["+str(i) +"]" for i in range(1, n+1)) return rs def add_simple_roots(self, root1, root2): """Add two simple roots together The function takes as input two integers, root1 and root2. It then uses these integers as keys in the dictionary of simple roots, and gets the corresponding simple roots, and then adds them together. Examples ======== >>> from sympy.liealgebras.root_system import RootSystem >>> c = RootSystem("A3") >>> newroot = c.add_simple_roots(1, 2) >>> newroot [1, 0, -1, 0] """ alpha = self.simple_roots() if root1 > len(alpha) or root2 > len(alpha): raise ValueError("You've used a root that doesn't exist!") a1 = alpha[root1] a2 = alpha[root2] newroot = [_a1 + _a2 for _a1, _a2 in zip(a1, a2)] return newroot def add_as_roots(self, root1, root2): """Add two roots together if and only if their sum is also a root It takes as input two vectors which should be roots. It then computes their sum and checks if it is in the list of all possible roots. If it is, it returns the sum. Otherwise it returns a string saying that the sum is not a root. Examples ======== >>> from sympy.liealgebras.root_system import RootSystem >>> c = RootSystem("A3") >>> c.add_as_roots([1, 0, -1, 0], [0, 0, 1, -1]) [1, 0, 0, -1] >>> c.add_as_roots([1, -1, 0, 0], [0, 0, -1, 1]) 'The sum of these two roots is not a root' """ alpha = self.all_roots() newroot = [r1 + r2 for r1, r2 in zip(root1, root2)] if newroot in alpha.values(): return newroot else: return "The sum of these two roots is not a root" def cartan_matrix(self): """Cartan matrix of Lie algebra associated with this root system Examples ======== >>> from sympy.liealgebras.root_system import RootSystem >>> c = RootSystem("A3") >>> c.cartan_matrix() Matrix([ [ 2, -1, 0], [-1, 2, -1], [ 0, -1, 2]]) """ return self.cartan_type.cartan_matrix() def dynkin_diagram(self): """Dynkin diagram of the Lie algebra associated with this root system Examples ======== >>> from sympy.liealgebras.root_system import RootSystem >>> c = RootSystem("A3") >>> print(c.dynkin_diagram()) 0---0---0 1 2 3 """ return self.cartan_type.dynkin_diagram()
5fba992791a61e51caa24514305a1a42aaea5f68cb46ae1bed6d86e5a5a7b733
""" Finite difference weights ========================= This module implements an algorithm for efficient generation of finite difference weights for ordinary differentials of functions for derivatives from 0 (interpolation) up to arbitrary order. The core algorithm is provided in the finite difference weight generating function (``finite_diff_weights``), and two convenience functions are provided for: - estimating a derivative (or interpolate) directly from a series of points is also provided (``apply_finite_diff``). - differentiating by using finite difference approximations (``differentiate_finite``). """ from sympy.core.function import Derivative from sympy.core.singleton import S from sympy.core.function import Subs from sympy.core.traversal import preorder_traversal from sympy.utilities.exceptions import sympy_deprecation_warning from sympy.utilities.iterables import iterable def finite_diff_weights(order, x_list, x0=S.One): """ Calculates the finite difference weights for an arbitrarily spaced one-dimensional grid (``x_list``) for derivatives at ``x0`` of order 0, 1, ..., up to ``order`` using a recursive formula. Order of accuracy is at least ``len(x_list) - order``, if ``x_list`` is defined correctly. Parameters ========== order: int Up to what derivative order weights should be calculated. 0 corresponds to interpolation. x_list: sequence Sequence of (unique) values for the independent variable. It is useful (but not necessary) to order ``x_list`` from nearest to furthest from ``x0``; see examples below. x0: Number or Symbol Root or value of the independent variable for which the finite difference weights should be generated. Default is ``S.One``. Returns ======= list A list of sublists, each corresponding to coefficients for increasing derivative order, and each containing lists of coefficients for increasing subsets of x_list. Examples ======== >>> from sympy import finite_diff_weights, S >>> res = finite_diff_weights(1, [-S(1)/2, S(1)/2, S(3)/2, S(5)/2], 0) >>> res [[[1, 0, 0, 0], [1/2, 1/2, 0, 0], [3/8, 3/4, -1/8, 0], [5/16, 15/16, -5/16, 1/16]], [[0, 0, 0, 0], [-1, 1, 0, 0], [-1, 1, 0, 0], [-23/24, 7/8, 1/8, -1/24]]] >>> res[0][-1] # FD weights for 0th derivative, using full x_list [5/16, 15/16, -5/16, 1/16] >>> res[1][-1] # FD weights for 1st derivative [-23/24, 7/8, 1/8, -1/24] >>> res[1][-2] # FD weights for 1st derivative, using x_list[:-1] [-1, 1, 0, 0] >>> res[1][-1][0] # FD weight for 1st deriv. for x_list[0] -23/24 >>> res[1][-1][1] # FD weight for 1st deriv. for x_list[1], etc. 7/8 Each sublist contains the most accurate formula at the end. Note, that in the above example ``res[1][1]`` is the same as ``res[1][2]``. Since res[1][2] has an order of accuracy of ``len(x_list[:3]) - order = 3 - 1 = 2``, the same is true for ``res[1][1]``! >>> res = finite_diff_weights(1, [S(0), S(1), -S(1), S(2), -S(2)], 0)[1] >>> res [[0, 0, 0, 0, 0], [-1, 1, 0, 0, 0], [0, 1/2, -1/2, 0, 0], [-1/2, 1, -1/3, -1/6, 0], [0, 2/3, -2/3, -1/12, 1/12]] >>> res[0] # no approximation possible, using x_list[0] only [0, 0, 0, 0, 0] >>> res[1] # classic forward step approximation [-1, 1, 0, 0, 0] >>> res[2] # classic centered approximation [0, 1/2, -1/2, 0, 0] >>> res[3:] # higher order approximations [[-1/2, 1, -1/3, -1/6, 0], [0, 2/3, -2/3, -1/12, 1/12]] Let us compare this to a differently defined ``x_list``. Pay attention to ``foo[i][k]`` corresponding to the gridpoint defined by ``x_list[k]``. >>> foo = finite_diff_weights(1, [-S(2), -S(1), S(0), S(1), S(2)], 0)[1] >>> foo [[0, 0, 0, 0, 0], [-1, 1, 0, 0, 0], [1/2, -2, 3/2, 0, 0], [1/6, -1, 1/2, 1/3, 0], [1/12, -2/3, 0, 2/3, -1/12]] >>> foo[1] # not the same and of lower accuracy as res[1]! [-1, 1, 0, 0, 0] >>> foo[2] # classic double backward step approximation [1/2, -2, 3/2, 0, 0] >>> foo[4] # the same as res[4] [1/12, -2/3, 0, 2/3, -1/12] Note that, unless you plan on using approximations based on subsets of ``x_list``, the order of gridpoints does not matter. The capability to generate weights at arbitrary points can be used e.g. to minimize Runge's phenomenon by using Chebyshev nodes: >>> from sympy import cos, symbols, pi, simplify >>> N, (h, x) = 4, symbols('h x') >>> x_list = [x+h*cos(i*pi/(N)) for i in range(N,-1,-1)] # chebyshev nodes >>> print(x_list) [-h + x, -sqrt(2)*h/2 + x, x, sqrt(2)*h/2 + x, h + x] >>> mycoeffs = finite_diff_weights(1, x_list, 0)[1][4] >>> [simplify(c) for c in mycoeffs] #doctest: +NORMALIZE_WHITESPACE [(h**3/2 + h**2*x - 3*h*x**2 - 4*x**3)/h**4, (-sqrt(2)*h**3 - 4*h**2*x + 3*sqrt(2)*h*x**2 + 8*x**3)/h**4, (6*h**2*x - 8*x**3)/h**4, (sqrt(2)*h**3 - 4*h**2*x - 3*sqrt(2)*h*x**2 + 8*x**3)/h**4, (-h**3/2 + h**2*x + 3*h*x**2 - 4*x**3)/h**4] Notes ===== If weights for a finite difference approximation of 3rd order derivative is wanted, weights for 0th, 1st and 2nd order are calculated "for free", so are formulae using subsets of ``x_list``. This is something one can take advantage of to save computational cost. Be aware that one should define ``x_list`` from nearest to furthest from ``x0``. If not, subsets of ``x_list`` will yield poorer approximations, which might not grand an order of accuracy of ``len(x_list) - order``. See also ======== sympy.calculus.finite_diff.apply_finite_diff References ========== .. [1] Generation of Finite Difference Formulas on Arbitrarily Spaced Grids, Bengt Fornberg; Mathematics of computation; 51; 184; (1988); 699-706; doi:10.1090/S0025-5718-1988-0935077-0 """ # The notation below closely corresponds to the one used in the paper. order = S(order) if not order.is_number: raise ValueError("Cannot handle symbolic order.") if order < 0: raise ValueError("Negative derivative order illegal.") if int(order) != order: raise ValueError("Non-integer order illegal") M = order N = len(x_list) - 1 delta = [[[0 for nu in range(N+1)] for n in range(N+1)] for m in range(M+1)] delta[0][0][0] = S.One c1 = S.One for n in range(1, N+1): c2 = S.One for nu in range(n): c3 = x_list[n] - x_list[nu] c2 = c2 * c3 if n <= M: delta[n][n-1][nu] = 0 for m in range(min(n, M)+1): delta[m][n][nu] = (x_list[n]-x0)*delta[m][n-1][nu] -\ m*delta[m-1][n-1][nu] delta[m][n][nu] /= c3 for m in range(min(n, M)+1): delta[m][n][n] = c1/c2*(m*delta[m-1][n-1][n-1] - (x_list[n-1]-x0)*delta[m][n-1][n-1]) c1 = c2 return delta def apply_finite_diff(order, x_list, y_list, x0=S.Zero): """ Calculates the finite difference approximation of the derivative of requested order at ``x0`` from points provided in ``x_list`` and ``y_list``. Parameters ========== order: int order of derivative to approximate. 0 corresponds to interpolation. x_list: sequence Sequence of (unique) values for the independent variable. y_list: sequence The function value at corresponding values for the independent variable in x_list. x0: Number or Symbol At what value of the independent variable the derivative should be evaluated. Defaults to 0. Returns ======= sympy.core.add.Add or sympy.core.numbers.Number The finite difference expression approximating the requested derivative order at ``x0``. Examples ======== >>> from sympy import apply_finite_diff >>> cube = lambda arg: (1.0*arg)**3 >>> xlist = range(-3,3+1) >>> apply_finite_diff(2, xlist, map(cube, xlist), 2) - 12 # doctest: +SKIP -3.55271367880050e-15 we see that the example above only contain rounding errors. apply_finite_diff can also be used on more abstract objects: >>> from sympy import IndexedBase, Idx >>> x, y = map(IndexedBase, 'xy') >>> i = Idx('i') >>> x_list, y_list = zip(*[(x[i+j], y[i+j]) for j in range(-1,2)]) >>> apply_finite_diff(1, x_list, y_list, x[i]) ((x[i + 1] - x[i])/(-x[i - 1] + x[i]) - 1)*y[i]/(x[i + 1] - x[i]) - (x[i + 1] - x[i])*y[i - 1]/((x[i + 1] - x[i - 1])*(-x[i - 1] + x[i])) + (-x[i - 1] + x[i])*y[i + 1]/((x[i + 1] - x[i - 1])*(x[i + 1] - x[i])) Notes ===== Order = 0 corresponds to interpolation. Only supply so many points you think makes sense to around x0 when extracting the derivative (the function need to be well behaved within that region). Also beware of Runge's phenomenon. See also ======== sympy.calculus.finite_diff.finite_diff_weights References ========== Fortran 90 implementation with Python interface for numerics: finitediff_ .. _finitediff: https://github.com/bjodah/finitediff """ # In the original paper the following holds for the notation: # M = order # N = len(x_list) - 1 N = len(x_list) - 1 if len(x_list) != len(y_list): raise ValueError("x_list and y_list not equal in length.") delta = finite_diff_weights(order, x_list, x0) derivative = 0 for nu in range(len(x_list)): derivative += delta[order][N][nu]*y_list[nu] return derivative def _as_finite_diff(derivative, points=1, x0=None, wrt=None): """ Returns an approximation of a derivative of a function in the form of a finite difference formula. The expression is a weighted sum of the function at a number of discrete values of (one of) the independent variable(s). Parameters ========== derivative: a Derivative instance points: sequence or coefficient, optional If sequence: discrete values (length >= order+1) of the independent variable used for generating the finite difference weights. If it is a coefficient, it will be used as the step-size for generating an equidistant sequence of length order+1 centered around ``x0``. default: 1 (step-size 1) x0: number or Symbol, optional the value of the independent variable (``wrt``) at which the derivative is to be approximated. Default: same as ``wrt``. wrt: Symbol, optional "with respect to" the variable for which the (partial) derivative is to be approximated for. If not provided it is required that the Derivative is ordinary. Default: ``None``. Examples ======== >>> from sympy import symbols, Function, exp, sqrt, Symbol >>> from sympy.calculus.finite_diff import _as_finite_diff >>> x, h = symbols('x h') >>> f = Function('f') >>> _as_finite_diff(f(x).diff(x)) -f(x - 1/2) + f(x + 1/2) The default step size and number of points are 1 and ``order + 1`` respectively. We can change the step size by passing a symbol as a parameter: >>> _as_finite_diff(f(x).diff(x), h) -f(-h/2 + x)/h + f(h/2 + x)/h We can also specify the discretized values to be used in a sequence: >>> _as_finite_diff(f(x).diff(x), [x, x+h, x+2*h]) -3*f(x)/(2*h) + 2*f(h + x)/h - f(2*h + x)/(2*h) The algorithm is not restricted to use equidistant spacing, nor do we need to make the approximation around ``x0``, but we can get an expression estimating the derivative at an offset: >>> e, sq2 = exp(1), sqrt(2) >>> xl = [x-h, x+h, x+e*h] >>> _as_finite_diff(f(x).diff(x, 1), xl, x+h*sq2) 2*h*((h + sqrt(2)*h)/(2*h) - (-sqrt(2)*h + h)/(2*h))*f(E*h + x)/((-h + E*h)*(h + E*h)) + (-(-sqrt(2)*h + h)/(2*h) - (-sqrt(2)*h + E*h)/(2*h))*f(-h + x)/(h + E*h) + (-(h + sqrt(2)*h)/(2*h) + (-sqrt(2)*h + E*h)/(2*h))*f(h + x)/(-h + E*h) Partial derivatives are also supported: >>> y = Symbol('y') >>> d2fdxdy=f(x,y).diff(x,y) >>> _as_finite_diff(d2fdxdy, wrt=x) -Derivative(f(x - 1/2, y), y) + Derivative(f(x + 1/2, y), y) See also ======== sympy.calculus.finite_diff.apply_finite_diff sympy.calculus.finite_diff.finite_diff_weights """ if derivative.is_Derivative: pass elif derivative.is_Atom: return derivative else: return derivative.fromiter( [_as_finite_diff(ar, points, x0, wrt) for ar in derivative.args], **derivative.assumptions0) if wrt is None: old = None for v in derivative.variables: if old is v: continue derivative = _as_finite_diff(derivative, points, x0, v) old = v return derivative order = derivative.variables.count(wrt) if x0 is None: x0 = wrt if not iterable(points): if getattr(points, 'is_Function', False) and wrt in points.args: points = points.subs(wrt, x0) # points is simply the step-size, let's make it a # equidistant sequence centered around x0 if order % 2 == 0: # even order => odd number of points, grid point included points = [x0 + points*i for i in range(-order//2, order//2 + 1)] else: # odd order => even number of points, half-way wrt grid point points = [x0 + points*S(i)/2 for i in range(-order, order + 1, 2)] others = [wrt, 0] for v in set(derivative.variables): if v == wrt: continue others += [v, derivative.variables.count(v)] if len(points) < order+1: raise ValueError("Too few points for order %d" % order) return apply_finite_diff(order, points, [ Derivative(derivative.expr.subs({wrt: x}), *others) for x in points], x0) def differentiate_finite(expr, *symbols, points=1, x0=None, wrt=None, evaluate=False): r""" Differentiate expr and replace Derivatives with finite differences. Parameters ========== expr : expression \*symbols : differentiate with respect to symbols points: sequence, coefficient or undefined function, optional see ``Derivative.as_finite_difference`` x0: number or Symbol, optional see ``Derivative.as_finite_difference`` wrt: Symbol, optional see ``Derivative.as_finite_difference`` Examples ======== >>> from sympy import sin, Function, differentiate_finite >>> from sympy.abc import x, y, h >>> f, g = Function('f'), Function('g') >>> differentiate_finite(f(x)*g(x), x, points=[x-h, x+h]) -f(-h + x)*g(-h + x)/(2*h) + f(h + x)*g(h + x)/(2*h) ``differentiate_finite`` works on any expression, including the expressions with embedded derivatives: >>> differentiate_finite(f(x) + sin(x), x, 2) -2*f(x) + f(x - 1) + f(x + 1) - 2*sin(x) + sin(x - 1) + sin(x + 1) >>> differentiate_finite(f(x, y), x, y) f(x - 1/2, y - 1/2) - f(x - 1/2, y + 1/2) - f(x + 1/2, y - 1/2) + f(x + 1/2, y + 1/2) >>> differentiate_finite(f(x)*g(x).diff(x), x) (-g(x) + g(x + 1))*f(x + 1/2) - (g(x) - g(x - 1))*f(x - 1/2) To make finite difference with non-constant discretization step use undefined functions: >>> dx = Function('dx') >>> differentiate_finite(f(x)*g(x).diff(x), points=dx(x)) -(-g(x - dx(x)/2 - dx(x - dx(x)/2)/2)/dx(x - dx(x)/2) + g(x - dx(x)/2 + dx(x - dx(x)/2)/2)/dx(x - dx(x)/2))*f(x - dx(x)/2)/dx(x) + (-g(x + dx(x)/2 - dx(x + dx(x)/2)/2)/dx(x + dx(x)/2) + g(x + dx(x)/2 + dx(x + dx(x)/2)/2)/dx(x + dx(x)/2))*f(x + dx(x)/2)/dx(x) """ if any(term.is_Derivative for term in list(preorder_traversal(expr))): evaluate = False Dexpr = expr.diff(*symbols, evaluate=evaluate) if evaluate: sympy_deprecation_warning(""" The evaluate flag to differentiate_finite() is deprecated. evaluate=True expands the intermediate derivatives before computing differences, but this usually not what you want, as it does not satisfy the product rule. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-differentiate_finite-evaluate", ) return Dexpr.replace( lambda arg: arg.is_Derivative, lambda arg: arg.as_finite_difference(points=points, x0=x0, wrt=wrt)) else: DFexpr = Dexpr.as_finite_difference(points=points, x0=x0, wrt=wrt) return DFexpr.replace( lambda arg: isinstance(arg, Subs), lambda arg: arg.expr.as_finite_difference( points=points, x0=arg.point[0], wrt=arg.variables[0]))
650ed7a17b794891ffb6b09dc61c1fd1d9d01ee26399a72641b37d8b6ec31909
from .accumulationbounds import AccumBounds, AccumulationBounds # noqa: F401 from .singularities import singularities from sympy.core import Pow, S from sympy.core.function import diff, expand_mul from sympy.core.kind import NumberKind from sympy.core.mod import Mod from sympy.core.relational import Relational from sympy.core.symbol import Symbol, Dummy from sympy.core.sympify import _sympify from sympy.functions.elementary.complexes import Abs, im, re from sympy.functions.elementary.exponential import exp, log from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import ( TrigonometricFunction, sin, cos, csc, sec) from sympy.polys.polytools import degree, lcm_list from sympy.sets.sets import (Interval, Intersection, FiniteSet, Union, Complement) from sympy.sets.fancysets import ImageSet from sympy.utilities import filldedent from sympy.utilities.iterables import iterable def continuous_domain(f, symbol, domain): """ Returns the intervals in the given domain for which the function is continuous. This method is limited by the ability to determine the various singularities and discontinuities of the given function. Parameters ========== f : :py:class:`~.Expr` The concerned function. symbol : :py:class:`~.Symbol` The variable for which the intervals are to be determined. domain : :py:class:`~.Interval` The domain over which the continuity of the symbol has to be checked. Examples ======== >>> from sympy import Interval, Symbol, S, tan, log, pi, sqrt >>> from sympy.calculus.util import continuous_domain >>> x = Symbol('x') >>> continuous_domain(1/x, x, S.Reals) Union(Interval.open(-oo, 0), Interval.open(0, oo)) >>> continuous_domain(tan(x), x, Interval(0, pi)) Union(Interval.Ropen(0, pi/2), Interval.Lopen(pi/2, pi)) >>> continuous_domain(sqrt(x - 2), x, Interval(-5, 5)) Interval(2, 5) >>> continuous_domain(log(2*x - 1), x, S.Reals) Interval.open(1/2, oo) Returns ======= :py:class:`~.Interval` Union of all intervals where the function is continuous. Raises ====== NotImplementedError If the method to determine continuity of such a function has not yet been developed. """ from sympy.solvers.inequalities import solve_univariate_inequality if domain.is_subset(S.Reals): constrained_interval = domain for atom in f.atoms(Pow): den = atom.exp.as_numer_denom()[1] if den.is_even and den.is_nonzero: constraint = solve_univariate_inequality(atom.base >= 0, symbol).as_set() constrained_interval = Intersection(constraint, constrained_interval) for atom in f.atoms(log): constraint = solve_univariate_inequality(atom.args[0] > 0, symbol).as_set() constrained_interval = Intersection(constraint, constrained_interval) return constrained_interval - singularities(f, symbol, domain) def function_range(f, symbol, domain): """ Finds the range of a function in a given domain. This method is limited by the ability to determine the singularities and determine limits. Parameters ========== f : :py:class:`~.Expr` The concerned function. symbol : :py:class:`~.Symbol` The variable for which the range of function is to be determined. domain : :py:class:`~.Interval` The domain under which the range of the function has to be found. Examples ======== >>> from sympy import Interval, Symbol, S, exp, log, pi, sqrt, sin, tan >>> from sympy.calculus.util import function_range >>> x = Symbol('x') >>> function_range(sin(x), x, Interval(0, 2*pi)) Interval(-1, 1) >>> function_range(tan(x), x, Interval(-pi/2, pi/2)) Interval(-oo, oo) >>> function_range(1/x, x, S.Reals) Union(Interval.open(-oo, 0), Interval.open(0, oo)) >>> function_range(exp(x), x, S.Reals) Interval.open(0, oo) >>> function_range(log(x), x, S.Reals) Interval(-oo, oo) >>> function_range(sqrt(x), x, Interval(-5, 9)) Interval(0, 3) Returns ======= :py:class:`~.Interval` Union of all ranges for all intervals under domain where function is continuous. Raises ====== NotImplementedError If any of the intervals, in the given domain, for which function is continuous are not finite or real, OR if the critical points of the function on the domain cannot be found. """ if domain is S.EmptySet: return S.EmptySet period = periodicity(f, symbol) if period == S.Zero: # the expression is constant wrt symbol return FiniteSet(f.expand()) from sympy.series.limits import limit from sympy.solvers.solveset import solveset if period is not None: if isinstance(domain, Interval): if (domain.inf - domain.sup).is_infinite: domain = Interval(0, period) elif isinstance(domain, Union): for sub_dom in domain.args: if isinstance(sub_dom, Interval) and \ ((sub_dom.inf - sub_dom.sup).is_infinite): domain = Interval(0, period) intervals = continuous_domain(f, symbol, domain) range_int = S.EmptySet if isinstance(intervals,(Interval, FiniteSet)): interval_iter = (intervals,) elif isinstance(intervals, Union): interval_iter = intervals.args else: raise NotImplementedError(filldedent(''' Unable to find range for the given domain. ''')) for interval in interval_iter: if isinstance(interval, FiniteSet): for singleton in interval: if singleton in domain: range_int += FiniteSet(f.subs(symbol, singleton)) elif isinstance(interval, Interval): vals = S.EmptySet critical_points = S.EmptySet critical_values = S.EmptySet bounds = ((interval.left_open, interval.inf, '+'), (interval.right_open, interval.sup, '-')) for is_open, limit_point, direction in bounds: if is_open: critical_values += FiniteSet(limit(f, symbol, limit_point, direction)) vals += critical_values else: vals += FiniteSet(f.subs(symbol, limit_point)) solution = solveset(f.diff(symbol), symbol, interval) if not iterable(solution): raise NotImplementedError( 'Unable to find critical points for {}'.format(f)) if isinstance(solution, ImageSet): raise NotImplementedError( 'Infinite number of critical points for {}'.format(f)) critical_points += solution for critical_point in critical_points: vals += FiniteSet(f.subs(symbol, critical_point)) left_open, right_open = False, False if critical_values is not S.EmptySet: if critical_values.inf == vals.inf: left_open = True if critical_values.sup == vals.sup: right_open = True range_int += Interval(vals.inf, vals.sup, left_open, right_open) else: raise NotImplementedError(filldedent(''' Unable to find range for the given domain. ''')) return range_int def not_empty_in(finset_intersection, *syms): """ Finds the domain of the functions in ``finset_intersection`` in which the ``finite_set`` is not-empty Parameters ========== finset_intersection : Intersection of FiniteSet The unevaluated intersection of FiniteSet containing real-valued functions with Union of Sets syms : Tuple of symbols Symbol for which domain is to be found Raises ====== NotImplementedError The algorithms to find the non-emptiness of the given FiniteSet are not yet implemented. ValueError The input is not valid. RuntimeError It is a bug, please report it to the github issue tracker (https://github.com/sympy/sympy/issues). Examples ======== >>> from sympy import FiniteSet, Interval, not_empty_in, oo >>> from sympy.abc import x >>> not_empty_in(FiniteSet(x/2).intersect(Interval(0, 1)), x) Interval(0, 2) >>> not_empty_in(FiniteSet(x, x**2).intersect(Interval(1, 2)), x) Union(Interval(1, 2), Interval(-sqrt(2), -1)) >>> not_empty_in(FiniteSet(x**2/(x + 2)).intersect(Interval(1, oo)), x) Union(Interval.Lopen(-2, -1), Interval(2, oo)) """ # TODO: handle piecewise defined functions # TODO: handle transcendental functions # TODO: handle multivariate functions if len(syms) == 0: raise ValueError("One or more symbols must be given in syms.") if finset_intersection is S.EmptySet: return S.EmptySet if isinstance(finset_intersection, Union): elm_in_sets = finset_intersection.args[0] return Union(not_empty_in(finset_intersection.args[1], *syms), elm_in_sets) if isinstance(finset_intersection, FiniteSet): finite_set = finset_intersection _sets = S.Reals else: finite_set = finset_intersection.args[1] _sets = finset_intersection.args[0] if not isinstance(finite_set, FiniteSet): raise ValueError('A FiniteSet must be given, not %s: %s' % (type(finite_set), finite_set)) if len(syms) == 1: symb = syms[0] else: raise NotImplementedError('more than one variables %s not handled' % (syms,)) def elm_domain(expr, intrvl): """ Finds the domain of an expression in any given interval """ from sympy.solvers.solveset import solveset _start = intrvl.start _end = intrvl.end _singularities = solveset(expr.as_numer_denom()[1], symb, domain=S.Reals) if intrvl.right_open: if _end is S.Infinity: _domain1 = S.Reals else: _domain1 = solveset(expr < _end, symb, domain=S.Reals) else: _domain1 = solveset(expr <= _end, symb, domain=S.Reals) if intrvl.left_open: if _start is S.NegativeInfinity: _domain2 = S.Reals else: _domain2 = solveset(expr > _start, symb, domain=S.Reals) else: _domain2 = solveset(expr >= _start, symb, domain=S.Reals) # domain in the interval expr_with_sing = Intersection(_domain1, _domain2) expr_domain = Complement(expr_with_sing, _singularities) return expr_domain if isinstance(_sets, Interval): return Union(*[elm_domain(element, _sets) for element in finite_set]) if isinstance(_sets, Union): _domain = S.EmptySet for intrvl in _sets.args: _domain_element = Union(*[elm_domain(element, intrvl) for element in finite_set]) _domain = Union(_domain, _domain_element) return _domain def periodicity(f, symbol, check=False): """ Tests the given function for periodicity in the given symbol. Parameters ========== f : :py:class:`~.Expr`. The concerned function. symbol : :py:class:`~.Symbol` The variable for which the period is to be determined. check : bool, optional The flag to verify whether the value being returned is a period or not. Returns ======= period The period of the function is returned. ``None`` is returned when the function is aperiodic or has a complex period. The value of $0$ is returned as the period of a constant function. Raises ====== NotImplementedError The value of the period computed cannot be verified. Notes ===== Currently, we do not support functions with a complex period. The period of functions having complex periodic values such as ``exp``, ``sinh`` is evaluated to ``None``. The value returned might not be the "fundamental" period of the given function i.e. it may not be the smallest periodic value of the function. The verification of the period through the ``check`` flag is not reliable due to internal simplification of the given expression. Hence, it is set to ``False`` by default. Examples ======== >>> from sympy import periodicity, Symbol, sin, cos, tan, exp >>> x = Symbol('x') >>> f = sin(x) + sin(2*x) + sin(3*x) >>> periodicity(f, x) 2*pi >>> periodicity(sin(x)*cos(x), x) pi >>> periodicity(exp(tan(2*x) - 1), x) pi/2 >>> periodicity(sin(4*x)**cos(2*x), x) pi >>> periodicity(exp(x), x) """ if symbol.kind is not NumberKind: raise NotImplementedError("Cannot use symbol of kind %s" % symbol.kind) temp = Dummy('x', real=True) f = f.subs(symbol, temp) symbol = temp def _check(orig_f, period): '''Return the checked period or raise an error.''' new_f = orig_f.subs(symbol, symbol + period) if new_f.equals(orig_f): return period else: raise NotImplementedError(filldedent(''' The period of the given function cannot be verified. When `%s` was replaced with `%s + %s` in `%s`, the result was `%s` which was not recognized as being the same as the original function. So either the period was wrong or the two forms were not recognized as being equal. Set check=False to obtain the value.''' % (symbol, symbol, period, orig_f, new_f))) orig_f = f period = None if isinstance(f, Relational): f = f.lhs - f.rhs f = f.simplify() if symbol not in f.free_symbols: return S.Zero if isinstance(f, TrigonometricFunction): try: period = f.period(symbol) except NotImplementedError: pass if isinstance(f, Abs): arg = f.args[0] if isinstance(arg, (sec, csc, cos)): # all but tan and cot might have a # a period that is half as large # so recast as sin arg = sin(arg.args[0]) period = periodicity(arg, symbol) if period is not None and isinstance(arg, sin): # the argument of Abs was a trigonometric other than # cot or tan; test to see if the half-period # is valid. Abs(arg) has behaviour equivalent to # orig_f, so use that for test: orig_f = Abs(arg) try: return _check(orig_f, period/2) except NotImplementedError as err: if check: raise NotImplementedError(err) # else let new orig_f and period be # checked below if isinstance(f, exp) or (f.is_Pow and f.base == S.Exp1): f = Pow(S.Exp1, expand_mul(f.exp)) if im(f) != 0: period_real = periodicity(re(f), symbol) period_imag = periodicity(im(f), symbol) if period_real is not None and period_imag is not None: period = lcim([period_real, period_imag]) if f.is_Pow and f.base != S.Exp1: base, expo = f.args base_has_sym = base.has(symbol) expo_has_sym = expo.has(symbol) if base_has_sym and not expo_has_sym: period = periodicity(base, symbol) elif expo_has_sym and not base_has_sym: period = periodicity(expo, symbol) else: period = _periodicity(f.args, symbol) elif f.is_Mul: coeff, g = f.as_independent(symbol, as_Add=False) if isinstance(g, TrigonometricFunction) or coeff != 1: period = periodicity(g, symbol) else: period = _periodicity(g.args, symbol) elif f.is_Add: k, g = f.as_independent(symbol) if k is not S.Zero: return periodicity(g, symbol) period = _periodicity(g.args, symbol) elif isinstance(f, Mod): a, n = f.args if a == symbol: period = n elif isinstance(a, TrigonometricFunction): period = periodicity(a, symbol) #check if 'f' is linear in 'symbol' elif (a.is_polynomial(symbol) and degree(a, symbol) == 1 and symbol not in n.free_symbols): period = Abs(n / a.diff(symbol)) elif isinstance(f, Piecewise): pass # not handling Piecewise yet as the return type is not favorable elif period is None: from sympy.solvers.decompogen import compogen, decompogen g_s = decompogen(f, symbol) num_of_gs = len(g_s) if num_of_gs > 1: for index, g in enumerate(reversed(g_s)): start_index = num_of_gs - 1 - index g = compogen(g_s[start_index:], symbol) if g not in (orig_f, f): # Fix for issue 12620 period = periodicity(g, symbol) if period is not None: break if period is not None: if check: return _check(orig_f, period) return period return None def _periodicity(args, symbol): """ Helper for `periodicity` to find the period of a list of simpler functions. It uses the `lcim` method to find the least common period of all the functions. Parameters ========== args : Tuple of :py:class:`~.Symbol` All the symbols present in a function. symbol : :py:class:`~.Symbol` The symbol over which the function is to be evaluated. Returns ======= period The least common period of the function for all the symbols of the function. ``None`` if for at least one of the symbols the function is aperiodic. """ periods = [] for f in args: period = periodicity(f, symbol) if period is None: return None if period is not S.Zero: periods.append(period) if len(periods) > 1: return lcim(periods) if periods: return periods[0] def lcim(numbers): """Returns the least common integral multiple of a list of numbers. The numbers can be rational or irrational or a mixture of both. `None` is returned for incommensurable numbers. Parameters ========== numbers : list Numbers (rational and/or irrational) for which lcim is to be found. Returns ======= number lcim if it exists, otherwise ``None`` for incommensurable numbers. Examples ======== >>> from sympy.calculus.util import lcim >>> from sympy import S, pi >>> lcim([S(1)/2, S(3)/4, S(5)/6]) 15/2 >>> lcim([2*pi, 3*pi, pi, pi/2]) 6*pi >>> lcim([S(1), 2*pi]) """ result = None if all(num.is_irrational for num in numbers): factorized_nums = list(map(lambda num: num.factor(), numbers)) factors_num = list( map(lambda num: num.as_coeff_Mul(), factorized_nums)) term = factors_num[0][1] if all(factor == term for coeff, factor in factors_num): common_term = term coeffs = [coeff for coeff, factor in factors_num] result = lcm_list(coeffs) * common_term elif all(num.is_rational for num in numbers): result = lcm_list(numbers) else: pass return result def is_convex(f, *syms, domain=S.Reals): r"""Determines the convexity of the function passed in the argument. Parameters ========== f : :py:class:`~.Expr` The concerned function. syms : Tuple of :py:class:`~.Symbol` The variables with respect to which the convexity is to be determined. domain : :py:class:`~.Interval`, optional The domain over which the convexity of the function has to be checked. If unspecified, S.Reals will be the default domain. Returns ======= bool The method returns ``True`` if the function is convex otherwise it returns ``False``. Raises ====== NotImplementedError The check for the convexity of multivariate functions is not implemented yet. Notes ===== To determine concavity of a function pass `-f` as the concerned function. To determine logarithmic convexity of a function pass `\log(f)` as concerned function. To determine logarithmic concavity of a function pass `-\log(f)` as concerned function. Currently, convexity check of multivariate functions is not handled. Examples ======== >>> from sympy import is_convex, symbols, exp, oo, Interval >>> x = symbols('x') >>> is_convex(exp(x), x) True >>> is_convex(x**3, x, domain = Interval(-1, oo)) False >>> is_convex(1/x**2, x, domain=Interval.open(0, oo)) True References ========== .. [1] https://en.wikipedia.org/wiki/Convex_function .. [2] http://www.ifp.illinois.edu/~angelia/L3_convfunc.pdf .. [3] https://en.wikipedia.org/wiki/Logarithmically_convex_function .. [4] https://en.wikipedia.org/wiki/Logarithmically_concave_function .. [5] https://en.wikipedia.org/wiki/Concave_function """ if len(syms) > 1: raise NotImplementedError( "The check for the convexity of multivariate functions is not implemented yet.") from sympy.solvers.inequalities import solve_univariate_inequality f = _sympify(f) var = syms[0] if any(s in domain for s in singularities(f, var)): return False condition = f.diff(var, 2) < 0 if solve_univariate_inequality(condition, var, False, domain): return False return True def stationary_points(f, symbol, domain=S.Reals): """ Returns the stationary points of a function (where derivative of the function is 0) in the given domain. Parameters ========== f : :py:class:`~.Expr` The concerned function. symbol : :py:class:`~.Symbol` The variable for which the stationary points are to be determined. domain : :py:class:`~.Interval` The domain over which the stationary points have to be checked. If unspecified, ``S.Reals`` will be the default domain. Returns ======= Set A set of stationary points for the function. If there are no stationary point, an :py:class:`~.EmptySet` is returned. Examples ======== >>> from sympy import Interval, Symbol, S, sin, pi, pprint, stationary_points >>> x = Symbol('x') >>> stationary_points(1/x, x, S.Reals) EmptySet >>> pprint(stationary_points(sin(x), x), use_unicode=False) pi 3*pi {2*n*pi + -- | n in Integers} U {2*n*pi + ---- | n in Integers} 2 2 >>> stationary_points(sin(x),x, Interval(0, 4*pi)) {pi/2, 3*pi/2, 5*pi/2, 7*pi/2} """ from sympy.solvers.solveset import solveset if domain is S.EmptySet: return S.EmptySet domain = continuous_domain(f, symbol, domain) set = solveset(diff(f, symbol), symbol, domain) return set def maximum(f, symbol, domain=S.Reals): """ Returns the maximum value of a function in the given domain. Parameters ========== f : :py:class:`~.Expr` The concerned function. symbol : :py:class:`~.Symbol` The variable for maximum value needs to be determined. domain : :py:class:`~.Interval` The domain over which the maximum have to be checked. If unspecified, then the global maximum is returned. Returns ======= number Maximum value of the function in given domain. Examples ======== >>> from sympy import Interval, Symbol, S, sin, cos, pi, maximum >>> x = Symbol('x') >>> f = -x**2 + 2*x + 5 >>> maximum(f, x, S.Reals) 6 >>> maximum(sin(x), x, Interval(-pi, pi/4)) sqrt(2)/2 >>> maximum(sin(x)*cos(x), x) 1/2 """ if isinstance(symbol, Symbol): if domain is S.EmptySet: raise ValueError("Maximum value not defined for empty domain.") return function_range(f, symbol, domain).sup else: raise ValueError("%s is not a valid symbol." % symbol) def minimum(f, symbol, domain=S.Reals): """ Returns the minimum value of a function in the given domain. Parameters ========== f : :py:class:`~.Expr` The concerned function. symbol : :py:class:`~.Symbol` The variable for minimum value needs to be determined. domain : :py:class:`~.Interval` The domain over which the minimum have to be checked. If unspecified, then the global minimum is returned. Returns ======= number Minimum value of the function in the given domain. Examples ======== >>> from sympy import Interval, Symbol, S, sin, cos, minimum >>> x = Symbol('x') >>> f = x**2 + 2*x + 5 >>> minimum(f, x, S.Reals) 4 >>> minimum(sin(x), x, Interval(2, 3)) sin(3) >>> minimum(sin(x)*cos(x), x) -1/2 """ if isinstance(symbol, Symbol): if domain is S.EmptySet: raise ValueError("Minimum value not defined for empty domain.") return function_range(f, symbol, domain).inf else: raise ValueError("%s is not a valid symbol." % symbol)
870af5ad92d9eca53d5df91b6790100ffab78a75d25b7f9c7ff3ec53ae01cf81
"""Module for compiling codegen output, and wrap the binary for use in python. .. note:: To use the autowrap module it must first be imported >>> from sympy.utilities.autowrap import autowrap This module provides a common interface for different external backends, such as f2py, fwrap, Cython, SWIG(?) etc. (Currently only f2py and Cython are implemented) The goal is to provide access to compiled binaries of acceptable performance with a one-button user interface, e.g., >>> from sympy.abc import x,y >>> expr = (x - y)**25 >>> flat = expr.expand() >>> binary_callable = autowrap(flat) >>> binary_callable(2, 3) -1.0 Although a SymPy user might primarily be interested in working with mathematical expressions and not in the details of wrapping tools needed to evaluate such expressions efficiently in numerical form, the user cannot do so without some understanding of the limits in the target language. For example, the expanded expression contains large coefficients which result in loss of precision when computing the expression: >>> binary_callable(3, 2) 0.0 >>> binary_callable(4, 5), binary_callable(5, 4) (-22925376.0, 25165824.0) Wrapping the unexpanded expression gives the expected behavior: >>> e = autowrap(expr) >>> e(4, 5), e(5, 4) (-1.0, 1.0) The callable returned from autowrap() is a binary Python function, not a SymPy object. If it is desired to use the compiled function in symbolic expressions, it is better to use binary_function() which returns a SymPy Function object. The binary callable is attached as the _imp_ attribute and invoked when a numerical evaluation is requested with evalf(), or with lambdify(). >>> from sympy.utilities.autowrap import binary_function >>> f = binary_function('f', expr) >>> 2*f(x, y) + y y + 2*f(x, y) >>> (2*f(x, y) + y).evalf(2, subs={x: 1, y:2}) 0.e-110 When is this useful? 1) For computations on large arrays, Python iterations may be too slow, and depending on the mathematical expression, it may be difficult to exploit the advanced index operations provided by NumPy. 2) For *really* long expressions that will be called repeatedly, the compiled binary should be significantly faster than SymPy's .evalf() 3) If you are generating code with the codegen utility in order to use it in another project, the automatic Python wrappers let you test the binaries immediately from within SymPy. 4) To create customized ufuncs for use with numpy arrays. See *ufuncify*. When is this module NOT the best approach? 1) If you are really concerned about speed or memory optimizations, you will probably get better results by working directly with the wrapper tools and the low level code. However, the files generated by this utility may provide a useful starting point and reference code. Temporary files will be left intact if you supply the keyword tempdir="path/to/files/". 2) If the array computation can be handled easily by numpy, and you do not need the binaries for another project. """ import sys import os import shutil import tempfile from subprocess import STDOUT, CalledProcessError, check_output from string import Template from warnings import warn from sympy.core.cache import cacheit from sympy.core.function import Lambda from sympy.core.relational import Eq from sympy.core.symbol import Dummy, Symbol from sympy.tensor.indexed import Idx, IndexedBase from sympy.utilities.codegen import (make_routine, get_code_generator, OutputArgument, InOutArgument, InputArgument, CodeGenArgumentListError, Result, ResultBase, C99CodeGen) from sympy.utilities.iterables import iterable from sympy.utilities.lambdify import implemented_function from sympy.utilities.decorator import doctest_depends_on _doctest_depends_on = {'exe': ('f2py', 'gfortran', 'gcc'), 'modules': ('numpy',)} class CodeWrapError(Exception): pass class CodeWrapper: """Base Class for code wrappers""" _filename = "wrapped_code" _module_basename = "wrapper_module" _module_counter = 0 @property def filename(self): return "%s_%s" % (self._filename, CodeWrapper._module_counter) @property def module_name(self): return "%s_%s" % (self._module_basename, CodeWrapper._module_counter) def __init__(self, generator, filepath=None, flags=[], verbose=False): """ generator -- the code generator to use """ self.generator = generator self.filepath = filepath self.flags = flags self.quiet = not verbose @property def include_header(self): return bool(self.filepath) @property def include_empty(self): return bool(self.filepath) def _generate_code(self, main_routine, routines): routines.append(main_routine) self.generator.write( routines, self.filename, True, self.include_header, self.include_empty) def wrap_code(self, routine, helpers=None): helpers = helpers or [] if self.filepath: workdir = os.path.abspath(self.filepath) else: workdir = tempfile.mkdtemp("_sympy_compile") if not os.access(workdir, os.F_OK): os.mkdir(workdir) oldwork = os.getcwd() os.chdir(workdir) try: sys.path.append(workdir) self._generate_code(routine, helpers) self._prepare_files(routine) self._process_files(routine) mod = __import__(self.module_name) finally: sys.path.remove(workdir) CodeWrapper._module_counter += 1 os.chdir(oldwork) if not self.filepath: try: shutil.rmtree(workdir) except OSError: # Could be some issues on Windows pass return self._get_wrapped_function(mod, routine.name) def _process_files(self, routine): command = self.command command.extend(self.flags) try: retoutput = check_output(command, stderr=STDOUT) except CalledProcessError as e: raise CodeWrapError( "Error while executing command: %s. Command output is:\n%s" % ( " ".join(command), e.output.decode('utf-8'))) if not self.quiet: print(retoutput) class DummyWrapper(CodeWrapper): """Class used for testing independent of backends """ template = """# dummy module for testing of SymPy def %(name)s(): return "%(expr)s" %(name)s.args = "%(args)s" %(name)s.returns = "%(retvals)s" """ def _prepare_files(self, routine): return def _generate_code(self, routine, helpers): with open('%s.py' % self.module_name, 'w') as f: printed = ", ".join( [str(res.expr) for res in routine.result_variables]) # convert OutputArguments to return value like f2py args = filter(lambda x: not isinstance( x, OutputArgument), routine.arguments) retvals = [] for val in routine.result_variables: if isinstance(val, Result): retvals.append('nameless') else: retvals.append(val.result_var) print(DummyWrapper.template % { 'name': routine.name, 'expr': printed, 'args': ", ".join([str(a.name) for a in args]), 'retvals': ", ".join([str(val) for val in retvals]) }, end="", file=f) def _process_files(self, routine): return @classmethod def _get_wrapped_function(cls, mod, name): return getattr(mod, name) class CythonCodeWrapper(CodeWrapper): """Wrapper that uses Cython""" setup_template = """\ try: from setuptools import setup from setuptools import Extension except ImportError: from distutils.core import setup from distutils.extension import Extension from Cython.Build import cythonize cy_opts = {cythonize_options} {np_import} ext_mods = [Extension( {ext_args}, include_dirs={include_dirs}, library_dirs={library_dirs}, libraries={libraries}, extra_compile_args={extra_compile_args}, extra_link_args={extra_link_args} )] setup(ext_modules=cythonize(ext_mods, **cy_opts)) """ _cythonize_options = {'compiler_directives':{'language_level' : "3"}} pyx_imports = ( "import numpy as np\n" "cimport numpy as np\n\n") pyx_header = ( "cdef extern from '{header_file}.h':\n" " {prototype}\n\n") pyx_func = ( "def {name}_c({arg_string}):\n" "\n" "{declarations}" "{body}") std_compile_flag = '-std=c99' def __init__(self, *args, **kwargs): """Instantiates a Cython code wrapper. The following optional parameters get passed to ``distutils.Extension`` for building the Python extension module. Read its documentation to learn more. Parameters ========== include_dirs : [list of strings] A list of directories to search for C/C++ header files (in Unix form for portability). library_dirs : [list of strings] A list of directories to search for C/C++ libraries at link time. libraries : [list of strings] A list of library names (not filenames or paths) to link against. extra_compile_args : [list of strings] Any extra platform- and compiler-specific information to use when compiling the source files in 'sources'. For platforms and compilers where "command line" makes sense, this is typically a list of command-line arguments, but for other platforms it could be anything. Note that the attribute ``std_compile_flag`` will be appended to this list. extra_link_args : [list of strings] Any extra platform- and compiler-specific information to use when linking object files together to create the extension (or to create a new static Python interpreter). Similar interpretation as for 'extra_compile_args'. cythonize_options : [dictionary] Keyword arguments passed on to cythonize. """ self._include_dirs = kwargs.pop('include_dirs', []) self._library_dirs = kwargs.pop('library_dirs', []) self._libraries = kwargs.pop('libraries', []) self._extra_compile_args = kwargs.pop('extra_compile_args', []) self._extra_compile_args.append(self.std_compile_flag) self._extra_link_args = kwargs.pop('extra_link_args', []) self._cythonize_options = kwargs.pop('cythonize_options', self._cythonize_options) self._need_numpy = False super().__init__(*args, **kwargs) @property def command(self): command = [sys.executable, "setup.py", "build_ext", "--inplace"] return command def _prepare_files(self, routine, build_dir=os.curdir): # NOTE : build_dir is used for testing purposes. pyxfilename = self.module_name + '.pyx' codefilename = "%s.%s" % (self.filename, self.generator.code_extension) # pyx with open(os.path.join(build_dir, pyxfilename), 'w') as f: self.dump_pyx([routine], f, self.filename) # setup.py ext_args = [repr(self.module_name), repr([pyxfilename, codefilename])] if self._need_numpy: np_import = 'import numpy as np\n' self._include_dirs.append('np.get_include()') else: np_import = '' with open(os.path.join(build_dir, 'setup.py'), 'w') as f: includes = str(self._include_dirs).replace("'np.get_include()'", 'np.get_include()') f.write(self.setup_template.format( ext_args=", ".join(ext_args), np_import=np_import, include_dirs=includes, library_dirs=self._library_dirs, libraries=self._libraries, extra_compile_args=self._extra_compile_args, extra_link_args=self._extra_link_args, cythonize_options=self._cythonize_options )) @classmethod def _get_wrapped_function(cls, mod, name): return getattr(mod, name + '_c') def dump_pyx(self, routines, f, prefix): """Write a Cython file with Python wrappers This file contains all the definitions of the routines in c code and refers to the header file. Arguments --------- routines List of Routine instances f File-like object to write the file to prefix The filename prefix, used to refer to the proper header file. Only the basename of the prefix is used. """ headers = [] functions = [] for routine in routines: prototype = self.generator.get_prototype(routine) # C Function Header Import headers.append(self.pyx_header.format(header_file=prefix, prototype=prototype)) # Partition the C function arguments into categories py_rets, py_args, py_loc, py_inf = self._partition_args(routine.arguments) # Function prototype name = routine.name arg_string = ", ".join(self._prototype_arg(arg) for arg in py_args) # Local Declarations local_decs = [] for arg, val in py_inf.items(): proto = self._prototype_arg(arg) mat, ind = [self._string_var(v) for v in val] local_decs.append(" cdef {} = {}.shape[{}]".format(proto, mat, ind)) local_decs.extend([" cdef {}".format(self._declare_arg(a)) for a in py_loc]) declarations = "\n".join(local_decs) if declarations: declarations = declarations + "\n" # Function Body args_c = ", ".join([self._call_arg(a) for a in routine.arguments]) rets = ", ".join([self._string_var(r.name) for r in py_rets]) if routine.results: body = ' return %s(%s)' % (routine.name, args_c) if rets: body = body + ', ' + rets else: body = ' %s(%s)\n' % (routine.name, args_c) body = body + ' return ' + rets functions.append(self.pyx_func.format(name=name, arg_string=arg_string, declarations=declarations, body=body)) # Write text to file if self._need_numpy: # Only import numpy if required f.write(self.pyx_imports) f.write('\n'.join(headers)) f.write('\n'.join(functions)) def _partition_args(self, args): """Group function arguments into categories.""" py_args = [] py_returns = [] py_locals = [] py_inferred = {} for arg in args: if isinstance(arg, OutputArgument): py_returns.append(arg) py_locals.append(arg) elif isinstance(arg, InOutArgument): py_returns.append(arg) py_args.append(arg) else: py_args.append(arg) # Find arguments that are array dimensions. These can be inferred # locally in the Cython code. if isinstance(arg, (InputArgument, InOutArgument)) and arg.dimensions: dims = [d[1] + 1 for d in arg.dimensions] sym_dims = [(i, d) for (i, d) in enumerate(dims) if isinstance(d, Symbol)] for (i, d) in sym_dims: py_inferred[d] = (arg.name, i) for arg in args: if arg.name in py_inferred: py_inferred[arg] = py_inferred.pop(arg.name) # Filter inferred arguments from py_args py_args = [a for a in py_args if a not in py_inferred] return py_returns, py_args, py_locals, py_inferred def _prototype_arg(self, arg): mat_dec = "np.ndarray[{mtype}, ndim={ndim}] {name}" np_types = {'double': 'np.double_t', 'int': 'np.int_t'} t = arg.get_datatype('c') if arg.dimensions: self._need_numpy = True ndim = len(arg.dimensions) mtype = np_types[t] return mat_dec.format(mtype=mtype, ndim=ndim, name=self._string_var(arg.name)) else: return "%s %s" % (t, self._string_var(arg.name)) def _declare_arg(self, arg): proto = self._prototype_arg(arg) if arg.dimensions: shape = '(' + ','.join(self._string_var(i[1] + 1) for i in arg.dimensions) + ')' return proto + " = np.empty({shape})".format(shape=shape) else: return proto + " = 0" def _call_arg(self, arg): if arg.dimensions: t = arg.get_datatype('c') return "<{}*> {}.data".format(t, self._string_var(arg.name)) elif isinstance(arg, ResultBase): return "&{}".format(self._string_var(arg.name)) else: return self._string_var(arg.name) def _string_var(self, var): printer = self.generator.printer.doprint return printer(var) class F2PyCodeWrapper(CodeWrapper): """Wrapper that uses f2py""" def __init__(self, *args, **kwargs): ext_keys = ['include_dirs', 'library_dirs', 'libraries', 'extra_compile_args', 'extra_link_args'] msg = ('The compilation option kwarg {} is not supported with the f2py ' 'backend.') for k in ext_keys: if k in kwargs.keys(): warn(msg.format(k)) kwargs.pop(k, None) super().__init__(*args, **kwargs) @property def command(self): filename = self.filename + '.' + self.generator.code_extension args = ['-c', '-m', self.module_name, filename] command = [sys.executable, "-c", "import numpy.f2py as f2py2e;f2py2e.main()"]+args return command def _prepare_files(self, routine): pass @classmethod def _get_wrapped_function(cls, mod, name): return getattr(mod, name) # Here we define a lookup of backends -> tuples of languages. For now, each # tuple is of length 1, but if a backend supports more than one language, # the most preferable language is listed first. _lang_lookup = {'CYTHON': ('C99', 'C89', 'C'), 'F2PY': ('F95',), 'NUMPY': ('C99', 'C89', 'C'), 'DUMMY': ('F95',)} # Dummy here just for testing def _infer_language(backend): """For a given backend, return the top choice of language""" langs = _lang_lookup.get(backend.upper(), False) if not langs: raise ValueError("Unrecognized backend: " + backend) return langs[0] def _validate_backend_language(backend, language): """Throws error if backend and language are incompatible""" langs = _lang_lookup.get(backend.upper(), False) if not langs: raise ValueError("Unrecognized backend: " + backend) if language.upper() not in langs: raise ValueError(("Backend {} and language {} are " "incompatible").format(backend, language)) @cacheit @doctest_depends_on(exe=('f2py', 'gfortran'), modules=('numpy',)) def autowrap(expr, language=None, backend='f2py', tempdir=None, args=None, flags=None, verbose=False, helpers=None, code_gen=None, **kwargs): """Generates Python callable binaries based on the math expression. Parameters ========== expr The SymPy expression that should be wrapped as a binary routine. language : string, optional If supplied, (options: 'C' or 'F95'), specifies the language of the generated code. If ``None`` [default], the language is inferred based upon the specified backend. backend : string, optional Backend used to wrap the generated code. Either 'f2py' [default], or 'cython'. tempdir : string, optional Path to directory for temporary files. If this argument is supplied, the generated code and the wrapper input files are left intact in the specified path. args : iterable, optional An ordered iterable of symbols. Specifies the argument sequence for the function. flags : iterable, optional Additional option flags that will be passed to the backend. verbose : bool, optional If True, autowrap will not mute the command line backends. This can be helpful for debugging. helpers : 3-tuple or iterable of 3-tuples, optional Used to define auxiliary expressions needed for the main expr. If the main expression needs to call a specialized function it should be passed in via ``helpers``. Autowrap will then make sure that the compiled main expression can link to the helper routine. Items should be 3-tuples with (<function_name>, <sympy_expression>, <argument_tuple>). It is mandatory to supply an argument sequence to helper routines. code_gen : CodeGen instance An instance of a CodeGen subclass. Overrides ``language``. include_dirs : [string] A list of directories to search for C/C++ header files (in Unix form for portability). library_dirs : [string] A list of directories to search for C/C++ libraries at link time. libraries : [string] A list of library names (not filenames or paths) to link against. extra_compile_args : [string] Any extra platform- and compiler-specific information to use when compiling the source files in 'sources'. For platforms and compilers where "command line" makes sense, this is typically a list of command-line arguments, but for other platforms it could be anything. extra_link_args : [string] Any extra platform- and compiler-specific information to use when linking object files together to create the extension (or to create a new static Python interpreter). Similar interpretation as for 'extra_compile_args'. Examples ======== >>> from sympy.abc import x, y, z >>> from sympy.utilities.autowrap import autowrap >>> expr = ((x - y + z)**(13)).expand() >>> binary_func = autowrap(expr) >>> binary_func(1, 4, 2) -1.0 """ if language: if not isinstance(language, type): _validate_backend_language(backend, language) else: language = _infer_language(backend) # two cases 1) helpers is an iterable of 3-tuples and 2) helpers is a # 3-tuple if iterable(helpers) and len(helpers) != 0 and iterable(helpers[0]): helpers = helpers if helpers else () else: helpers = [helpers] if helpers else () args = list(args) if iterable(args, exclude=set) else args if code_gen is None: code_gen = get_code_generator(language, "autowrap") CodeWrapperClass = { 'F2PY': F2PyCodeWrapper, 'CYTHON': CythonCodeWrapper, 'DUMMY': DummyWrapper }[backend.upper()] code_wrapper = CodeWrapperClass(code_gen, tempdir, flags if flags else (), verbose, **kwargs) helps = [] for name_h, expr_h, args_h in helpers: helps.append(code_gen.routine(name_h, expr_h, args_h)) for name_h, expr_h, args_h in helpers: if expr.has(expr_h): name_h = binary_function(name_h, expr_h, backend='dummy') expr = expr.subs(expr_h, name_h(*args_h)) try: routine = code_gen.routine('autofunc', expr, args) except CodeGenArgumentListError as e: # if all missing arguments are for pure output, we simply attach them # at the end and try again, because the wrappers will silently convert # them to return values anyway. new_args = [] for missing in e.missing_args: if not isinstance(missing, OutputArgument): raise new_args.append(missing.name) routine = code_gen.routine('autofunc', expr, args + new_args) return code_wrapper.wrap_code(routine, helpers=helps) @doctest_depends_on(exe=('f2py', 'gfortran'), modules=('numpy',)) def binary_function(symfunc, expr, **kwargs): """Returns a SymPy function with expr as binary implementation This is a convenience function that automates the steps needed to autowrap the SymPy expression and attaching it to a Function object with implemented_function(). Parameters ========== symfunc : SymPy Function The function to bind the callable to. expr : SymPy Expression The expression used to generate the function. kwargs : dict Any kwargs accepted by autowrap. Examples ======== >>> from sympy.abc import x, y >>> from sympy.utilities.autowrap import binary_function >>> expr = ((x - y)**(25)).expand() >>> f = binary_function('f', expr) >>> type(f) <class 'sympy.core.function.UndefinedFunction'> >>> 2*f(x, y) 2*f(x, y) >>> f(x, y).evalf(2, subs={x: 1, y: 2}) -1.0 """ binary = autowrap(expr, **kwargs) return implemented_function(symfunc, binary) ################################################################# # UFUNCIFY # ################################################################# _ufunc_top = Template("""\ #include "Python.h" #include "math.h" #include "numpy/ndarraytypes.h" #include "numpy/ufuncobject.h" #include "numpy/halffloat.h" #include ${include_file} static PyMethodDef ${module}Methods[] = { {NULL, NULL, 0, NULL} };""") _ufunc_outcalls = Template("*((double *)out${outnum}) = ${funcname}(${call_args});") _ufunc_body = Template("""\ static void ${funcname}_ufunc(char **args, npy_intp *dimensions, npy_intp* steps, void* data) { npy_intp i; npy_intp n = dimensions[0]; ${declare_args} ${declare_steps} for (i = 0; i < n; i++) { ${outcalls} ${step_increments} } } PyUFuncGenericFunction ${funcname}_funcs[1] = {&${funcname}_ufunc}; static char ${funcname}_types[${n_types}] = ${types} static void *${funcname}_data[1] = {NULL};""") _ufunc_bottom = Template("""\ #if PY_VERSION_HEX >= 0x03000000 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "${module}", NULL, -1, ${module}Methods, NULL, NULL, NULL, NULL }; PyMODINIT_FUNC PyInit_${module}(void) { PyObject *m, *d; ${function_creation} m = PyModule_Create(&moduledef); if (!m) { return NULL; } import_array(); import_umath(); d = PyModule_GetDict(m); ${ufunc_init} return m; } #else PyMODINIT_FUNC init${module}(void) { PyObject *m, *d; ${function_creation} m = Py_InitModule("${module}", ${module}Methods); if (m == NULL) { return; } import_array(); import_umath(); d = PyModule_GetDict(m); ${ufunc_init} } #endif\ """) _ufunc_init_form = Template("""\ ufunc${ind} = PyUFunc_FromFuncAndData(${funcname}_funcs, ${funcname}_data, ${funcname}_types, 1, ${n_in}, ${n_out}, PyUFunc_None, "${module}", ${docstring}, 0); PyDict_SetItemString(d, "${funcname}", ufunc${ind}); Py_DECREF(ufunc${ind});""") _ufunc_setup = Template("""\ def configuration(parent_package='', top_path=None): import numpy from numpy.distutils.misc_util import Configuration config = Configuration('', parent_package, top_path) config.add_extension('${module}', sources=['${module}.c', '${filename}.c']) return config if __name__ == "__main__": from numpy.distutils.core import setup setup(configuration=configuration)""") class UfuncifyCodeWrapper(CodeWrapper): """Wrapper for Ufuncify""" def __init__(self, *args, **kwargs): ext_keys = ['include_dirs', 'library_dirs', 'libraries', 'extra_compile_args', 'extra_link_args'] msg = ('The compilation option kwarg {} is not supported with the numpy' ' backend.') for k in ext_keys: if k in kwargs.keys(): warn(msg.format(k)) kwargs.pop(k, None) super().__init__(*args, **kwargs) @property def command(self): command = [sys.executable, "setup.py", "build_ext", "--inplace"] return command def wrap_code(self, routines, helpers=None): # This routine overrides CodeWrapper because we can't assume funcname == routines[0].name # Therefore we have to break the CodeWrapper private API. # There isn't an obvious way to extend multi-expr support to # the other autowrap backends, so we limit this change to ufuncify. helpers = helpers if helpers is not None else [] # We just need a consistent name funcname = 'wrapped_' + str(id(routines) + id(helpers)) workdir = self.filepath or tempfile.mkdtemp("_sympy_compile") if not os.access(workdir, os.F_OK): os.mkdir(workdir) oldwork = os.getcwd() os.chdir(workdir) try: sys.path.append(workdir) self._generate_code(routines, helpers) self._prepare_files(routines, funcname) self._process_files(routines) mod = __import__(self.module_name) finally: sys.path.remove(workdir) CodeWrapper._module_counter += 1 os.chdir(oldwork) if not self.filepath: try: shutil.rmtree(workdir) except OSError: # Could be some issues on Windows pass return self._get_wrapped_function(mod, funcname) def _generate_code(self, main_routines, helper_routines): all_routines = main_routines + helper_routines self.generator.write( all_routines, self.filename, True, self.include_header, self.include_empty) def _prepare_files(self, routines, funcname): # C codefilename = self.module_name + '.c' with open(codefilename, 'w') as f: self.dump_c(routines, f, self.filename, funcname=funcname) # setup.py with open('setup.py', 'w') as f: self.dump_setup(f) @classmethod def _get_wrapped_function(cls, mod, name): return getattr(mod, name) def dump_setup(self, f): setup = _ufunc_setup.substitute(module=self.module_name, filename=self.filename) f.write(setup) def dump_c(self, routines, f, prefix, funcname=None): """Write a C file with Python wrappers This file contains all the definitions of the routines in c code. Arguments --------- routines List of Routine instances f File-like object to write the file to prefix The filename prefix, used to name the imported module. funcname Name of the main function to be returned. """ if funcname is None: if len(routines) == 1: funcname = routines[0].name else: msg = 'funcname must be specified for multiple output routines' raise ValueError(msg) functions = [] function_creation = [] ufunc_init = [] module = self.module_name include_file = "\"{}.h\"".format(prefix) top = _ufunc_top.substitute(include_file=include_file, module=module) name = funcname # Partition the C function arguments into categories # Here we assume all routines accept the same arguments r_index = 0 py_in, _ = self._partition_args(routines[0].arguments) n_in = len(py_in) n_out = len(routines) # Declare Args form = "char *{0}{1} = args[{2}];" arg_decs = [form.format('in', i, i) for i in range(n_in)] arg_decs.extend([form.format('out', i, i+n_in) for i in range(n_out)]) declare_args = '\n '.join(arg_decs) # Declare Steps form = "npy_intp {0}{1}_step = steps[{2}];" step_decs = [form.format('in', i, i) for i in range(n_in)] step_decs.extend([form.format('out', i, i+n_in) for i in range(n_out)]) declare_steps = '\n '.join(step_decs) # Call Args form = "*(double *)in{0}" call_args = ', '.join([form.format(a) for a in range(n_in)]) # Step Increments form = "{0}{1} += {0}{1}_step;" step_incs = [form.format('in', i) for i in range(n_in)] step_incs.extend([form.format('out', i, i) for i in range(n_out)]) step_increments = '\n '.join(step_incs) # Types n_types = n_in + n_out types = "{" + ', '.join(["NPY_DOUBLE"]*n_types) + "};" # Docstring docstring = '"Created in SymPy with Ufuncify"' # Function Creation function_creation.append("PyObject *ufunc{};".format(r_index)) # Ufunc initialization init_form = _ufunc_init_form.substitute(module=module, funcname=name, docstring=docstring, n_in=n_in, n_out=n_out, ind=r_index) ufunc_init.append(init_form) outcalls = [_ufunc_outcalls.substitute( outnum=i, call_args=call_args, funcname=routines[i].name) for i in range(n_out)] body = _ufunc_body.substitute(module=module, funcname=name, declare_args=declare_args, declare_steps=declare_steps, call_args=call_args, step_increments=step_increments, n_types=n_types, types=types, outcalls='\n '.join(outcalls)) functions.append(body) body = '\n\n'.join(functions) ufunc_init = '\n '.join(ufunc_init) function_creation = '\n '.join(function_creation) bottom = _ufunc_bottom.substitute(module=module, ufunc_init=ufunc_init, function_creation=function_creation) text = [top, body, bottom] f.write('\n\n'.join(text)) def _partition_args(self, args): """Group function arguments into categories.""" py_in = [] py_out = [] for arg in args: if isinstance(arg, OutputArgument): py_out.append(arg) elif isinstance(arg, InOutArgument): raise ValueError("Ufuncify doesn't support InOutArguments") else: py_in.append(arg) return py_in, py_out @cacheit @doctest_depends_on(exe=('f2py', 'gfortran', 'gcc'), modules=('numpy',)) def ufuncify(args, expr, language=None, backend='numpy', tempdir=None, flags=None, verbose=False, helpers=None, **kwargs): """Generates a binary function that supports broadcasting on numpy arrays. Parameters ========== args : iterable Either a Symbol or an iterable of symbols. Specifies the argument sequence for the function. expr A SymPy expression that defines the element wise operation. language : string, optional If supplied, (options: 'C' or 'F95'), specifies the language of the generated code. If ``None`` [default], the language is inferred based upon the specified backend. backend : string, optional Backend used to wrap the generated code. Either 'numpy' [default], 'cython', or 'f2py'. tempdir : string, optional Path to directory for temporary files. If this argument is supplied, the generated code and the wrapper input files are left intact in the specified path. flags : iterable, optional Additional option flags that will be passed to the backend. verbose : bool, optional If True, autowrap will not mute the command line backends. This can be helpful for debugging. helpers : iterable, optional Used to define auxiliary expressions needed for the main expr. If the main expression needs to call a specialized function it should be put in the ``helpers`` iterable. Autowrap will then make sure that the compiled main expression can link to the helper routine. Items should be tuples with (<funtion_name>, <sympy_expression>, <arguments>). It is mandatory to supply an argument sequence to helper routines. kwargs : dict These kwargs will be passed to autowrap if the `f2py` or `cython` backend is used and ignored if the `numpy` backend is used. Notes ===== The default backend ('numpy') will create actual instances of ``numpy.ufunc``. These support ndimensional broadcasting, and implicit type conversion. Use of the other backends will result in a "ufunc-like" function, which requires equal length 1-dimensional arrays for all arguments, and will not perform any type conversions. References ========== .. [1] http://docs.scipy.org/doc/numpy/reference/ufuncs.html Examples ======== >>> from sympy.utilities.autowrap import ufuncify >>> from sympy.abc import x, y >>> import numpy as np >>> f = ufuncify((x, y), y + x**2) >>> type(f) <class 'numpy.ufunc'> >>> f([1, 2, 3], 2) array([ 3., 6., 11.]) >>> f(np.arange(5), 3) array([ 3., 4., 7., 12., 19.]) For the 'f2py' and 'cython' backends, inputs are required to be equal length 1-dimensional arrays. The 'f2py' backend will perform type conversion, but the Cython backend will error if the inputs are not of the expected type. >>> f_fortran = ufuncify((x, y), y + x**2, backend='f2py') >>> f_fortran(1, 2) array([ 3.]) >>> f_fortran(np.array([1, 2, 3]), np.array([1.0, 2.0, 3.0])) array([ 2., 6., 12.]) >>> f_cython = ufuncify((x, y), y + x**2, backend='Cython') >>> f_cython(1, 2) # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: Argument '_x' has incorrect type (expected numpy.ndarray, got int) >>> f_cython(np.array([1.0]), np.array([2.0])) array([ 3.]) """ if isinstance(args, Symbol): args = (args,) else: args = tuple(args) if language: _validate_backend_language(backend, language) else: language = _infer_language(backend) helpers = helpers if helpers else () flags = flags if flags else () if backend.upper() == 'NUMPY': # maxargs is set by numpy compile-time constant NPY_MAXARGS # If a future version of numpy modifies or removes this restriction # this variable should be changed or removed maxargs = 32 helps = [] for name, expr, args in helpers: helps.append(make_routine(name, expr, args)) code_wrapper = UfuncifyCodeWrapper(C99CodeGen("ufuncify"), tempdir, flags, verbose) if not isinstance(expr, (list, tuple)): expr = [expr] if len(expr) == 0: raise ValueError('Expression iterable has zero length') if len(expr) + len(args) > maxargs: msg = ('Cannot create ufunc with more than {0} total arguments: ' 'got {1} in, {2} out') raise ValueError(msg.format(maxargs, len(args), len(expr))) routines = [make_routine('autofunc{}'.format(idx), exprx, args) for idx, exprx in enumerate(expr)] return code_wrapper.wrap_code(routines, helpers=helps) else: # Dummies are used for all added expressions to prevent name clashes # within the original expression. y = IndexedBase(Dummy('y')) m = Dummy('m', integer=True) i = Idx(Dummy('i', integer=True), m) f_dummy = Dummy('f') f = implemented_function('%s_%d' % (f_dummy.name, f_dummy.dummy_index), Lambda(args, expr)) # For each of the args create an indexed version. indexed_args = [IndexedBase(Dummy(str(a))) for a in args] # Order the arguments (out, args, dim) args = [y] + indexed_args + [m] args_with_indices = [a[i] for a in indexed_args] return autowrap(Eq(y[i], f(*args_with_indices)), language, backend, tempdir, args, flags, verbose, helpers, **kwargs)
61b298e8270dfb0be3b20e77cd43cbd8199fbf26fad873385b8c63b6f3342f9b
""" This module provides convenient functions to transform SymPy expressions to lambda functions which can be used to calculate numerical values very fast. """ from typing import Any, Dict as tDict import builtins import inspect import keyword import textwrap import linecache # Required despite static analysis claiming it is not used from sympy.external import import_module # noqa:F401 from sympy.utilities.exceptions import sympy_deprecation_warning from sympy.utilities.decorator import doctest_depends_on from sympy.utilities.iterables import (is_sequence, iterable, NotIterable, flatten) from sympy.utilities.misc import filldedent __doctest_requires__ = {('lambdify',): ['numpy', 'tensorflow']} # Default namespaces, letting us define translations that can't be defined # by simple variable maps, like I => 1j MATH_DEFAULT = {} # type: tDict[str, Any] MPMATH_DEFAULT = {} # type: tDict[str, Any] NUMPY_DEFAULT = {"I": 1j} # type: tDict[str, Any] SCIPY_DEFAULT = {"I": 1j} # type: tDict[str, Any] CUPY_DEFAULT = {"I": 1j} # type: tDict[str, Any] JAX_DEFAULT = {"I": 1j} # type: tDict[str, Any] TENSORFLOW_DEFAULT = {} # type: tDict[str, Any] SYMPY_DEFAULT = {} # type: tDict[str, Any] NUMEXPR_DEFAULT = {} # type: tDict[str, Any] # These are the namespaces the lambda functions will use. # These are separate from the names above because they are modified # throughout this file, whereas the defaults should remain unmodified. MATH = MATH_DEFAULT.copy() MPMATH = MPMATH_DEFAULT.copy() NUMPY = NUMPY_DEFAULT.copy() SCIPY = SCIPY_DEFAULT.copy() CUPY = CUPY_DEFAULT.copy() JAX = JAX_DEFAULT.copy() TENSORFLOW = TENSORFLOW_DEFAULT.copy() SYMPY = SYMPY_DEFAULT.copy() NUMEXPR = NUMEXPR_DEFAULT.copy() # Mappings between SymPy and other modules function names. MATH_TRANSLATIONS = { "ceiling": "ceil", "E": "e", "ln": "log", } # NOTE: This dictionary is reused in Function._eval_evalf to allow subclasses # of Function to automatically evalf. MPMATH_TRANSLATIONS = { "Abs": "fabs", "elliptic_k": "ellipk", "elliptic_f": "ellipf", "elliptic_e": "ellipe", "elliptic_pi": "ellippi", "ceiling": "ceil", "chebyshevt": "chebyt", "chebyshevu": "chebyu", "E": "e", "I": "j", "ln": "log", #"lowergamma":"lower_gamma", "oo": "inf", #"uppergamma":"upper_gamma", "LambertW": "lambertw", "MutableDenseMatrix": "matrix", "ImmutableDenseMatrix": "matrix", "conjugate": "conj", "dirichlet_eta": "altzeta", "Ei": "ei", "Shi": "shi", "Chi": "chi", "Si": "si", "Ci": "ci", "RisingFactorial": "rf", "FallingFactorial": "ff", "betainc_regularized": "betainc", } NUMPY_TRANSLATIONS = { "Heaviside": "heaviside", } # type: tDict[str, str] SCIPY_TRANSLATIONS = {} # type: tDict[str, str] CUPY_TRANSLATIONS = {} # type: tDict[str, str] JAX_TRANSLATIONS = {} # type: tDict[str, str] TENSORFLOW_TRANSLATIONS = {} # type: tDict[str, str] NUMEXPR_TRANSLATIONS = {} # type: tDict[str, str] # Available modules: MODULES = { "math": (MATH, MATH_DEFAULT, MATH_TRANSLATIONS, ("from math import *",)), "mpmath": (MPMATH, MPMATH_DEFAULT, MPMATH_TRANSLATIONS, ("from mpmath import *",)), "numpy": (NUMPY, NUMPY_DEFAULT, NUMPY_TRANSLATIONS, ("import numpy; from numpy import *; from numpy.linalg import *",)), "scipy": (SCIPY, SCIPY_DEFAULT, SCIPY_TRANSLATIONS, ("import scipy; import numpy; from scipy import *; from scipy.special import *",)), "cupy": (CUPY, CUPY_DEFAULT, CUPY_TRANSLATIONS, ("import cupy",)), "jax": (JAX, JAX_DEFAULT, JAX_TRANSLATIONS, ("import jax",)), "tensorflow": (TENSORFLOW, TENSORFLOW_DEFAULT, TENSORFLOW_TRANSLATIONS, ("import tensorflow",)), "sympy": (SYMPY, SYMPY_DEFAULT, {}, ( "from sympy.functions import *", "from sympy.matrices import *", "from sympy import Integral, pi, oo, nan, zoo, E, I",)), "numexpr" : (NUMEXPR, NUMEXPR_DEFAULT, NUMEXPR_TRANSLATIONS, ("import_module('numexpr')", )), } def _import(module, reload=False): """ Creates a global translation dictionary for module. The argument module has to be one of the following strings: "math", "mpmath", "numpy", "sympy", "tensorflow", "jax". These dictionaries map names of Python functions to their equivalent in other modules. """ try: namespace, namespace_default, translations, import_commands = MODULES[ module] except KeyError: raise NameError( "'%s' module cannot be used for lambdification" % module) # Clear namespace or exit if namespace != namespace_default: # The namespace was already generated, don't do it again if not forced. if reload: namespace.clear() namespace.update(namespace_default) else: return for import_command in import_commands: if import_command.startswith('import_module'): module = eval(import_command) if module is not None: namespace.update(module.__dict__) continue else: try: exec(import_command, {}, namespace) continue except ImportError: pass raise ImportError( "Cannot import '%s' with '%s' command" % (module, import_command)) # Add translated names to namespace for sympyname, translation in translations.items(): namespace[sympyname] = namespace[translation] # For computing the modulus of a SymPy expression we use the builtin abs # function, instead of the previously used fabs function for all # translation modules. This is because the fabs function in the math # module does not accept complex valued arguments. (see issue 9474). The # only exception, where we don't use the builtin abs function is the # mpmath translation module, because mpmath.fabs returns mpf objects in # contrast to abs(). if 'Abs' not in namespace: namespace['Abs'] = abs # Used for dynamically generated filenames that are inserted into the # linecache. _lambdify_generated_counter = 1 @doctest_depends_on(modules=('numpy', 'scipy', 'tensorflow',), python_version=(3,)) def lambdify(args, expr, modules=None, printer=None, use_imps=True, dummify=False, cse=False): """Convert a SymPy expression into a function that allows for fast numeric evaluation. .. warning:: This function uses ``exec``, and thus should not be used on unsanitized input. .. deprecated:: 1.7 Passing a set for the *args* parameter is deprecated as sets are unordered. Use an ordered iterable such as a list or tuple. Explanation =========== For example, to convert the SymPy expression ``sin(x) + cos(x)`` to an equivalent NumPy function that numerically evaluates it: >>> from sympy import sin, cos, symbols, lambdify >>> import numpy as np >>> x = symbols('x') >>> expr = sin(x) + cos(x) >>> expr sin(x) + cos(x) >>> f = lambdify(x, expr, 'numpy') >>> a = np.array([1, 2]) >>> f(a) [1.38177329 0.49315059] The primary purpose of this function is to provide a bridge from SymPy expressions to numerical libraries such as NumPy, SciPy, NumExpr, mpmath, and tensorflow. In general, SymPy functions do not work with objects from other libraries, such as NumPy arrays, and functions from numeric libraries like NumPy or mpmath do not work on SymPy expressions. ``lambdify`` bridges the two by converting a SymPy expression to an equivalent numeric function. The basic workflow with ``lambdify`` is to first create a SymPy expression representing whatever mathematical function you wish to evaluate. This should be done using only SymPy functions and expressions. Then, use ``lambdify`` to convert this to an equivalent function for numerical evaluation. For instance, above we created ``expr`` using the SymPy symbol ``x`` and SymPy functions ``sin`` and ``cos``, then converted it to an equivalent NumPy function ``f``, and called it on a NumPy array ``a``. Parameters ========== args : List[Symbol] A variable or a list of variables whose nesting represents the nesting of the arguments that will be passed to the function. Variables can be symbols, undefined functions, or matrix symbols. >>> from sympy import Eq >>> from sympy.abc import x, y, z The list of variables should match the structure of how the arguments will be passed to the function. Simply enclose the parameters as they will be passed in a list. To call a function like ``f(x)`` then ``[x]`` should be the first argument to ``lambdify``; for this case a single ``x`` can also be used: >>> f = lambdify(x, x + 1) >>> f(1) 2 >>> f = lambdify([x], x + 1) >>> f(1) 2 To call a function like ``f(x, y)`` then ``[x, y]`` will be the first argument of the ``lambdify``: >>> f = lambdify([x, y], x + y) >>> f(1, 1) 2 To call a function with a single 3-element tuple like ``f((x, y, z))`` then ``[(x, y, z)]`` will be the first argument of the ``lambdify``: >>> f = lambdify([(x, y, z)], Eq(z**2, x**2 + y**2)) >>> f((3, 4, 5)) True If two args will be passed and the first is a scalar but the second is a tuple with two arguments then the items in the list should match that structure: >>> f = lambdify([x, (y, z)], x + y + z) >>> f(1, (2, 3)) 6 expr : Expr An expression, list of expressions, or matrix to be evaluated. Lists may be nested. If the expression is a list, the output will also be a list. >>> f = lambdify(x, [x, [x + 1, x + 2]]) >>> f(1) [1, [2, 3]] If it is a matrix, an array will be returned (for the NumPy module). >>> from sympy import Matrix >>> f = lambdify(x, Matrix([x, x + 1])) >>> f(1) [[1] [2]] Note that the argument order here (variables then expression) is used to emulate the Python ``lambda`` keyword. ``lambdify(x, expr)`` works (roughly) like ``lambda x: expr`` (see :ref:`lambdify-how-it-works` below). modules : str, optional Specifies the numeric library to use. If not specified, *modules* defaults to: - ``["scipy", "numpy"]`` if SciPy is installed - ``["numpy"]`` if only NumPy is installed - ``["math", "mpmath", "sympy"]`` if neither is installed. That is, SymPy functions are replaced as far as possible by either ``scipy`` or ``numpy`` functions if available, and Python's standard library ``math``, or ``mpmath`` functions otherwise. *modules* can be one of the following types: - The strings ``"math"``, ``"mpmath"``, ``"numpy"``, ``"numexpr"``, ``"scipy"``, ``"sympy"``, or ``"tensorflow"`` or ``"jax"``. This uses the corresponding printer and namespace mapping for that module. - A module (e.g., ``math``). This uses the global namespace of the module. If the module is one of the above known modules, it will also use the corresponding printer and namespace mapping (i.e., ``modules=numpy`` is equivalent to ``modules="numpy"``). - A dictionary that maps names of SymPy functions to arbitrary functions (e.g., ``{'sin': custom_sin}``). - A list that contains a mix of the arguments above, with higher priority given to entries appearing first (e.g., to use the NumPy module but override the ``sin`` function with a custom version, you can use ``[{'sin': custom_sin}, 'numpy']``). dummify : bool, optional Whether or not the variables in the provided expression that are not valid Python identifiers are substituted with dummy symbols. This allows for undefined functions like ``Function('f')(t)`` to be supplied as arguments. By default, the variables are only dummified if they are not valid Python identifiers. Set ``dummify=True`` to replace all arguments with dummy symbols (if ``args`` is not a string) - for example, to ensure that the arguments do not redefine any built-in names. cse : bool, or callable, optional Large expressions can be computed more efficiently when common subexpressions are identified and precomputed before being used multiple time. Finding the subexpressions will make creation of the 'lambdify' function slower, however. When ``True``, ``sympy.simplify.cse`` is used, otherwise (the default) the user may pass a function matching the ``cse`` signature. Examples ======== >>> from sympy.utilities.lambdify import implemented_function >>> from sympy import sqrt, sin, Matrix >>> from sympy import Function >>> from sympy.abc import w, x, y, z >>> f = lambdify(x, x**2) >>> f(2) 4 >>> f = lambdify((x, y, z), [z, y, x]) >>> f(1,2,3) [3, 2, 1] >>> f = lambdify(x, sqrt(x)) >>> f(4) 2.0 >>> f = lambdify((x, y), sin(x*y)**2) >>> f(0, 5) 0.0 >>> row = lambdify((x, y), Matrix((x, x + y)).T, modules='sympy') >>> row(1, 2) Matrix([[1, 3]]) ``lambdify`` can be used to translate SymPy expressions into mpmath functions. This may be preferable to using ``evalf`` (which uses mpmath on the backend) in some cases. >>> f = lambdify(x, sin(x), 'mpmath') >>> f(1) 0.8414709848078965 Tuple arguments are handled and the lambdified function should be called with the same type of arguments as were used to create the function: >>> f = lambdify((x, (y, z)), x + y) >>> f(1, (2, 4)) 3 The ``flatten`` function can be used to always work with flattened arguments: >>> from sympy.utilities.iterables import flatten >>> args = w, (x, (y, z)) >>> vals = 1, (2, (3, 4)) >>> f = lambdify(flatten(args), w + x + y + z) >>> f(*flatten(vals)) 10 Functions present in ``expr`` can also carry their own numerical implementations, in a callable attached to the ``_imp_`` attribute. This can be used with undefined functions using the ``implemented_function`` factory: >>> f = implemented_function(Function('f'), lambda x: x+1) >>> func = lambdify(x, f(x)) >>> func(4) 5 ``lambdify`` always prefers ``_imp_`` implementations to implementations in other namespaces, unless the ``use_imps`` input parameter is False. Usage with Tensorflow: >>> import tensorflow as tf >>> from sympy import Max, sin, lambdify >>> from sympy.abc import x >>> f = Max(x, sin(x)) >>> func = lambdify(x, f, 'tensorflow') After tensorflow v2, eager execution is enabled by default. If you want to get the compatible result across tensorflow v1 and v2 as same as this tutorial, run this line. >>> tf.compat.v1.enable_eager_execution() If you have eager execution enabled, you can get the result out immediately as you can use numpy. If you pass tensorflow objects, you may get an ``EagerTensor`` object instead of value. >>> result = func(tf.constant(1.0)) >>> print(result) tf.Tensor(1.0, shape=(), dtype=float32) >>> print(result.__class__) <class 'tensorflow.python.framework.ops.EagerTensor'> You can use ``.numpy()`` to get the numpy value of the tensor. >>> result.numpy() 1.0 >>> var = tf.Variable(2.0) >>> result = func(var) # also works for tf.Variable and tf.Placeholder >>> result.numpy() 2.0 And it works with any shape array. >>> tensor = tf.constant([[1.0, 2.0], [3.0, 4.0]]) >>> result = func(tensor) >>> result.numpy() [[1. 2.] [3. 4.]] Notes ===== - For functions involving large array calculations, numexpr can provide a significant speedup over numpy. Please note that the available functions for numexpr are more limited than numpy but can be expanded with ``implemented_function`` and user defined subclasses of Function. If specified, numexpr may be the only option in modules. The official list of numexpr functions can be found at: https://numexpr.readthedocs.io/en/latest/user_guide.html#supported-functions - In the above examples, the generated functions can accept scalar values or numpy arrays as arguments. However, in some cases the generated function relies on the input being a numpy array: >>> import numpy >>> from sympy import Piecewise >>> from sympy.testing.pytest import ignore_warnings >>> f = lambdify(x, Piecewise((x, x <= 1), (1/x, x > 1)), "numpy") >>> with ignore_warnings(RuntimeWarning): ... f(numpy.array([-1, 0, 1, 2])) [-1. 0. 1. 0.5] >>> f(0) Traceback (most recent call last): ... ZeroDivisionError: division by zero In such cases, the input should be wrapped in a numpy array: >>> with ignore_warnings(RuntimeWarning): ... float(f(numpy.array([0]))) 0.0 Or if numpy functionality is not required another module can be used: >>> f = lambdify(x, Piecewise((x, x <= 1), (1/x, x > 1)), "math") >>> f(0) 0 .. _lambdify-how-it-works: How it works ============ When using this function, it helps a great deal to have an idea of what it is doing. At its core, lambdify is nothing more than a namespace translation, on top of a special printer that makes some corner cases work properly. To understand lambdify, first we must properly understand how Python namespaces work. Say we had two files. One called ``sin_cos_sympy.py``, with .. code:: python # sin_cos_sympy.py from sympy.functions.elementary.trigonometric import (cos, sin) def sin_cos(x): return sin(x) + cos(x) and one called ``sin_cos_numpy.py`` with .. code:: python # sin_cos_numpy.py from numpy import sin, cos def sin_cos(x): return sin(x) + cos(x) The two files define an identical function ``sin_cos``. However, in the first file, ``sin`` and ``cos`` are defined as the SymPy ``sin`` and ``cos``. In the second, they are defined as the NumPy versions. If we were to import the first file and use the ``sin_cos`` function, we would get something like >>> from sin_cos_sympy import sin_cos # doctest: +SKIP >>> sin_cos(1) # doctest: +SKIP cos(1) + sin(1) On the other hand, if we imported ``sin_cos`` from the second file, we would get >>> from sin_cos_numpy import sin_cos # doctest: +SKIP >>> sin_cos(1) # doctest: +SKIP 1.38177329068 In the first case we got a symbolic output, because it used the symbolic ``sin`` and ``cos`` functions from SymPy. In the second, we got a numeric result, because ``sin_cos`` used the numeric ``sin`` and ``cos`` functions from NumPy. But notice that the versions of ``sin`` and ``cos`` that were used was not inherent to the ``sin_cos`` function definition. Both ``sin_cos`` definitions are exactly the same. Rather, it was based on the names defined at the module where the ``sin_cos`` function was defined. The key point here is that when function in Python references a name that is not defined in the function, that name is looked up in the "global" namespace of the module where that function is defined. Now, in Python, we can emulate this behavior without actually writing a file to disk using the ``exec`` function. ``exec`` takes a string containing a block of Python code, and a dictionary that should contain the global variables of the module. It then executes the code "in" that dictionary, as if it were the module globals. The following is equivalent to the ``sin_cos`` defined in ``sin_cos_sympy.py``: >>> import sympy >>> module_dictionary = {'sin': sympy.sin, 'cos': sympy.cos} >>> exec(''' ... def sin_cos(x): ... return sin(x) + cos(x) ... ''', module_dictionary) >>> sin_cos = module_dictionary['sin_cos'] >>> sin_cos(1) cos(1) + sin(1) and similarly with ``sin_cos_numpy``: >>> import numpy >>> module_dictionary = {'sin': numpy.sin, 'cos': numpy.cos} >>> exec(''' ... def sin_cos(x): ... return sin(x) + cos(x) ... ''', module_dictionary) >>> sin_cos = module_dictionary['sin_cos'] >>> sin_cos(1) 1.38177329068 So now we can get an idea of how ``lambdify`` works. The name "lambdify" comes from the fact that we can think of something like ``lambdify(x, sin(x) + cos(x), 'numpy')`` as ``lambda x: sin(x) + cos(x)``, where ``sin`` and ``cos`` come from the ``numpy`` namespace. This is also why the symbols argument is first in ``lambdify``, as opposed to most SymPy functions where it comes after the expression: to better mimic the ``lambda`` keyword. ``lambdify`` takes the input expression (like ``sin(x) + cos(x)``) and 1. Converts it to a string 2. Creates a module globals dictionary based on the modules that are passed in (by default, it uses the NumPy module) 3. Creates the string ``"def func({vars}): return {expr}"``, where ``{vars}`` is the list of variables separated by commas, and ``{expr}`` is the string created in step 1., then ``exec``s that string with the module globals namespace and returns ``func``. In fact, functions returned by ``lambdify`` support inspection. So you can see exactly how they are defined by using ``inspect.getsource``, or ``??`` if you are using IPython or the Jupyter notebook. >>> f = lambdify(x, sin(x) + cos(x)) >>> import inspect >>> print(inspect.getsource(f)) def _lambdifygenerated(x): return sin(x) + cos(x) This shows us the source code of the function, but not the namespace it was defined in. We can inspect that by looking at the ``__globals__`` attribute of ``f``: >>> f.__globals__['sin'] <ufunc 'sin'> >>> f.__globals__['cos'] <ufunc 'cos'> >>> f.__globals__['sin'] is numpy.sin True This shows us that ``sin`` and ``cos`` in the namespace of ``f`` will be ``numpy.sin`` and ``numpy.cos``. Note that there are some convenience layers in each of these steps, but at the core, this is how ``lambdify`` works. Step 1 is done using the ``LambdaPrinter`` printers defined in the printing module (see :mod:`sympy.printing.lambdarepr`). This allows different SymPy expressions to define how they should be converted to a string for different modules. You can change which printer ``lambdify`` uses by passing a custom printer in to the ``printer`` argument. Step 2 is augmented by certain translations. There are default translations for each module, but you can provide your own by passing a list to the ``modules`` argument. For instance, >>> def mysin(x): ... print('taking the sin of', x) ... return numpy.sin(x) ... >>> f = lambdify(x, sin(x), [{'sin': mysin}, 'numpy']) >>> f(1) taking the sin of 1 0.8414709848078965 The globals dictionary is generated from the list by merging the dictionary ``{'sin': mysin}`` and the module dictionary for NumPy. The merging is done so that earlier items take precedence, which is why ``mysin`` is used above instead of ``numpy.sin``. If you want to modify the way ``lambdify`` works for a given function, it is usually easiest to do so by modifying the globals dictionary as such. In more complicated cases, it may be necessary to create and pass in a custom printer. Finally, step 3 is augmented with certain convenience operations, such as the addition of a docstring. Understanding how ``lambdify`` works can make it easier to avoid certain gotchas when using it. For instance, a common mistake is to create a lambdified function for one module (say, NumPy), and pass it objects from another (say, a SymPy expression). For instance, say we create >>> from sympy.abc import x >>> f = lambdify(x, x + 1, 'numpy') Now if we pass in a NumPy array, we get that array plus 1 >>> import numpy >>> a = numpy.array([1, 2]) >>> f(a) [2 3] But what happens if you make the mistake of passing in a SymPy expression instead of a NumPy array: >>> f(x + 1) x + 2 This worked, but it was only by accident. Now take a different lambdified function: >>> from sympy import sin >>> g = lambdify(x, x + sin(x), 'numpy') This works as expected on NumPy arrays: >>> g(a) [1.84147098 2.90929743] But if we try to pass in a SymPy expression, it fails >>> try: ... g(x + 1) ... # NumPy release after 1.17 raises TypeError instead of ... # AttributeError ... except (AttributeError, TypeError): ... raise AttributeError() # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... AttributeError: Now, let's look at what happened. The reason this fails is that ``g`` calls ``numpy.sin`` on the input expression, and ``numpy.sin`` does not know how to operate on a SymPy object. **As a general rule, NumPy functions do not know how to operate on SymPy expressions, and SymPy functions do not know how to operate on NumPy arrays. This is why lambdify exists: to provide a bridge between SymPy and NumPy.** However, why is it that ``f`` did work? That's because ``f`` does not call any functions, it only adds 1. So the resulting function that is created, ``def _lambdifygenerated(x): return x + 1`` does not depend on the globals namespace it is defined in. Thus it works, but only by accident. A future version of ``lambdify`` may remove this behavior. Be aware that certain implementation details described here may change in future versions of SymPy. The API of passing in custom modules and printers will not change, but the details of how a lambda function is created may change. However, the basic idea will remain the same, and understanding it will be helpful to understanding the behavior of lambdify. **In general: you should create lambdified functions for one module (say, NumPy), and only pass it input types that are compatible with that module (say, NumPy arrays).** Remember that by default, if the ``module`` argument is not provided, ``lambdify`` creates functions using the NumPy and SciPy namespaces. """ from sympy.core.symbol import Symbol from sympy.core.expr import Expr # If the user hasn't specified any modules, use what is available. if modules is None: try: _import("scipy") except ImportError: try: _import("numpy") except ImportError: # Use either numpy (if available) or python.math where possible. # XXX: This leads to different behaviour on different systems and # might be the reason for irreproducible errors. modules = ["math", "mpmath", "sympy"] else: modules = ["numpy"] else: modules = ["numpy", "scipy"] # Get the needed namespaces. namespaces = [] # First find any function implementations if use_imps: namespaces.append(_imp_namespace(expr)) # Check for dict before iterating if isinstance(modules, (dict, str)) or not hasattr(modules, '__iter__'): namespaces.append(modules) else: # consistency check if _module_present('numexpr', modules) and len(modules) > 1: raise TypeError("numexpr must be the only item in 'modules'") namespaces += list(modules) # fill namespace with first having highest priority namespace = {} # type: tDict[str, Any] for m in namespaces[::-1]: buf = _get_namespace(m) namespace.update(buf) if hasattr(expr, "atoms"): #Try if you can extract symbols from the expression. #Move on if expr.atoms in not implemented. syms = expr.atoms(Symbol) for term in syms: namespace.update({str(term): term}) if printer is None: if _module_present('mpmath', namespaces): from sympy.printing.pycode import MpmathPrinter as Printer # type: ignore elif _module_present('scipy', namespaces): from sympy.printing.numpy import SciPyPrinter as Printer # type: ignore elif _module_present('numpy', namespaces): from sympy.printing.numpy import NumPyPrinter as Printer # type: ignore elif _module_present('cupy', namespaces): from sympy.printing.numpy import CuPyPrinter as Printer # type: ignore elif _module_present('jax', namespaces): from sympy.printing.numpy import JaxPrinter as Printer # type: ignore elif _module_present('numexpr', namespaces): from sympy.printing.lambdarepr import NumExprPrinter as Printer # type: ignore elif _module_present('tensorflow', namespaces): from sympy.printing.tensorflow import TensorflowPrinter as Printer # type: ignore elif _module_present('sympy', namespaces): from sympy.printing.pycode import SymPyPrinter as Printer # type: ignore else: from sympy.printing.pycode import PythonCodePrinter as Printer # type: ignore user_functions = {} for m in namespaces[::-1]: if isinstance(m, dict): for k in m: user_functions[k] = k printer = Printer({'fully_qualified_modules': False, 'inline': True, 'allow_unknown_functions': True, 'user_functions': user_functions}) if isinstance(args, set): sympy_deprecation_warning( """ Passing the function arguments to lambdify() as a set is deprecated. This leads to unpredictable results since sets are unordered. Instead, use a list or tuple for the function arguments. """, deprecated_since_version="1.6.3", active_deprecations_target="deprecated-lambdify-arguments-set", ) # Get the names of the args, for creating a docstring iterable_args = (args,) if isinstance(args, Expr) else args names = [] # Grab the callers frame, for getting the names by inspection (if needed) callers_local_vars = inspect.currentframe().f_back.f_locals.items() # type: ignore for n, var in enumerate(iterable_args): if hasattr(var, 'name'): names.append(var.name) else: # It's an iterable. Try to get name by inspection of calling frame. name_list = [var_name for var_name, var_val in callers_local_vars if var_val is var] if len(name_list) == 1: names.append(name_list[0]) else: # Cannot infer name with certainty. arg_# will have to do. names.append('arg_' + str(n)) # Create the function definition code and execute it funcname = '_lambdifygenerated' if _module_present('tensorflow', namespaces): funcprinter = _TensorflowEvaluatorPrinter(printer, dummify) # type: _EvaluatorPrinter else: funcprinter = _EvaluatorPrinter(printer, dummify) if cse == True: from sympy.simplify.cse_main import cse as _cse cses, _expr = _cse(expr, list=False) elif callable(cse): cses, _expr = cse(expr) else: cses, _expr = (), expr funcstr = funcprinter.doprint(funcname, iterable_args, _expr, cses=cses) # Collect the module imports from the code printers. imp_mod_lines = [] for mod, keys in (getattr(printer, 'module_imports', None) or {}).items(): for k in keys: if k not in namespace: ln = "from %s import %s" % (mod, k) try: exec(ln, {}, namespace) except ImportError: # Tensorflow 2.0 has issues with importing a specific # function from its submodule. # https://github.com/tensorflow/tensorflow/issues/33022 ln = "%s = %s.%s" % (k, mod, k) exec(ln, {}, namespace) imp_mod_lines.append(ln) # Provide lambda expression with builtins, and compatible implementation of range namespace.update({'builtins':builtins, 'range':range}) funclocals = {} # type: tDict[str, Any] global _lambdify_generated_counter filename = '<lambdifygenerated-%s>' % _lambdify_generated_counter _lambdify_generated_counter += 1 c = compile(funcstr, filename, 'exec') exec(c, namespace, funclocals) # mtime has to be None or else linecache.checkcache will remove it linecache.cache[filename] = (len(funcstr), None, funcstr.splitlines(True), filename) # type: ignore func = funclocals[funcname] # Apply the docstring sig = "func({})".format(", ".join(str(i) for i in names)) sig = textwrap.fill(sig, subsequent_indent=' '*8) expr_str = str(expr) if len(expr_str) > 78: expr_str = textwrap.wrap(expr_str, 75)[0] + '...' func.__doc__ = ( "Created with lambdify. Signature:\n\n" "{sig}\n\n" "Expression:\n\n" "{expr}\n\n" "Source code:\n\n" "{src}\n\n" "Imported modules:\n\n" "{imp_mods}" ).format(sig=sig, expr=expr_str, src=funcstr, imp_mods='\n'.join(imp_mod_lines)) return func def _module_present(modname, modlist): if modname in modlist: return True for m in modlist: if hasattr(m, '__name__') and m.__name__ == modname: return True return False def _get_namespace(m): """ This is used by _lambdify to parse its arguments. """ if isinstance(m, str): _import(m) return MODULES[m][0] elif isinstance(m, dict): return m elif hasattr(m, "__dict__"): return m.__dict__ else: raise TypeError("Argument must be either a string, dict or module but it is: %s" % m) def _recursive_to_string(doprint, arg): """Functions in lambdify accept both SymPy types and non-SymPy types such as python lists and tuples. This method ensures that we only call the doprint method of the printer with SymPy types (so that the printer safely can use SymPy-methods).""" from sympy.matrices.common import MatrixOperations from sympy.core.basic import Basic if isinstance(arg, (Basic, MatrixOperations)): return doprint(arg) elif iterable(arg): if isinstance(arg, list): left, right = "[", "]" elif isinstance(arg, tuple): left, right = "(", ",)" else: raise NotImplementedError("unhandled type: %s, %s" % (type(arg), arg)) return left +', '.join(_recursive_to_string(doprint, e) for e in arg) + right elif isinstance(arg, str): return arg else: return doprint(arg) def lambdastr(args, expr, printer=None, dummify=None): """ Returns a string that can be evaluated to a lambda function. Examples ======== >>> from sympy.abc import x, y, z >>> from sympy.utilities.lambdify import lambdastr >>> lambdastr(x, x**2) 'lambda x: (x**2)' >>> lambdastr((x,y,z), [z,y,x]) 'lambda x,y,z: ([z, y, x])' Although tuples may not appear as arguments to lambda in Python 3, lambdastr will create a lambda function that will unpack the original arguments so that nested arguments can be handled: >>> lambdastr((x, (y, z)), x + y) 'lambda _0,_1: (lambda x,y,z: (x + y))(_0,_1[0],_1[1])' """ # Transforming everything to strings. from sympy.matrices import DeferredVector from sympy.core.basic import Basic from sympy.core.function import (Derivative, Function) from sympy.core.symbol import (Dummy, Symbol) from sympy.core.sympify import sympify if printer is not None: if inspect.isfunction(printer): lambdarepr = printer else: if inspect.isclass(printer): lambdarepr = lambda expr: printer().doprint(expr) else: lambdarepr = lambda expr: printer.doprint(expr) else: #XXX: This has to be done here because of circular imports from sympy.printing.lambdarepr import lambdarepr def sub_args(args, dummies_dict): if isinstance(args, str): return args elif isinstance(args, DeferredVector): return str(args) elif iterable(args): dummies = flatten([sub_args(a, dummies_dict) for a in args]) return ",".join(str(a) for a in dummies) else: # replace these with Dummy symbols if isinstance(args, (Function, Symbol, Derivative)): dummies = Dummy() dummies_dict.update({args : dummies}) return str(dummies) else: return str(args) def sub_expr(expr, dummies_dict): expr = sympify(expr) # dict/tuple are sympified to Basic if isinstance(expr, Basic): expr = expr.xreplace(dummies_dict) # list is not sympified to Basic elif isinstance(expr, list): expr = [sub_expr(a, dummies_dict) for a in expr] return expr # Transform args def isiter(l): return iterable(l, exclude=(str, DeferredVector, NotIterable)) def flat_indexes(iterable): n = 0 for el in iterable: if isiter(el): for ndeep in flat_indexes(el): yield (n,) + ndeep else: yield (n,) n += 1 if dummify is None: dummify = any(isinstance(a, Basic) and a.atoms(Function, Derivative) for a in ( args if isiter(args) else [args])) if isiter(args) and any(isiter(i) for i in args): dum_args = [str(Dummy(str(i))) for i in range(len(args))] indexed_args = ','.join([ dum_args[ind[0]] + ''.join(["[%s]" % k for k in ind[1:]]) for ind in flat_indexes(args)]) lstr = lambdastr(flatten(args), expr, printer=printer, dummify=dummify) return 'lambda %s: (%s)(%s)' % (','.join(dum_args), lstr, indexed_args) dummies_dict = {} if dummify: args = sub_args(args, dummies_dict) else: if isinstance(args, str): pass elif iterable(args, exclude=DeferredVector): args = ",".join(str(a) for a in args) # Transform expr if dummify: if isinstance(expr, str): pass else: expr = sub_expr(expr, dummies_dict) expr = _recursive_to_string(lambdarepr, expr) return "lambda %s: (%s)" % (args, expr) class _EvaluatorPrinter: def __init__(self, printer=None, dummify=False): self._dummify = dummify #XXX: This has to be done here because of circular imports from sympy.printing.lambdarepr import LambdaPrinter if printer is None: printer = LambdaPrinter() if inspect.isfunction(printer): self._exprrepr = printer else: if inspect.isclass(printer): printer = printer() self._exprrepr = printer.doprint #if hasattr(printer, '_print_Symbol'): # symbolrepr = printer._print_Symbol #if hasattr(printer, '_print_Dummy'): # dummyrepr = printer._print_Dummy # Used to print the generated function arguments in a standard way self._argrepr = LambdaPrinter().doprint def doprint(self, funcname, args, expr, *, cses=()): """ Returns the function definition code as a string. """ from sympy.core.symbol import Dummy funcbody = [] if not iterable(args): args = [args] if cses: subvars, subexprs = zip(*cses) try: exprs = expr + list(subexprs) except TypeError: try: exprs = expr + tuple(subexprs) except TypeError: expr = [expr] exprs = expr + list(subexprs) argstrs, exprs = self._preprocess(args, exprs) expr, subexprs = exprs[:len(expr)], exprs[len(expr):] cses = zip(subvars, subexprs) else: argstrs, expr = self._preprocess(args, expr) # Generate argument unpacking and final argument list funcargs = [] unpackings = [] for argstr in argstrs: if iterable(argstr): funcargs.append(self._argrepr(Dummy())) unpackings.extend(self._print_unpacking(argstr, funcargs[-1])) else: funcargs.append(argstr) funcsig = 'def {}({}):'.format(funcname, ', '.join(funcargs)) # Wrap input arguments before unpacking funcbody.extend(self._print_funcargwrapping(funcargs)) funcbody.extend(unpackings) for s, e in cses: if e is None: funcbody.append('del {}'.format(s)) else: funcbody.append('{} = {}'.format(s, self._exprrepr(e))) str_expr = _recursive_to_string(self._exprrepr, expr) if '\n' in str_expr: str_expr = '({})'.format(str_expr) funcbody.append('return {}'.format(str_expr)) funclines = [funcsig] funclines.extend([' ' + line for line in funcbody]) return '\n'.join(funclines) + '\n' @classmethod def _is_safe_ident(cls, ident): return isinstance(ident, str) and ident.isidentifier() \ and not keyword.iskeyword(ident) def _preprocess(self, args, expr): """Preprocess args, expr to replace arguments that do not map to valid Python identifiers. Returns string form of args, and updated expr. """ from sympy.core.basic import Basic from sympy.core.sorting import ordered from sympy.core.function import (Derivative, Function) from sympy.core.symbol import Dummy, uniquely_named_symbol from sympy.matrices import DeferredVector from sympy.core.expr import Expr # Args of type Dummy can cause name collisions with args # of type Symbol. Force dummify of everything in this # situation. dummify = self._dummify or any( isinstance(arg, Dummy) for arg in flatten(args)) argstrs = [None]*len(args) for arg, i in reversed(list(ordered(zip(args, range(len(args)))))): if iterable(arg): s, expr = self._preprocess(arg, expr) elif isinstance(arg, DeferredVector): s = str(arg) elif isinstance(arg, Basic) and arg.is_symbol: s = self._argrepr(arg) if dummify or not self._is_safe_ident(s): dummy = Dummy() if isinstance(expr, Expr): dummy = uniquely_named_symbol( dummy.name, expr, modify=lambda s: '_' + s) s = self._argrepr(dummy) expr = self._subexpr(expr, {arg: dummy}) elif dummify or isinstance(arg, (Function, Derivative)): dummy = Dummy() s = self._argrepr(dummy) expr = self._subexpr(expr, {arg: dummy}) else: s = str(arg) argstrs[i] = s return argstrs, expr def _subexpr(self, expr, dummies_dict): from sympy.matrices import DeferredVector from sympy.core.sympify import sympify expr = sympify(expr) xreplace = getattr(expr, 'xreplace', None) if xreplace is not None: expr = xreplace(dummies_dict) else: if isinstance(expr, DeferredVector): pass elif isinstance(expr, dict): k = [self._subexpr(sympify(a), dummies_dict) for a in expr.keys()] v = [self._subexpr(sympify(a), dummies_dict) for a in expr.values()] expr = dict(zip(k, v)) elif isinstance(expr, tuple): expr = tuple(self._subexpr(sympify(a), dummies_dict) for a in expr) elif isinstance(expr, list): expr = [self._subexpr(sympify(a), dummies_dict) for a in expr] return expr def _print_funcargwrapping(self, args): """Generate argument wrapping code. args is the argument list of the generated function (strings). Return value is a list of lines of code that will be inserted at the beginning of the function definition. """ return [] def _print_unpacking(self, unpackto, arg): """Generate argument unpacking code. arg is the function argument to be unpacked (a string), and unpackto is a list or nested lists of the variable names (strings) to unpack to. """ def unpack_lhs(lvalues): return '[{}]'.format(', '.join( unpack_lhs(val) if iterable(val) else val for val in lvalues)) return ['{} = {}'.format(unpack_lhs(unpackto), arg)] class _TensorflowEvaluatorPrinter(_EvaluatorPrinter): def _print_unpacking(self, lvalues, rvalue): """Generate argument unpacking code. This method is used when the input value is not interable, but can be indexed (see issue #14655). """ def flat_indexes(elems): n = 0 for el in elems: if iterable(el): for ndeep in flat_indexes(el): yield (n,) + ndeep else: yield (n,) n += 1 indexed = ', '.join('{}[{}]'.format(rvalue, ']['.join(map(str, ind))) for ind in flat_indexes(lvalues)) return ['[{}] = [{}]'.format(', '.join(flatten(lvalues)), indexed)] def _imp_namespace(expr, namespace=None): """ Return namespace dict with function implementations We need to search for functions in anything that can be thrown at us - that is - anything that could be passed as ``expr``. Examples include SymPy expressions, as well as tuples, lists and dicts that may contain SymPy expressions. Parameters ---------- expr : object Something passed to lambdify, that will generate valid code from ``str(expr)``. namespace : None or mapping Namespace to fill. None results in new empty dict Returns ------- namespace : dict dict with keys of implemented function names within ``expr`` and corresponding values being the numerical implementation of function Examples ======== >>> from sympy.abc import x >>> from sympy.utilities.lambdify import implemented_function, _imp_namespace >>> from sympy import Function >>> f = implemented_function(Function('f'), lambda x: x+1) >>> g = implemented_function(Function('g'), lambda x: x*10) >>> namespace = _imp_namespace(f(g(x))) >>> sorted(namespace.keys()) ['f', 'g'] """ # Delayed import to avoid circular imports from sympy.core.function import FunctionClass if namespace is None: namespace = {} # tuples, lists, dicts are valid expressions if is_sequence(expr): for arg in expr: _imp_namespace(arg, namespace) return namespace elif isinstance(expr, dict): for key, val in expr.items(): # functions can be in dictionary keys _imp_namespace(key, namespace) _imp_namespace(val, namespace) return namespace # SymPy expressions may be Functions themselves func = getattr(expr, 'func', None) if isinstance(func, FunctionClass): imp = getattr(func, '_imp_', None) if imp is not None: name = expr.func.__name__ if name in namespace and namespace[name] != imp: raise ValueError('We found more than one ' 'implementation with name ' '"%s"' % name) namespace[name] = imp # and / or they may take Functions as arguments if hasattr(expr, 'args'): for arg in expr.args: _imp_namespace(arg, namespace) return namespace def implemented_function(symfunc, implementation): """ Add numerical ``implementation`` to function ``symfunc``. ``symfunc`` can be an ``UndefinedFunction`` instance, or a name string. In the latter case we create an ``UndefinedFunction`` instance with that name. Be aware that this is a quick workaround, not a general method to create special symbolic functions. If you want to create a symbolic function to be used by all the machinery of SymPy you should subclass the ``Function`` class. Parameters ---------- symfunc : ``str`` or ``UndefinedFunction`` instance If ``str``, then create new ``UndefinedFunction`` with this as name. If ``symfunc`` is an Undefined function, create a new function with the same name and the implemented function attached. implementation : callable numerical implementation to be called by ``evalf()`` or ``lambdify`` Returns ------- afunc : sympy.FunctionClass instance function with attached implementation Examples ======== >>> from sympy.abc import x >>> from sympy.utilities.lambdify import implemented_function >>> from sympy import lambdify >>> f = implemented_function('f', lambda x: x+1) >>> lam_f = lambdify(x, f(x)) >>> lam_f(4) 5 """ # Delayed import to avoid circular imports from sympy.core.function import UndefinedFunction # if name, create function to hold implementation kwargs = {} if isinstance(symfunc, UndefinedFunction): kwargs = symfunc._kwargs symfunc = symfunc.__name__ if isinstance(symfunc, str): # Keyword arguments to UndefinedFunction are added as attributes to # the created class. symfunc = UndefinedFunction( symfunc, _imp_=staticmethod(implementation), **kwargs) elif not isinstance(symfunc, UndefinedFunction): raise ValueError(filldedent(''' symfunc should be either a string or an UndefinedFunction instance.''')) return symfunc
f8d4217fe45be611d2878aa3f9a57058ce30b9a60c60ad07005261dfc281f600
from collections import defaultdict, OrderedDict from itertools import ( chain, combinations, combinations_with_replacement, cycle, islice, permutations, product ) # For backwards compatibility from itertools import product as cartes # noqa: F401 from operator import gt # this is the logical location of these functions from sympy.utilities.enumerative import ( multiset_partitions_taocp, list_visitor, MultisetPartitionTraverser) from sympy.utilities.misc import as_int from sympy.utilities.decorator import deprecated def is_palindromic(s, i=0, j=None): """ Return True if the sequence is the same from left to right as it is from right to left in the whole sequence (default) or in the Python slice ``s[i: j]``; else False. Examples ======== >>> from sympy.utilities.iterables import is_palindromic >>> is_palindromic([1, 0, 1]) True >>> is_palindromic('abcbb') False >>> is_palindromic('abcbb', 1) False Normal Python slicing is performed in place so there is no need to create a slice of the sequence for testing: >>> is_palindromic('abcbb', 1, -1) True >>> is_palindromic('abcbb', -4, -1) True See Also ======== sympy.ntheory.digits.is_palindromic: tests integers """ i, j, _ = slice(i, j).indices(len(s)) m = (j - i)//2 # if length is odd, middle element will be ignored return all(s[i + k] == s[j - 1 - k] for k in range(m)) def flatten(iterable, levels=None, cls=None): # noqa: F811 """ Recursively denest iterable containers. >>> from sympy import flatten >>> flatten([1, 2, 3]) [1, 2, 3] >>> flatten([1, 2, [3]]) [1, 2, 3] >>> flatten([1, [2, 3], [4, 5]]) [1, 2, 3, 4, 5] >>> flatten([1.0, 2, (1, None)]) [1.0, 2, 1, None] If you want to denest only a specified number of levels of nested containers, then set ``levels`` flag to the desired number of levels:: >>> ls = [[(-2, -1), (1, 2)], [(0, 0)]] >>> flatten(ls, levels=1) [(-2, -1), (1, 2), (0, 0)] If cls argument is specified, it will only flatten instances of that class, for example: >>> from sympy import Basic, S >>> class MyOp(Basic): ... pass ... >>> flatten([MyOp(S(1), MyOp(S(2), S(3)))], cls=MyOp) [1, 2, 3] adapted from https://kogs-www.informatik.uni-hamburg.de/~meine/python_tricks """ from sympy.tensor.array import NDimArray if levels is not None: if not levels: return iterable elif levels > 0: levels -= 1 else: raise ValueError( "expected non-negative number of levels, got %s" % levels) if cls is None: reducible = lambda x: is_sequence(x, set) else: reducible = lambda x: isinstance(x, cls) result = [] for el in iterable: if reducible(el): if hasattr(el, 'args') and not isinstance(el, NDimArray): el = el.args result.extend(flatten(el, levels=levels, cls=cls)) else: result.append(el) return result def unflatten(iter, n=2): """Group ``iter`` into tuples of length ``n``. Raise an error if the length of ``iter`` is not a multiple of ``n``. """ if n < 1 or len(iter) % n: raise ValueError('iter length is not a multiple of %i' % n) return list(zip(*(iter[i::n] for i in range(n)))) def reshape(seq, how): """Reshape the sequence according to the template in ``how``. Examples ======== >>> from sympy.utilities import reshape >>> seq = list(range(1, 9)) >>> reshape(seq, [4]) # lists of 4 [[1, 2, 3, 4], [5, 6, 7, 8]] >>> reshape(seq, (4,)) # tuples of 4 [(1, 2, 3, 4), (5, 6, 7, 8)] >>> reshape(seq, (2, 2)) # tuples of 4 [(1, 2, 3, 4), (5, 6, 7, 8)] >>> reshape(seq, (2, [2])) # (i, i, [i, i]) [(1, 2, [3, 4]), (5, 6, [7, 8])] >>> reshape(seq, ((2,), [2])) # etc.... [((1, 2), [3, 4]), ((5, 6), [7, 8])] >>> reshape(seq, (1, [2], 1)) [(1, [2, 3], 4), (5, [6, 7], 8)] >>> reshape(tuple(seq), ([[1], 1, (2,)],)) (([[1], 2, (3, 4)],), ([[5], 6, (7, 8)],)) >>> reshape(tuple(seq), ([1], 1, (2,))) (([1], 2, (3, 4)), ([5], 6, (7, 8))) >>> reshape(list(range(12)), [2, [3], {2}, (1, (3,), 1)]) [[0, 1, [2, 3, 4], {5, 6}, (7, (8, 9, 10), 11)]] """ m = sum(flatten(how)) n, rem = divmod(len(seq), m) if m < 0 or rem: raise ValueError('template must sum to positive number ' 'that divides the length of the sequence') i = 0 container = type(how) rv = [None]*n for k in range(len(rv)): _rv = [] for hi in how: if isinstance(hi, int): _rv.extend(seq[i: i + hi]) i += hi else: n = sum(flatten(hi)) hi_type = type(hi) _rv.append(hi_type(reshape(seq[i: i + n], hi)[0])) i += n rv[k] = container(_rv) return type(seq)(rv) def group(seq, multiple=True): """ Splits a sequence into a list of lists of equal, adjacent elements. Examples ======== >>> from sympy import group >>> group([1, 1, 1, 2, 2, 3]) [[1, 1, 1], [2, 2], [3]] >>> group([1, 1, 1, 2, 2, 3], multiple=False) [(1, 3), (2, 2), (3, 1)] >>> group([1, 1, 3, 2, 2, 1], multiple=False) [(1, 2), (3, 1), (2, 2), (1, 1)] See Also ======== multiset """ if not seq: return [] current, groups = [seq[0]], [] for elem in seq[1:]: if elem == current[-1]: current.append(elem) else: groups.append(current) current = [elem] groups.append(current) if multiple: return groups for i, current in enumerate(groups): groups[i] = (current[0], len(current)) return groups def _iproduct2(iterable1, iterable2): '''Cartesian product of two possibly infinite iterables''' it1 = iter(iterable1) it2 = iter(iterable2) elems1 = [] elems2 = [] sentinel = object() def append(it, elems): e = next(it, sentinel) if e is not sentinel: elems.append(e) n = 0 append(it1, elems1) append(it2, elems2) while n <= len(elems1) + len(elems2): for m in range(n-len(elems1)+1, len(elems2)): yield (elems1[n-m], elems2[m]) n += 1 append(it1, elems1) append(it2, elems2) def iproduct(*iterables): ''' Cartesian product of iterables. Generator of the Cartesian product of iterables. This is analogous to itertools.product except that it works with infinite iterables and will yield any item from the infinite product eventually. Examples ======== >>> from sympy.utilities.iterables import iproduct >>> sorted(iproduct([1,2], [3,4])) [(1, 3), (1, 4), (2, 3), (2, 4)] With an infinite iterator: >>> from sympy import S >>> (3,) in iproduct(S.Integers) True >>> (3, 4) in iproduct(S.Integers, S.Integers) True .. seealso:: `itertools.product <https://docs.python.org/3/library/itertools.html#itertools.product>`_ ''' if len(iterables) == 0: yield () return elif len(iterables) == 1: for e in iterables[0]: yield (e,) elif len(iterables) == 2: yield from _iproduct2(*iterables) else: first, others = iterables[0], iterables[1:] for ef, eo in _iproduct2(first, iproduct(*others)): yield (ef,) + eo def multiset(seq): """Return the hashable sequence in multiset form with values being the multiplicity of the item in the sequence. Examples ======== >>> from sympy.utilities.iterables import multiset >>> multiset('mississippi') {'i': 4, 'm': 1, 'p': 2, 's': 4} See Also ======== group """ rv = defaultdict(int) for s in seq: rv[s] += 1 return dict(rv) def ibin(n, bits=None, str=False): """Return a list of length ``bits`` corresponding to the binary value of ``n`` with small bits to the right (last). If bits is omitted, the length will be the number required to represent ``n``. If the bits are desired in reversed order, use the ``[::-1]`` slice of the returned list. If a sequence of all bits-length lists starting from ``[0, 0,..., 0]`` through ``[1, 1, ..., 1]`` are desired, pass a non-integer for bits, e.g. ``'all'``. If the bit *string* is desired pass ``str=True``. Examples ======== >>> from sympy.utilities.iterables import ibin >>> ibin(2) [1, 0] >>> ibin(2, 4) [0, 0, 1, 0] If all lists corresponding to 0 to 2**n - 1, pass a non-integer for bits: >>> bits = 2 >>> for i in ibin(2, 'all'): ... print(i) (0, 0) (0, 1) (1, 0) (1, 1) If a bit string is desired of a given length, use str=True: >>> n = 123 >>> bits = 10 >>> ibin(n, bits, str=True) '0001111011' >>> ibin(n, bits, str=True)[::-1] # small bits left '1101111000' >>> list(ibin(3, 'all', str=True)) ['000', '001', '010', '011', '100', '101', '110', '111'] """ if n < 0: raise ValueError("negative numbers are not allowed") n = as_int(n) if bits is None: bits = 0 else: try: bits = as_int(bits) except ValueError: bits = -1 else: if n.bit_length() > bits: raise ValueError( "`bits` must be >= {}".format(n.bit_length())) if not str: if bits >= 0: return [1 if i == "1" else 0 for i in bin(n)[2:].rjust(bits, "0")] else: return variations(list(range(2)), n, repetition=True) else: if bits >= 0: return bin(n)[2:].rjust(bits, "0") else: return (bin(i)[2:].rjust(n, "0") for i in range(2**n)) def variations(seq, n, repetition=False): r"""Returns an iterator over the n-sized variations of ``seq`` (size N). ``repetition`` controls whether items in ``seq`` can appear more than once; Examples ======== ``variations(seq, n)`` will return `\frac{N!}{(N - n)!}` permutations without repetition of ``seq``'s elements: >>> from sympy import variations >>> list(variations([1, 2], 2)) [(1, 2), (2, 1)] ``variations(seq, n, True)`` will return the `N^n` permutations obtained by allowing repetition of elements: >>> list(variations([1, 2], 2, repetition=True)) [(1, 1), (1, 2), (2, 1), (2, 2)] If you ask for more items than are in the set you get the empty set unless you allow repetitions: >>> list(variations([0, 1], 3, repetition=False)) [] >>> list(variations([0, 1], 3, repetition=True))[:4] [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1)] .. seealso:: `itertools.permutations <https://docs.python.org/3/library/itertools.html#itertools.permutations>`_, `itertools.product <https://docs.python.org/3/library/itertools.html#itertools.product>`_ """ if not repetition: seq = tuple(seq) if len(seq) < n: return iter(()) # 0 length iterator return permutations(seq, n) else: if n == 0: return iter(((),)) # yields 1 empty tuple else: return product(seq, repeat=n) def subsets(seq, k=None, repetition=False): r"""Generates all `k`-subsets (combinations) from an `n`-element set, ``seq``. A `k`-subset of an `n`-element set is any subset of length exactly `k`. The number of `k`-subsets of an `n`-element set is given by ``binomial(n, k)``, whereas there are `2^n` subsets all together. If `k` is ``None`` then all `2^n` subsets will be returned from shortest to longest. Examples ======== >>> from sympy import subsets ``subsets(seq, k)`` will return the `\frac{n!}{k!(n - k)!}` `k`-subsets (combinations) without repetition, i.e. once an item has been removed, it can no longer be "taken": >>> list(subsets([1, 2], 2)) [(1, 2)] >>> list(subsets([1, 2])) [(), (1,), (2,), (1, 2)] >>> list(subsets([1, 2, 3], 2)) [(1, 2), (1, 3), (2, 3)] ``subsets(seq, k, repetition=True)`` will return the `\frac{(n - 1 + k)!}{k!(n - 1)!}` combinations *with* repetition: >>> list(subsets([1, 2], 2, repetition=True)) [(1, 1), (1, 2), (2, 2)] If you ask for more items than are in the set you get the empty set unless you allow repetitions: >>> list(subsets([0, 1], 3, repetition=False)) [] >>> list(subsets([0, 1], 3, repetition=True)) [(0, 0, 0), (0, 0, 1), (0, 1, 1), (1, 1, 1)] """ if k is None: if not repetition: return chain.from_iterable((combinations(seq, k) for k in range(len(seq) + 1))) else: return chain.from_iterable((combinations_with_replacement(seq, k) for k in range(len(seq) + 1))) else: if not repetition: return combinations(seq, k) else: return combinations_with_replacement(seq, k) def filter_symbols(iterator, exclude): """ Only yield elements from `iterator` that do not occur in `exclude`. Parameters ========== iterator : iterable iterator to take elements from exclude : iterable elements to exclude Returns ======= iterator : iterator filtered iterator """ exclude = set(exclude) for s in iterator: if s not in exclude: yield s def numbered_symbols(prefix='x', cls=None, start=0, exclude=(), *args, **assumptions): """ Generate an infinite stream of Symbols consisting of a prefix and increasing subscripts provided that they do not occur in ``exclude``. Parameters ========== prefix : str, optional The prefix to use. By default, this function will generate symbols of the form "x0", "x1", etc. cls : class, optional The class to use. By default, it uses ``Symbol``, but you can also use ``Wild`` or ``Dummy``. start : int, optional The start number. By default, it is 0. Returns ======= sym : Symbol The subscripted symbols. """ exclude = set(exclude or []) if cls is None: # We can't just make the default cls=Symbol because it isn't # imported yet. from sympy.core import Symbol cls = Symbol while True: name = '%s%s' % (prefix, start) s = cls(name, *args, **assumptions) if s not in exclude: yield s start += 1 def capture(func): """Return the printed output of func(). ``func`` should be a function without arguments that produces output with print statements. >>> from sympy.utilities.iterables import capture >>> from sympy import pprint >>> from sympy.abc import x >>> def foo(): ... print('hello world!') ... >>> 'hello' in capture(foo) # foo, not foo() True >>> capture(lambda: pprint(2/x)) '2\\n-\\nx\\n' """ from io import StringIO import sys stdout = sys.stdout sys.stdout = file = StringIO() try: func() finally: sys.stdout = stdout return file.getvalue() def sift(seq, keyfunc, binary=False): """ Sift the sequence, ``seq`` according to ``keyfunc``. Returns ======= When ``binary`` is ``False`` (default), the output is a dictionary where elements of ``seq`` are stored in a list keyed to the value of keyfunc for that element. If ``binary`` is True then a tuple with lists ``T`` and ``F`` are returned where ``T`` is a list containing elements of seq for which ``keyfunc`` was ``True`` and ``F`` containing those elements for which ``keyfunc`` was ``False``; a ValueError is raised if the ``keyfunc`` is not binary. Examples ======== >>> from sympy.utilities import sift >>> from sympy.abc import x, y >>> from sympy import sqrt, exp, pi, Tuple >>> sift(range(5), lambda x: x % 2) {0: [0, 2, 4], 1: [1, 3]} sift() returns a defaultdict() object, so any key that has no matches will give []. >>> sift([x], lambda x: x.is_commutative) {True: [x]} >>> _[False] [] Sometimes you will not know how many keys you will get: >>> sift([sqrt(x), exp(x), (y**x)**2], ... lambda x: x.as_base_exp()[0]) {E: [exp(x)], x: [sqrt(x)], y: [y**(2*x)]} Sometimes you expect the results to be binary; the results can be unpacked by setting ``binary`` to True: >>> sift(range(4), lambda x: x % 2, binary=True) ([1, 3], [0, 2]) >>> sift(Tuple(1, pi), lambda x: x.is_rational, binary=True) ([1], [pi]) A ValueError is raised if the predicate was not actually binary (which is a good test for the logic where sifting is used and binary results were expected): >>> unknown = exp(1) - pi # the rationality of this is unknown >>> args = Tuple(1, pi, unknown) >>> sift(args, lambda x: x.is_rational, binary=True) Traceback (most recent call last): ... ValueError: keyfunc gave non-binary output The non-binary sifting shows that there were 3 keys generated: >>> set(sift(args, lambda x: x.is_rational).keys()) {None, False, True} If you need to sort the sifted items it might be better to use ``ordered`` which can economically apply multiple sort keys to a sequence while sorting. See Also ======== ordered """ if not binary: m = defaultdict(list) for i in seq: m[keyfunc(i)].append(i) return m sift = F, T = [], [] for i in seq: try: sift[keyfunc(i)].append(i) except (IndexError, TypeError): raise ValueError('keyfunc gave non-binary output') return T, F def take(iter, n): """Return ``n`` items from ``iter`` iterator. """ return [ value for _, value in zip(range(n), iter) ] def dict_merge(*dicts): """Merge dictionaries into a single dictionary. """ merged = {} for dict in dicts: merged.update(dict) return merged def common_prefix(*seqs): """Return the subsequence that is a common start of sequences in ``seqs``. >>> from sympy.utilities.iterables import common_prefix >>> common_prefix(list(range(3))) [0, 1, 2] >>> common_prefix(list(range(3)), list(range(4))) [0, 1, 2] >>> common_prefix([1, 2, 3], [1, 2, 5]) [1, 2] >>> common_prefix([1, 2, 3], [1, 3, 5]) [1] """ if not all(seqs): return [] elif len(seqs) == 1: return seqs[0] i = 0 for i in range(min(len(s) for s in seqs)): if not all(seqs[j][i] == seqs[0][i] for j in range(len(seqs))): break else: i += 1 return seqs[0][:i] def common_suffix(*seqs): """Return the subsequence that is a common ending of sequences in ``seqs``. >>> from sympy.utilities.iterables import common_suffix >>> common_suffix(list(range(3))) [0, 1, 2] >>> common_suffix(list(range(3)), list(range(4))) [] >>> common_suffix([1, 2, 3], [9, 2, 3]) [2, 3] >>> common_suffix([1, 2, 3], [9, 7, 3]) [3] """ if not all(seqs): return [] elif len(seqs) == 1: return seqs[0] i = 0 for i in range(-1, -min(len(s) for s in seqs) - 1, -1): if not all(seqs[j][i] == seqs[0][i] for j in range(len(seqs))): break else: i -= 1 if i == -1: return [] else: return seqs[0][i + 1:] def prefixes(seq): """ Generate all prefixes of a sequence. Examples ======== >>> from sympy.utilities.iterables import prefixes >>> list(prefixes([1,2,3,4])) [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]] """ n = len(seq) for i in range(n): yield seq[:i + 1] def postfixes(seq): """ Generate all postfixes of a sequence. Examples ======== >>> from sympy.utilities.iterables import postfixes >>> list(postfixes([1,2,3,4])) [[4], [3, 4], [2, 3, 4], [1, 2, 3, 4]] """ n = len(seq) for i in range(n): yield seq[n - i - 1:] def topological_sort(graph, key=None): r""" Topological sort of graph's vertices. Parameters ========== graph : tuple[list, list[tuple[T, T]] A tuple consisting of a list of vertices and a list of edges of a graph to be sorted topologically. key : callable[T] (optional) Ordering key for vertices on the same level. By default the natural (e.g. lexicographic) ordering is used (in this case the base type must implement ordering relations). Examples ======== Consider a graph:: +---+ +---+ +---+ | 7 |\ | 5 | | 3 | +---+ \ +---+ +---+ | _\___/ ____ _/ | | / \___/ \ / | V V V V | +----+ +---+ | | 11 | | 8 | | +----+ +---+ | | | \____ ___/ _ | | \ \ / / \ | V \ V V / V V +---+ \ +---+ | +----+ | 2 | | | 9 | | | 10 | +---+ | +---+ | +----+ \________/ where vertices are integers. This graph can be encoded using elementary Python's data structures as follows:: >>> V = [2, 3, 5, 7, 8, 9, 10, 11] >>> E = [(7, 11), (7, 8), (5, 11), (3, 8), (3, 10), ... (11, 2), (11, 9), (11, 10), (8, 9)] To compute a topological sort for graph ``(V, E)`` issue:: >>> from sympy.utilities.iterables import topological_sort >>> topological_sort((V, E)) [3, 5, 7, 8, 11, 2, 9, 10] If specific tie breaking approach is needed, use ``key`` parameter:: >>> topological_sort((V, E), key=lambda v: -v) [7, 5, 11, 3, 10, 8, 9, 2] Only acyclic graphs can be sorted. If the input graph has a cycle, then ``ValueError`` will be raised:: >>> topological_sort((V, E + [(10, 7)])) Traceback (most recent call last): ... ValueError: cycle detected References ========== .. [1] https://en.wikipedia.org/wiki/Topological_sorting """ V, E = graph L = [] S = set(V) E = list(E) for v, u in E: S.discard(u) if key is None: key = lambda value: value S = sorted(S, key=key, reverse=True) while S: node = S.pop() L.append(node) for u, v in list(E): if u == node: E.remove((u, v)) for _u, _v in E: if v == _v: break else: kv = key(v) for i, s in enumerate(S): ks = key(s) if kv > ks: S.insert(i, v) break else: S.append(v) if E: raise ValueError("cycle detected") else: return L def strongly_connected_components(G): r""" Strongly connected components of a directed graph in reverse topological order. Parameters ========== graph : tuple[list, list[tuple[T, T]] A tuple consisting of a list of vertices and a list of edges of a graph whose strongly connected components are to be found. Examples ======== Consider a directed graph (in dot notation):: digraph { A -> B A -> C B -> C C -> B B -> D } .. graphviz:: digraph { A -> B A -> C B -> C C -> B B -> D } where vertices are the letters A, B, C and D. This graph can be encoded using Python's elementary data structures as follows:: >>> V = ['A', 'B', 'C', 'D'] >>> E = [('A', 'B'), ('A', 'C'), ('B', 'C'), ('C', 'B'), ('B', 'D')] The strongly connected components of this graph can be computed as >>> from sympy.utilities.iterables import strongly_connected_components >>> strongly_connected_components((V, E)) [['D'], ['B', 'C'], ['A']] This also gives the components in reverse topological order. Since the subgraph containing B and C has a cycle they must be together in a strongly connected component. A and D are connected to the rest of the graph but not in a cyclic manner so they appear as their own strongly connected components. Notes ===== The vertices of the graph must be hashable for the data structures used. If the vertices are unhashable replace them with integer indices. This function uses Tarjan's algorithm to compute the strongly connected components in `O(|V|+|E|)` (linear) time. References ========== .. [1] https://en.wikipedia.org/wiki/Strongly_connected_component .. [2] https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm See Also ======== sympy.utilities.iterables.connected_components """ # Map from a vertex to its neighbours V, E = G Gmap = {vi: [] for vi in V} for v1, v2 in E: Gmap[v1].append(v2) return _strongly_connected_components(V, Gmap) def _strongly_connected_components(V, Gmap): """More efficient internal routine for strongly_connected_components""" # # Here V is an iterable of vertices and Gmap is a dict mapping each vertex # to a list of neighbours e.g.: # # V = [0, 1, 2, 3] # Gmap = {0: [2, 3], 1: [0]} # # For a large graph these data structures can often be created more # efficiently then those expected by strongly_connected_components() which # in this case would be # # V = [0, 1, 2, 3] # Gmap = [(0, 2), (0, 3), (1, 0)] # # XXX: Maybe this should be the recommended function to use instead... # # Non-recursive Tarjan's algorithm: lowlink = {} indices = {} stack = OrderedDict() callstack = [] components = [] nomore = object() def start(v): index = len(stack) indices[v] = lowlink[v] = index stack[v] = None callstack.append((v, iter(Gmap[v]))) def finish(v1): # Finished a component? if lowlink[v1] == indices[v1]: component = [stack.popitem()[0]] while component[-1] is not v1: component.append(stack.popitem()[0]) components.append(component[::-1]) v2, _ = callstack.pop() if callstack: v1, _ = callstack[-1] lowlink[v1] = min(lowlink[v1], lowlink[v2]) for v in V: if v in indices: continue start(v) while callstack: v1, it1 = callstack[-1] v2 = next(it1, nomore) # Finished children of v1? if v2 is nomore: finish(v1) # Recurse on v2 elif v2 not in indices: start(v2) elif v2 in stack: lowlink[v1] = min(lowlink[v1], indices[v2]) # Reverse topological sort order: return components def connected_components(G): r""" Connected components of an undirected graph or weakly connected components of a directed graph. Parameters ========== graph : tuple[list, list[tuple[T, T]] A tuple consisting of a list of vertices and a list of edges of a graph whose connected components are to be found. Examples ======== Given an undirected graph:: graph { A -- B C -- D } .. graphviz:: graph { A -- B C -- D } We can find the connected components using this function if we include each edge in both directions:: >>> from sympy.utilities.iterables import connected_components >>> V = ['A', 'B', 'C', 'D'] >>> E = [('A', 'B'), ('B', 'A'), ('C', 'D'), ('D', 'C')] >>> connected_components((V, E)) [['A', 'B'], ['C', 'D']] The weakly connected components of a directed graph can found the same way. Notes ===== The vertices of the graph must be hashable for the data structures used. If the vertices are unhashable replace them with integer indices. This function uses Tarjan's algorithm to compute the connected components in `O(|V|+|E|)` (linear) time. References ========== .. [1] https://en.wikipedia.org/wiki/Connected_component_(graph_theory) .. [2] https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm See Also ======== sympy.utilities.iterables.strongly_connected_components """ # Duplicate edges both ways so that the graph is effectively undirected # and return the strongly connected components: V, E = G E_undirected = [] for v1, v2 in E: E_undirected.extend([(v1, v2), (v2, v1)]) return strongly_connected_components((V, E_undirected)) def rotate_left(x, y): """ Left rotates a list x by the number of steps specified in y. Examples ======== >>> from sympy.utilities.iterables import rotate_left >>> a = [0, 1, 2] >>> rotate_left(a, 1) [1, 2, 0] """ if len(x) == 0: return [] y = y % len(x) return x[y:] + x[:y] def rotate_right(x, y): """ Right rotates a list x by the number of steps specified in y. Examples ======== >>> from sympy.utilities.iterables import rotate_right >>> a = [0, 1, 2] >>> rotate_right(a, 1) [2, 0, 1] """ if len(x) == 0: return [] y = len(x) - y % len(x) return x[y:] + x[:y] def least_rotation(x, key=None): ''' Returns the number of steps of left rotation required to obtain lexicographically minimal string/list/tuple, etc. Examples ======== >>> from sympy.utilities.iterables import least_rotation, rotate_left >>> a = [3, 1, 5, 1, 2] >>> least_rotation(a) 3 >>> rotate_left(a, _) [1, 2, 3, 1, 5] References ========== .. [1] https://en.wikipedia.org/wiki/Lexicographically_minimal_string_rotation ''' from sympy.functions.elementary.miscellaneous import Id if key is None: key = Id S = x + x # Concatenate string to it self to avoid modular arithmetic f = [-1] * len(S) # Failure function k = 0 # Least rotation of string found so far for j in range(1,len(S)): sj = S[j] i = f[j-k-1] while i != -1 and sj != S[k+i+1]: if key(sj) < key(S[k+i+1]): k = j-i-1 i = f[i] if sj != S[k+i+1]: if key(sj) < key(S[k]): k = j f[j-k] = -1 else: f[j-k] = i+1 return k def multiset_combinations(m, n, g=None): """ Return the unique combinations of size ``n`` from multiset ``m``. Examples ======== >>> from sympy.utilities.iterables import multiset_combinations >>> from itertools import combinations >>> [''.join(i) for i in multiset_combinations('baby', 3)] ['abb', 'aby', 'bby'] >>> def count(f, s): return len(list(f(s, 3))) The number of combinations depends on the number of letters; the number of unique combinations depends on how the letters are repeated. >>> s1 = 'abracadabra' >>> s2 = 'banana tree' >>> count(combinations, s1), count(multiset_combinations, s1) (165, 23) >>> count(combinations, s2), count(multiset_combinations, s2) (165, 54) """ from sympy.core.sorting import ordered if g is None: if isinstance(m, dict): if any(as_int(v) < 0 for v in m.values()): raise ValueError('counts cannot be negative') N = sum(m.values()) if n > N: return g = [[k, m[k]] for k in ordered(m)] else: m = list(m) N = len(m) if n > N: return try: m = multiset(m) g = [(k, m[k]) for k in ordered(m)] except TypeError: m = list(ordered(m)) g = [list(i) for i in group(m, multiple=False)] del m else: # not checking counts since g is intended for internal use N = sum(v for k, v in g) if n > N or not n: yield [] else: for i, (k, v) in enumerate(g): if v >= n: yield [k]*n v = n - 1 for v in range(min(n, v), 0, -1): for j in multiset_combinations(None, n - v, g[i + 1:]): rv = [k]*v + j if len(rv) == n: yield rv def multiset_permutations(m, size=None, g=None): """ Return the unique permutations of multiset ``m``. Examples ======== >>> from sympy.utilities.iterables import multiset_permutations >>> from sympy import factorial >>> [''.join(i) for i in multiset_permutations('aab')] ['aab', 'aba', 'baa'] >>> factorial(len('banana')) 720 >>> len(list(multiset_permutations('banana'))) 60 """ from sympy.core.sorting import ordered if g is None: if isinstance(m, dict): if any(as_int(v) < 0 for v in m.values()): raise ValueError('counts cannot be negative') g = [[k, m[k]] for k in ordered(m)] else: m = list(ordered(m)) g = [list(i) for i in group(m, multiple=False)] del m do = [gi for gi in g if gi[1] > 0] SUM = sum([gi[1] for gi in do]) if not do or size is not None and (size > SUM or size < 1): if not do and size is None or size == 0: yield [] return elif size == 1: for k, v in do: yield [k] elif len(do) == 1: k, v = do[0] v = v if size is None else (size if size <= v else 0) yield [k for i in range(v)] elif all(v == 1 for k, v in do): for p in permutations([k for k, v in do], size): yield list(p) else: size = size if size is not None else SUM for i, (k, v) in enumerate(do): do[i][1] -= 1 for j in multiset_permutations(None, size - 1, do): if j: yield [k] + j do[i][1] += 1 def _partition(seq, vector, m=None): """ Return the partition of seq as specified by the partition vector. Examples ======== >>> from sympy.utilities.iterables import _partition >>> _partition('abcde', [1, 0, 1, 2, 0]) [['b', 'e'], ['a', 'c'], ['d']] Specifying the number of bins in the partition is optional: >>> _partition('abcde', [1, 0, 1, 2, 0], 3) [['b', 'e'], ['a', 'c'], ['d']] The output of _set_partitions can be passed as follows: >>> output = (3, [1, 0, 1, 2, 0]) >>> _partition('abcde', *output) [['b', 'e'], ['a', 'c'], ['d']] See Also ======== combinatorics.partitions.Partition.from_rgs """ if m is None: m = max(vector) + 1 elif isinstance(vector, int): # entered as m, vector vector, m = m, vector p = [[] for i in range(m)] for i, v in enumerate(vector): p[v].append(seq[i]) return p def _set_partitions(n): """Cycle through all partions of n elements, yielding the current number of partitions, ``m``, and a mutable list, ``q`` such that ``element[i]`` is in part ``q[i]`` of the partition. NOTE: ``q`` is modified in place and generally should not be changed between function calls. Examples ======== >>> from sympy.utilities.iterables import _set_partitions, _partition >>> for m, q in _set_partitions(3): ... print('%s %s %s' % (m, q, _partition('abc', q, m))) 1 [0, 0, 0] [['a', 'b', 'c']] 2 [0, 0, 1] [['a', 'b'], ['c']] 2 [0, 1, 0] [['a', 'c'], ['b']] 2 [0, 1, 1] [['a'], ['b', 'c']] 3 [0, 1, 2] [['a'], ['b'], ['c']] Notes ===== This algorithm is similar to, and solves the same problem as, Algorithm 7.2.1.5H, from volume 4A of Knuth's The Art of Computer Programming. Knuth uses the term "restricted growth string" where this code refers to a "partition vector". In each case, the meaning is the same: the value in the ith element of the vector specifies to which part the ith set element is to be assigned. At the lowest level, this code implements an n-digit big-endian counter (stored in the array q) which is incremented (with carries) to get the next partition in the sequence. A special twist is that a digit is constrained to be at most one greater than the maximum of all the digits to the left of it. The array p maintains this maximum, so that the code can efficiently decide when a digit can be incremented in place or whether it needs to be reset to 0 and trigger a carry to the next digit. The enumeration starts with all the digits 0 (which corresponds to all the set elements being assigned to the same 0th part), and ends with 0123...n, which corresponds to each set element being assigned to a different, singleton, part. This routine was rewritten to use 0-based lists while trying to preserve the beauty and efficiency of the original algorithm. References ========== .. [1] Nijenhuis, Albert and Wilf, Herbert. (1978) Combinatorial Algorithms, 2nd Ed, p 91, algorithm "nexequ". Available online from https://www.math.upenn.edu/~wilf/website/CombAlgDownld.html (viewed November 17, 2012). """ p = [0]*n q = [0]*n nc = 1 yield nc, q while nc != n: m = n while 1: m -= 1 i = q[m] if p[i] != 1: break q[m] = 0 i += 1 q[m] = i m += 1 nc += m - n p[0] += n - m if i == nc: p[nc] = 0 nc += 1 p[i - 1] -= 1 p[i] += 1 yield nc, q def multiset_partitions(multiset, m=None): """ Return unique partitions of the given multiset (in list form). If ``m`` is None, all multisets will be returned, otherwise only partitions with ``m`` parts will be returned. If ``multiset`` is an integer, a range [0, 1, ..., multiset - 1] will be supplied. Examples ======== >>> from sympy.utilities.iterables import multiset_partitions >>> list(multiset_partitions([1, 2, 3, 4], 2)) [[[1, 2, 3], [4]], [[1, 2, 4], [3]], [[1, 2], [3, 4]], [[1, 3, 4], [2]], [[1, 3], [2, 4]], [[1, 4], [2, 3]], [[1], [2, 3, 4]]] >>> list(multiset_partitions([1, 2, 3, 4], 1)) [[[1, 2, 3, 4]]] Only unique partitions are returned and these will be returned in a canonical order regardless of the order of the input: >>> a = [1, 2, 2, 1] >>> ans = list(multiset_partitions(a, 2)) >>> a.sort() >>> list(multiset_partitions(a, 2)) == ans True >>> a = range(3, 1, -1) >>> (list(multiset_partitions(a)) == ... list(multiset_partitions(sorted(a)))) True If m is omitted then all partitions will be returned: >>> list(multiset_partitions([1, 1, 2])) [[[1, 1, 2]], [[1, 1], [2]], [[1, 2], [1]], [[1], [1], [2]]] >>> list(multiset_partitions([1]*3)) [[[1, 1, 1]], [[1], [1, 1]], [[1], [1], [1]]] Counting ======== The number of partitions of a set is given by the bell number: >>> from sympy import bell >>> len(list(multiset_partitions(5))) == bell(5) == 52 True The number of partitions of length k from a set of size n is given by the Stirling Number of the 2nd kind: >>> from sympy.functions.combinatorial.numbers import stirling >>> stirling(5, 2) == len(list(multiset_partitions(5, 2))) == 15 True These comments on counting apply to *sets*, not multisets. Notes ===== When all the elements are the same in the multiset, the order of the returned partitions is determined by the ``partitions`` routine. If one is counting partitions then it is better to use the ``nT`` function. See Also ======== partitions sympy.combinatorics.partitions.Partition sympy.combinatorics.partitions.IntegerPartition sympy.functions.combinatorial.numbers.nT """ # This function looks at the supplied input and dispatches to # several special-case routines as they apply. if isinstance(multiset, int): n = multiset if m and m > n: return multiset = list(range(n)) if m == 1: yield [multiset[:]] return # If m is not None, it can sometimes be faster to use # MultisetPartitionTraverser.enum_range() even for inputs # which are sets. Since the _set_partitions code is quite # fast, this is only advantageous when the overall set # partitions outnumber those with the desired number of parts # by a large factor. (At least 60.) Such a switch is not # currently implemented. for nc, q in _set_partitions(n): if m is None or nc == m: rv = [[] for i in range(nc)] for i in range(n): rv[q[i]].append(multiset[i]) yield rv return if len(multiset) == 1 and isinstance(multiset, str): multiset = [multiset] if not has_variety(multiset): # Only one component, repeated n times. The resulting # partitions correspond to partitions of integer n. n = len(multiset) if m and m > n: return if m == 1: yield [multiset[:]] return x = multiset[:1] for size, p in partitions(n, m, size=True): if m is None or size == m: rv = [] for k in sorted(p): rv.extend([x*k]*p[k]) yield rv else: from sympy.core.sorting import ordered multiset = list(ordered(multiset)) n = len(multiset) if m and m > n: return if m == 1: yield [multiset[:]] return # Split the information of the multiset into two lists - # one of the elements themselves, and one (of the same length) # giving the number of repeats for the corresponding element. elements, multiplicities = zip(*group(multiset, False)) if len(elements) < len(multiset): # General case - multiset with more than one distinct element # and at least one element repeated more than once. if m: mpt = MultisetPartitionTraverser() for state in mpt.enum_range(multiplicities, m-1, m): yield list_visitor(state, elements) else: for state in multiset_partitions_taocp(multiplicities): yield list_visitor(state, elements) else: # Set partitions case - no repeated elements. Pretty much # same as int argument case above, with same possible, but # currently unimplemented optimization for some cases when # m is not None for nc, q in _set_partitions(n): if m is None or nc == m: rv = [[] for i in range(nc)] for i in range(n): rv[q[i]].append(i) yield [[multiset[j] for j in i] for i in rv] def partitions(n, m=None, k=None, size=False): """Generate all partitions of positive integer, n. Parameters ========== m : integer (default gives partitions of all sizes) limits number of parts in partition (mnemonic: m, maximum parts) k : integer (default gives partitions number from 1 through n) limits the numbers that are kept in the partition (mnemonic: k, keys) size : bool (default False, only partition is returned) when ``True`` then (M, P) is returned where M is the sum of the multiplicities and P is the generated partition. Each partition is represented as a dictionary, mapping an integer to the number of copies of that integer in the partition. For example, the first partition of 4 returned is {4: 1}, "4: one of them". Examples ======== >>> from sympy.utilities.iterables import partitions The numbers appearing in the partition (the key of the returned dict) are limited with k: >>> for p in partitions(6, k=2): # doctest: +SKIP ... print(p) {2: 3} {1: 2, 2: 2} {1: 4, 2: 1} {1: 6} The maximum number of parts in the partition (the sum of the values in the returned dict) are limited with m (default value, None, gives partitions from 1 through n): >>> for p in partitions(6, m=2): # doctest: +SKIP ... print(p) ... {6: 1} {1: 1, 5: 1} {2: 1, 4: 1} {3: 2} References ========== .. [1] modified from Tim Peter's version to allow for k and m values: http://code.activestate.com/recipes/218332-generator-for-integer-partitions/ See Also ======== sympy.combinatorics.partitions.Partition sympy.combinatorics.partitions.IntegerPartition """ if (n <= 0 or m is not None and m < 1 or k is not None and k < 1 or m and k and m*k < n): # the empty set is the only way to handle these inputs # and returning {} to represent it is consistent with # the counting convention, e.g. nT(0) == 1. if size: yield 0, {} else: yield {} return if m is None: m = n else: m = min(m, n) k = min(k or n, n) n, m, k = as_int(n), as_int(m), as_int(k) q, r = divmod(n, k) ms = {k: q} keys = [k] # ms.keys(), from largest to smallest if r: ms[r] = 1 keys.append(r) room = m - q - bool(r) if size: yield sum(ms.values()), ms.copy() else: yield ms.copy() while keys != [1]: # Reuse any 1's. if keys[-1] == 1: del keys[-1] reuse = ms.pop(1) room += reuse else: reuse = 0 while 1: # Let i be the smallest key larger than 1. Reuse one # instance of i. i = keys[-1] newcount = ms[i] = ms[i] - 1 reuse += i if newcount == 0: del keys[-1], ms[i] room += 1 # Break the remainder into pieces of size i-1. i -= 1 q, r = divmod(reuse, i) need = q + bool(r) if need > room: if not keys: return continue ms[i] = q keys.append(i) if r: ms[r] = 1 keys.append(r) break room -= need if size: yield sum(ms.values()), ms.copy() else: yield ms.copy() def ordered_partitions(n, m=None, sort=True): """Generates ordered partitions of integer ``n``. Parameters ========== m : integer (default None) The default value gives partitions of all sizes else only those with size m. In addition, if ``m`` is not None then partitions are generated *in place* (see examples). sort : bool (default True) Controls whether partitions are returned in sorted order when ``m`` is not None; when False, the partitions are returned as fast as possible with elements sorted, but when m|n the partitions will not be in ascending lexicographical order. Examples ======== >>> from sympy.utilities.iterables import ordered_partitions All partitions of 5 in ascending lexicographical: >>> for p in ordered_partitions(5): ... print(p) [1, 1, 1, 1, 1] [1, 1, 1, 2] [1, 1, 3] [1, 2, 2] [1, 4] [2, 3] [5] Only partitions of 5 with two parts: >>> for p in ordered_partitions(5, 2): ... print(p) [1, 4] [2, 3] When ``m`` is given, a given list objects will be used more than once for speed reasons so you will not see the correct partitions unless you make a copy of each as it is generated: >>> [p for p in ordered_partitions(7, 3)] [[1, 1, 1], [1, 1, 1], [1, 1, 1], [2, 2, 2]] >>> [list(p) for p in ordered_partitions(7, 3)] [[1, 1, 5], [1, 2, 4], [1, 3, 3], [2, 2, 3]] When ``n`` is a multiple of ``m``, the elements are still sorted but the partitions themselves will be *unordered* if sort is False; the default is to return them in ascending lexicographical order. >>> for p in ordered_partitions(6, 2): ... print(p) [1, 5] [2, 4] [3, 3] But if speed is more important than ordering, sort can be set to False: >>> for p in ordered_partitions(6, 2, sort=False): ... print(p) [1, 5] [3, 3] [2, 4] References ========== .. [1] Generating Integer Partitions, [online], Available: https://jeromekelleher.net/generating-integer-partitions.html .. [2] Jerome Kelleher and Barry O'Sullivan, "Generating All Partitions: A Comparison Of Two Encodings", [online], Available: https://arxiv.org/pdf/0909.2331v2.pdf """ if n < 1 or m is not None and m < 1: # the empty set is the only way to handle these inputs # and returning {} to represent it is consistent with # the counting convention, e.g. nT(0) == 1. yield [] return if m is None: # The list `a`'s leading elements contain the partition in which # y is the biggest element and x is either the same as y or the # 2nd largest element; v and w are adjacent element indices # to which x and y are being assigned, respectively. a = [1]*n y = -1 v = n while v > 0: v -= 1 x = a[v] + 1 while y >= 2 * x: a[v] = x y -= x v += 1 w = v + 1 while x <= y: a[v] = x a[w] = y yield a[:w + 1] x += 1 y -= 1 a[v] = x + y y = a[v] - 1 yield a[:w] elif m == 1: yield [n] elif n == m: yield [1]*n else: # recursively generate partitions of size m for b in range(1, n//m + 1): a = [b]*m x = n - b*m if not x: if sort: yield a elif not sort and x <= m: for ax in ordered_partitions(x, sort=False): mi = len(ax) a[-mi:] = [i + b for i in ax] yield a a[-mi:] = [b]*mi else: for mi in range(1, m): for ax in ordered_partitions(x, mi, sort=True): a[-mi:] = [i + b for i in ax] yield a a[-mi:] = [b]*mi def binary_partitions(n): """ Generates the binary partition of n. A binary partition consists only of numbers that are powers of two. Each step reduces a `2^{k+1}` to `2^k` and `2^k`. Thus 16 is converted to 8 and 8. Examples ======== >>> from sympy.utilities.iterables import binary_partitions >>> for i in binary_partitions(5): ... print(i) ... [4, 1] [2, 2, 1] [2, 1, 1, 1] [1, 1, 1, 1, 1] References ========== .. [1] TAOCP 4, section 7.2.1.5, problem 64 """ from math import ceil, log power = int(2**(ceil(log(n, 2)))) acc = 0 partition = [] while power: if acc + power <= n: partition.append(power) acc += power power >>= 1 last_num = len(partition) - 1 - (n & 1) while last_num >= 0: yield partition if partition[last_num] == 2: partition[last_num] = 1 partition.append(1) last_num -= 1 continue partition.append(1) partition[last_num] >>= 1 x = partition[last_num + 1] = partition[last_num] last_num += 1 while x > 1: if x <= len(partition) - last_num - 1: del partition[-x + 1:] last_num += 1 partition[last_num] = x else: x >>= 1 yield [1]*n def has_dups(seq): """Return True if there are any duplicate elements in ``seq``. Examples ======== >>> from sympy import has_dups, Dict, Set >>> has_dups((1, 2, 1)) True >>> has_dups(range(3)) False >>> all(has_dups(c) is False for c in (set(), Set(), dict(), Dict())) True """ from sympy.core.containers import Dict from sympy.sets.sets import Set if isinstance(seq, (dict, set, Dict, Set)): return False unique = set() try: return any(True for s in seq if s in unique or unique.add(s)) except TypeError: return len(seq) != len(list(uniq(seq))) def has_variety(seq): """Return True if there are any different elements in ``seq``. Examples ======== >>> from sympy import has_variety >>> has_variety((1, 2, 1)) True >>> has_variety((1, 1, 1)) False """ for i, s in enumerate(seq): if i == 0: sentinel = s else: if s != sentinel: return True return False def uniq(seq, result=None): """ Yield unique elements from ``seq`` as an iterator. The second parameter ``result`` is used internally; it is not necessary to pass anything for this. Note: changing the sequence during iteration will raise a RuntimeError if the size of the sequence is known; if you pass an iterator and advance the iterator you will change the output of this routine but there will be no warning. Examples ======== >>> from sympy.utilities.iterables import uniq >>> dat = [1, 4, 1, 5, 4, 2, 1, 2] >>> type(uniq(dat)) in (list, tuple) False >>> list(uniq(dat)) [1, 4, 5, 2] >>> list(uniq(x for x in dat)) [1, 4, 5, 2] >>> list(uniq([[1], [2, 1], [1]])) [[1], [2, 1]] """ try: n = len(seq) except TypeError: n = None def check(): # check that size of seq did not change during iteration; # if n == None the object won't support size changing, e.g. # an iterator can't be changed if n is not None and len(seq) != n: raise RuntimeError('sequence changed size during iteration') try: seen = set() result = result or [] for i, s in enumerate(seq): if not (s in seen or seen.add(s)): yield s check() except TypeError: if s not in result: yield s check() result.append(s) if hasattr(seq, '__getitem__'): yield from uniq(seq[i + 1:], result) else: yield from uniq(seq, result) def generate_bell(n): """Return permutations of [0, 1, ..., n - 1] such that each permutation differs from the last by the exchange of a single pair of neighbors. The ``n!`` permutations are returned as an iterator. In order to obtain the next permutation from a random starting permutation, use the ``next_trotterjohnson`` method of the Permutation class (which generates the same sequence in a different manner). Examples ======== >>> from itertools import permutations >>> from sympy.utilities.iterables import generate_bell >>> from sympy import zeros, Matrix This is the sort of permutation used in the ringing of physical bells, and does not produce permutations in lexicographical order. Rather, the permutations differ from each other by exactly one inversion, and the position at which the swapping occurs varies periodically in a simple fashion. Consider the first few permutations of 4 elements generated by ``permutations`` and ``generate_bell``: >>> list(permutations(range(4)))[:5] [(0, 1, 2, 3), (0, 1, 3, 2), (0, 2, 1, 3), (0, 2, 3, 1), (0, 3, 1, 2)] >>> list(generate_bell(4))[:5] [(0, 1, 2, 3), (0, 1, 3, 2), (0, 3, 1, 2), (3, 0, 1, 2), (3, 0, 2, 1)] Notice how the 2nd and 3rd lexicographical permutations have 3 elements out of place whereas each "bell" permutation always has only two elements out of place relative to the previous permutation (and so the signature (+/-1) of a permutation is opposite of the signature of the previous permutation). How the position of inversion varies across the elements can be seen by tracing out where the largest number appears in the permutations: >>> m = zeros(4, 24) >>> for i, p in enumerate(generate_bell(4)): ... m[:, i] = Matrix([j - 3 for j in list(p)]) # make largest zero >>> m.print_nonzero('X') [XXX XXXXXX XXXXXX XXX] [XX XX XXXX XX XXXX XX XX] [X XXXX XX XXXX XX XXXX X] [ XXXXXX XXXXXX XXXXXX ] See Also ======== sympy.combinatorics.permutations.Permutation.next_trotterjohnson References ========== .. [1] https://en.wikipedia.org/wiki/Method_ringing .. [2] https://stackoverflow.com/questions/4856615/recursive-permutation/4857018 .. [3] http://programminggeeks.com/bell-algorithm-for-permutation/ .. [4] https://en.wikipedia.org/wiki/Steinhaus%E2%80%93Johnson%E2%80%93Trotter_algorithm .. [5] Generating involutions, derangements, and relatives by ECO Vincent Vajnovszki, DMTCS vol 1 issue 12, 2010 """ n = as_int(n) if n < 1: raise ValueError('n must be a positive integer') if n == 1: yield (0,) elif n == 2: yield (0, 1) yield (1, 0) elif n == 3: yield from [(0, 1, 2), (0, 2, 1), (2, 0, 1), (2, 1, 0), (1, 2, 0), (1, 0, 2)] else: m = n - 1 op = [0] + [-1]*m l = list(range(n)) while True: yield tuple(l) # find biggest element with op big = None, -1 # idx, value for i in range(n): if op[i] and l[i] > big[1]: big = i, l[i] i, _ = big if i is None: break # there are no ops left # swap it with neighbor in the indicated direction j = i + op[i] l[i], l[j] = l[j], l[i] op[i], op[j] = op[j], op[i] # if it landed at the end or if the neighbor in the same # direction is bigger then turn off op if j == 0 or j == m or l[j + op[j]] > l[j]: op[j] = 0 # any element bigger to the left gets +1 op for i in range(j): if l[i] > l[j]: op[i] = 1 # any element bigger to the right gets -1 op for i in range(j + 1, n): if l[i] > l[j]: op[i] = -1 def generate_involutions(n): """ Generates involutions. An involution is a permutation that when multiplied by itself equals the identity permutation. In this implementation the involutions are generated using Fixed Points. Alternatively, an involution can be considered as a permutation that does not contain any cycles with a length that is greater than two. Examples ======== >>> from sympy.utilities.iterables import generate_involutions >>> list(generate_involutions(3)) [(0, 1, 2), (0, 2, 1), (1, 0, 2), (2, 1, 0)] >>> len(list(generate_involutions(4))) 10 References ========== .. [1] http://mathworld.wolfram.com/PermutationInvolution.html """ idx = list(range(n)) for p in permutations(idx): for i in idx: if p[p[i]] != i: break else: yield p def multiset_derangements(s): """Generate derangements of the elements of s *in place*. Examples ======== >>> from sympy.utilities.iterables import multiset_derangements, uniq Because the derangements of multisets (not sets) are generated in place, copies of the return value must be made if a collection of derangements is desired or else all values will be the same: >>> list(uniq([i for i in multiset_derangements('1233')])) [[None, None, None, None]] >>> [i.copy() for i in multiset_derangements('1233')] [['3', '3', '1', '2'], ['3', '3', '2', '1']] >>> [''.join(i) for i in multiset_derangements('1233')] ['3312', '3321'] """ from sympy.core.sorting import ordered # create multiset dictionary of hashable elements or else # remap elements to integers try: ms = multiset(s) except TypeError: # give each element a canonical integer value key = dict(enumerate(ordered(uniq(s)))) h = [] for si in s: for k in key: if key[k] == si: h.append(k) break for i in multiset_derangements(h): yield [key[j] for j in i] return mx = max(ms.values()) # max repetition of any element n = len(s) # the number of elements ## special cases # 1) one element has more than half the total cardinality of s: no # derangements are possible. if mx*2 > n: return # 2) all elements appear once: singletons if len(ms) == n: yield from _set_derangements(s) return # find the first element that is repeated the most to place # in the following two special cases where the selection # is unambiguous: either there are two elements with multiplicity # of mx or else there is only one with multiplicity mx for M in ms: if ms[M] == mx: break inonM = [i for i in range(n) if s[i] != M] # location of non-M iM = [i for i in range(n) if s[i] == M] # locations of M rv = [None]*n # 3) half are the same if 2*mx == n: # M goes into non-M locations for i in inonM: rv[i] = M # permutations of non-M go to M locations for p in multiset_permutations([s[i] for i in inonM]): for i, pi in zip(iM, p): rv[i] = pi yield rv # clean-up (and encourages proper use of routine) rv[:] = [None]*n return # 4) single repeat covers all but 1 of the non-repeats: # if there is one repeat then the multiset of the values # of ms would be {mx: 1, 1: n - mx}, i.e. there would # be n - mx + 1 values with the condition that n - 2*mx = 1 if n - 2*mx == 1 and len(ms.values()) == n - mx + 1: for i, i1 in enumerate(inonM): ifill = inonM[:i] + inonM[i+1:] for j in ifill: rv[j] = M for p in permutations([s[j] for j in ifill]): rv[i1] = s[i1] for j, pi in zip(iM, p): rv[j] = pi k = i1 for j in iM: rv[j], rv[k] = rv[k], rv[j] yield rv k = j # clean-up (and encourages proper use of routine) rv[:] = [None]*n return ## general case is handled with 3 helpers: # 1) `finish_derangements` will place the last two elements # which have arbitrary multiplicities, e.g. for multiset # {c: 3, a: 2, b: 2}, the last two elements are a and b # 2) `iopen` will tell where a given element can be placed # 3) `do` will recursively place elements into subsets of # valid locations def finish_derangements(): """Place the last two elements into the partially completed derangement, and yield the results. """ a = take[1][0] # penultimate element a_ct = take[1][1] b = take[0][0] # last element to be placed b_ct = take[0][1] # split the indexes of the not-already-assigned elemements of rv into # three categories forced_a = [] # positions which must have an a forced_b = [] # positions which must have a b open_free = [] # positions which could take either for i in range(len(s)): if rv[i] is None: if s[i] == a: forced_b.append(i) elif s[i] == b: forced_a.append(i) else: open_free.append(i) if len(forced_a) > a_ct or len(forced_b) > b_ct: # No derangement possible return for i in forced_a: rv[i] = a for i in forced_b: rv[i] = b for a_place in combinations(open_free, a_ct - len(forced_a)): for a_pos in a_place: rv[a_pos] = a for i in open_free: if rv[i] is None: # anything not in the subset is set to b rv[i] = b yield rv # Clean up/undo the final placements for i in open_free: rv[i] = None # additional cleanup - clear forced_a, forced_b for i in forced_a: rv[i] = None for i in forced_b: rv[i] = None def iopen(v): # return indices at which element v can be placed in rv: # locations which are not already occupied if that location # does not already contain v in the same location of s return [i for i in range(n) if rv[i] is None and s[i] != v] def do(j): if j == 1: # handle the last two elements (regardless of multiplicity) # with a special method yield from finish_derangements() else: # place the mx elements of M into a subset of places # into which it can be replaced M, mx = take[j] for i in combinations(iopen(M), mx): # place M for ii in i: rv[ii] = M # recursively place the next element yield from do(j - 1) # mark positions where M was placed as once again # open for placement of other elements for ii in i: rv[ii] = None # process elements in order of canonically decreasing multiplicity take = sorted(ms.items(), key=lambda x:(x[1], x[0])) yield from do(len(take) - 1) rv[:] = [None]*n def random_derangement(t, choice=None, strict=True): """Return a list of elements in which none are in the same positions as they were originally. If an element fills more than half of the positions then an error will be raised since no derangement is possible. To obtain a derangement of as many items as possible--with some of the most numerous remaining in their original positions--pass `strict=False`. To produce a pseudorandom derangment, pass a pseudorandom selector like `choice` (see below). Examples ======== >>> from sympy.utilities.iterables import random_derangement >>> t = 'SymPy: a CAS in pure Python' >>> d = random_derangement(t) >>> all(i != j for i, j in zip(d, t)) True A predictable result can be obtained by using a pseudorandom generator for the choice: >>> from sympy.core.random import seed, choice as c >>> seed(1) >>> d = [''.join(random_derangement(t, c)) for i in range(5)] >>> assert len(set(d)) != 1 # we got different values By reseeding, the same sequence can be obtained: >>> seed(1) >>> d2 = [''.join(random_derangement(t, c)) for i in range(5)] >>> assert d == d2 """ if choice is None: import secrets choice = secrets.choice def shuffle(rv): '''Knuth shuffle''' for i in range(len(rv) - 1, 0, -1): x = choice(rv[:i + 1]) j = rv.index(x) rv[i], rv[j] = rv[j], rv[i] def pick(rv, n): '''shuffle rv and return the first n values ''' shuffle(rv) return rv[:n] ms = multiset(t) tot = len(t) ms = sorted(ms.items(), key=lambda x: x[1]) # if there are not enough spaces for the most # plentiful element to move to then some of them # will have to stay in place M, mx = ms[-1] n = len(t) xs = 2*mx - tot if xs > 0: if strict: raise ValueError('no derangement possible') opts = [i for (i, c) in enumerate(t) if c == ms[-1][0]] pick(opts, xs) stay = sorted(opts[:xs]) rv = list(t) for i in reversed(stay): rv.pop(i) rv = random_derangement(rv, choice) for i in stay: rv.insert(i, ms[-1][0]) return ''.join(rv) if type(t) is str else rv # the normal derangement calculated from here if n == len(ms): # approx 1/3 will succeed rv = list(t) while True: shuffle(rv) if all(i != j for i,j in zip(rv, t)): break else: # general case rv = [None]*n while True: j = 0 while j > -len(ms): # do most numerous first j -= 1 e, c = ms[j] opts = [i for i in range(n) if rv[i] is None and t[i] != e] if len(opts) < c: for i in range(n): rv[i] = None break # try again pick(opts, c) for i in range(c): rv[opts[i]] = e else: return rv return rv def _set_derangements(s): """ yield derangements of items in ``s`` which are assumed to contain no repeated elements """ if len(s) < 2: return if len(s) == 2: yield [s[1], s[0]] return if len(s) == 3: yield [s[1], s[2], s[0]] yield [s[2], s[0], s[1]] return for p in permutations(s): if not any(i == j for i, j in zip(p, s)): yield list(p) def generate_derangements(s): """ Return unique derangements of the elements of iterable ``s``. Examples ======== >>> from sympy.utilities.iterables import generate_derangements >>> list(generate_derangements([0, 1, 2])) [[1, 2, 0], [2, 0, 1]] >>> list(generate_derangements([0, 1, 2, 2])) [[2, 2, 0, 1], [2, 2, 1, 0]] >>> list(generate_derangements([0, 1, 1])) [] See Also ======== sympy.functions.combinatorial.factorials.subfactorial """ if not has_dups(s): yield from _set_derangements(s) else: for p in multiset_derangements(s): yield list(p) def necklaces(n, k, free=False): """ A routine to generate necklaces that may (free=True) or may not (free=False) be turned over to be viewed. The "necklaces" returned are comprised of ``n`` integers (beads) with ``k`` different values (colors). Only unique necklaces are returned. Examples ======== >>> from sympy.utilities.iterables import necklaces, bracelets >>> def show(s, i): ... return ''.join(s[j] for j in i) The "unrestricted necklace" is sometimes also referred to as a "bracelet" (an object that can be turned over, a sequence that can be reversed) and the term "necklace" is used to imply a sequence that cannot be reversed. So ACB == ABC for a bracelet (rotate and reverse) while the two are different for a necklace since rotation alone cannot make the two sequences the same. (mnemonic: Bracelets can be viewed Backwards, but Not Necklaces.) >>> B = [show('ABC', i) for i in bracelets(3, 3)] >>> N = [show('ABC', i) for i in necklaces(3, 3)] >>> set(N) - set(B) {'ACB'} >>> list(necklaces(4, 2)) [(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 1, 1), (0, 1, 0, 1), (0, 1, 1, 1), (1, 1, 1, 1)] >>> [show('.o', i) for i in bracelets(4, 2)] ['....', '...o', '..oo', '.o.o', '.ooo', 'oooo'] References ========== .. [1] http://mathworld.wolfram.com/Necklace.html """ return uniq(minlex(i, directed=not free) for i in variations(list(range(k)), n, repetition=True)) def bracelets(n, k): """Wrapper to necklaces to return a free (unrestricted) necklace.""" return necklaces(n, k, free=True) def generate_oriented_forest(n): """ This algorithm generates oriented forests. An oriented graph is a directed graph having no symmetric pair of directed edges. A forest is an acyclic graph, i.e., it has no cycles. A forest can also be described as a disjoint union of trees, which are graphs in which any two vertices are connected by exactly one simple path. Examples ======== >>> from sympy.utilities.iterables import generate_oriented_forest >>> list(generate_oriented_forest(4)) [[0, 1, 2, 3], [0, 1, 2, 2], [0, 1, 2, 1], [0, 1, 2, 0], \ [0, 1, 1, 1], [0, 1, 1, 0], [0, 1, 0, 1], [0, 1, 0, 0], [0, 0, 0, 0]] References ========== .. [1] T. Beyer and S.M. Hedetniemi: constant time generation of rooted trees, SIAM J. Computing Vol. 9, No. 4, November 1980 .. [2] https://stackoverflow.com/questions/1633833/oriented-forest-taocp-algorithm-in-python """ P = list(range(-1, n)) while True: yield P[1:] if P[n] > 0: P[n] = P[P[n]] else: for p in range(n - 1, 0, -1): if P[p] != 0: target = P[p] - 1 for q in range(p - 1, 0, -1): if P[q] == target: break offset = p - q for i in range(p, n + 1): P[i] = P[i - offset] break else: break def minlex(seq, directed=True, key=None): r""" Return the rotation of the sequence in which the lexically smallest elements appear first, e.g. `cba \rightarrow acb`. The sequence returned is a tuple, unless the input sequence is a string in which case a string is returned. If ``directed`` is False then the smaller of the sequence and the reversed sequence is returned, e.g. `cba \rightarrow abc`. If ``key`` is not None then it is used to extract a comparison key from each element in iterable. Examples ======== >>> from sympy.combinatorics.polyhedron import minlex >>> minlex((1, 2, 0)) (0, 1, 2) >>> minlex((1, 0, 2)) (0, 2, 1) >>> minlex((1, 0, 2), directed=False) (0, 1, 2) >>> minlex('11010011000', directed=True) '00011010011' >>> minlex('11010011000', directed=False) '00011001011' >>> minlex(('bb', 'aaa', 'c', 'a')) ('a', 'bb', 'aaa', 'c') >>> minlex(('bb', 'aaa', 'c', 'a'), key=len) ('c', 'a', 'bb', 'aaa') """ from sympy.functions.elementary.miscellaneous import Id if key is None: key = Id best = rotate_left(seq, least_rotation(seq, key=key)) if not directed: rseq = seq[::-1] rbest = rotate_left(rseq, least_rotation(rseq, key=key)) best = min(best, rbest, key=key) # Convert to tuple, unless we started with a string. return tuple(best) if not isinstance(seq, str) else best def runs(seq, op=gt): """Group the sequence into lists in which successive elements all compare the same with the comparison operator, ``op``: op(seq[i + 1], seq[i]) is True from all elements in a run. Examples ======== >>> from sympy.utilities.iterables import runs >>> from operator import ge >>> runs([0, 1, 2, 2, 1, 4, 3, 2, 2]) [[0, 1, 2], [2], [1, 4], [3], [2], [2]] >>> runs([0, 1, 2, 2, 1, 4, 3, 2, 2], op=ge) [[0, 1, 2, 2], [1, 4], [3], [2, 2]] """ cycles = [] seq = iter(seq) try: run = [next(seq)] except StopIteration: return [] while True: try: ei = next(seq) except StopIteration: break if op(ei, run[-1]): run.append(ei) continue else: cycles.append(run) run = [ei] if run: cycles.append(run) return cycles def kbins(l, k, ordered=None): """ Return sequence ``l`` partitioned into ``k`` bins. Examples ======== The default is to give the items in the same order, but grouped into k partitions without any reordering: >>> from sympy.utilities.iterables import kbins >>> for p in kbins(list(range(5)), 2): ... print(p) ... [[0], [1, 2, 3, 4]] [[0, 1], [2, 3, 4]] [[0, 1, 2], [3, 4]] [[0, 1, 2, 3], [4]] The ``ordered`` flag is either None (to give the simple partition of the elements) or is a 2 digit integer indicating whether the order of the bins and the order of the items in the bins matters. Given:: A = [[0], [1, 2]] B = [[1, 2], [0]] C = [[2, 1], [0]] D = [[0], [2, 1]] the following values for ``ordered`` have the shown meanings:: 00 means A == B == C == D 01 means A == B 10 means A == D 11 means A == A >>> for ordered_flag in [None, 0, 1, 10, 11]: ... print('ordered = %s' % ordered_flag) ... for p in kbins(list(range(3)), 2, ordered=ordered_flag): ... print(' %s' % p) ... ordered = None [[0], [1, 2]] [[0, 1], [2]] ordered = 0 [[0, 1], [2]] [[0, 2], [1]] [[0], [1, 2]] ordered = 1 [[0], [1, 2]] [[0], [2, 1]] [[1], [0, 2]] [[1], [2, 0]] [[2], [0, 1]] [[2], [1, 0]] ordered = 10 [[0, 1], [2]] [[2], [0, 1]] [[0, 2], [1]] [[1], [0, 2]] [[0], [1, 2]] [[1, 2], [0]] ordered = 11 [[0], [1, 2]] [[0, 1], [2]] [[0], [2, 1]] [[0, 2], [1]] [[1], [0, 2]] [[1, 0], [2]] [[1], [2, 0]] [[1, 2], [0]] [[2], [0, 1]] [[2, 0], [1]] [[2], [1, 0]] [[2, 1], [0]] See Also ======== partitions, multiset_partitions """ def partition(lista, bins): # EnricoGiampieri's partition generator from # https://stackoverflow.com/questions/13131491/ # partition-n-items-into-k-bins-in-python-lazily if len(lista) == 1 or bins == 1: yield [lista] elif len(lista) > 1 and bins > 1: for i in range(1, len(lista)): for part in partition(lista[i:], bins - 1): if len([lista[:i]] + part) == bins: yield [lista[:i]] + part if ordered is None: yield from partition(l, k) elif ordered == 11: for pl in multiset_permutations(l): pl = list(pl) yield from partition(pl, k) elif ordered == 00: yield from multiset_partitions(l, k) elif ordered == 10: for p in multiset_partitions(l, k): for perm in permutations(p): yield list(perm) elif ordered == 1: for kgot, p in partitions(len(l), k, size=True): if kgot != k: continue for li in multiset_permutations(l): rv = [] i = j = 0 li = list(li) for size, multiplicity in sorted(p.items()): for m in range(multiplicity): j = i + size rv.append(li[i: j]) i = j yield rv else: raise ValueError( 'ordered must be one of 00, 01, 10 or 11, not %s' % ordered) def permute_signs(t): """Return iterator in which the signs of non-zero elements of t are permuted. Examples ======== >>> from sympy.utilities.iterables import permute_signs >>> list(permute_signs((0, 1, 2))) [(0, 1, 2), (0, -1, 2), (0, 1, -2), (0, -1, -2)] """ for signs in product(*[(1, -1)]*(len(t) - t.count(0))): signs = list(signs) yield type(t)([i*signs.pop() if i else i for i in t]) def signed_permutations(t): """Return iterator in which the signs of non-zero elements of t and the order of the elements are permuted. Examples ======== >>> from sympy.utilities.iterables import signed_permutations >>> list(signed_permutations((0, 1, 2))) [(0, 1, 2), (0, -1, 2), (0, 1, -2), (0, -1, -2), (0, 2, 1), (0, -2, 1), (0, 2, -1), (0, -2, -1), (1, 0, 2), (-1, 0, 2), (1, 0, -2), (-1, 0, -2), (1, 2, 0), (-1, 2, 0), (1, -2, 0), (-1, -2, 0), (2, 0, 1), (-2, 0, 1), (2, 0, -1), (-2, 0, -1), (2, 1, 0), (-2, 1, 0), (2, -1, 0), (-2, -1, 0)] """ return (type(t)(i) for j in permutations(t) for i in permute_signs(j)) def rotations(s, dir=1): """Return a generator giving the items in s as list where each subsequent list has the items rotated to the left (default) or right (``dir=-1``) relative to the previous list. Examples ======== >>> from sympy import rotations >>> list(rotations([1,2,3])) [[1, 2, 3], [2, 3, 1], [3, 1, 2]] >>> list(rotations([1,2,3], -1)) [[1, 2, 3], [3, 1, 2], [2, 3, 1]] """ seq = list(s) for i in range(len(seq)): yield seq seq = rotate_left(seq, dir) def roundrobin(*iterables): """roundrobin recipe taken from itertools documentation: https://docs.python.org/3/library/itertools.html#recipes roundrobin('ABC', 'D', 'EF') --> A D E B F C Recipe credited to George Sakkis """ nexts = cycle(iter(it).__next__ for it in iterables) pending = len(iterables) while pending: try: for nxt in nexts: yield nxt() except StopIteration: pending -= 1 nexts = cycle(islice(nexts, pending)) class NotIterable: """ Use this as mixin when creating a class which is not supposed to return true when iterable() is called on its instances because calling list() on the instance, for example, would result in an infinite loop. """ pass def iterable(i, exclude=(str, dict, NotIterable)): """ Return a boolean indicating whether ``i`` is SymPy iterable. True also indicates that the iterator is finite, e.g. you can call list(...) on the instance. When SymPy is working with iterables, it is almost always assuming that the iterable is not a string or a mapping, so those are excluded by default. If you want a pure Python definition, make exclude=None. To exclude multiple items, pass them as a tuple. You can also set the _iterable attribute to True or False on your class, which will override the checks here, including the exclude test. As a rule of thumb, some SymPy functions use this to check if they should recursively map over an object. If an object is technically iterable in the Python sense but does not desire this behavior (e.g., because its iteration is not finite, or because iteration might induce an unwanted computation), it should disable it by setting the _iterable attribute to False. See also: is_sequence Examples ======== >>> from sympy.utilities.iterables import iterable >>> from sympy import Tuple >>> things = [[1], (1,), set([1]), Tuple(1), (j for j in [1, 2]), {1:2}, '1', 1] >>> for i in things: ... print('%s %s' % (iterable(i), type(i))) True <... 'list'> True <... 'tuple'> True <... 'set'> True <class 'sympy.core.containers.Tuple'> True <... 'generator'> False <... 'dict'> False <... 'str'> False <... 'int'> >>> iterable({}, exclude=None) True >>> iterable({}, exclude=str) True >>> iterable("no", exclude=str) False """ if hasattr(i, '_iterable'): return i._iterable try: iter(i) except TypeError: return False if exclude: return not isinstance(i, exclude) return True def is_sequence(i, include=None): """ Return a boolean indicating whether ``i`` is a sequence in the SymPy sense. If anything that fails the test below should be included as being a sequence for your application, set 'include' to that object's type; multiple types should be passed as a tuple of types. Note: although generators can generate a sequence, they often need special handling to make sure their elements are captured before the generator is exhausted, so these are not included by default in the definition of a sequence. See also: iterable Examples ======== >>> from sympy.utilities.iterables import is_sequence >>> from types import GeneratorType >>> is_sequence([]) True >>> is_sequence(set()) False >>> is_sequence('abc') False >>> is_sequence('abc', include=str) True >>> generator = (c for c in 'abc') >>> is_sequence(generator) False >>> is_sequence(generator, include=(str, GeneratorType)) True """ return (hasattr(i, '__getitem__') and iterable(i) or bool(include) and isinstance(i, include)) @deprecated( """ Using postorder_traversal from the sympy.utilities.iterables submodule is deprecated. Instead, use postorder_traversal from the top-level sympy namespace, like sympy.postorder_traversal """, deprecated_since_version="1.10", active_deprecations_target="deprecated-traversal-functions-moved") def postorder_traversal(node, keys=None): from sympy.core.traversal import postorder_traversal as _postorder_traversal return _postorder_traversal(node, keys=keys) @deprecated( """ Using interactive_traversal from the sympy.utilities.iterables submodule is deprecated. Instead, use interactive_traversal from the top-level sympy namespace, like sympy.interactive_traversal """, deprecated_since_version="1.10", active_deprecations_target="deprecated-traversal-functions-moved") def interactive_traversal(expr): from sympy.interactive.traversal import interactive_traversal as _interactive_traversal return _interactive_traversal(expr) @deprecated( """ Importing default_sort_key from sympy.utilities.iterables is deprecated. Use from sympy import default_sort_key instead. """, deprecated_since_version="1.10", active_deprecations_target="deprecated-sympy-core-compatibility", ) def default_sort_key(*args, **kwargs): from sympy import default_sort_key as _default_sort_key return _default_sort_key(*args, **kwargs) @deprecated( """ Importing default_sort_key from sympy.utilities.iterables is deprecated. Use from sympy import default_sort_key instead. """, deprecated_since_version="1.10", active_deprecations_target="deprecated-sympy-core-compatibility", ) def ordered(*args, **kwargs): from sympy import ordered as _ordered return _ordered(*args, **kwargs)
96b2d8e581d3f4d24c621cb149cfe243d641c593de3a52d92070eca65f4c6847
from sympy.core import S from sympy.core.function import Lambda from sympy.core.power import Pow from .pycode import PythonCodePrinter, _known_functions_math, _print_known_const, _print_known_func, _unpack_integral_limits, ArrayPrinter from .codeprinter import CodePrinter _not_in_numpy = 'erf erfc factorial gamma loggamma'.split() _in_numpy = [(k, v) for k, v in _known_functions_math.items() if k not in _not_in_numpy] _known_functions_numpy = dict(_in_numpy, **{ 'acos': 'arccos', 'acosh': 'arccosh', 'asin': 'arcsin', 'asinh': 'arcsinh', 'atan': 'arctan', 'atan2': 'arctan2', 'atanh': 'arctanh', 'exp2': 'exp2', 'sign': 'sign', 'logaddexp': 'logaddexp', 'logaddexp2': 'logaddexp2', }) _known_constants_numpy = { 'Exp1': 'e', 'Pi': 'pi', 'EulerGamma': 'euler_gamma', 'NaN': 'nan', 'Infinity': 'PINF', 'NegativeInfinity': 'NINF' } _numpy_known_functions = {k: 'numpy.' + v for k, v in _known_functions_numpy.items()} _numpy_known_constants = {k: 'numpy.' + v for k, v in _known_constants_numpy.items()} class NumPyPrinter(ArrayPrinter, PythonCodePrinter): """ Numpy printer which handles vectorized piecewise functions, logical operators, etc. """ _module = 'numpy' _kf = _numpy_known_functions _kc = _numpy_known_constants def __init__(self, settings=None): """ `settings` is passed to CodePrinter.__init__() `module` specifies the array module to use, currently 'NumPy', 'CuPy' or 'JAX'. """ self.language = "Python with {}".format(self._module) self.printmethod = "_{}code".format(self._module) self._kf = {**PythonCodePrinter._kf, **self._kf} super().__init__(settings=settings) def _print_seq(self, seq): "General sequence printer: converts to tuple" # Print tuples here instead of lists because numba supports # tuples in nopython mode. delimiter=', ' return '({},)'.format(delimiter.join(self._print(item) for item in seq)) def _print_MatMul(self, expr): "Matrix multiplication printer" if expr.as_coeff_matrices()[0] is not S.One: expr_list = expr.as_coeff_matrices()[1]+[(expr.as_coeff_matrices()[0])] return '({})'.format(').dot('.join(self._print(i) for i in expr_list)) return '({})'.format(').dot('.join(self._print(i) for i in expr.args)) def _print_MatPow(self, expr): "Matrix power printer" return '{}({}, {})'.format(self._module_format(self._module + '.linalg.matrix_power'), self._print(expr.args[0]), self._print(expr.args[1])) def _print_Inverse(self, expr): "Matrix inverse printer" return '{}({})'.format(self._module_format(self._module + '.linalg.inv'), self._print(expr.args[0])) def _print_DotProduct(self, expr): # DotProduct allows any shape order, but numpy.dot does matrix # multiplication, so we have to make sure it gets 1 x n by n x 1. arg1, arg2 = expr.args if arg1.shape[0] != 1: arg1 = arg1.T if arg2.shape[1] != 1: arg2 = arg2.T return "%s(%s, %s)" % (self._module_format(self._module + '.dot'), self._print(arg1), self._print(arg2)) def _print_MatrixSolve(self, expr): return "%s(%s, %s)" % (self._module_format(self._module + '.linalg.solve'), self._print(expr.matrix), self._print(expr.vector)) def _print_ZeroMatrix(self, expr): return '{}({})'.format(self._module_format(self._module + '.zeros'), self._print(expr.shape)) def _print_OneMatrix(self, expr): return '{}({})'.format(self._module_format(self._module + '.ones'), self._print(expr.shape)) def _print_FunctionMatrix(self, expr): from sympy.abc import i, j lamda = expr.lamda if not isinstance(lamda, Lambda): lamda = Lambda((i, j), lamda(i, j)) return '{}(lambda {}: {}, {})'.format(self._module_format(self._module + '.fromfunction'), ', '.join(self._print(arg) for arg in lamda.args[0]), self._print(lamda.args[1]), self._print(expr.shape)) def _print_HadamardProduct(self, expr): func = self._module_format(self._module + '.multiply') return ''.join('{}({}, '.format(func, self._print(arg)) \ for arg in expr.args[:-1]) + "{}{}".format(self._print(expr.args[-1]), ')' * (len(expr.args) - 1)) def _print_KroneckerProduct(self, expr): func = self._module_format(self._module + '.kron') return ''.join('{}({}, '.format(func, self._print(arg)) \ for arg in expr.args[:-1]) + "{}{}".format(self._print(expr.args[-1]), ')' * (len(expr.args) - 1)) def _print_Adjoint(self, expr): return '{}({}({}))'.format( self._module_format(self._module + '.conjugate'), self._module_format(self._module + '.transpose'), self._print(expr.args[0])) def _print_DiagonalOf(self, expr): vect = '{}({})'.format( self._module_format(self._module + '.diag'), self._print(expr.arg)) return '{}({}, (-1, 1))'.format( self._module_format(self._module + '.reshape'), vect) def _print_DiagMatrix(self, expr): return '{}({})'.format(self._module_format(self._module + '.diagflat'), self._print(expr.args[0])) def _print_DiagonalMatrix(self, expr): return '{}({}, {}({}, {}))'.format(self._module_format(self._module + '.multiply'), self._print(expr.arg), self._module_format(self._module + '.eye'), self._print(expr.shape[0]), self._print(expr.shape[1])) def _print_Piecewise(self, expr): "Piecewise function printer" from sympy.logic.boolalg import ITE, simplify_logic def print_cond(cond): """ Problem having an ITE in the cond. """ if cond.has(ITE): return self._print(simplify_logic(cond)) else: return self._print(cond) exprs = '[{}]'.format(','.join(self._print(arg.expr) for arg in expr.args)) conds = '[{}]'.format(','.join(print_cond(arg.cond) for arg in expr.args)) # If [default_value, True] is a (expr, cond) sequence in a Piecewise object # it will behave the same as passing the 'default' kwarg to select() # *as long as* it is the last element in expr.args. # If this is not the case, it may be triggered prematurely. return '{}({}, {}, default={})'.format( self._module_format(self._module + '.select'), conds, exprs, self._print(S.NaN)) def _print_Relational(self, expr): "Relational printer for Equality and Unequality" op = { '==' :'equal', '!=' :'not_equal', '<' :'less', '<=' :'less_equal', '>' :'greater', '>=' :'greater_equal', } if expr.rel_op in op: lhs = self._print(expr.lhs) rhs = self._print(expr.rhs) return '{op}({lhs}, {rhs})'.format(op=self._module_format(self._module + '.'+op[expr.rel_op]), lhs=lhs, rhs=rhs) return super()._print_Relational(expr) def _print_And(self, expr): "Logical And printer" # We have to override LambdaPrinter because it uses Python 'and' keyword. # If LambdaPrinter didn't define it, we could use StrPrinter's # version of the function and add 'logical_and' to NUMPY_TRANSLATIONS. return '{}.reduce(({}))'.format(self._module_format(self._module + '.logical_and'), ','.join(self._print(i) for i in expr.args)) def _print_Or(self, expr): "Logical Or printer" # We have to override LambdaPrinter because it uses Python 'or' keyword. # If LambdaPrinter didn't define it, we could use StrPrinter's # version of the function and add 'logical_or' to NUMPY_TRANSLATIONS. return '{}.reduce(({}))'.format(self._module_format(self._module + '.logical_or'), ','.join(self._print(i) for i in expr.args)) def _print_Not(self, expr): "Logical Not printer" # We have to override LambdaPrinter because it uses Python 'not' keyword. # If LambdaPrinter didn't define it, we would still have to define our # own because StrPrinter doesn't define it. return '{}({})'.format(self._module_format(self._module + '.logical_not'), ','.join(self._print(i) for i in expr.args)) def _print_Pow(self, expr, rational=False): # XXX Workaround for negative integer power error if expr.exp.is_integer and expr.exp.is_negative: expr = Pow(expr.base, expr.exp.evalf(), evaluate=False) return self._hprint_Pow(expr, rational=rational, sqrt=self._module + '.sqrt') def _print_Min(self, expr): return '{}(({}), axis=0)'.format(self._module_format(self._module + '.amin'), ','.join(self._print(i) for i in expr.args)) def _print_Max(self, expr): return '{}(({}), axis=0)'.format(self._module_format(self._module + '.amax'), ','.join(self._print(i) for i in expr.args)) def _print_arg(self, expr): return "%s(%s)" % (self._module_format(self._module + '.angle'), self._print(expr.args[0])) def _print_im(self, expr): return "%s(%s)" % (self._module_format(self._module + '.imag'), self._print(expr.args[0])) def _print_Mod(self, expr): return "%s(%s)" % (self._module_format(self._module + '.mod'), ', '.join( map(lambda arg: self._print(arg), expr.args))) def _print_re(self, expr): return "%s(%s)" % (self._module_format(self._module + '.real'), self._print(expr.args[0])) def _print_sinc(self, expr): return "%s(%s)" % (self._module_format(self._module + '.sinc'), self._print(expr.args[0]/S.Pi)) def _print_MatrixBase(self, expr): func = self.known_functions.get(expr.__class__.__name__, None) if func is None: func = self._module_format(self._module + '.array') return "%s(%s)" % (func, self._print(expr.tolist())) def _print_Identity(self, expr): shape = expr.shape if all(dim.is_Integer for dim in shape): return "%s(%s)" % (self._module_format(self._module + '.eye'), self._print(expr.shape[0])) else: raise NotImplementedError("Symbolic matrix dimensions are not yet supported for identity matrices") def _print_BlockMatrix(self, expr): return '{}({})'.format(self._module_format(self._module + '.block'), self._print(expr.args[0].tolist())) def _print_NDimArray(self, expr): if len(expr.shape) == 1: return self._module + '.array(' + self._print(expr.args[0]) + ')' if len(expr.shape) == 2: return self._print(expr.tomatrix()) # Should be possible to extend to more dimensions return CodePrinter._print_not_supported(self, expr) _add = "add" _einsum = "einsum" _transpose = "transpose" _ones = "ones" _zeros = "zeros" _print_lowergamma = CodePrinter._print_not_supported _print_uppergamma = CodePrinter._print_not_supported _print_fresnelc = CodePrinter._print_not_supported _print_fresnels = CodePrinter._print_not_supported for func in _numpy_known_functions: setattr(NumPyPrinter, f'_print_{func}', _print_known_func) for const in _numpy_known_constants: setattr(NumPyPrinter, f'_print_{const}', _print_known_const) _known_functions_scipy_special = { 'erf': 'erf', 'erfc': 'erfc', 'besselj': 'jv', 'bessely': 'yv', 'besseli': 'iv', 'besselk': 'kv', 'cosm1': 'cosm1', 'factorial': 'factorial', 'gamma': 'gamma', 'loggamma': 'gammaln', 'digamma': 'psi', 'RisingFactorial': 'poch', 'jacobi': 'eval_jacobi', 'gegenbauer': 'eval_gegenbauer', 'chebyshevt': 'eval_chebyt', 'chebyshevu': 'eval_chebyu', 'legendre': 'eval_legendre', 'hermite': 'eval_hermite', 'laguerre': 'eval_laguerre', 'assoc_laguerre': 'eval_genlaguerre', 'beta': 'beta', 'LambertW' : 'lambertw', } _known_constants_scipy_constants = { 'GoldenRatio': 'golden_ratio', 'Pi': 'pi', } _scipy_known_functions = {k : "scipy.special." + v for k, v in _known_functions_scipy_special.items()} _scipy_known_constants = {k : "scipy.constants." + v for k, v in _known_constants_scipy_constants.items()} class SciPyPrinter(NumPyPrinter): _kf = {**NumPyPrinter._kf, **_scipy_known_functions} _kc = {**NumPyPrinter._kc, **_scipy_known_constants} def __init__(self, settings=None): super().__init__(settings=settings) self.language = "Python with SciPy and NumPy" def _print_SparseRepMatrix(self, expr): i, j, data = [], [], [] for (r, c), v in expr.todok().items(): i.append(r) j.append(c) data.append(v) return "{name}(({data}, ({i}, {j})), shape={shape})".format( name=self._module_format('scipy.sparse.coo_matrix'), data=data, i=i, j=j, shape=expr.shape ) _print_ImmutableSparseMatrix = _print_SparseRepMatrix # SciPy's lpmv has a different order of arguments from assoc_legendre def _print_assoc_legendre(self, expr): return "{0}({2}, {1}, {3})".format( self._module_format('scipy.special.lpmv'), self._print(expr.args[0]), self._print(expr.args[1]), self._print(expr.args[2])) def _print_lowergamma(self, expr): return "{0}({2})*{1}({2}, {3})".format( self._module_format('scipy.special.gamma'), self._module_format('scipy.special.gammainc'), self._print(expr.args[0]), self._print(expr.args[1])) def _print_uppergamma(self, expr): return "{0}({2})*{1}({2}, {3})".format( self._module_format('scipy.special.gamma'), self._module_format('scipy.special.gammaincc'), self._print(expr.args[0]), self._print(expr.args[1])) def _print_betainc(self, expr): betainc = self._module_format('scipy.special.betainc') beta = self._module_format('scipy.special.beta') args = [self._print(arg) for arg in expr.args] return f"({betainc}({args[0]}, {args[1]}, {args[3]}) - {betainc}({args[0]}, {args[1]}, {args[2]})) \ * {beta}({args[0]}, {args[1]})" def _print_betainc_regularized(self, expr): return "{0}({1}, {2}, {4}) - {0}({1}, {2}, {3})".format( self._module_format('scipy.special.betainc'), self._print(expr.args[0]), self._print(expr.args[1]), self._print(expr.args[2]), self._print(expr.args[3])) def _print_fresnels(self, expr): return "{}({})[0]".format( self._module_format("scipy.special.fresnel"), self._print(expr.args[0])) def _print_fresnelc(self, expr): return "{}({})[1]".format( self._module_format("scipy.special.fresnel"), self._print(expr.args[0])) def _print_airyai(self, expr): return "{}({})[0]".format( self._module_format("scipy.special.airy"), self._print(expr.args[0])) def _print_airyaiprime(self, expr): return "{}({})[1]".format( self._module_format("scipy.special.airy"), self._print(expr.args[0])) def _print_airybi(self, expr): return "{}({})[2]".format( self._module_format("scipy.special.airy"), self._print(expr.args[0])) def _print_airybiprime(self, expr): return "{}({})[3]".format( self._module_format("scipy.special.airy"), self._print(expr.args[0])) def _print_Integral(self, e): integration_vars, limits = _unpack_integral_limits(e) if len(limits) == 1: # nicer (but not necessary) to prefer quad over nquad for 1D case module_str = self._module_format("scipy.integrate.quad") limit_str = "%s, %s" % tuple(map(self._print, limits[0])) else: module_str = self._module_format("scipy.integrate.nquad") limit_str = "({})".format(", ".join( "(%s, %s)" % tuple(map(self._print, l)) for l in limits)) return "{}(lambda {}: {}, {})[0]".format( module_str, ", ".join(map(self._print, integration_vars)), self._print(e.args[0]), limit_str) for func in _scipy_known_functions: setattr(SciPyPrinter, f'_print_{func}', _print_known_func) for const in _scipy_known_constants: setattr(SciPyPrinter, f'_print_{const}', _print_known_const) _cupy_known_functions = {k : "cupy." + v for k, v in _known_functions_numpy.items()} _cupy_known_constants = {k : "cupy." + v for k, v in _known_constants_numpy.items()} class CuPyPrinter(NumPyPrinter): """ CuPy printer which handles vectorized piecewise functions, logical operators, etc. """ _module = 'cupy' _kf = _cupy_known_functions _kc = _cupy_known_constants def __init__(self, settings=None): super().__init__(settings=settings) for func in _cupy_known_functions: setattr(CuPyPrinter, f'_print_{func}', _print_known_func) for const in _cupy_known_constants: setattr(CuPyPrinter, f'_print_{const}', _print_known_const) _jax_known_functions = {k: 'jax.numpy.' + v for k, v in _known_functions_numpy.items()} _jax_known_constants = {k: 'jax.numpy.' + v for k, v in _known_constants_numpy.items()} class JaxPrinter(NumPyPrinter): """ JAX printer which handles vectorized piecewise functions, logical operators, etc. """ _module = "jax.numpy" _kf = _jax_known_functions _kc = _jax_known_constants def __init__(self, settings=None): super().__init__(settings=settings) # These need specific override to allow for the lack of "jax.numpy.reduce" def _print_And(self, expr): "Logical And printer" return "{}({}.asarray([{}]), axis=0)".format( self._module_format(self._module + ".all"), self._module_format(self._module), ",".join(self._print(i) for i in expr.args), ) def _print_Or(self, expr): "Logical Or printer" return "{}({}.asarray([{}]), axis=0)".format( self._module_format(self._module + ".any"), self._module_format(self._module), ",".join(self._print(i) for i in expr.args), ) for func in _jax_known_functions: setattr(JaxPrinter, f'_print_{func}', _print_known_func) for const in _jax_known_constants: setattr(JaxPrinter, f'_print_{const}', _print_known_const)
44caeab532cc47f87902b2ecf1421c2b805715f6dfb953b3c1b17bc1abaf9ee5
""" Python code printers This module contains Python code printers for plain Python as well as NumPy & SciPy enabled code. """ from collections import defaultdict from itertools import chain from sympy.core import S from sympy.core.mod import Mod from .precedence import precedence from .codeprinter import CodePrinter _kw = { 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield', 'None', 'False', 'nonlocal', 'True' } _known_functions = { 'Abs': 'abs', 'Min': 'min', 'Max': 'max', } _known_functions_math = { 'acos': 'acos', 'acosh': 'acosh', 'asin': 'asin', 'asinh': 'asinh', 'atan': 'atan', 'atan2': 'atan2', 'atanh': 'atanh', 'ceiling': 'ceil', 'cos': 'cos', 'cosh': 'cosh', 'erf': 'erf', 'erfc': 'erfc', 'exp': 'exp', 'expm1': 'expm1', 'factorial': 'factorial', 'floor': 'floor', 'gamma': 'gamma', 'hypot': 'hypot', 'loggamma': 'lgamma', 'log': 'log', 'ln': 'log', 'log10': 'log10', 'log1p': 'log1p', 'log2': 'log2', 'sin': 'sin', 'sinh': 'sinh', 'Sqrt': 'sqrt', 'tan': 'tan', 'tanh': 'tanh' } # Not used from ``math``: [copysign isclose isfinite isinf isnan ldexp frexp pow modf # radians trunc fmod fsum gcd degrees fabs] _known_constants_math = { 'Exp1': 'e', 'Pi': 'pi', 'E': 'e', 'Infinity': 'inf', 'NaN': 'nan', 'ComplexInfinity': 'nan' } def _print_known_func(self, expr): known = self.known_functions[expr.__class__.__name__] return '{name}({args})'.format(name=self._module_format(known), args=', '.join(map(lambda arg: self._print(arg), expr.args))) def _print_known_const(self, expr): known = self.known_constants[expr.__class__.__name__] return self._module_format(known) class AbstractPythonCodePrinter(CodePrinter): printmethod = "_pythoncode" language = "Python" reserved_words = _kw modules = None # initialized to a set in __init__ tab = ' ' _kf = dict(chain( _known_functions.items(), [(k, 'math.' + v) for k, v in _known_functions_math.items()] )) _kc = {k: 'math.'+v for k, v in _known_constants_math.items()} _operators = {'and': 'and', 'or': 'or', 'not': 'not'} _default_settings = dict( CodePrinter._default_settings, user_functions={}, precision=17, inline=True, fully_qualified_modules=True, contract=False, standard='python3', ) def __init__(self, settings=None): super().__init__(settings) # Python standard handler std = self._settings['standard'] if std is None: import sys std = 'python{}'.format(sys.version_info.major) if std != 'python3': raise ValueError('Only Python 3 is supported.') self.standard = std self.module_imports = defaultdict(set) # Known functions and constants handler self.known_functions = dict(self._kf, **(settings or {}).get( 'user_functions', {})) self.known_constants = dict(self._kc, **(settings or {}).get( 'user_constants', {})) def _declare_number_const(self, name, value): return "%s = %s" % (name, value) def _module_format(self, fqn, register=True): parts = fqn.split('.') if register and len(parts) > 1: self.module_imports['.'.join(parts[:-1])].add(parts[-1]) if self._settings['fully_qualified_modules']: return fqn else: return fqn.split('(')[0].split('[')[0].split('.')[-1] def _format_code(self, lines): return lines def _get_statement(self, codestring): return "{}".format(codestring) def _get_comment(self, text): return " # {}".format(text) def _expand_fold_binary_op(self, op, args): """ This method expands a fold on binary operations. ``functools.reduce`` is an example of a folded operation. For example, the expression `A + B + C + D` is folded into `((A + B) + C) + D` """ if len(args) == 1: return self._print(args[0]) else: return "%s(%s, %s)" % ( self._module_format(op), self._expand_fold_binary_op(op, args[:-1]), self._print(args[-1]), ) def _expand_reduce_binary_op(self, op, args): """ This method expands a reductin on binary operations. Notice: this is NOT the same as ``functools.reduce``. For example, the expression `A + B + C + D` is reduced into: `(A + B) + (C + D)` """ if len(args) == 1: return self._print(args[0]) else: N = len(args) Nhalf = N // 2 return "%s(%s, %s)" % ( self._module_format(op), self._expand_reduce_binary_op(args[:Nhalf]), self._expand_reduce_binary_op(args[Nhalf:]), ) def _print_NaN(self, expr): return "float('nan')" def _print_Infinity(self, expr): return "float('inf')" def _print_NegativeInfinity(self, expr): return "float('-inf')" def _print_ComplexInfinity(self, expr): return self._print_NaN(expr) def _print_Mod(self, expr): PREC = precedence(expr) return ('{} % {}'.format(*map(lambda x: self.parenthesize(x, PREC), expr.args))) def _print_Piecewise(self, expr): result = [] i = 0 for arg in expr.args: e = arg.expr c = arg.cond if i == 0: result.append('(') result.append('(') result.append(self._print(e)) result.append(')') result.append(' if ') result.append(self._print(c)) result.append(' else ') i += 1 result = result[:-1] if result[-1] == 'True': result = result[:-2] result.append(')') else: result.append(' else None)') return ''.join(result) def _print_Relational(self, expr): "Relational printer for Equality and Unequality" op = { '==' :'equal', '!=' :'not_equal', '<' :'less', '<=' :'less_equal', '>' :'greater', '>=' :'greater_equal', } if expr.rel_op in op: lhs = self._print(expr.lhs) rhs = self._print(expr.rhs) return '({lhs} {op} {rhs})'.format(op=expr.rel_op, lhs=lhs, rhs=rhs) return super()._print_Relational(expr) def _print_ITE(self, expr): from sympy.functions.elementary.piecewise import Piecewise return self._print(expr.rewrite(Piecewise)) def _print_Sum(self, expr): loops = ( 'for {i} in range({a}, {b}+1)'.format( i=self._print(i), a=self._print(a), b=self._print(b)) for i, a, b in expr.limits) return '(builtins.sum({function} {loops}))'.format( function=self._print(expr.function), loops=' '.join(loops)) def _print_ImaginaryUnit(self, expr): return '1j' def _print_KroneckerDelta(self, expr): a, b = expr.args return '(1 if {a} == {b} else 0)'.format( a = self._print(a), b = self._print(b) ) def _print_MatrixBase(self, expr): name = expr.__class__.__name__ func = self.known_functions.get(name, name) return "%s(%s)" % (func, self._print(expr.tolist())) _print_SparseRepMatrix = \ _print_MutableSparseMatrix = \ _print_ImmutableSparseMatrix = \ _print_Matrix = \ _print_DenseMatrix = \ _print_MutableDenseMatrix = \ _print_ImmutableMatrix = \ _print_ImmutableDenseMatrix = \ lambda self, expr: self._print_MatrixBase(expr) def _indent_codestring(self, codestring): return '\n'.join([self.tab + line for line in codestring.split('\n')]) def _print_FunctionDefinition(self, fd): body = '\n'.join(map(lambda arg: self._print(arg), fd.body)) return "def {name}({parameters}):\n{body}".format( name=self._print(fd.name), parameters=', '.join([self._print(var.symbol) for var in fd.parameters]), body=self._indent_codestring(body) ) def _print_While(self, whl): body = '\n'.join(map(lambda arg: self._print(arg), whl.body)) return "while {cond}:\n{body}".format( cond=self._print(whl.condition), body=self._indent_codestring(body) ) def _print_Declaration(self, decl): return '%s = %s' % ( self._print(decl.variable.symbol), self._print(decl.variable.value) ) def _print_Return(self, ret): arg, = ret.args return 'return %s' % self._print(arg) def _print_Print(self, prnt): print_args = ', '.join(map(lambda arg: self._print(arg), prnt.print_args)) if prnt.format_string != None: # Must be '!= None', cannot be 'is not None' print_args = '{} % ({})'.format( self._print(prnt.format_string), print_args) if prnt.file != None: # Must be '!= None', cannot be 'is not None' print_args += ', file=%s' % self._print(prnt.file) return 'print(%s)' % print_args def _print_Stream(self, strm): if str(strm.name) == 'stdout': return self._module_format('sys.stdout') elif str(strm.name) == 'stderr': return self._module_format('sys.stderr') else: return self._print(strm.name) def _print_NoneToken(self, arg): return 'None' def _hprint_Pow(self, expr, rational=False, sqrt='math.sqrt'): """Printing helper function for ``Pow`` Notes ===== This preprocesses the ``sqrt`` as math formatter and prints division Examples ======== >>> from sympy import sqrt >>> from sympy.printing.pycode import PythonCodePrinter >>> from sympy.abc import x Python code printer automatically looks up ``math.sqrt``. >>> printer = PythonCodePrinter() >>> printer._hprint_Pow(sqrt(x), rational=True) 'x**(1/2)' >>> printer._hprint_Pow(sqrt(x), rational=False) 'math.sqrt(x)' >>> printer._hprint_Pow(1/sqrt(x), rational=True) 'x**(-1/2)' >>> printer._hprint_Pow(1/sqrt(x), rational=False) '1/math.sqrt(x)' >>> printer._hprint_Pow(1/x, rational=False) '1/x' >>> printer._hprint_Pow(1/x, rational=True) 'x**(-1)' Using sqrt from numpy or mpmath >>> printer._hprint_Pow(sqrt(x), sqrt='numpy.sqrt') 'numpy.sqrt(x)' >>> printer._hprint_Pow(sqrt(x), sqrt='mpmath.sqrt') 'mpmath.sqrt(x)' See Also ======== sympy.printing.str.StrPrinter._print_Pow """ PREC = precedence(expr) if expr.exp == S.Half and not rational: func = self._module_format(sqrt) arg = self._print(expr.base) return '{func}({arg})'.format(func=func, arg=arg) if expr.is_commutative and not rational: if -expr.exp is S.Half: func = self._module_format(sqrt) num = self._print(S.One) arg = self._print(expr.base) return f"{num}/{func}({arg})" if expr.exp is S.NegativeOne: num = self._print(S.One) arg = self.parenthesize(expr.base, PREC, strict=False) return f"{num}/{arg}" base_str = self.parenthesize(expr.base, PREC, strict=False) exp_str = self.parenthesize(expr.exp, PREC, strict=False) return "{}**{}".format(base_str, exp_str) class ArrayPrinter: def _arrayify(self, indexed): from sympy.tensor.array.expressions.conv_indexed_to_array import convert_indexed_to_array try: return convert_indexed_to_array(indexed) except Exception: return indexed def _get_einsum_string(self, subranks, contraction_indices): letters = self._get_letter_generator_for_einsum() contraction_string = "" counter = 0 d = {j: min(i) for i in contraction_indices for j in i} indices = [] for rank_arg in subranks: lindices = [] for i in range(rank_arg): if counter in d: lindices.append(d[counter]) else: lindices.append(counter) counter += 1 indices.append(lindices) mapping = {} letters_free = [] letters_dum = [] for i in indices: for j in i: if j not in mapping: l = next(letters) mapping[j] = l else: l = mapping[j] contraction_string += l if j in d: if l not in letters_dum: letters_dum.append(l) else: letters_free.append(l) contraction_string += "," contraction_string = contraction_string[:-1] return contraction_string, letters_free, letters_dum def _get_letter_generator_for_einsum(self): for i in range(97, 123): yield chr(i) for i in range(65, 91): yield chr(i) raise ValueError("out of letters") def _print_ArrayTensorProduct(self, expr): letters = self._get_letter_generator_for_einsum() contraction_string = ",".join(["".join([next(letters) for j in range(i)]) for i in expr.subranks]) return '%s("%s", %s)' % ( self._module_format(self._module + "." + self._einsum), contraction_string, ", ".join([self._print(arg) for arg in expr.args]) ) def _print_ArrayContraction(self, expr): from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct base = expr.expr contraction_indices = expr.contraction_indices if isinstance(base, ArrayTensorProduct): elems = ",".join(["%s" % (self._print(arg)) for arg in base.args]) ranks = base.subranks else: elems = self._print(base) ranks = [len(base.shape)] contraction_string, letters_free, letters_dum = self._get_einsum_string(ranks, contraction_indices) if not contraction_indices: return self._print(base) if isinstance(base, ArrayTensorProduct): elems = ",".join(["%s" % (self._print(arg)) for arg in base.args]) else: elems = self._print(base) return "%s(\"%s\", %s)" % ( self._module_format(self._module + "." + self._einsum), "{}->{}".format(contraction_string, "".join(sorted(letters_free))), elems, ) def _print_ArrayDiagonal(self, expr): from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct diagonal_indices = list(expr.diagonal_indices) if isinstance(expr.expr, ArrayTensorProduct): subranks = expr.expr.subranks elems = expr.expr.args else: subranks = expr.subranks elems = [expr.expr] diagonal_string, letters_free, letters_dum = self._get_einsum_string(subranks, diagonal_indices) elems = [self._print(i) for i in elems] return '%s("%s", %s)' % ( self._module_format(self._module + "." + self._einsum), "{}->{}".format(diagonal_string, "".join(letters_free+letters_dum)), ", ".join(elems) ) def _print_PermuteDims(self, expr): return "%s(%s, %s)" % ( self._module_format(self._module + "." + self._transpose), self._print(expr.expr), self._print(expr.permutation.array_form), ) def _print_ArrayAdd(self, expr): return self._expand_fold_binary_op(self._module + "." + self._add, expr.args) def _print_OneArray(self, expr): return "%s((%s,))" % ( self._module_format(self._module+ "." + self._ones), ','.join(map(self._print,expr.args)) ) def _print_ZeroArray(self, expr): return "%s((%s,))" % ( self._module_format(self._module+ "." + self._zeros), ','.join(map(self._print,expr.args)) ) def _print_Assignment(self, expr): #XXX: maybe this needs to happen at a higher level e.g. at _print or #doprint? lhs = self._print(self._arrayify(expr.lhs)) rhs = self._print(self._arrayify(expr.rhs)) return "%s = %s" % ( lhs, rhs ) def _print_IndexedBase(self, expr): return self._print_ArraySymbol(expr) class PythonCodePrinter(AbstractPythonCodePrinter): def _print_sign(self, e): return '(0.0 if {e} == 0 else {f}(1, {e}))'.format( f=self._module_format('math.copysign'), e=self._print(e.args[0])) def _print_Not(self, expr): PREC = precedence(expr) return self._operators['not'] + self.parenthesize(expr.args[0], PREC) def _print_Indexed(self, expr): base = expr.args[0] index = expr.args[1:] return "{}[{}]".format(str(base), ", ".join([self._print(ind) for ind in index])) def _print_Pow(self, expr, rational=False): return self._hprint_Pow(expr, rational=rational) def _print_Rational(self, expr): return '{}/{}'.format(expr.p, expr.q) def _print_Half(self, expr): return self._print_Rational(expr) def _print_frac(self, expr): return self._print_Mod(Mod(expr.args[0], 1)) def _print_Symbol(self, expr): name = super()._print_Symbol(expr) if name in self.reserved_words: if self._settings['error_on_reserved']: msg = ('This expression includes the symbol "{}" which is a ' 'reserved keyword in this language.') raise ValueError(msg.format(name)) return name + self._settings['reserved_word_suffix'] elif '{' in name: # Remove curly braces from subscripted variables return name.replace('{', '').replace('}', '') else: return name _print_lowergamma = CodePrinter._print_not_supported _print_uppergamma = CodePrinter._print_not_supported _print_fresnelc = CodePrinter._print_not_supported _print_fresnels = CodePrinter._print_not_supported for k in PythonCodePrinter._kf: setattr(PythonCodePrinter, '_print_%s' % k, _print_known_func) for k in _known_constants_math: setattr(PythonCodePrinter, '_print_%s' % k, _print_known_const) def pycode(expr, **settings): """ Converts an expr to a string of Python code Parameters ========== expr : Expr A SymPy expression. fully_qualified_modules : bool Whether or not to write out full module names of functions (``math.sin`` vs. ``sin``). default: ``True``. standard : str or None, optional Only 'python3' (default) is supported. This parameter may be removed in the future. Examples ======== >>> from sympy import pycode, tan, Symbol >>> pycode(tan(Symbol('x')) + 1) 'math.tan(x) + 1' """ return PythonCodePrinter(settings).doprint(expr) _not_in_mpmath = 'log1p log2'.split() _in_mpmath = [(k, v) for k, v in _known_functions_math.items() if k not in _not_in_mpmath] _known_functions_mpmath = dict(_in_mpmath, **{ 'beta': 'beta', 'frac': 'frac', 'fresnelc': 'fresnelc', 'fresnels': 'fresnels', 'sign': 'sign', 'loggamma': 'loggamma', 'hyper': 'hyper', 'meijerg': 'meijerg', 'besselj': 'besselj', 'bessely': 'bessely', 'besseli': 'besseli', 'besselk': 'besselk', }) _known_constants_mpmath = { 'Exp1': 'e', 'Pi': 'pi', 'GoldenRatio': 'phi', 'EulerGamma': 'euler', 'Catalan': 'catalan', 'NaN': 'nan', 'Infinity': 'inf', 'NegativeInfinity': 'ninf' } def _unpack_integral_limits(integral_expr): """ helper function for _print_Integral that - accepts an Integral expression - returns a tuple of - a list variables of integration - a list of tuples of the upper and lower limits of integration """ integration_vars = [] limits = [] for integration_range in integral_expr.limits: if len(integration_range) == 3: integration_var, lower_limit, upper_limit = integration_range else: raise NotImplementedError("Only definite integrals are supported") integration_vars.append(integration_var) limits.append((lower_limit, upper_limit)) return integration_vars, limits class MpmathPrinter(PythonCodePrinter): """ Lambda printer for mpmath which maintains precision for floats """ printmethod = "_mpmathcode" language = "Python with mpmath" _kf = dict(chain( _known_functions.items(), [(k, 'mpmath.' + v) for k, v in _known_functions_mpmath.items()] )) _kc = {k: 'mpmath.'+v for k, v in _known_constants_mpmath.items()} def _print_Float(self, e): # XXX: This does not handle setting mpmath.mp.dps. It is assumed that # the caller of the lambdified function will have set it to sufficient # precision to match the Floats in the expression. # Remove 'mpz' if gmpy is installed. args = str(tuple(map(int, e._mpf_))) return '{func}({args})'.format(func=self._module_format('mpmath.mpf'), args=args) def _print_Rational(self, e): return "{func}({p})/{func}({q})".format( func=self._module_format('mpmath.mpf'), q=self._print(e.q), p=self._print(e.p) ) def _print_Half(self, e): return self._print_Rational(e) def _print_uppergamma(self, e): return "{}({}, {}, {})".format( self._module_format('mpmath.gammainc'), self._print(e.args[0]), self._print(e.args[1]), self._module_format('mpmath.inf')) def _print_lowergamma(self, e): return "{}({}, 0, {})".format( self._module_format('mpmath.gammainc'), self._print(e.args[0]), self._print(e.args[1])) def _print_log2(self, e): return '{0}({1})/{0}(2)'.format( self._module_format('mpmath.log'), self._print(e.args[0])) def _print_log1p(self, e): return '{}({}+1)'.format( self._module_format('mpmath.log'), self._print(e.args[0])) def _print_Pow(self, expr, rational=False): return self._hprint_Pow(expr, rational=rational, sqrt='mpmath.sqrt') def _print_Integral(self, e): integration_vars, limits = _unpack_integral_limits(e) return "{}(lambda {}: {}, {})".format( self._module_format("mpmath.quad"), ", ".join(map(self._print, integration_vars)), self._print(e.args[0]), ", ".join("(%s, %s)" % tuple(map(self._print, l)) for l in limits)) for k in MpmathPrinter._kf: setattr(MpmathPrinter, '_print_%s' % k, _print_known_func) for k in _known_constants_mpmath: setattr(MpmathPrinter, '_print_%s' % k, _print_known_const) class SymPyPrinter(AbstractPythonCodePrinter): language = "Python with SymPy" def _print_Function(self, expr): mod = expr.func.__module__ or '' return '%s(%s)' % (self._module_format(mod + ('.' if mod else '') + expr.func.__name__), ', '.join(map(lambda arg: self._print(arg), expr.args))) def _print_Pow(self, expr, rational=False): return self._hprint_Pow(expr, rational=rational, sqrt='sympy.sqrt')
a4ed5f8020ffe12fb90bc5d0248bde0f0be913ffc6ae692276b437f2d25e7ba6
""" A Printer for generating readable representation of most SymPy classes. """ from typing import Any, Dict as tDict from sympy.core import S, Rational, Pow, Basic, Mul, Number, Add from sympy.core.mul import _keep_coeff from sympy.core.relational import Relational from sympy.core.sorting import default_sort_key from sympy.core.sympify import SympifyError from sympy.utilities.iterables import sift from .precedence import precedence, PRECEDENCE from .printer import Printer, print_function from mpmath.libmp import prec_to_dps, to_str as mlib_to_str class StrPrinter(Printer): printmethod = "_sympystr" _default_settings = { "order": None, "full_prec": "auto", "sympy_integers": False, "abbrev": False, "perm_cyclic": True, "min": None, "max": None, } # type: tDict[str, Any] _relationals = {} # type: tDict[str, str] def parenthesize(self, item, level, strict=False): if (precedence(item) < level) or ((not strict) and precedence(item) <= level): return "(%s)" % self._print(item) else: return self._print(item) def stringify(self, args, sep, level=0): return sep.join([self.parenthesize(item, level) for item in args]) def emptyPrinter(self, expr): if isinstance(expr, str): return expr elif isinstance(expr, Basic): return repr(expr) else: return str(expr) def _print_Add(self, expr, order=None): terms = self._as_ordered_terms(expr, order=order) PREC = precedence(expr) l = [] for term in terms: t = self._print(term) if t.startswith('-'): sign = "-" t = t[1:] else: sign = "+" if precedence(term) < PREC or isinstance(term, Add): l.extend([sign, "(%s)" % t]) else: l.extend([sign, t]) sign = l.pop(0) if sign == '+': sign = "" return sign + ' '.join(l) def _print_BooleanTrue(self, expr): return "True" def _print_BooleanFalse(self, expr): return "False" def _print_Not(self, expr): return '~%s' %(self.parenthesize(expr.args[0],PRECEDENCE["Not"])) def _print_And(self, expr): args = list(expr.args) for j, i in enumerate(args): if isinstance(i, Relational) and ( i.canonical.rhs is S.NegativeInfinity): args.insert(0, args.pop(j)) return self.stringify(args, " & ", PRECEDENCE["BitwiseAnd"]) def _print_Or(self, expr): return self.stringify(expr.args, " | ", PRECEDENCE["BitwiseOr"]) def _print_Xor(self, expr): return self.stringify(expr.args, " ^ ", PRECEDENCE["BitwiseXor"]) def _print_AppliedPredicate(self, expr): return '%s(%s)' % ( self._print(expr.function), self.stringify(expr.arguments, ", ")) def _print_Basic(self, expr): l = [self._print(o) for o in expr.args] return expr.__class__.__name__ + "(%s)" % ", ".join(l) def _print_BlockMatrix(self, B): if B.blocks.shape == (1, 1): self._print(B.blocks[0, 0]) return self._print(B.blocks) def _print_Catalan(self, expr): return 'Catalan' def _print_ComplexInfinity(self, expr): return 'zoo' def _print_ConditionSet(self, s): args = tuple([self._print(i) for i in (s.sym, s.condition)]) if s.base_set is S.UniversalSet: return 'ConditionSet(%s, %s)' % args args += (self._print(s.base_set),) return 'ConditionSet(%s, %s, %s)' % args def _print_Derivative(self, expr): dexpr = expr.expr dvars = [i[0] if i[1] == 1 else i for i in expr.variable_count] return 'Derivative(%s)' % ", ".join(map(lambda arg: self._print(arg), [dexpr] + dvars)) def _print_dict(self, d): keys = sorted(d.keys(), key=default_sort_key) items = [] for key in keys: item = "%s: %s" % (self._print(key), self._print(d[key])) items.append(item) return "{%s}" % ", ".join(items) def _print_Dict(self, expr): return self._print_dict(expr) def _print_RandomDomain(self, d): if hasattr(d, 'as_boolean'): return 'Domain: ' + self._print(d.as_boolean()) elif hasattr(d, 'set'): return ('Domain: ' + self._print(d.symbols) + ' in ' + self._print(d.set)) else: return 'Domain on ' + self._print(d.symbols) def _print_Dummy(self, expr): return '_' + expr.name def _print_EulerGamma(self, expr): return 'EulerGamma' def _print_Exp1(self, expr): return 'E' def _print_ExprCondPair(self, expr): return '(%s, %s)' % (self._print(expr.expr), self._print(expr.cond)) def _print_Function(self, expr): return expr.func.__name__ + "(%s)" % self.stringify(expr.args, ", ") def _print_GoldenRatio(self, expr): return 'GoldenRatio' def _print_Heaviside(self, expr): # Same as _print_Function but uses pargs to suppress default 1/2 for # 2nd args return expr.func.__name__ + "(%s)" % self.stringify(expr.pargs, ", ") def _print_TribonacciConstant(self, expr): return 'TribonacciConstant' def _print_ImaginaryUnit(self, expr): return 'I' def _print_Infinity(self, expr): return 'oo' def _print_Integral(self, expr): def _xab_tostr(xab): if len(xab) == 1: return self._print(xab[0]) else: return self._print((xab[0],) + tuple(xab[1:])) L = ', '.join([_xab_tostr(l) for l in expr.limits]) return 'Integral(%s, %s)' % (self._print(expr.function), L) def _print_Interval(self, i): fin = 'Interval{m}({a}, {b})' a, b, l, r = i.args if a.is_infinite and b.is_infinite: m = '' elif a.is_infinite and not r: m = '' elif b.is_infinite and not l: m = '' elif not l and not r: m = '' elif l and r: m = '.open' elif l: m = '.Lopen' else: m = '.Ropen' return fin.format(**{'a': a, 'b': b, 'm': m}) def _print_AccumulationBounds(self, i): return "AccumBounds(%s, %s)" % (self._print(i.min), self._print(i.max)) def _print_Inverse(self, I): return "%s**(-1)" % self.parenthesize(I.arg, PRECEDENCE["Pow"]) def _print_Lambda(self, obj): expr = obj.expr sig = obj.signature if len(sig) == 1 and sig[0].is_symbol: sig = sig[0] return "Lambda(%s, %s)" % (self._print(sig), self._print(expr)) def _print_LatticeOp(self, expr): args = sorted(expr.args, key=default_sort_key) return expr.func.__name__ + "(%s)" % ", ".join(self._print(arg) for arg in args) def _print_Limit(self, expr): e, z, z0, dir = expr.args if str(dir) == "+": return "Limit(%s, %s, %s)" % tuple(map(self._print, (e, z, z0))) else: return "Limit(%s, %s, %s, dir='%s')" % tuple(map(self._print, (e, z, z0, dir))) def _print_list(self, expr): return "[%s]" % self.stringify(expr, ", ") def _print_List(self, expr): return self._print_list(expr) def _print_MatrixBase(self, expr): return expr._format_str(self) def _print_MatrixElement(self, expr): return self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) \ + '[%s, %s]' % (self._print(expr.i), self._print(expr.j)) def _print_MatrixSlice(self, expr): def strslice(x, dim): x = list(x) if x[2] == 1: del x[2] if x[0] == 0: x[0] = '' if x[1] == dim: x[1] = '' return ':'.join(map(lambda arg: self._print(arg), x)) return (self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) + '[' + strslice(expr.rowslice, expr.parent.rows) + ', ' + strslice(expr.colslice, expr.parent.cols) + ']') def _print_DeferredVector(self, expr): return expr.name def _print_Mul(self, expr): prec = precedence(expr) # Check for unevaluated Mul. In this case we need to make sure the # identities are visible, multiple Rational factors are not combined # etc so we display in a straight-forward form that fully preserves all # args and their order. args = expr.args if args[0] is S.One or any( isinstance(a, Number) or a.is_Pow and all(ai.is_Integer for ai in a.args) for a in args[1:]): d, n = sift(args, lambda x: isinstance(x, Pow) and bool(x.exp.as_coeff_Mul()[0] < 0), binary=True) for i, di in enumerate(d): if di.exp.is_Number: e = -di.exp else: dargs = list(di.exp.args) dargs[0] = -dargs[0] e = Mul._from_args(dargs) d[i] = Pow(di.base, e, evaluate=False) if e - 1 else di.base pre = [] # don't parenthesize first factor if negative if n and n[0].could_extract_minus_sign(): pre = [str(n.pop(0))] nfactors = pre + [self.parenthesize(a, prec, strict=False) for a in n] if not nfactors: nfactors = ['1'] # don't parenthesize first of denominator unless singleton if len(d) > 1 and d[0].could_extract_minus_sign(): pre = [str(d.pop(0))] else: pre = [] dfactors = pre + [self.parenthesize(a, prec, strict=False) for a in d] n = '*'.join(nfactors) d = '*'.join(dfactors) if len(dfactors) > 1: return '%s/(%s)' % (n, d) elif dfactors: return '%s/%s' % (n, d) return n c, e = expr.as_coeff_Mul() if c < 0: expr = _keep_coeff(-c, e) sign = "-" else: sign = "" a = [] # items in the numerator b = [] # items that are in the denominator (if any) pow_paren = [] # Will collect all pow with more than one base element and exp = -1 if self.order not in ('old', 'none'): args = expr.as_ordered_factors() else: # use make_args in case expr was something like -x -> x args = Mul.make_args(expr) # Gather args for numerator/denominator def apow(i): b, e = i.as_base_exp() eargs = list(Mul.make_args(e)) if eargs[0] is S.NegativeOne: eargs = eargs[1:] else: eargs[0] = -eargs[0] e = Mul._from_args(eargs) if isinstance(i, Pow): return i.func(b, e, evaluate=False) return i.func(e, evaluate=False) for item in args: if (item.is_commutative and isinstance(item, Pow) and bool(item.exp.as_coeff_Mul()[0] < 0)): if item.exp is not S.NegativeOne: b.append(apow(item)) else: if (len(item.args[0].args) != 1 and isinstance(item.base, (Mul, Pow))): # To avoid situations like #14160 pow_paren.append(item) b.append(item.base) elif item.is_Rational and item is not S.Infinity: if item.p != 1: a.append(Rational(item.p)) if item.q != 1: b.append(Rational(item.q)) else: a.append(item) a = a or [S.One] a_str = [self.parenthesize(x, prec, strict=False) for x in a] b_str = [self.parenthesize(x, prec, strict=False) for x in b] # To parenthesize Pow with exp = -1 and having more than one Symbol for item in pow_paren: if item.base in b: b_str[b.index(item.base)] = "(%s)" % b_str[b.index(item.base)] if not b: return sign + '*'.join(a_str) elif len(b) == 1: return sign + '*'.join(a_str) + "/" + b_str[0] else: return sign + '*'.join(a_str) + "/(%s)" % '*'.join(b_str) def _print_MatMul(self, expr): c, m = expr.as_coeff_mmul() sign = "" if c.is_number: re, im = c.as_real_imag() if im.is_zero and re.is_negative: expr = _keep_coeff(-c, m) sign = "-" elif re.is_zero and im.is_negative: expr = _keep_coeff(-c, m) sign = "-" return sign + '*'.join( [self.parenthesize(arg, precedence(expr)) for arg in expr.args] ) def _print_ElementwiseApplyFunction(self, expr): return "{}.({})".format( expr.function, self._print(expr.expr), ) def _print_NaN(self, expr): return 'nan' def _print_NegativeInfinity(self, expr): return '-oo' def _print_Order(self, expr): if not expr.variables or all(p is S.Zero for p in expr.point): if len(expr.variables) <= 1: return 'O(%s)' % self._print(expr.expr) else: return 'O(%s)' % self.stringify((expr.expr,) + expr.variables, ', ', 0) else: return 'O(%s)' % self.stringify(expr.args, ', ', 0) def _print_Ordinal(self, expr): return expr.__str__() def _print_Cycle(self, expr): return expr.__str__() def _print_Permutation(self, expr): from sympy.combinatorics.permutations import Permutation, Cycle from sympy.utilities.exceptions import sympy_deprecation_warning perm_cyclic = Permutation.print_cyclic if perm_cyclic is not None: sympy_deprecation_warning( f""" Setting Permutation.print_cyclic is deprecated. Instead use init_printing(perm_cyclic={perm_cyclic}). """, deprecated_since_version="1.6", active_deprecations_target="deprecated-permutation-print_cyclic", stacklevel=7, ) else: perm_cyclic = self._settings.get("perm_cyclic", True) if perm_cyclic: if not expr.size: return '()' # before taking Cycle notation, see if the last element is # a singleton and move it to the head of the string s = Cycle(expr)(expr.size - 1).__repr__()[len('Cycle'):] last = s.rfind('(') if not last == 0 and ',' not in s[last:]: s = s[last:] + s[:last] s = s.replace(',', '') return s else: s = expr.support() if not s: if expr.size < 5: return 'Permutation(%s)' % self._print(expr.array_form) return 'Permutation([], size=%s)' % self._print(expr.size) trim = self._print(expr.array_form[:s[-1] + 1]) + ', size=%s' % self._print(expr.size) use = full = self._print(expr.array_form) if len(trim) < len(full): use = trim return 'Permutation(%s)' % use def _print_Subs(self, obj): expr, old, new = obj.args if len(obj.point) == 1: old = old[0] new = new[0] return "Subs(%s, %s, %s)" % ( self._print(expr), self._print(old), self._print(new)) def _print_TensorIndex(self, expr): return expr._print() def _print_TensorHead(self, expr): return expr._print() def _print_Tensor(self, expr): return expr._print() def _print_TensMul(self, expr): # prints expressions like "A(a)", "3*A(a)", "(1+x)*A(a)" sign, args = expr._get_args_for_traditional_printer() return sign + "*".join( [self.parenthesize(arg, precedence(expr)) for arg in args] ) def _print_TensAdd(self, expr): return expr._print() def _print_ArraySymbol(self, expr): return self._print(expr.name) def _print_ArrayElement(self, expr): return "%s[%s]" % ( self.parenthesize(expr.name, PRECEDENCE["Func"], True), ", ".join([self._print(i) for i in expr.indices])) def _print_PermutationGroup(self, expr): p = [' %s' % self._print(a) for a in expr.args] return 'PermutationGroup([\n%s])' % ',\n'.join(p) def _print_Pi(self, expr): return 'pi' def _print_PolyRing(self, ring): return "Polynomial ring in %s over %s with %s order" % \ (", ".join(map(lambda rs: self._print(rs), ring.symbols)), self._print(ring.domain), self._print(ring.order)) def _print_FracField(self, field): return "Rational function field in %s over %s with %s order" % \ (", ".join(map(lambda fs: self._print(fs), field.symbols)), self._print(field.domain), self._print(field.order)) def _print_FreeGroupElement(self, elm): return elm.__str__() def _print_GaussianElement(self, poly): return "(%s + %s*I)" % (poly.x, poly.y) def _print_PolyElement(self, poly): return poly.str(self, PRECEDENCE, "%s**%s", "*") def _print_FracElement(self, frac): if frac.denom == 1: return self._print(frac.numer) else: numer = self.parenthesize(frac.numer, PRECEDENCE["Mul"], strict=True) denom = self.parenthesize(frac.denom, PRECEDENCE["Atom"], strict=True) return numer + "/" + denom def _print_Poly(self, expr): ATOM_PREC = PRECEDENCE["Atom"] - 1 terms, gens = [], [ self.parenthesize(s, ATOM_PREC) for s in expr.gens ] for monom, coeff in expr.terms(): s_monom = [] for i, e in enumerate(monom): if e > 0: if e == 1: s_monom.append(gens[i]) else: s_monom.append(gens[i] + "**%d" % e) s_monom = "*".join(s_monom) if coeff.is_Add: if s_monom: s_coeff = "(" + self._print(coeff) + ")" else: s_coeff = self._print(coeff) else: if s_monom: if coeff is S.One: terms.extend(['+', s_monom]) continue if coeff is S.NegativeOne: terms.extend(['-', s_monom]) continue s_coeff = self._print(coeff) if not s_monom: s_term = s_coeff else: s_term = s_coeff + "*" + s_monom if s_term.startswith('-'): terms.extend(['-', s_term[1:]]) else: terms.extend(['+', s_term]) if terms[0] in ('-', '+'): modifier = terms.pop(0) if modifier == '-': terms[0] = '-' + terms[0] format = expr.__class__.__name__ + "(%s, %s" from sympy.polys.polyerrors import PolynomialError try: format += ", modulus=%s" % expr.get_modulus() except PolynomialError: format += ", domain='%s'" % expr.get_domain() format += ")" for index, item in enumerate(gens): if len(item) > 2 and (item[:1] == "(" and item[len(item) - 1:] == ")"): gens[index] = item[1:len(item) - 1] return format % (' '.join(terms), ', '.join(gens)) def _print_UniversalSet(self, p): return 'UniversalSet' def _print_AlgebraicNumber(self, expr): if expr.is_aliased: return self._print(expr.as_poly().as_expr()) else: return self._print(expr.as_expr()) def _print_Pow(self, expr, rational=False): """Printing helper function for ``Pow`` Parameters ========== rational : bool, optional If ``True``, it will not attempt printing ``sqrt(x)`` or ``x**S.Half`` as ``sqrt``, and will use ``x**(1/2)`` instead. See examples for additional details Examples ======== >>> from sympy import sqrt, StrPrinter >>> from sympy.abc import x How ``rational`` keyword works with ``sqrt``: >>> printer = StrPrinter() >>> printer._print_Pow(sqrt(x), rational=True) 'x**(1/2)' >>> printer._print_Pow(sqrt(x), rational=False) 'sqrt(x)' >>> printer._print_Pow(1/sqrt(x), rational=True) 'x**(-1/2)' >>> printer._print_Pow(1/sqrt(x), rational=False) '1/sqrt(x)' Notes ===== ``sqrt(x)`` is canonicalized as ``Pow(x, S.Half)`` in SymPy, so there is no need of defining a separate printer for ``sqrt``. Instead, it should be handled here as well. """ PREC = precedence(expr) if expr.exp is S.Half and not rational: return "sqrt(%s)" % self._print(expr.base) if expr.is_commutative: if -expr.exp is S.Half and not rational: # Note: Don't test "expr.exp == -S.Half" here, because that will # match -0.5, which we don't want. return "%s/sqrt(%s)" % tuple(map(lambda arg: self._print(arg), (S.One, expr.base))) if expr.exp is -S.One: # Similarly to the S.Half case, don't test with "==" here. return '%s/%s' % (self._print(S.One), self.parenthesize(expr.base, PREC, strict=False)) e = self.parenthesize(expr.exp, PREC, strict=False) if self.printmethod == '_sympyrepr' and expr.exp.is_Rational and expr.exp.q != 1: # the parenthesized exp should be '(Rational(a, b))' so strip parens, # but just check to be sure. if e.startswith('(Rational'): return '%s**%s' % (self.parenthesize(expr.base, PREC, strict=False), e[1:-1]) return '%s**%s' % (self.parenthesize(expr.base, PREC, strict=False), e) def _print_UnevaluatedExpr(self, expr): return self._print(expr.args[0]) def _print_MatPow(self, expr): PREC = precedence(expr) return '%s**%s' % (self.parenthesize(expr.base, PREC, strict=False), self.parenthesize(expr.exp, PREC, strict=False)) def _print_Integer(self, expr): if self._settings.get("sympy_integers", False): return "S(%s)" % (expr) return str(expr.p) def _print_Integers(self, expr): return 'Integers' def _print_Naturals(self, expr): return 'Naturals' def _print_Naturals0(self, expr): return 'Naturals0' def _print_Rationals(self, expr): return 'Rationals' def _print_Reals(self, expr): return 'Reals' def _print_Complexes(self, expr): return 'Complexes' def _print_EmptySet(self, expr): return 'EmptySet' def _print_EmptySequence(self, expr): return 'EmptySequence' def _print_int(self, expr): return str(expr) def _print_mpz(self, expr): return str(expr) def _print_Rational(self, expr): if expr.q == 1: return str(expr.p) else: if self._settings.get("sympy_integers", False): return "S(%s)/%s" % (expr.p, expr.q) return "%s/%s" % (expr.p, expr.q) def _print_PythonRational(self, expr): if expr.q == 1: return str(expr.p) else: return "%d/%d" % (expr.p, expr.q) def _print_Fraction(self, expr): if expr.denominator == 1: return str(expr.numerator) else: return "%s/%s" % (expr.numerator, expr.denominator) def _print_mpq(self, expr): if expr.denominator == 1: return str(expr.numerator) else: return "%s/%s" % (expr.numerator, expr.denominator) def _print_Float(self, expr): prec = expr._prec if prec < 5: dps = 0 else: dps = prec_to_dps(expr._prec) if self._settings["full_prec"] is True: strip = False elif self._settings["full_prec"] is False: strip = True elif self._settings["full_prec"] == "auto": strip = self._print_level > 1 low = self._settings["min"] if "min" in self._settings else None high = self._settings["max"] if "max" in self._settings else None rv = mlib_to_str(expr._mpf_, dps, strip_zeros=strip, min_fixed=low, max_fixed=high) if rv.startswith('-.0'): rv = '-0.' + rv[3:] elif rv.startswith('.0'): rv = '0.' + rv[2:] if rv.startswith('+'): # e.g., +inf -> inf rv = rv[1:] return rv def _print_Relational(self, expr): charmap = { "==": "Eq", "!=": "Ne", ":=": "Assignment", '+=': "AddAugmentedAssignment", "-=": "SubAugmentedAssignment", "*=": "MulAugmentedAssignment", "/=": "DivAugmentedAssignment", "%=": "ModAugmentedAssignment", } if expr.rel_op in charmap: return '%s(%s, %s)' % (charmap[expr.rel_op], self._print(expr.lhs), self._print(expr.rhs)) return '%s %s %s' % (self.parenthesize(expr.lhs, precedence(expr)), self._relationals.get(expr.rel_op) or expr.rel_op, self.parenthesize(expr.rhs, precedence(expr))) def _print_ComplexRootOf(self, expr): return "CRootOf(%s, %d)" % (self._print_Add(expr.expr, order='lex'), expr.index) def _print_RootSum(self, expr): args = [self._print_Add(expr.expr, order='lex')] if expr.fun is not S.IdentityFunction: args.append(self._print(expr.fun)) return "RootSum(%s)" % ", ".join(args) def _print_GroebnerBasis(self, basis): cls = basis.__class__.__name__ exprs = [self._print_Add(arg, order=basis.order) for arg in basis.exprs] exprs = "[%s]" % ", ".join(exprs) gens = [ self._print(gen) for gen in basis.gens ] domain = "domain='%s'" % self._print(basis.domain) order = "order='%s'" % self._print(basis.order) args = [exprs] + gens + [domain, order] return "%s(%s)" % (cls, ", ".join(args)) def _print_set(self, s): items = sorted(s, key=default_sort_key) args = ', '.join(self._print(item) for item in items) if not args: return "set()" return '{%s}' % args def _print_FiniteSet(self, s): from sympy.sets.sets import FiniteSet items = sorted(s, key=default_sort_key) args = ', '.join(self._print(item) for item in items) if any(item.has(FiniteSet) for item in items): return 'FiniteSet({})'.format(args) return '{{{}}}'.format(args) def _print_Partition(self, s): items = sorted(s, key=default_sort_key) args = ', '.join(self._print(arg) for arg in items) return 'Partition({})'.format(args) def _print_frozenset(self, s): if not s: return "frozenset()" return "frozenset(%s)" % self._print_set(s) def _print_Sum(self, expr): def _xab_tostr(xab): if len(xab) == 1: return self._print(xab[0]) else: return self._print((xab[0],) + tuple(xab[1:])) L = ', '.join([_xab_tostr(l) for l in expr.limits]) return 'Sum(%s, %s)' % (self._print(expr.function), L) def _print_Symbol(self, expr): return expr.name _print_MatrixSymbol = _print_Symbol _print_RandomSymbol = _print_Symbol def _print_Identity(self, expr): return "I" def _print_ZeroMatrix(self, expr): return "0" def _print_OneMatrix(self, expr): return "1" def _print_Predicate(self, expr): return "Q.%s" % expr.name def _print_str(self, expr): return str(expr) def _print_tuple(self, expr): if len(expr) == 1: return "(%s,)" % self._print(expr[0]) else: return "(%s)" % self.stringify(expr, ", ") def _print_Tuple(self, expr): return self._print_tuple(expr) def _print_Transpose(self, T): return "%s.T" % self.parenthesize(T.arg, PRECEDENCE["Pow"]) def _print_Uniform(self, expr): return "Uniform(%s, %s)" % (self._print(expr.a), self._print(expr.b)) def _print_Quantity(self, expr): if self._settings.get("abbrev", False): return "%s" % expr.abbrev return "%s" % expr.name def _print_Quaternion(self, expr): s = [self.parenthesize(i, PRECEDENCE["Mul"], strict=True) for i in expr.args] a = [s[0]] + [i+"*"+j for i, j in zip(s[1:], "ijk")] return " + ".join(a) def _print_Dimension(self, expr): return str(expr) def _print_Wild(self, expr): return expr.name + '_' def _print_WildFunction(self, expr): return expr.name + '_' def _print_WildDot(self, expr): return expr.name def _print_WildPlus(self, expr): return expr.name def _print_WildStar(self, expr): return expr.name def _print_Zero(self, expr): if self._settings.get("sympy_integers", False): return "S(0)" return "0" def _print_DMP(self, p): try: if p.ring is not None: # TODO incorporate order return self._print(p.ring.to_sympy(p)) except SympifyError: pass cls = p.__class__.__name__ rep = self._print(p.rep) dom = self._print(p.dom) ring = self._print(p.ring) return "%s(%s, %s, %s)" % (cls, rep, dom, ring) def _print_DMF(self, expr): return self._print_DMP(expr) def _print_Object(self, obj): return 'Object("%s")' % obj.name def _print_IdentityMorphism(self, morphism): return 'IdentityMorphism(%s)' % morphism.domain def _print_NamedMorphism(self, morphism): return 'NamedMorphism(%s, %s, "%s")' % \ (morphism.domain, morphism.codomain, morphism.name) def _print_Category(self, category): return 'Category("%s")' % category.name def _print_Manifold(self, manifold): return manifold.name.name def _print_Patch(self, patch): return patch.name.name def _print_CoordSystem(self, coords): return coords.name.name def _print_BaseScalarField(self, field): return field._coord_sys.symbols[field._index].name def _print_BaseVectorField(self, field): return 'e_%s' % field._coord_sys.symbols[field._index].name def _print_Differential(self, diff): field = diff._form_field if hasattr(field, '_coord_sys'): return 'd%s' % field._coord_sys.symbols[field._index].name else: return 'd(%s)' % self._print(field) def _print_Tr(self, expr): #TODO : Handle indices return "%s(%s)" % ("Tr", self._print(expr.args[0])) def _print_Str(self, s): return self._print(s.name) def _print_AppliedBinaryRelation(self, expr): rel = expr.function return '%s(%s, %s)' % (self._print(rel), self._print(expr.lhs), self._print(expr.rhs)) @print_function(StrPrinter) def sstr(expr, **settings): """Returns the expression as a string. For large expressions where speed is a concern, use the setting order='none'. If abbrev=True setting is used then units are printed in abbreviated form. Examples ======== >>> from sympy import symbols, Eq, sstr >>> a, b = symbols('a b') >>> sstr(Eq(a + b, 0)) 'Eq(a + b, 0)' """ p = StrPrinter(settings) s = p.doprint(expr) return s class StrReprPrinter(StrPrinter): """(internal) -- see sstrrepr""" def _print_str(self, s): return repr(s) def _print_Str(self, s): # Str does not to be printed same as str here return "%s(%s)" % (s.__class__.__name__, self._print(s.name)) @print_function(StrReprPrinter) def sstrrepr(expr, **settings): """return expr in mixed str/repr form i.e. strings are returned in repr form with quotes, and everything else is returned in str form. This function could be useful for hooking into sys.displayhook """ p = StrReprPrinter(settings) s = p.doprint(expr) return s
c1adf6945e76e7800e3e76d5f45e4ebd04ddd473a4d2b7cdf8751e91c3751e62
''' Use llvmlite to create executable functions from SymPy expressions This module requires llvmlite (https://github.com/numba/llvmlite). ''' import ctypes from sympy.external import import_module from sympy.printing.printer import Printer from sympy.core.singleton import S from sympy.tensor.indexed import IndexedBase from sympy.utilities.decorator import doctest_depends_on llvmlite = import_module('llvmlite') if llvmlite: ll = import_module('llvmlite.ir').ir llvm = import_module('llvmlite.binding').binding llvm.initialize() llvm.initialize_native_target() llvm.initialize_native_asmprinter() __doctest_requires__ = {('llvm_callable'): ['llvmlite']} class LLVMJitPrinter(Printer): '''Convert expressions to LLVM IR''' def __init__(self, module, builder, fn, *args, **kwargs): self.func_arg_map = kwargs.pop("func_arg_map", {}) if not llvmlite: raise ImportError("llvmlite is required for LLVMJITPrinter") super().__init__(*args, **kwargs) self.fp_type = ll.DoubleType() self.module = module self.builder = builder self.fn = fn self.ext_fn = {} # keep track of wrappers to external functions self.tmp_var = {} def _add_tmp_var(self, name, value): self.tmp_var[name] = value def _print_Number(self, n): return ll.Constant(self.fp_type, float(n)) def _print_Integer(self, expr): return ll.Constant(self.fp_type, float(expr.p)) def _print_Symbol(self, s): val = self.tmp_var.get(s) if not val: # look up parameter with name s val = self.func_arg_map.get(s) if not val: raise LookupError("Symbol not found: %s" % s) return val def _print_Pow(self, expr): base0 = self._print(expr.base) if expr.exp == S.NegativeOne: return self.builder.fdiv(ll.Constant(self.fp_type, 1.0), base0) if expr.exp == S.Half: fn = self.ext_fn.get("sqrt") if not fn: fn_type = ll.FunctionType(self.fp_type, [self.fp_type]) fn = ll.Function(self.module, fn_type, "sqrt") self.ext_fn["sqrt"] = fn return self.builder.call(fn, [base0], "sqrt") if expr.exp == 2: return self.builder.fmul(base0, base0) exp0 = self._print(expr.exp) fn = self.ext_fn.get("pow") if not fn: fn_type = ll.FunctionType(self.fp_type, [self.fp_type, self.fp_type]) fn = ll.Function(self.module, fn_type, "pow") self.ext_fn["pow"] = fn return self.builder.call(fn, [base0, exp0], "pow") def _print_Mul(self, expr): nodes = [self._print(a) for a in expr.args] e = nodes[0] for node in nodes[1:]: e = self.builder.fmul(e, node) return e def _print_Add(self, expr): nodes = [self._print(a) for a in expr.args] e = nodes[0] for node in nodes[1:]: e = self.builder.fadd(e, node) return e # TODO - assumes all called functions take one double precision argument. # Should have a list of math library functions to validate this. def _print_Function(self, expr): name = expr.func.__name__ e0 = self._print(expr.args[0]) fn = self.ext_fn.get(name) if not fn: fn_type = ll.FunctionType(self.fp_type, [self.fp_type]) fn = ll.Function(self.module, fn_type, name) self.ext_fn[name] = fn return self.builder.call(fn, [e0], name) def emptyPrinter(self, expr): raise TypeError("Unsupported type for LLVM JIT conversion: %s" % type(expr)) # Used when parameters are passed by array. Often used in callbacks to # handle a variable number of parameters. class LLVMJitCallbackPrinter(LLVMJitPrinter): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def _print_Indexed(self, expr): array, idx = self.func_arg_map[expr.base] offset = int(expr.indices[0].evalf()) array_ptr = self.builder.gep(array, [ll.Constant(ll.IntType(32), offset)]) fp_array_ptr = self.builder.bitcast(array_ptr, ll.PointerType(self.fp_type)) value = self.builder.load(fp_array_ptr) return value def _print_Symbol(self, s): val = self.tmp_var.get(s) if val: return val array, idx = self.func_arg_map.get(s, [None, 0]) if not array: raise LookupError("Symbol not found: %s" % s) array_ptr = self.builder.gep(array, [ll.Constant(ll.IntType(32), idx)]) fp_array_ptr = self.builder.bitcast(array_ptr, ll.PointerType(self.fp_type)) value = self.builder.load(fp_array_ptr) return value # ensure lifetime of the execution engine persists (else call to compiled # function will seg fault) exe_engines = [] # ensure names for generated functions are unique link_names = set() current_link_suffix = 0 class LLVMJitCode: def __init__(self, signature): self.signature = signature self.fp_type = ll.DoubleType() self.module = ll.Module('mod1') self.fn = None self.llvm_arg_types = [] self.llvm_ret_type = self.fp_type self.param_dict = {} # map symbol name to LLVM function argument self.link_name = '' def _from_ctype(self, ctype): if ctype == ctypes.c_int: return ll.IntType(32) if ctype == ctypes.c_double: return self.fp_type if ctype == ctypes.POINTER(ctypes.c_double): return ll.PointerType(self.fp_type) if ctype == ctypes.c_void_p: return ll.PointerType(ll.IntType(32)) if ctype == ctypes.py_object: return ll.PointerType(ll.IntType(32)) print("Unhandled ctype = %s" % str(ctype)) def _create_args(self, func_args): """Create types for function arguments""" self.llvm_ret_type = self._from_ctype(self.signature.ret_type) self.llvm_arg_types = \ [self._from_ctype(a) for a in self.signature.arg_ctypes] def _create_function_base(self): """Create function with name and type signature""" global link_names, current_link_suffix default_link_name = 'jit_func' current_link_suffix += 1 self.link_name = default_link_name + str(current_link_suffix) link_names.add(self.link_name) fn_type = ll.FunctionType(self.llvm_ret_type, self.llvm_arg_types) self.fn = ll.Function(self.module, fn_type, name=self.link_name) def _create_param_dict(self, func_args): """Mapping of symbolic values to function arguments""" for i, a in enumerate(func_args): self.fn.args[i].name = str(a) self.param_dict[a] = self.fn.args[i] def _create_function(self, expr): """Create function body and return LLVM IR""" bb_entry = self.fn.append_basic_block('entry') builder = ll.IRBuilder(bb_entry) lj = LLVMJitPrinter(self.module, builder, self.fn, func_arg_map=self.param_dict) ret = self._convert_expr(lj, expr) lj.builder.ret(self._wrap_return(lj, ret)) strmod = str(self.module) return strmod def _wrap_return(self, lj, vals): # Return a single double if there is one return value, # else return a tuple of doubles. # Don't wrap return value in this case if self.signature.ret_type == ctypes.c_double: return vals[0] # Use this instead of a real PyObject* void_ptr = ll.PointerType(ll.IntType(32)) # Create a wrapped double: PyObject* PyFloat_FromDouble(double v) wrap_type = ll.FunctionType(void_ptr, [self.fp_type]) wrap_fn = ll.Function(lj.module, wrap_type, "PyFloat_FromDouble") wrapped_vals = [lj.builder.call(wrap_fn, [v]) for v in vals] if len(vals) == 1: final_val = wrapped_vals[0] else: # Create a tuple: PyObject* PyTuple_Pack(Py_ssize_t n, ...) # This should be Py_ssize_t tuple_arg_types = [ll.IntType(32)] tuple_arg_types.extend([void_ptr]*len(vals)) tuple_type = ll.FunctionType(void_ptr, tuple_arg_types) tuple_fn = ll.Function(lj.module, tuple_type, "PyTuple_Pack") tuple_args = [ll.Constant(ll.IntType(32), len(wrapped_vals))] tuple_args.extend(wrapped_vals) final_val = lj.builder.call(tuple_fn, tuple_args) return final_val def _convert_expr(self, lj, expr): try: # Match CSE return data structure. if len(expr) == 2: tmp_exprs = expr[0] final_exprs = expr[1] if len(final_exprs) != 1 and self.signature.ret_type == ctypes.c_double: raise NotImplementedError("Return of multiple expressions not supported for this callback") for name, e in tmp_exprs: val = lj._print(e) lj._add_tmp_var(name, val) except TypeError: final_exprs = [expr] vals = [lj._print(e) for e in final_exprs] return vals def _compile_function(self, strmod): global exe_engines llmod = llvm.parse_assembly(strmod) pmb = llvm.create_pass_manager_builder() pmb.opt_level = 2 pass_manager = llvm.create_module_pass_manager() pmb.populate(pass_manager) pass_manager.run(llmod) target_machine = \ llvm.Target.from_default_triple().create_target_machine() exe_eng = llvm.create_mcjit_compiler(llmod, target_machine) exe_eng.finalize_object() exe_engines.append(exe_eng) if False: print("Assembly") print(target_machine.emit_assembly(llmod)) fptr = exe_eng.get_function_address(self.link_name) return fptr class LLVMJitCodeCallback(LLVMJitCode): def __init__(self, signature): super().__init__(signature) def _create_param_dict(self, func_args): for i, a in enumerate(func_args): if isinstance(a, IndexedBase): self.param_dict[a] = (self.fn.args[i], i) self.fn.args[i].name = str(a) else: self.param_dict[a] = (self.fn.args[self.signature.input_arg], i) def _create_function(self, expr): """Create function body and return LLVM IR""" bb_entry = self.fn.append_basic_block('entry') builder = ll.IRBuilder(bb_entry) lj = LLVMJitCallbackPrinter(self.module, builder, self.fn, func_arg_map=self.param_dict) ret = self._convert_expr(lj, expr) if self.signature.ret_arg: output_fp_ptr = builder.bitcast(self.fn.args[self.signature.ret_arg], ll.PointerType(self.fp_type)) for i, val in enumerate(ret): index = ll.Constant(ll.IntType(32), i) output_array_ptr = builder.gep(output_fp_ptr, [index]) builder.store(val, output_array_ptr) builder.ret(ll.Constant(ll.IntType(32), 0)) # return success else: lj.builder.ret(self._wrap_return(lj, ret)) strmod = str(self.module) return strmod class CodeSignature: def __init__(self, ret_type): self.ret_type = ret_type self.arg_ctypes = [] # Input argument array element index self.input_arg = 0 # For the case output value is referenced through a parameter rather # than the return value self.ret_arg = None def _llvm_jit_code(args, expr, signature, callback_type): """Create a native code function from a SymPy expression""" if callback_type is None: jit = LLVMJitCode(signature) else: jit = LLVMJitCodeCallback(signature) jit._create_args(args) jit._create_function_base() jit._create_param_dict(args) strmod = jit._create_function(expr) if False: print("LLVM IR") print(strmod) fptr = jit._compile_function(strmod) return fptr @doctest_depends_on(modules=('llvmlite', 'scipy')) def llvm_callable(args, expr, callback_type=None): '''Compile function from a SymPy expression Expressions are evaluated using double precision arithmetic. Some single argument math functions (exp, sin, cos, etc.) are supported in expressions. Parameters ========== args : List of Symbol Arguments to the generated function. Usually the free symbols in the expression. Currently each one is assumed to convert to a double precision scalar. expr : Expr, or (Replacements, Expr) as returned from 'cse' Expression to compile. callback_type : string Create function with signature appropriate to use as a callback. Currently supported: 'scipy.integrate' 'scipy.integrate.test' 'cubature' Returns ======= Compiled function that can evaluate the expression. Examples ======== >>> import sympy.printing.llvmjitcode as jit >>> from sympy.abc import a >>> e = a*a + a + 1 >>> e1 = jit.llvm_callable([a], e) >>> e.subs(a, 1.1) # Evaluate via substitution 3.31000000000000 >>> e1(1.1) # Evaluate using JIT-compiled code 3.3100000000000005 Callbacks for integration functions can be JIT compiled. >>> import sympy.printing.llvmjitcode as jit >>> from sympy.abc import a >>> from sympy import integrate >>> from scipy.integrate import quad >>> e = a*a >>> e1 = jit.llvm_callable([a], e, callback_type='scipy.integrate') >>> integrate(e, (a, 0.0, 2.0)) 2.66666666666667 >>> quad(e1, 0.0, 2.0)[0] 2.66666666666667 The 'cubature' callback is for the Python wrapper around the cubature package ( https://github.com/saullocastro/cubature ) and ( http://ab-initio.mit.edu/wiki/index.php/Cubature ) There are two signatures for the SciPy integration callbacks. The first ('scipy.integrate') is the function to be passed to the integration routine, and will pass the signature checks. The second ('scipy.integrate.test') is only useful for directly calling the function using ctypes variables. It will not pass the signature checks for scipy.integrate. The return value from the cse module can also be compiled. This can improve the performance of the compiled function. If multiple expressions are given to cse, the compiled function returns a tuple. The 'cubature' callback handles multiple expressions (set `fdim` to match in the integration call.) >>> import sympy.printing.llvmjitcode as jit >>> from sympy import cse >>> from sympy.abc import x,y >>> e1 = x*x + y*y >>> e2 = 4*(x*x + y*y) + 8.0 >>> after_cse = cse([e1,e2]) >>> after_cse ([(x0, x**2), (x1, y**2)], [x0 + x1, 4*x0 + 4*x1 + 8.0]) >>> j1 = jit.llvm_callable([x,y], after_cse) >>> j1(1.0, 2.0) (5.0, 28.0) ''' if not llvmlite: raise ImportError("llvmlite is required for llvmjitcode") signature = CodeSignature(ctypes.py_object) arg_ctypes = [] if callback_type is None: for _ in args: arg_ctype = ctypes.c_double arg_ctypes.append(arg_ctype) elif callback_type in ('scipy.integrate', 'scipy.integrate.test'): signature.ret_type = ctypes.c_double arg_ctypes = [ctypes.c_int, ctypes.POINTER(ctypes.c_double)] arg_ctypes_formal = [ctypes.c_int, ctypes.c_double] signature.input_arg = 1 elif callback_type == 'cubature': arg_ctypes = [ctypes.c_int, ctypes.POINTER(ctypes.c_double), ctypes.c_void_p, ctypes.c_int, ctypes.POINTER(ctypes.c_double) ] signature.ret_type = ctypes.c_int signature.input_arg = 1 signature.ret_arg = 4 else: raise ValueError("Unknown callback type: %s" % callback_type) signature.arg_ctypes = arg_ctypes fptr = _llvm_jit_code(args, expr, signature, callback_type) if callback_type and callback_type == 'scipy.integrate': arg_ctypes = arg_ctypes_formal # PYFUNCTYPE holds the GIL which is needed to prevent a segfault when # calling PyFloat_FromDouble on Python 3.10. Probably it is better to use # ctypes.c_double when returning a float rather than using ctypes.py_object # and returning a PyFloat from inside the jitted function (i.e. let ctypes # handle the conversion from double to PyFloat). if signature.ret_type == ctypes.py_object: FUNCTYPE = ctypes.PYFUNCTYPE else: FUNCTYPE = ctypes.CFUNCTYPE cfunc = FUNCTYPE(signature.ret_type, *arg_ctypes)(fptr) return cfunc
534b127150e35342e1d521723de47c1a9a0e7b7fd7ad7d0f54cb1f177468316b
""" A Printer which converts an expression into its LaTeX equivalent. """ from __future__ import annotations from typing import Any, Callable, TYPE_CHECKING import itertools from sympy.core import Add, Float, Mod, Mul, Number, S, Symbol, Expr from sympy.core.alphabets import greeks from sympy.core.containers import Tuple from sympy.core.function import Function, AppliedUndef, Derivative from sympy.core.operations import AssocOp from sympy.core.power import Pow from sympy.core.sorting import default_sort_key from sympy.core.sympify import SympifyError from sympy.logic.boolalg import true, BooleanTrue, BooleanFalse from sympy.tensor.array import NDimArray # sympy.printing imports from sympy.printing.precedence import precedence_traditional from sympy.printing.printer import Printer, print_function from sympy.printing.conventions import split_super_sub, requires_partial from sympy.printing.precedence import precedence, PRECEDENCE from mpmath.libmp.libmpf import prec_to_dps, to_str as mlib_to_str from sympy.utilities.iterables import has_variety, sift import re if TYPE_CHECKING: from sympy.vector.basisdependent import BasisDependent # Hand-picked functions which can be used directly in both LaTeX and MathJax # Complete list at # https://docs.mathjax.org/en/latest/tex.html#supported-latex-commands # This variable only contains those functions which SymPy uses. accepted_latex_functions = ['arcsin', 'arccos', 'arctan', 'sin', 'cos', 'tan', 'sinh', 'cosh', 'tanh', 'sqrt', 'ln', 'log', 'sec', 'csc', 'cot', 'coth', 're', 'im', 'frac', 'root', 'arg', ] tex_greek_dictionary = { 'Alpha': r'\mathrm{A}', 'Beta': r'\mathrm{B}', 'Gamma': r'\Gamma', 'Delta': r'\Delta', 'Epsilon': r'\mathrm{E}', 'Zeta': r'\mathrm{Z}', 'Eta': r'\mathrm{H}', 'Theta': r'\Theta', 'Iota': r'\mathrm{I}', 'Kappa': r'\mathrm{K}', 'Lambda': r'\Lambda', 'Mu': r'\mathrm{M}', 'Nu': r'\mathrm{N}', 'Xi': r'\Xi', 'omicron': 'o', 'Omicron': r'\mathrm{O}', 'Pi': r'\Pi', 'Rho': r'\mathrm{P}', 'Sigma': r'\Sigma', 'Tau': r'\mathrm{T}', 'Upsilon': r'\Upsilon', 'Phi': r'\Phi', 'Chi': r'\mathrm{X}', 'Psi': r'\Psi', 'Omega': r'\Omega', 'lamda': r'\lambda', 'Lamda': r'\Lambda', 'khi': r'\chi', 'Khi': r'\mathrm{X}', 'varepsilon': r'\varepsilon', 'varkappa': r'\varkappa', 'varphi': r'\varphi', 'varpi': r'\varpi', 'varrho': r'\varrho', 'varsigma': r'\varsigma', 'vartheta': r'\vartheta', } other_symbols = {'aleph', 'beth', 'daleth', 'gimel', 'ell', 'eth', 'hbar', 'hslash', 'mho', 'wp'} # Variable name modifiers modifier_dict: dict[str, Callable[[str], str]] = { # Accents 'mathring': lambda s: r'\mathring{'+s+r'}', 'ddddot': lambda s: r'\ddddot{'+s+r'}', 'dddot': lambda s: r'\dddot{'+s+r'}', 'ddot': lambda s: r'\ddot{'+s+r'}', 'dot': lambda s: r'\dot{'+s+r'}', 'check': lambda s: r'\check{'+s+r'}', 'breve': lambda s: r'\breve{'+s+r'}', 'acute': lambda s: r'\acute{'+s+r'}', 'grave': lambda s: r'\grave{'+s+r'}', 'tilde': lambda s: r'\tilde{'+s+r'}', 'hat': lambda s: r'\hat{'+s+r'}', 'bar': lambda s: r'\bar{'+s+r'}', 'vec': lambda s: r'\vec{'+s+r'}', 'prime': lambda s: "{"+s+"}'", 'prm': lambda s: "{"+s+"}'", # Faces 'bold': lambda s: r'\boldsymbol{'+s+r'}', 'bm': lambda s: r'\boldsymbol{'+s+r'}', 'cal': lambda s: r'\mathcal{'+s+r'}', 'scr': lambda s: r'\mathscr{'+s+r'}', 'frak': lambda s: r'\mathfrak{'+s+r'}', # Brackets 'norm': lambda s: r'\left\|{'+s+r'}\right\|', 'avg': lambda s: r'\left\langle{'+s+r'}\right\rangle', 'abs': lambda s: r'\left|{'+s+r'}\right|', 'mag': lambda s: r'\left|{'+s+r'}\right|', } greek_letters_set = frozenset(greeks) _between_two_numbers_p = ( re.compile(r'[0-9][} ]*$'), # search re.compile(r'[0-9]'), # match ) def latex_escape(s: str) -> str: """ Escape a string such that latex interprets it as plaintext. We cannot use verbatim easily with mathjax, so escaping is easier. Rules from https://tex.stackexchange.com/a/34586/41112. """ s = s.replace('\\', r'\textbackslash') for c in '&%$#_{}': s = s.replace(c, '\\' + c) s = s.replace('~', r'\textasciitilde') s = s.replace('^', r'\textasciicircum') return s class LatexPrinter(Printer): printmethod = "_latex" _default_settings: dict[str, Any] = { "full_prec": False, "fold_frac_powers": False, "fold_func_brackets": False, "fold_short_frac": None, "inv_trig_style": "abbreviated", "itex": False, "ln_notation": False, "long_frac_ratio": None, "mat_delim": "[", "mat_str": None, "mode": "plain", "mul_symbol": None, "order": None, "symbol_names": {}, "root_notation": True, "mat_symbol_style": "plain", "imaginary_unit": "i", "gothic_re_im": False, "decimal_separator": "period", "perm_cyclic": True, "parenthesize_super": True, "min": None, "max": None, "diff_operator": "d", } def __init__(self, settings=None): Printer.__init__(self, settings) if 'mode' in self._settings: valid_modes = ['inline', 'plain', 'equation', 'equation*'] if self._settings['mode'] not in valid_modes: raise ValueError("'mode' must be one of 'inline', 'plain', " "'equation' or 'equation*'") if self._settings['fold_short_frac'] is None and \ self._settings['mode'] == 'inline': self._settings['fold_short_frac'] = True mul_symbol_table = { None: r" ", "ldot": r" \,.\, ", "dot": r" \cdot ", "times": r" \times " } try: self._settings['mul_symbol_latex'] = \ mul_symbol_table[self._settings['mul_symbol']] except KeyError: self._settings['mul_symbol_latex'] = \ self._settings['mul_symbol'] try: self._settings['mul_symbol_latex_numbers'] = \ mul_symbol_table[self._settings['mul_symbol'] or 'dot'] except KeyError: if (self._settings['mul_symbol'].strip() in ['', ' ', '\\', '\\,', '\\:', '\\;', '\\quad']): self._settings['mul_symbol_latex_numbers'] = \ mul_symbol_table['dot'] else: self._settings['mul_symbol_latex_numbers'] = \ self._settings['mul_symbol'] self._delim_dict = {'(': ')', '[': ']'} imaginary_unit_table = { None: r"i", "i": r"i", "ri": r"\mathrm{i}", "ti": r"\text{i}", "j": r"j", "rj": r"\mathrm{j}", "tj": r"\text{j}", } imag_unit = self._settings['imaginary_unit'] self._settings['imaginary_unit_latex'] = imaginary_unit_table.get(imag_unit, imag_unit) diff_operator_table = { None: r"d", "d": r"d", "rd": r"\mathrm{d}", "td": r"\text{d}", } diff_operator = self._settings['diff_operator'] self._settings["diff_operator_latex"] = diff_operator_table.get(diff_operator, diff_operator) def _add_parens(self, s) -> str: return r"\left({}\right)".format(s) # TODO: merge this with the above, which requires a lot of test changes def _add_parens_lspace(self, s) -> str: return r"\left( {}\right)".format(s) def parenthesize(self, item, level, is_neg=False, strict=False) -> str: prec_val = precedence_traditional(item) if is_neg and strict: return self._add_parens(self._print(item)) if (prec_val < level) or ((not strict) and prec_val <= level): return self._add_parens(self._print(item)) else: return self._print(item) def parenthesize_super(self, s): """ Protect superscripts in s If the parenthesize_super option is set, protect with parentheses, else wrap in braces. """ if "^" in s: if self._settings['parenthesize_super']: return self._add_parens(s) else: return "{{{}}}".format(s) return s def doprint(self, expr) -> str: tex = Printer.doprint(self, expr) if self._settings['mode'] == 'plain': return tex elif self._settings['mode'] == 'inline': return r"$%s$" % tex elif self._settings['itex']: return r"$$%s$$" % tex else: env_str = self._settings['mode'] return r"\begin{%s}%s\end{%s}" % (env_str, tex, env_str) def _needs_brackets(self, expr) -> bool: """ Returns True if the expression needs to be wrapped in brackets when printed, False otherwise. For example: a + b => True; a => False; 10 => False; -10 => True. """ return not ((expr.is_Integer and expr.is_nonnegative) or (expr.is_Atom and (expr is not S.NegativeOne and expr.is_Rational is False))) def _needs_function_brackets(self, expr) -> bool: """ Returns True if the expression needs to be wrapped in brackets when passed as an argument to a function, False otherwise. This is a more liberal version of _needs_brackets, in that many expressions which need to be wrapped in brackets when added/subtracted/raised to a power do not need them when passed to a function. Such an example is a*b. """ if not self._needs_brackets(expr): return False else: # Muls of the form a*b*c... can be folded if expr.is_Mul and not self._mul_is_clean(expr): return True # Pows which don't need brackets can be folded elif expr.is_Pow and not self._pow_is_clean(expr): return True # Add and Function always need brackets elif expr.is_Add or expr.is_Function: return True else: return False def _needs_mul_brackets(self, expr, first=False, last=False) -> bool: """ Returns True if the expression needs to be wrapped in brackets when printed as part of a Mul, False otherwise. This is True for Add, but also for some container objects that would not need brackets when appearing last in a Mul, e.g. an Integral. ``last=True`` specifies that this expr is the last to appear in a Mul. ``first=True`` specifies that this expr is the first to appear in a Mul. """ from sympy.concrete.products import Product from sympy.concrete.summations import Sum from sympy.integrals.integrals import Integral if expr.is_Mul: if not first and expr.could_extract_minus_sign(): return True elif precedence_traditional(expr) < PRECEDENCE["Mul"]: return True elif expr.is_Relational: return True if expr.is_Piecewise: return True if any(expr.has(x) for x in (Mod,)): return True if (not last and any(expr.has(x) for x in (Integral, Product, Sum))): return True return False def _needs_add_brackets(self, expr) -> bool: """ Returns True if the expression needs to be wrapped in brackets when printed as part of an Add, False otherwise. This is False for most things. """ if expr.is_Relational: return True if any(expr.has(x) for x in (Mod,)): return True if expr.is_Add: return True return False def _mul_is_clean(self, expr) -> bool: for arg in expr.args: if arg.is_Function: return False return True def _pow_is_clean(self, expr) -> bool: return not self._needs_brackets(expr.base) def _do_exponent(self, expr: str, exp): if exp is not None: return r"\left(%s\right)^{%s}" % (expr, exp) else: return expr def _print_Basic(self, expr): name = self._deal_with_super_sub(expr.__class__.__name__) if expr.args: ls = [self._print(o) for o in expr.args] s = r"\operatorname{{{}}}\left({}\right)" return s.format(name, ", ".join(ls)) else: return r"\text{{{}}}".format(name) def _print_bool(self, e: bool | BooleanTrue | BooleanFalse): return r"\text{%s}" % e _print_BooleanTrue = _print_bool _print_BooleanFalse = _print_bool def _print_NoneType(self, e): return r"\text{%s}" % e def _print_Add(self, expr, order=None): terms = self._as_ordered_terms(expr, order=order) tex = "" for i, term in enumerate(terms): if i == 0: pass elif term.could_extract_minus_sign(): tex += " - " term = -term else: tex += " + " term_tex = self._print(term) if self._needs_add_brackets(term): term_tex = r"\left(%s\right)" % term_tex tex += term_tex return tex def _print_Cycle(self, expr): from sympy.combinatorics.permutations import Permutation if expr.size == 0: return r"\left( \right)" expr = Permutation(expr) expr_perm = expr.cyclic_form siz = expr.size if expr.array_form[-1] == siz - 1: expr_perm = expr_perm + [[siz - 1]] term_tex = '' for i in expr_perm: term_tex += str(i).replace(',', r"\;") term_tex = term_tex.replace('[', r"\left( ") term_tex = term_tex.replace(']', r"\right)") return term_tex def _print_Permutation(self, expr): from sympy.combinatorics.permutations import Permutation from sympy.utilities.exceptions import sympy_deprecation_warning perm_cyclic = Permutation.print_cyclic if perm_cyclic is not None: sympy_deprecation_warning( f""" Setting Permutation.print_cyclic is deprecated. Instead use init_printing(perm_cyclic={perm_cyclic}). """, deprecated_since_version="1.6", active_deprecations_target="deprecated-permutation-print_cyclic", stacklevel=8, ) else: perm_cyclic = self._settings.get("perm_cyclic", True) if perm_cyclic: return self._print_Cycle(expr) if expr.size == 0: return r"\left( \right)" lower = [self._print(arg) for arg in expr.array_form] upper = [self._print(arg) for arg in range(len(lower))] row1 = " & ".join(upper) row2 = " & ".join(lower) mat = r" \\ ".join((row1, row2)) return r"\begin{pmatrix} %s \end{pmatrix}" % mat def _print_AppliedPermutation(self, expr): perm, var = expr.args return r"\sigma_{%s}(%s)" % (self._print(perm), self._print(var)) def _print_Float(self, expr): # Based off of that in StrPrinter dps = prec_to_dps(expr._prec) strip = False if self._settings['full_prec'] else True low = self._settings["min"] if "min" in self._settings else None high = self._settings["max"] if "max" in self._settings else None str_real = mlib_to_str(expr._mpf_, dps, strip_zeros=strip, min_fixed=low, max_fixed=high) # Must always have a mul symbol (as 2.5 10^{20} just looks odd) # thus we use the number separator separator = self._settings['mul_symbol_latex_numbers'] if 'e' in str_real: (mant, exp) = str_real.split('e') if exp[0] == '+': exp = exp[1:] if self._settings['decimal_separator'] == 'comma': mant = mant.replace('.','{,}') return r"%s%s10^{%s}" % (mant, separator, exp) elif str_real == "+inf": return r"\infty" elif str_real == "-inf": return r"- \infty" else: if self._settings['decimal_separator'] == 'comma': str_real = str_real.replace('.','{,}') return str_real def _print_Cross(self, expr): vec1 = expr._expr1 vec2 = expr._expr2 return r"%s \times %s" % (self.parenthesize(vec1, PRECEDENCE['Mul']), self.parenthesize(vec2, PRECEDENCE['Mul'])) def _print_Curl(self, expr): vec = expr._expr return r"\nabla\times %s" % self.parenthesize(vec, PRECEDENCE['Mul']) def _print_Divergence(self, expr): vec = expr._expr return r"\nabla\cdot %s" % self.parenthesize(vec, PRECEDENCE['Mul']) def _print_Dot(self, expr): vec1 = expr._expr1 vec2 = expr._expr2 return r"%s \cdot %s" % (self.parenthesize(vec1, PRECEDENCE['Mul']), self.parenthesize(vec2, PRECEDENCE['Mul'])) def _print_Gradient(self, expr): func = expr._expr return r"\nabla %s" % self.parenthesize(func, PRECEDENCE['Mul']) def _print_Laplacian(self, expr): func = expr._expr return r"\Delta %s" % self.parenthesize(func, PRECEDENCE['Mul']) def _print_Mul(self, expr: Expr): from sympy.physics.units import Quantity from sympy.physics.units.prefixes import Prefix from sympy.simplify import fraction separator: str = self._settings['mul_symbol_latex'] numbersep: str = self._settings['mul_symbol_latex_numbers'] def convert(expr) -> str: if not expr.is_Mul: return str(self._print(expr)) else: if self.order not in ('old', 'none'): args = expr.as_ordered_factors() else: args = list(expr.args) # If quantities are present append them at the back units, nonunits = sift(args, lambda x: isinstance(x, (Quantity, Prefix)) or (isinstance(x, Pow) and isinstance(x.base, Quantity)), binary=True) prefixes, units = sift(units, lambda x: isinstance(x, Prefix), binary=True) return convert_args(nonunits + prefixes + units) def convert_args(args) -> str: _tex = last_term_tex = "" for i, term in enumerate(args): term_tex = self._print(term) if not isinstance(term, (Quantity, Prefix)): if self._needs_mul_brackets(term, first=(i == 0), last=(i == len(args) - 1)): term_tex = r"\left(%s\right)" % term_tex if _between_two_numbers_p[0].search(last_term_tex) and \ _between_two_numbers_p[1].match(str(term)): # between two numbers _tex += numbersep elif _tex: _tex += separator elif _tex: _tex += separator _tex += term_tex last_term_tex = term_tex return _tex # Check for unevaluated Mul. In this case we need to make sure the # identities are visible, multiple Rational factors are not combined # etc so we display in a straight-forward form that fully preserves all # args and their order. # XXX: _print_Pow calls this routine with instances of Pow... if isinstance(expr, Mul): args = expr.args if args[0] is S.One or any(isinstance(arg, Number) for arg in args[1:]): return convert_args(args) include_parens = False if expr.could_extract_minus_sign(): expr = -expr tex = "- " if expr.is_Add: tex += "(" include_parens = True else: tex = "" numer, denom = fraction(expr, exact=True) if denom is S.One and Pow(1, -1, evaluate=False) not in expr.args: # use the original expression here, since fraction() may have # altered it when producing numer and denom tex += convert(expr) else: snumer = convert(numer) sdenom = convert(denom) ldenom = len(sdenom.split()) ratio = self._settings['long_frac_ratio'] if self._settings['fold_short_frac'] and ldenom <= 2 and \ "^" not in sdenom: # handle short fractions if self._needs_mul_brackets(numer, last=False): tex += r"\left(%s\right) / %s" % (snumer, sdenom) else: tex += r"%s / %s" % (snumer, sdenom) elif ratio is not None and \ len(snumer.split()) > ratio*ldenom: # handle long fractions if self._needs_mul_brackets(numer, last=True): tex += r"\frac{1}{%s}%s\left(%s\right)" \ % (sdenom, separator, snumer) elif numer.is_Mul: # split a long numerator a = S.One b = S.One for x in numer.args: if self._needs_mul_brackets(x, last=False) or \ len(convert(a*x).split()) > ratio*ldenom or \ (b.is_commutative is x.is_commutative is False): b *= x else: a *= x if self._needs_mul_brackets(b, last=True): tex += r"\frac{%s}{%s}%s\left(%s\right)" \ % (convert(a), sdenom, separator, convert(b)) else: tex += r"\frac{%s}{%s}%s%s" \ % (convert(a), sdenom, separator, convert(b)) else: tex += r"\frac{1}{%s}%s%s" % (sdenom, separator, snumer) else: tex += r"\frac{%s}{%s}" % (snumer, sdenom) if include_parens: tex += ")" return tex def _print_AlgebraicNumber(self, expr): if expr.is_aliased: return self._print(expr.as_poly().as_expr()) else: return self._print(expr.as_expr()) def _print_PrimeIdeal(self, expr): p = self._print(expr.p) if expr.is_inert: return rf'\left({p}\right)' alpha = self._print(expr.alpha.as_expr()) return rf'\left({p}, {alpha}\right)' def _print_Pow(self, expr: Pow): # Treat x**Rational(1,n) as special case if expr.exp.is_Rational: p: int = expr.exp.p # type: ignore q: int = expr.exp.q # type: ignore if abs(p) == 1 and q != 1 and self._settings['root_notation']: base = self._print(expr.base) if q == 2: tex = r"\sqrt{%s}" % base elif self._settings['itex']: tex = r"\root{%d}{%s}" % (q, base) else: tex = r"\sqrt[%d]{%s}" % (q, base) if expr.exp.is_negative: return r"\frac{1}{%s}" % tex else: return tex elif self._settings['fold_frac_powers'] and q != 1: base = self.parenthesize(expr.base, PRECEDENCE['Pow']) # issue #12886: add parentheses for superscripts raised to powers if expr.base.is_Symbol: base = self.parenthesize_super(base) if expr.base.is_Function: return self._print(expr.base, exp="%s/%s" % (p, q)) return r"%s^{%s/%s}" % (base, p, q) elif expr.exp.is_negative and expr.base.is_commutative: # special case for 1^(-x), issue 9216 if expr.base == 1: return r"%s^{%s}" % (expr.base, expr.exp) # special case for (1/x)^(-y) and (-1/-x)^(-y), issue 20252 if expr.base.is_Rational: base_p: int = expr.base.p # type: ignore base_q: int = expr.base.q # type: ignore if base_p * base_q == abs(base_q): if expr.exp == -1: return r"\frac{1}{\frac{%s}{%s}}" % (base_p, base_q) else: return r"\frac{1}{(\frac{%s}{%s})^{%s}}" % (base_p, base_q, abs(expr.exp)) # things like 1/x return self._print_Mul(expr) if expr.base.is_Function: return self._print(expr.base, exp=self._print(expr.exp)) tex = r"%s^{%s}" return self._helper_print_standard_power(expr, tex) def _helper_print_standard_power(self, expr, template: str) -> str: exp = self._print(expr.exp) # issue #12886: add parentheses around superscripts raised # to powers base = self.parenthesize(expr.base, PRECEDENCE['Pow']) if expr.base.is_Symbol: base = self.parenthesize_super(base) elif (isinstance(expr.base, Derivative) and base.startswith(r'\left(') and re.match(r'\\left\(\\d?d?dot', base) and base.endswith(r'\right)')): # don't use parentheses around dotted derivative base = base[6: -7] # remove outermost added parens return template % (base, exp) def _print_UnevaluatedExpr(self, expr): return self._print(expr.args[0]) def _print_Sum(self, expr): if len(expr.limits) == 1: tex = r"\sum_{%s=%s}^{%s} " % \ tuple([self._print(i) for i in expr.limits[0]]) else: def _format_ineq(l): return r"%s \leq %s \leq %s" % \ tuple([self._print(s) for s in (l[1], l[0], l[2])]) tex = r"\sum_{\substack{%s}} " % \ str.join('\\\\', [_format_ineq(l) for l in expr.limits]) if isinstance(expr.function, Add): tex += r"\left(%s\right)" % self._print(expr.function) else: tex += self._print(expr.function) return tex def _print_Product(self, expr): if len(expr.limits) == 1: tex = r"\prod_{%s=%s}^{%s} " % \ tuple([self._print(i) for i in expr.limits[0]]) else: def _format_ineq(l): return r"%s \leq %s \leq %s" % \ tuple([self._print(s) for s in (l[1], l[0], l[2])]) tex = r"\prod_{\substack{%s}} " % \ str.join('\\\\', [_format_ineq(l) for l in expr.limits]) if isinstance(expr.function, Add): tex += r"\left(%s\right)" % self._print(expr.function) else: tex += self._print(expr.function) return tex def _print_BasisDependent(self, expr: 'BasisDependent'): from sympy.vector import Vector o1: list[str] = [] if expr == expr.zero: return expr.zero._latex_form if isinstance(expr, Vector): items = expr.separate().items() else: items = [(0, expr)] for system, vect in items: inneritems = list(vect.components.items()) inneritems.sort(key=lambda x: x[0].__str__()) for k, v in inneritems: if v == 1: o1.append(' + ' + k._latex_form) elif v == -1: o1.append(' - ' + k._latex_form) else: arg_str = r'\left(' + self._print(v) + r'\right)' o1.append(' + ' + arg_str + k._latex_form) outstr = (''.join(o1)) if outstr[1] != '-': outstr = outstr[3:] else: outstr = outstr[1:] return outstr def _print_Indexed(self, expr): tex_base = self._print(expr.base) tex = '{'+tex_base+'}'+'_{%s}' % ','.join( map(self._print, expr.indices)) return tex def _print_IndexedBase(self, expr): return self._print(expr.label) def _print_Idx(self, expr): label = self._print(expr.label) if expr.upper is not None: upper = self._print(expr.upper) if expr.lower is not None: lower = self._print(expr.lower) else: lower = self._print(S.Zero) interval = '{lower}\\mathrel{{..}}\\nobreak {upper}'.format( lower = lower, upper = upper) return '{{{label}}}_{{{interval}}}'.format( label = label, interval = interval) #if no bounds are defined this just prints the label return label def _print_Derivative(self, expr): if requires_partial(expr.expr): diff_symbol = r'\partial' else: diff_symbol = self._settings["diff_operator_latex"] tex = "" dim = 0 for x, num in reversed(expr.variable_count): dim += num if num == 1: tex += r"%s %s" % (diff_symbol, self._print(x)) else: tex += r"%s %s^{%s}" % (diff_symbol, self.parenthesize_super(self._print(x)), self._print(num)) if dim == 1: tex = r"\frac{%s}{%s}" % (diff_symbol, tex) else: tex = r"\frac{%s^{%s}}{%s}" % (diff_symbol, self._print(dim), tex) if any(i.could_extract_minus_sign() for i in expr.args): return r"%s %s" % (tex, self.parenthesize(expr.expr, PRECEDENCE["Mul"], is_neg=True, strict=True)) return r"%s %s" % (tex, self.parenthesize(expr.expr, PRECEDENCE["Mul"], is_neg=False, strict=True)) def _print_Subs(self, subs): expr, old, new = subs.args latex_expr = self._print(expr) latex_old = (self._print(e) for e in old) latex_new = (self._print(e) for e in new) latex_subs = r'\\ '.join( e[0] + '=' + e[1] for e in zip(latex_old, latex_new)) return r'\left. %s \right|_{\substack{ %s }}' % (latex_expr, latex_subs) def _print_Integral(self, expr): tex, symbols = "", [] diff_symbol = self._settings["diff_operator_latex"] # Only up to \iiiint exists if len(expr.limits) <= 4 and all(len(lim) == 1 for lim in expr.limits): # Use len(expr.limits)-1 so that syntax highlighters don't think # \" is an escaped quote tex = r"\i" + "i"*(len(expr.limits) - 1) + "nt" symbols = [r"\, %s%s" % (diff_symbol, self._print(symbol[0])) for symbol in expr.limits] else: for lim in reversed(expr.limits): symbol = lim[0] tex += r"\int" if len(lim) > 1: if self._settings['mode'] != 'inline' \ and not self._settings['itex']: tex += r"\limits" if len(lim) == 3: tex += "_{%s}^{%s}" % (self._print(lim[1]), self._print(lim[2])) if len(lim) == 2: tex += "^{%s}" % (self._print(lim[1])) symbols.insert(0, r"\, %s%s" % (diff_symbol, self._print(symbol))) return r"%s %s%s" % (tex, self.parenthesize(expr.function, PRECEDENCE["Mul"], is_neg=any(i.could_extract_minus_sign() for i in expr.args), strict=True), "".join(symbols)) def _print_Limit(self, expr): e, z, z0, dir = expr.args tex = r"\lim_{%s \to " % self._print(z) if str(dir) == '+-' or z0 in (S.Infinity, S.NegativeInfinity): tex += r"%s}" % self._print(z0) else: tex += r"%s^%s}" % (self._print(z0), self._print(dir)) if isinstance(e, AssocOp): return r"%s\left(%s\right)" % (tex, self._print(e)) else: return r"%s %s" % (tex, self._print(e)) def _hprint_Function(self, func: str) -> str: r''' Logic to decide how to render a function to latex - if it is a recognized latex name, use the appropriate latex command - if it is a single letter, excluding sub- and superscripts, just use that letter - if it is a longer name, then put \operatorname{} around it and be mindful of undercores in the name ''' func = self._deal_with_super_sub(func) superscriptidx = func.find("^") subscriptidx = func.find("_") if func in accepted_latex_functions: name = r"\%s" % func elif len(func) == 1 or func.startswith('\\') or subscriptidx == 1 or superscriptidx == 1: name = func else: if superscriptidx > 0 and subscriptidx > 0: name = r"\operatorname{%s}%s" %( func[:min(subscriptidx,superscriptidx)], func[min(subscriptidx,superscriptidx):]) elif superscriptidx > 0: name = r"\operatorname{%s}%s" %( func[:superscriptidx], func[superscriptidx:]) elif subscriptidx > 0: name = r"\operatorname{%s}%s" %( func[:subscriptidx], func[subscriptidx:]) else: name = r"\operatorname{%s}" % func return name def _print_Function(self, expr: Function, exp=None) -> str: r''' Render functions to LaTeX, handling functions that LaTeX knows about e.g., sin, cos, ... by using the proper LaTeX command (\sin, \cos, ...). For single-letter function names, render them as regular LaTeX math symbols. For multi-letter function names that LaTeX does not know about, (e.g., Li, sech) use \operatorname{} so that the function name is rendered in Roman font and LaTeX handles spacing properly. expr is the expression involving the function exp is an exponent ''' func = expr.func.__name__ if hasattr(self, '_print_' + func) and \ not isinstance(expr, AppliedUndef): return getattr(self, '_print_' + func)(expr, exp) else: args = [str(self._print(arg)) for arg in expr.args] # How inverse trig functions should be displayed, formats are: # abbreviated: asin, full: arcsin, power: sin^-1 inv_trig_style = self._settings['inv_trig_style'] # If we are dealing with a power-style inverse trig function inv_trig_power_case = False # If it is applicable to fold the argument brackets can_fold_brackets = self._settings['fold_func_brackets'] and \ len(args) == 1 and \ not self._needs_function_brackets(expr.args[0]) inv_trig_table = [ "asin", "acos", "atan", "acsc", "asec", "acot", "asinh", "acosh", "atanh", "acsch", "asech", "acoth", ] # If the function is an inverse trig function, handle the style if func in inv_trig_table: if inv_trig_style == "abbreviated": pass elif inv_trig_style == "full": func = ("ar" if func[-1] == "h" else "arc") + func[1:] elif inv_trig_style == "power": func = func[1:] inv_trig_power_case = True # Can never fold brackets if we're raised to a power if exp is not None: can_fold_brackets = False if inv_trig_power_case: if func in accepted_latex_functions: name = r"\%s^{-1}" % func else: name = r"\operatorname{%s}^{-1}" % func elif exp is not None: func_tex = self._hprint_Function(func) func_tex = self.parenthesize_super(func_tex) name = r'%s^{%s}' % (func_tex, exp) else: name = self._hprint_Function(func) if can_fold_brackets: if func in accepted_latex_functions: # Wrap argument safely to avoid parse-time conflicts # with the function name itself name += r" {%s}" else: name += r"%s" else: name += r"{\left(%s \right)}" if inv_trig_power_case and exp is not None: name += r"^{%s}" % exp return name % ",".join(args) def _print_UndefinedFunction(self, expr): return self._hprint_Function(str(expr)) def _print_ElementwiseApplyFunction(self, expr): return r"{%s}_{\circ}\left({%s}\right)" % ( self._print(expr.function), self._print(expr.expr), ) @property def _special_function_classes(self): from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.functions.special.gamma_functions import gamma, lowergamma from sympy.functions.special.beta_functions import beta from sympy.functions.special.delta_functions import DiracDelta from sympy.functions.special.error_functions import Chi return {KroneckerDelta: r'\delta', gamma: r'\Gamma', lowergamma: r'\gamma', beta: r'\operatorname{B}', DiracDelta: r'\delta', Chi: r'\operatorname{Chi}'} def _print_FunctionClass(self, expr): for cls in self._special_function_classes: if issubclass(expr, cls) and expr.__name__ == cls.__name__: return self._special_function_classes[cls] return self._hprint_Function(str(expr)) def _print_Lambda(self, expr): symbols, expr = expr.args if len(symbols) == 1: symbols = self._print(symbols[0]) else: symbols = self._print(tuple(symbols)) tex = r"\left( %s \mapsto %s \right)" % (symbols, self._print(expr)) return tex def _print_IdentityFunction(self, expr): return r"\left( x \mapsto x \right)" def _hprint_variadic_function(self, expr, exp=None) -> str: args = sorted(expr.args, key=default_sort_key) texargs = [r"%s" % self._print(symbol) for symbol in args] tex = r"\%s\left(%s\right)" % (str(expr.func).lower(), ", ".join(texargs)) if exp is not None: return r"%s^{%s}" % (tex, exp) else: return tex _print_Min = _print_Max = _hprint_variadic_function def _print_floor(self, expr, exp=None): tex = r"\left\lfloor{%s}\right\rfloor" % self._print(expr.args[0]) if exp is not None: return r"%s^{%s}" % (tex, exp) else: return tex def _print_ceiling(self, expr, exp=None): tex = r"\left\lceil{%s}\right\rceil" % self._print(expr.args[0]) if exp is not None: return r"%s^{%s}" % (tex, exp) else: return tex def _print_log(self, expr, exp=None): if not self._settings["ln_notation"]: tex = r"\log{\left(%s \right)}" % self._print(expr.args[0]) else: tex = r"\ln{\left(%s \right)}" % self._print(expr.args[0]) if exp is not None: return r"%s^{%s}" % (tex, exp) else: return tex def _print_Abs(self, expr, exp=None): tex = r"\left|{%s}\right|" % self._print(expr.args[0]) if exp is not None: return r"%s^{%s}" % (tex, exp) else: return tex def _print_re(self, expr, exp=None): if self._settings['gothic_re_im']: tex = r"\Re{%s}" % self.parenthesize(expr.args[0], PRECEDENCE['Atom']) else: tex = r"\operatorname{{re}}{{{}}}".format(self.parenthesize(expr.args[0], PRECEDENCE['Atom'])) return self._do_exponent(tex, exp) def _print_im(self, expr, exp=None): if self._settings['gothic_re_im']: tex = r"\Im{%s}" % self.parenthesize(expr.args[0], PRECEDENCE['Atom']) else: tex = r"\operatorname{{im}}{{{}}}".format(self.parenthesize(expr.args[0], PRECEDENCE['Atom'])) return self._do_exponent(tex, exp) def _print_Not(self, e): from sympy.logic.boolalg import (Equivalent, Implies) if isinstance(e.args[0], Equivalent): return self._print_Equivalent(e.args[0], r"\not\Leftrightarrow") if isinstance(e.args[0], Implies): return self._print_Implies(e.args[0], r"\not\Rightarrow") if (e.args[0].is_Boolean): return r"\neg \left(%s\right)" % self._print(e.args[0]) else: return r"\neg %s" % self._print(e.args[0]) def _print_LogOp(self, args, char): arg = args[0] if arg.is_Boolean and not arg.is_Not: tex = r"\left(%s\right)" % self._print(arg) else: tex = r"%s" % self._print(arg) for arg in args[1:]: if arg.is_Boolean and not arg.is_Not: tex += r" %s \left(%s\right)" % (char, self._print(arg)) else: tex += r" %s %s" % (char, self._print(arg)) return tex def _print_And(self, e): args = sorted(e.args, key=default_sort_key) return self._print_LogOp(args, r"\wedge") def _print_Or(self, e): args = sorted(e.args, key=default_sort_key) return self._print_LogOp(args, r"\vee") def _print_Xor(self, e): args = sorted(e.args, key=default_sort_key) return self._print_LogOp(args, r"\veebar") def _print_Implies(self, e, altchar=None): return self._print_LogOp(e.args, altchar or r"\Rightarrow") def _print_Equivalent(self, e, altchar=None): args = sorted(e.args, key=default_sort_key) return self._print_LogOp(args, altchar or r"\Leftrightarrow") def _print_conjugate(self, expr, exp=None): tex = r"\overline{%s}" % self._print(expr.args[0]) if exp is not None: return r"%s^{%s}" % (tex, exp) else: return tex def _print_polar_lift(self, expr, exp=None): func = r"\operatorname{polar\_lift}" arg = r"{\left(%s \right)}" % self._print(expr.args[0]) if exp is not None: return r"%s^{%s}%s" % (func, exp, arg) else: return r"%s%s" % (func, arg) def _print_ExpBase(self, expr, exp=None): # TODO should exp_polar be printed differently? # what about exp_polar(0), exp_polar(1)? tex = r"e^{%s}" % self._print(expr.args[0]) return self._do_exponent(tex, exp) def _print_Exp1(self, expr, exp=None): return "e" def _print_elliptic_k(self, expr, exp=None): tex = r"\left(%s\right)" % self._print(expr.args[0]) if exp is not None: return r"K^{%s}%s" % (exp, tex) else: return r"K%s" % tex def _print_elliptic_f(self, expr, exp=None): tex = r"\left(%s\middle| %s\right)" % \ (self._print(expr.args[0]), self._print(expr.args[1])) if exp is not None: return r"F^{%s}%s" % (exp, tex) else: return r"F%s" % tex def _print_elliptic_e(self, expr, exp=None): if len(expr.args) == 2: tex = r"\left(%s\middle| %s\right)" % \ (self._print(expr.args[0]), self._print(expr.args[1])) else: tex = r"\left(%s\right)" % self._print(expr.args[0]) if exp is not None: return r"E^{%s}%s" % (exp, tex) else: return r"E%s" % tex def _print_elliptic_pi(self, expr, exp=None): if len(expr.args) == 3: tex = r"\left(%s; %s\middle| %s\right)" % \ (self._print(expr.args[0]), self._print(expr.args[1]), self._print(expr.args[2])) else: tex = r"\left(%s\middle| %s\right)" % \ (self._print(expr.args[0]), self._print(expr.args[1])) if exp is not None: return r"\Pi^{%s}%s" % (exp, tex) else: return r"\Pi%s" % tex def _print_beta(self, expr, exp=None): tex = r"\left(%s, %s\right)" % (self._print(expr.args[0]), self._print(expr.args[1])) if exp is not None: return r"\operatorname{B}^{%s}%s" % (exp, tex) else: return r"\operatorname{B}%s" % tex def _print_betainc(self, expr, exp=None, operator='B'): largs = [self._print(arg) for arg in expr.args] tex = r"\left(%s, %s\right)" % (largs[0], largs[1]) if exp is not None: return r"\operatorname{%s}_{(%s, %s)}^{%s}%s" % (operator, largs[2], largs[3], exp, tex) else: return r"\operatorname{%s}_{(%s, %s)}%s" % (operator, largs[2], largs[3], tex) def _print_betainc_regularized(self, expr, exp=None): return self._print_betainc(expr, exp, operator='I') def _print_uppergamma(self, expr, exp=None): tex = r"\left(%s, %s\right)" % (self._print(expr.args[0]), self._print(expr.args[1])) if exp is not None: return r"\Gamma^{%s}%s" % (exp, tex) else: return r"\Gamma%s" % tex def _print_lowergamma(self, expr, exp=None): tex = r"\left(%s, %s\right)" % (self._print(expr.args[0]), self._print(expr.args[1])) if exp is not None: return r"\gamma^{%s}%s" % (exp, tex) else: return r"\gamma%s" % tex def _hprint_one_arg_func(self, expr, exp=None) -> str: tex = r"\left(%s\right)" % self._print(expr.args[0]) if exp is not None: return r"%s^{%s}%s" % (self._print(expr.func), exp, tex) else: return r"%s%s" % (self._print(expr.func), tex) _print_gamma = _hprint_one_arg_func def _print_Chi(self, expr, exp=None): tex = r"\left(%s\right)" % self._print(expr.args[0]) if exp is not None: return r"\operatorname{Chi}^{%s}%s" % (exp, tex) else: return r"\operatorname{Chi}%s" % tex def _print_expint(self, expr, exp=None): tex = r"\left(%s\right)" % self._print(expr.args[1]) nu = self._print(expr.args[0]) if exp is not None: return r"\operatorname{E}_{%s}^{%s}%s" % (nu, exp, tex) else: return r"\operatorname{E}_{%s}%s" % (nu, tex) def _print_fresnels(self, expr, exp=None): tex = r"\left(%s\right)" % self._print(expr.args[0]) if exp is not None: return r"S^{%s}%s" % (exp, tex) else: return r"S%s" % tex def _print_fresnelc(self, expr, exp=None): tex = r"\left(%s\right)" % self._print(expr.args[0]) if exp is not None: return r"C^{%s}%s" % (exp, tex) else: return r"C%s" % tex def _print_subfactorial(self, expr, exp=None): tex = r"!%s" % self.parenthesize(expr.args[0], PRECEDENCE["Func"]) if exp is not None: return r"\left(%s\right)^{%s}" % (tex, exp) else: return tex def _print_factorial(self, expr, exp=None): tex = r"%s!" % self.parenthesize(expr.args[0], PRECEDENCE["Func"]) if exp is not None: return r"%s^{%s}" % (tex, exp) else: return tex def _print_factorial2(self, expr, exp=None): tex = r"%s!!" % self.parenthesize(expr.args[0], PRECEDENCE["Func"]) if exp is not None: return r"%s^{%s}" % (tex, exp) else: return tex def _print_binomial(self, expr, exp=None): tex = r"{\binom{%s}{%s}}" % (self._print(expr.args[0]), self._print(expr.args[1])) if exp is not None: return r"%s^{%s}" % (tex, exp) else: return tex def _print_RisingFactorial(self, expr, exp=None): n, k = expr.args base = r"%s" % self.parenthesize(n, PRECEDENCE['Func']) tex = r"{%s}^{\left(%s\right)}" % (base, self._print(k)) return self._do_exponent(tex, exp) def _print_FallingFactorial(self, expr, exp=None): n, k = expr.args sub = r"%s" % self.parenthesize(k, PRECEDENCE['Func']) tex = r"{\left(%s\right)}_{%s}" % (self._print(n), sub) return self._do_exponent(tex, exp) def _hprint_BesselBase(self, expr, exp, sym: str) -> str: tex = r"%s" % (sym) need_exp = False if exp is not None: if tex.find('^') == -1: tex = r"%s^{%s}" % (tex, exp) else: need_exp = True tex = r"%s_{%s}\left(%s\right)" % (tex, self._print(expr.order), self._print(expr.argument)) if need_exp: tex = self._do_exponent(tex, exp) return tex def _hprint_vec(self, vec) -> str: if not vec: return "" s = "" for i in vec[:-1]: s += "%s, " % self._print(i) s += self._print(vec[-1]) return s def _print_besselj(self, expr, exp=None): return self._hprint_BesselBase(expr, exp, 'J') def _print_besseli(self, expr, exp=None): return self._hprint_BesselBase(expr, exp, 'I') def _print_besselk(self, expr, exp=None): return self._hprint_BesselBase(expr, exp, 'K') def _print_bessely(self, expr, exp=None): return self._hprint_BesselBase(expr, exp, 'Y') def _print_yn(self, expr, exp=None): return self._hprint_BesselBase(expr, exp, 'y') def _print_jn(self, expr, exp=None): return self._hprint_BesselBase(expr, exp, 'j') def _print_hankel1(self, expr, exp=None): return self._hprint_BesselBase(expr, exp, 'H^{(1)}') def _print_hankel2(self, expr, exp=None): return self._hprint_BesselBase(expr, exp, 'H^{(2)}') def _print_hn1(self, expr, exp=None): return self._hprint_BesselBase(expr, exp, 'h^{(1)}') def _print_hn2(self, expr, exp=None): return self._hprint_BesselBase(expr, exp, 'h^{(2)}') def _hprint_airy(self, expr, exp=None, notation="") -> str: tex = r"\left(%s\right)" % self._print(expr.args[0]) if exp is not None: return r"%s^{%s}%s" % (notation, exp, tex) else: return r"%s%s" % (notation, tex) def _hprint_airy_prime(self, expr, exp=None, notation="") -> str: tex = r"\left(%s\right)" % self._print(expr.args[0]) if exp is not None: return r"{%s^\prime}^{%s}%s" % (notation, exp, tex) else: return r"%s^\prime%s" % (notation, tex) def _print_airyai(self, expr, exp=None): return self._hprint_airy(expr, exp, 'Ai') def _print_airybi(self, expr, exp=None): return self._hprint_airy(expr, exp, 'Bi') def _print_airyaiprime(self, expr, exp=None): return self._hprint_airy_prime(expr, exp, 'Ai') def _print_airybiprime(self, expr, exp=None): return self._hprint_airy_prime(expr, exp, 'Bi') def _print_hyper(self, expr, exp=None): tex = r"{{}_{%s}F_{%s}\left(\begin{matrix} %s \\ %s \end{matrix}" \ r"\middle| {%s} \right)}" % \ (self._print(len(expr.ap)), self._print(len(expr.bq)), self._hprint_vec(expr.ap), self._hprint_vec(expr.bq), self._print(expr.argument)) if exp is not None: tex = r"{%s}^{%s}" % (tex, exp) return tex def _print_meijerg(self, expr, exp=None): tex = r"{G_{%s, %s}^{%s, %s}\left(\begin{matrix} %s & %s \\" \ r"%s & %s \end{matrix} \middle| {%s} \right)}" % \ (self._print(len(expr.ap)), self._print(len(expr.bq)), self._print(len(expr.bm)), self._print(len(expr.an)), self._hprint_vec(expr.an), self._hprint_vec(expr.aother), self._hprint_vec(expr.bm), self._hprint_vec(expr.bother), self._print(expr.argument)) if exp is not None: tex = r"{%s}^{%s}" % (tex, exp) return tex def _print_dirichlet_eta(self, expr, exp=None): tex = r"\left(%s\right)" % self._print(expr.args[0]) if exp is not None: return r"\eta^{%s}%s" % (exp, tex) return r"\eta%s" % tex def _print_zeta(self, expr, exp=None): if len(expr.args) == 2: tex = r"\left(%s, %s\right)" % tuple(map(self._print, expr.args)) else: tex = r"\left(%s\right)" % self._print(expr.args[0]) if exp is not None: return r"\zeta^{%s}%s" % (exp, tex) return r"\zeta%s" % tex def _print_stieltjes(self, expr, exp=None): if len(expr.args) == 2: tex = r"_{%s}\left(%s\right)" % tuple(map(self._print, expr.args)) else: tex = r"_{%s}" % self._print(expr.args[0]) if exp is not None: return r"\gamma%s^{%s}" % (tex, exp) return r"\gamma%s" % tex def _print_lerchphi(self, expr, exp=None): tex = r"\left(%s, %s, %s\right)" % tuple(map(self._print, expr.args)) if exp is None: return r"\Phi%s" % tex return r"\Phi^{%s}%s" % (exp, tex) def _print_polylog(self, expr, exp=None): s, z = map(self._print, expr.args) tex = r"\left(%s\right)" % z if exp is None: return r"\operatorname{Li}_{%s}%s" % (s, tex) return r"\operatorname{Li}_{%s}^{%s}%s" % (s, exp, tex) def _print_jacobi(self, expr, exp=None): n, a, b, x = map(self._print, expr.args) tex = r"P_{%s}^{\left(%s,%s\right)}\left(%s\right)" % (n, a, b, x) if exp is not None: tex = r"\left(" + tex + r"\right)^{%s}" % (exp) return tex def _print_gegenbauer(self, expr, exp=None): n, a, x = map(self._print, expr.args) tex = r"C_{%s}^{\left(%s\right)}\left(%s\right)" % (n, a, x) if exp is not None: tex = r"\left(" + tex + r"\right)^{%s}" % (exp) return tex def _print_chebyshevt(self, expr, exp=None): n, x = map(self._print, expr.args) tex = r"T_{%s}\left(%s\right)" % (n, x) if exp is not None: tex = r"\left(" + tex + r"\right)^{%s}" % (exp) return tex def _print_chebyshevu(self, expr, exp=None): n, x = map(self._print, expr.args) tex = r"U_{%s}\left(%s\right)" % (n, x) if exp is not None: tex = r"\left(" + tex + r"\right)^{%s}" % (exp) return tex def _print_legendre(self, expr, exp=None): n, x = map(self._print, expr.args) tex = r"P_{%s}\left(%s\right)" % (n, x) if exp is not None: tex = r"\left(" + tex + r"\right)^{%s}" % (exp) return tex def _print_assoc_legendre(self, expr, exp=None): n, a, x = map(self._print, expr.args) tex = r"P_{%s}^{\left(%s\right)}\left(%s\right)" % (n, a, x) if exp is not None: tex = r"\left(" + tex + r"\right)^{%s}" % (exp) return tex def _print_hermite(self, expr, exp=None): n, x = map(self._print, expr.args) tex = r"H_{%s}\left(%s\right)" % (n, x) if exp is not None: tex = r"\left(" + tex + r"\right)^{%s}" % (exp) return tex def _print_laguerre(self, expr, exp=None): n, x = map(self._print, expr.args) tex = r"L_{%s}\left(%s\right)" % (n, x) if exp is not None: tex = r"\left(" + tex + r"\right)^{%s}" % (exp) return tex def _print_assoc_laguerre(self, expr, exp=None): n, a, x = map(self._print, expr.args) tex = r"L_{%s}^{\left(%s\right)}\left(%s\right)" % (n, a, x) if exp is not None: tex = r"\left(" + tex + r"\right)^{%s}" % (exp) return tex def _print_Ynm(self, expr, exp=None): n, m, theta, phi = map(self._print, expr.args) tex = r"Y_{%s}^{%s}\left(%s,%s\right)" % (n, m, theta, phi) if exp is not None: tex = r"\left(" + tex + r"\right)^{%s}" % (exp) return tex def _print_Znm(self, expr, exp=None): n, m, theta, phi = map(self._print, expr.args) tex = r"Z_{%s}^{%s}\left(%s,%s\right)" % (n, m, theta, phi) if exp is not None: tex = r"\left(" + tex + r"\right)^{%s}" % (exp) return tex def __print_mathieu_functions(self, character, args, prime=False, exp=None): a, q, z = map(self._print, args) sup = r"^{\prime}" if prime else "" exp = "" if not exp else "^{%s}" % exp return r"%s%s\left(%s, %s, %s\right)%s" % (character, sup, a, q, z, exp) def _print_mathieuc(self, expr, exp=None): return self.__print_mathieu_functions("C", expr.args, exp=exp) def _print_mathieus(self, expr, exp=None): return self.__print_mathieu_functions("S", expr.args, exp=exp) def _print_mathieucprime(self, expr, exp=None): return self.__print_mathieu_functions("C", expr.args, prime=True, exp=exp) def _print_mathieusprime(self, expr, exp=None): return self.__print_mathieu_functions("S", expr.args, prime=True, exp=exp) def _print_Rational(self, expr): if expr.q != 1: sign = "" p = expr.p if expr.p < 0: sign = "- " p = -p if self._settings['fold_short_frac']: return r"%s%d / %d" % (sign, p, expr.q) return r"%s\frac{%d}{%d}" % (sign, p, expr.q) else: return self._print(expr.p) def _print_Order(self, expr): s = self._print(expr.expr) if expr.point and any(p != S.Zero for p in expr.point) or \ len(expr.variables) > 1: s += '; ' if len(expr.variables) > 1: s += self._print(expr.variables) elif expr.variables: s += self._print(expr.variables[0]) s += r'\rightarrow ' if len(expr.point) > 1: s += self._print(expr.point) else: s += self._print(expr.point[0]) return r"O\left(%s\right)" % s def _print_Symbol(self, expr: Symbol, style='plain'): name: str = self._settings['symbol_names'].get(expr) if name is not None: return name return self._deal_with_super_sub(expr.name, style=style) _print_RandomSymbol = _print_Symbol def _deal_with_super_sub(self, string: str, style='plain') -> str: if '{' in string: name, supers, subs = string, [], [] else: name, supers, subs = split_super_sub(string) name = translate(name) supers = [translate(sup) for sup in supers] subs = [translate(sub) for sub in subs] # apply the style only to the name if style == 'bold': name = "\\mathbf{{{}}}".format(name) # glue all items together: if supers: name += "^{%s}" % " ".join(supers) if subs: name += "_{%s}" % " ".join(subs) return name def _print_Relational(self, expr): if self._settings['itex']: gt = r"\gt" lt = r"\lt" else: gt = ">" lt = "<" charmap = { "==": "=", ">": gt, "<": lt, ">=": r"\geq", "<=": r"\leq", "!=": r"\neq", } return "%s %s %s" % (self._print(expr.lhs), charmap[expr.rel_op], self._print(expr.rhs)) def _print_Piecewise(self, expr): ecpairs = [r"%s & \text{for}\: %s" % (self._print(e), self._print(c)) for e, c in expr.args[:-1]] if expr.args[-1].cond == true: ecpairs.append(r"%s & \text{otherwise}" % self._print(expr.args[-1].expr)) else: ecpairs.append(r"%s & \text{for}\: %s" % (self._print(expr.args[-1].expr), self._print(expr.args[-1].cond))) tex = r"\begin{cases} %s \end{cases}" return tex % r" \\".join(ecpairs) def _print_matrix_contents(self, expr): lines = [] for line in range(expr.rows): # horrible, should be 'rows' lines.append(" & ".join([self._print(i) for i in expr[line, :]])) mat_str = self._settings['mat_str'] if mat_str is None: if self._settings['mode'] == 'inline': mat_str = 'smallmatrix' else: if (expr.cols <= 10) is True: mat_str = 'matrix' else: mat_str = 'array' out_str = r'\begin{%MATSTR%}%s\end{%MATSTR%}' out_str = out_str.replace('%MATSTR%', mat_str) if mat_str == 'array': out_str = out_str.replace('%s', '{' + 'c'*expr.cols + '}%s') return out_str % r"\\".join(lines) def _print_MatrixBase(self, expr): out_str = self._print_matrix_contents(expr) if self._settings['mat_delim']: left_delim: str = self._settings['mat_delim'] right_delim = self._delim_dict[left_delim] out_str = r'\left' + left_delim + out_str + \ r'\right' + right_delim return out_str def _print_MatrixElement(self, expr): return self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True)\ + '_{%s, %s}' % (self._print(expr.i), self._print(expr.j)) def _print_MatrixSlice(self, expr): def latexslice(x, dim): x = list(x) if x[2] == 1: del x[2] if x[0] == 0: x[0] = None if x[1] == dim: x[1] = None return ':'.join(self._print(xi) if xi is not None else '' for xi in x) return (self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) + r'\left[' + latexslice(expr.rowslice, expr.parent.rows) + ', ' + latexslice(expr.colslice, expr.parent.cols) + r'\right]') def _print_BlockMatrix(self, expr): return self._print(expr.blocks) def _print_Transpose(self, expr): mat = expr.arg from sympy.matrices import MatrixSymbol, BlockMatrix if (not isinstance(mat, MatrixSymbol) and not isinstance(mat, BlockMatrix) and mat.is_MatrixExpr): return r"\left(%s\right)^{T}" % self._print(mat) else: s = self.parenthesize(mat, precedence_traditional(expr), True) if '^' in s: return r"\left(%s\right)^{T}" % s else: return "%s^{T}" % s def _print_Trace(self, expr): mat = expr.arg return r"\operatorname{tr}\left(%s \right)" % self._print(mat) def _print_Adjoint(self, expr): mat = expr.arg from sympy.matrices import MatrixSymbol, BlockMatrix if (not isinstance(mat, MatrixSymbol) and not isinstance(mat, BlockMatrix) and mat.is_MatrixExpr): return r"\left(%s\right)^{\dagger}" % self._print(mat) else: s = self.parenthesize(mat, precedence_traditional(expr), True) if '^' in s: return r"\left(%s\right)^{\dagger}" % s else: return r"%s^{\dagger}" % s def _print_MatMul(self, expr): from sympy import MatMul # Parenthesize nested MatMul but not other types of Mul objects: parens = lambda x: self._print(x) if isinstance(x, Mul) and not isinstance(x, MatMul) else \ self.parenthesize(x, precedence_traditional(expr), False) args = list(expr.args) if expr.could_extract_minus_sign(): if args[0] == -1: args = args[1:] else: args[0] = -args[0] return '- ' + ' '.join(map(parens, args)) else: return ' '.join(map(parens, args)) def _print_Determinant(self, expr): mat = expr.arg if mat.is_MatrixExpr: from sympy.matrices.expressions.blockmatrix import BlockMatrix if isinstance(mat, BlockMatrix): return r"\left|{%s}\right|" % self._print_matrix_contents(mat.blocks) return r"\left|{%s}\right|" % self._print(mat) return r"\left|{%s}\right|" % self._print_matrix_contents(mat) def _print_Mod(self, expr, exp=None): if exp is not None: return r'\left(%s \bmod %s\right)^{%s}' % \ (self.parenthesize(expr.args[0], PRECEDENCE['Mul'], strict=True), self.parenthesize(expr.args[1], PRECEDENCE['Mul'], strict=True), exp) return r'%s \bmod %s' % (self.parenthesize(expr.args[0], PRECEDENCE['Mul'], strict=True), self.parenthesize(expr.args[1], PRECEDENCE['Mul'], strict=True)) def _print_HadamardProduct(self, expr): args = expr.args prec = PRECEDENCE['Pow'] parens = self.parenthesize return r' \circ '.join( map(lambda arg: parens(arg, prec, strict=True), args)) def _print_HadamardPower(self, expr): if precedence_traditional(expr.exp) < PRECEDENCE["Mul"]: template = r"%s^{\circ \left({%s}\right)}" else: template = r"%s^{\circ {%s}}" return self._helper_print_standard_power(expr, template) def _print_KroneckerProduct(self, expr): args = expr.args prec = PRECEDENCE['Pow'] parens = self.parenthesize return r' \otimes '.join( map(lambda arg: parens(arg, prec, strict=True), args)) def _print_MatPow(self, expr): base, exp = expr.base, expr.exp from sympy.matrices import MatrixSymbol if not isinstance(base, MatrixSymbol) and base.is_MatrixExpr: return "\\left(%s\\right)^{%s}" % (self._print(base), self._print(exp)) else: base_str = self._print(base) if '^' in base_str: return r"\left(%s\right)^{%s}" % (base_str, self._print(exp)) else: return "%s^{%s}" % (base_str, self._print(exp)) def _print_MatrixSymbol(self, expr): return self._print_Symbol(expr, style=self._settings[ 'mat_symbol_style']) def _print_ZeroMatrix(self, Z): return "0" if self._settings[ 'mat_symbol_style'] == 'plain' else r"\mathbf{0}" def _print_OneMatrix(self, O): return "1" if self._settings[ 'mat_symbol_style'] == 'plain' else r"\mathbf{1}" def _print_Identity(self, I): return r"\mathbb{I}" if self._settings[ 'mat_symbol_style'] == 'plain' else r"\mathbf{I}" def _print_PermutationMatrix(self, P): perm_str = self._print(P.args[0]) return "P_{%s}" % perm_str def _print_NDimArray(self, expr: NDimArray): if expr.rank() == 0: return self._print(expr[()]) mat_str = self._settings['mat_str'] if mat_str is None: if self._settings['mode'] == 'inline': mat_str = 'smallmatrix' else: if (expr.rank() == 0) or (expr.shape[-1] <= 10): mat_str = 'matrix' else: mat_str = 'array' block_str = r'\begin{%MATSTR%}%s\end{%MATSTR%}' block_str = block_str.replace('%MATSTR%', mat_str) if mat_str == 'array': block_str= block_str.replace('%s','{}%s') if self._settings['mat_delim']: left_delim: str = self._settings['mat_delim'] right_delim = self._delim_dict[left_delim] block_str = r'\left' + left_delim + block_str + \ r'\right' + right_delim if expr.rank() == 0: return block_str % "" level_str: list[list[str]] = [[] for i in range(expr.rank() + 1)] shape_ranges = [list(range(i)) for i in expr.shape] for outer_i in itertools.product(*shape_ranges): level_str[-1].append(self._print(expr[outer_i])) even = True for back_outer_i in range(expr.rank()-1, -1, -1): if len(level_str[back_outer_i+1]) < expr.shape[back_outer_i]: break if even: level_str[back_outer_i].append( r" & ".join(level_str[back_outer_i+1])) else: level_str[back_outer_i].append( block_str % (r"\\".join(level_str[back_outer_i+1]))) if len(level_str[back_outer_i+1]) == 1: level_str[back_outer_i][-1] = r"\left[" + \ level_str[back_outer_i][-1] + r"\right]" even = not even level_str[back_outer_i+1] = [] out_str = level_str[0][0] if expr.rank() % 2 == 1: out_str = block_str % out_str return out_str def _printer_tensor_indices(self, name, indices, index_map: dict): out_str = self._print(name) last_valence = None prev_map = None for index in indices: new_valence = index.is_up if ((index in index_map) or prev_map) and \ last_valence == new_valence: out_str += "," if last_valence != new_valence: if last_valence is not None: out_str += "}" if index.is_up: out_str += "{}^{" else: out_str += "{}_{" out_str += self._print(index.args[0]) if index in index_map: out_str += "=" out_str += self._print(index_map[index]) prev_map = True else: prev_map = False last_valence = new_valence if last_valence is not None: out_str += "}" return out_str def _print_Tensor(self, expr): name = expr.args[0].args[0] indices = expr.get_indices() return self._printer_tensor_indices(name, indices, {}) def _print_TensorElement(self, expr): name = expr.expr.args[0].args[0] indices = expr.expr.get_indices() index_map = expr.index_map return self._printer_tensor_indices(name, indices, index_map) def _print_TensMul(self, expr): # prints expressions like "A(a)", "3*A(a)", "(1+x)*A(a)" sign, args = expr._get_args_for_traditional_printer() return sign + "".join( [self.parenthesize(arg, precedence(expr)) for arg in args] ) def _print_TensAdd(self, expr): a = [] args = expr.args for x in args: a.append(self.parenthesize(x, precedence(expr))) a.sort() s = ' + '.join(a) s = s.replace('+ -', '- ') return s def _print_TensorIndex(self, expr): return "{}%s{%s}" % ( "^" if expr.is_up else "_", self._print(expr.args[0]) ) def _print_PartialDerivative(self, expr): if len(expr.variables) == 1: return r"\frac{\partial}{\partial {%s}}{%s}" % ( self._print(expr.variables[0]), self.parenthesize(expr.expr, PRECEDENCE["Mul"], False) ) else: return r"\frac{\partial^{%s}}{%s}{%s}" % ( len(expr.variables), " ".join([r"\partial {%s}" % self._print(i) for i in expr.variables]), self.parenthesize(expr.expr, PRECEDENCE["Mul"], False) ) def _print_ArraySymbol(self, expr): return self._print(expr.name) def _print_ArrayElement(self, expr): return "{{%s}_{%s}}" % ( self.parenthesize(expr.name, PRECEDENCE["Func"], True), ", ".join([f"{self._print(i)}" for i in expr.indices])) def _print_UniversalSet(self, expr): return r"\mathbb{U}" def _print_frac(self, expr, exp=None): if exp is None: return r"\operatorname{frac}{\left(%s\right)}" % self._print(expr.args[0]) else: return r"\operatorname{frac}{\left(%s\right)}^{%s}" % ( self._print(expr.args[0]), exp) def _print_tuple(self, expr): if self._settings['decimal_separator'] == 'comma': sep = ";" elif self._settings['decimal_separator'] == 'period': sep = "," else: raise ValueError('Unknown Decimal Separator') if len(expr) == 1: # 1-tuple needs a trailing separator return self._add_parens_lspace(self._print(expr[0]) + sep) else: return self._add_parens_lspace( (sep + r" \ ").join([self._print(i) for i in expr])) def _print_TensorProduct(self, expr): elements = [self._print(a) for a in expr.args] return r' \otimes '.join(elements) def _print_WedgeProduct(self, expr): elements = [self._print(a) for a in expr.args] return r' \wedge '.join(elements) def _print_Tuple(self, expr): return self._print_tuple(expr) def _print_list(self, expr): if self._settings['decimal_separator'] == 'comma': return r"\left[ %s\right]" % \ r"; \ ".join([self._print(i) for i in expr]) elif self._settings['decimal_separator'] == 'period': return r"\left[ %s\right]" % \ r", \ ".join([self._print(i) for i in expr]) else: raise ValueError('Unknown Decimal Separator') def _print_dict(self, d): keys = sorted(d.keys(), key=default_sort_key) items = [] for key in keys: val = d[key] items.append("%s : %s" % (self._print(key), self._print(val))) return r"\left\{ %s\right\}" % r", \ ".join(items) def _print_Dict(self, expr): return self._print_dict(expr) def _print_DiracDelta(self, expr, exp=None): if len(expr.args) == 1 or expr.args[1] == 0: tex = r"\delta\left(%s\right)" % self._print(expr.args[0]) else: tex = r"\delta^{\left( %s \right)}\left( %s \right)" % ( self._print(expr.args[1]), self._print(expr.args[0])) if exp: tex = r"\left(%s\right)^{%s}" % (tex, exp) return tex def _print_SingularityFunction(self, expr, exp=None): shift = self._print(expr.args[0] - expr.args[1]) power = self._print(expr.args[2]) tex = r"{\left\langle %s \right\rangle}^{%s}" % (shift, power) if exp is not None: tex = r"{\left({\langle %s \rangle}^{%s}\right)}^{%s}" % (shift, power, exp) return tex def _print_Heaviside(self, expr, exp=None): pargs = ', '.join(self._print(arg) for arg in expr.pargs) tex = r"\theta\left(%s\right)" % pargs if exp: tex = r"\left(%s\right)^{%s}" % (tex, exp) return tex def _print_KroneckerDelta(self, expr, exp=None): i = self._print(expr.args[0]) j = self._print(expr.args[1]) if expr.args[0].is_Atom and expr.args[1].is_Atom: tex = r'\delta_{%s %s}' % (i, j) else: tex = r'\delta_{%s, %s}' % (i, j) if exp is not None: tex = r'\left(%s\right)^{%s}' % (tex, exp) return tex def _print_LeviCivita(self, expr, exp=None): indices = map(self._print, expr.args) if all(x.is_Atom for x in expr.args): tex = r'\varepsilon_{%s}' % " ".join(indices) else: tex = r'\varepsilon_{%s}' % ", ".join(indices) if exp: tex = r'\left(%s\right)^{%s}' % (tex, exp) return tex def _print_RandomDomain(self, d): if hasattr(d, 'as_boolean'): return '\\text{Domain: }' + self._print(d.as_boolean()) elif hasattr(d, 'set'): return ('\\text{Domain: }' + self._print(d.symbols) + ' \\in ' + self._print(d.set)) elif hasattr(d, 'symbols'): return '\\text{Domain on }' + self._print(d.symbols) else: return self._print(None) def _print_FiniteSet(self, s): items = sorted(s.args, key=default_sort_key) return self._print_set(items) def _print_set(self, s): items = sorted(s, key=default_sort_key) if self._settings['decimal_separator'] == 'comma': items = "; ".join(map(self._print, items)) elif self._settings['decimal_separator'] == 'period': items = ", ".join(map(self._print, items)) else: raise ValueError('Unknown Decimal Separator') return r"\left\{%s\right\}" % items _print_frozenset = _print_set def _print_Range(self, s): def _print_symbolic_range(): # Symbolic Range that cannot be resolved if s.args[0] == 0: if s.args[2] == 1: cont = self._print(s.args[1]) else: cont = ", ".join(self._print(arg) for arg in s.args) else: if s.args[2] == 1: cont = ", ".join(self._print(arg) for arg in s.args[:2]) else: cont = ", ".join(self._print(arg) for arg in s.args) return(f"\\text{{Range}}\\left({cont}\\right)") dots = object() if s.start.is_infinite and s.stop.is_infinite: if s.step.is_positive: printset = dots, -1, 0, 1, dots else: printset = dots, 1, 0, -1, dots elif s.start.is_infinite: printset = dots, s[-1] - s.step, s[-1] elif s.stop.is_infinite: it = iter(s) printset = next(it), next(it), dots elif s.is_empty is not None: if (s.size < 4) == True: printset = tuple(s) elif s.is_iterable: it = iter(s) printset = next(it), next(it), dots, s[-1] else: return _print_symbolic_range() else: return _print_symbolic_range() return (r"\left\{" + r", ".join(self._print(el) if el is not dots else r'\ldots' for el in printset) + r"\right\}") def __print_number_polynomial(self, expr, letter, exp=None): if len(expr.args) == 2: if exp is not None: return r"%s_{%s}^{%s}\left(%s\right)" % (letter, self._print(expr.args[0]), exp, self._print(expr.args[1])) return r"%s_{%s}\left(%s\right)" % (letter, self._print(expr.args[0]), self._print(expr.args[1])) tex = r"%s_{%s}" % (letter, self._print(expr.args[0])) if exp is not None: tex = r"%s^{%s}" % (tex, exp) return tex def _print_bernoulli(self, expr, exp=None): return self.__print_number_polynomial(expr, "B", exp) def _print_bell(self, expr, exp=None): if len(expr.args) == 3: tex1 = r"B_{%s, %s}" % (self._print(expr.args[0]), self._print(expr.args[1])) tex2 = r"\left(%s\right)" % r", ".join(self._print(el) for el in expr.args[2]) if exp is not None: tex = r"%s^{%s}%s" % (tex1, exp, tex2) else: tex = tex1 + tex2 return tex return self.__print_number_polynomial(expr, "B", exp) def _print_fibonacci(self, expr, exp=None): return self.__print_number_polynomial(expr, "F", exp) def _print_lucas(self, expr, exp=None): tex = r"L_{%s}" % self._print(expr.args[0]) if exp is not None: tex = r"%s^{%s}" % (tex, exp) return tex def _print_tribonacci(self, expr, exp=None): return self.__print_number_polynomial(expr, "T", exp) def _print_SeqFormula(self, s): dots = object() if len(s.start.free_symbols) > 0 or len(s.stop.free_symbols) > 0: return r"\left\{%s\right\}_{%s=%s}^{%s}" % ( self._print(s.formula), self._print(s.variables[0]), self._print(s.start), self._print(s.stop) ) if s.start is S.NegativeInfinity: stop = s.stop printset = (dots, s.coeff(stop - 3), s.coeff(stop - 2), s.coeff(stop - 1), s.coeff(stop)) elif s.stop is S.Infinity or s.length > 4: printset = s[:4] printset.append(dots) else: printset = tuple(s) return (r"\left[" + r", ".join(self._print(el) if el is not dots else r'\ldots' for el in printset) + r"\right]") _print_SeqPer = _print_SeqFormula _print_SeqAdd = _print_SeqFormula _print_SeqMul = _print_SeqFormula def _print_Interval(self, i): if i.start == i.end: return r"\left\{%s\right\}" % self._print(i.start) else: if i.left_open: left = '(' else: left = '[' if i.right_open: right = ')' else: right = ']' return r"\left%s%s, %s\right%s" % \ (left, self._print(i.start), self._print(i.end), right) def _print_AccumulationBounds(self, i): return r"\left\langle %s, %s\right\rangle" % \ (self._print(i.min), self._print(i.max)) def _print_Union(self, u): prec = precedence_traditional(u) args_str = [self.parenthesize(i, prec) for i in u.args] return r" \cup ".join(args_str) def _print_Complement(self, u): prec = precedence_traditional(u) args_str = [self.parenthesize(i, prec) for i in u.args] return r" \setminus ".join(args_str) def _print_Intersection(self, u): prec = precedence_traditional(u) args_str = [self.parenthesize(i, prec) for i in u.args] return r" \cap ".join(args_str) def _print_SymmetricDifference(self, u): prec = precedence_traditional(u) args_str = [self.parenthesize(i, prec) for i in u.args] return r" \triangle ".join(args_str) def _print_ProductSet(self, p): prec = precedence_traditional(p) if len(p.sets) >= 1 and not has_variety(p.sets): return self.parenthesize(p.sets[0], prec) + "^{%d}" % len(p.sets) return r" \times ".join( self.parenthesize(set, prec) for set in p.sets) def _print_EmptySet(self, e): return r"\emptyset" def _print_Naturals(self, n): return r"\mathbb{N}" def _print_Naturals0(self, n): return r"\mathbb{N}_0" def _print_Integers(self, i): return r"\mathbb{Z}" def _print_Rationals(self, i): return r"\mathbb{Q}" def _print_Reals(self, i): return r"\mathbb{R}" def _print_Complexes(self, i): return r"\mathbb{C}" def _print_ImageSet(self, s): expr = s.lamda.expr sig = s.lamda.signature xys = ((self._print(x), self._print(y)) for x, y in zip(sig, s.base_sets)) xinys = r", ".join(r"%s \in %s" % xy for xy in xys) return r"\left\{%s\; \middle|\; %s\right\}" % (self._print(expr), xinys) def _print_ConditionSet(self, s): vars_print = ', '.join([self._print(var) for var in Tuple(s.sym)]) if s.base_set is S.UniversalSet: return r"\left\{%s\; \middle|\; %s \right\}" % \ (vars_print, self._print(s.condition)) return r"\left\{%s\; \middle|\; %s \in %s \wedge %s \right\}" % ( vars_print, vars_print, self._print(s.base_set), self._print(s.condition)) def _print_PowerSet(self, expr): arg_print = self._print(expr.args[0]) return r"\mathcal{{P}}\left({}\right)".format(arg_print) def _print_ComplexRegion(self, s): vars_print = ', '.join([self._print(var) for var in s.variables]) return r"\left\{%s\; \middle|\; %s \in %s \right\}" % ( self._print(s.expr), vars_print, self._print(s.sets)) def _print_Contains(self, e): return r"%s \in %s" % tuple(self._print(a) for a in e.args) def _print_FourierSeries(self, s): if s.an.formula is S.Zero and s.bn.formula is S.Zero: return self._print(s.a0) return self._print_Add(s.truncate()) + r' + \ldots' def _print_FormalPowerSeries(self, s): return self._print_Add(s.infinite) def _print_FiniteField(self, expr): return r"\mathbb{F}_{%s}" % expr.mod def _print_IntegerRing(self, expr): return r"\mathbb{Z}" def _print_RationalField(self, expr): return r"\mathbb{Q}" def _print_RealField(self, expr): return r"\mathbb{R}" def _print_ComplexField(self, expr): return r"\mathbb{C}" def _print_PolynomialRing(self, expr): domain = self._print(expr.domain) symbols = ", ".join(map(self._print, expr.symbols)) return r"%s\left[%s\right]" % (domain, symbols) def _print_FractionField(self, expr): domain = self._print(expr.domain) symbols = ", ".join(map(self._print, expr.symbols)) return r"%s\left(%s\right)" % (domain, symbols) def _print_PolynomialRingBase(self, expr): domain = self._print(expr.domain) symbols = ", ".join(map(self._print, expr.symbols)) inv = "" if not expr.is_Poly: inv = r"S_<^{-1}" return r"%s%s\left[%s\right]" % (inv, domain, symbols) def _print_Poly(self, poly): cls = poly.__class__.__name__ terms = [] for monom, coeff in poly.terms(): s_monom = '' for i, exp in enumerate(monom): if exp > 0: if exp == 1: s_monom += self._print(poly.gens[i]) else: s_monom += self._print(pow(poly.gens[i], exp)) if coeff.is_Add: if s_monom: s_coeff = r"\left(%s\right)" % self._print(coeff) else: s_coeff = self._print(coeff) else: if s_monom: if coeff is S.One: terms.extend(['+', s_monom]) continue if coeff is S.NegativeOne: terms.extend(['-', s_monom]) continue s_coeff = self._print(coeff) if not s_monom: s_term = s_coeff else: s_term = s_coeff + " " + s_monom if s_term.startswith('-'): terms.extend(['-', s_term[1:]]) else: terms.extend(['+', s_term]) if terms[0] in ('-', '+'): modifier = terms.pop(0) if modifier == '-': terms[0] = '-' + terms[0] expr = ' '.join(terms) gens = list(map(self._print, poly.gens)) domain = "domain=%s" % self._print(poly.get_domain()) args = ", ".join([expr] + gens + [domain]) if cls in accepted_latex_functions: tex = r"\%s {\left(%s \right)}" % (cls, args) else: tex = r"\operatorname{%s}{\left( %s \right)}" % (cls, args) return tex def _print_ComplexRootOf(self, root): cls = root.__class__.__name__ if cls == "ComplexRootOf": cls = "CRootOf" expr = self._print(root.expr) index = root.index if cls in accepted_latex_functions: return r"\%s {\left(%s, %d\right)}" % (cls, expr, index) else: return r"\operatorname{%s} {\left(%s, %d\right)}" % (cls, expr, index) def _print_RootSum(self, expr): cls = expr.__class__.__name__ args = [self._print(expr.expr)] if expr.fun is not S.IdentityFunction: args.append(self._print(expr.fun)) if cls in accepted_latex_functions: return r"\%s {\left(%s\right)}" % (cls, ", ".join(args)) else: return r"\operatorname{%s} {\left(%s\right)}" % (cls, ", ".join(args)) def _print_OrdinalOmega(self, expr): return r"\omega" def _print_OmegaPower(self, expr): exp, mul = expr.args if mul != 1: if exp != 1: return r"{} \omega^{{{}}}".format(mul, exp) else: return r"{} \omega".format(mul) else: if exp != 1: return r"\omega^{{{}}}".format(exp) else: return r"\omega" def _print_Ordinal(self, expr): return " + ".join([self._print(arg) for arg in expr.args]) def _print_PolyElement(self, poly): mul_symbol = self._settings['mul_symbol_latex'] return poly.str(self, PRECEDENCE, "{%s}^{%d}", mul_symbol) def _print_FracElement(self, frac): if frac.denom == 1: return self._print(frac.numer) else: numer = self._print(frac.numer) denom = self._print(frac.denom) return r"\frac{%s}{%s}" % (numer, denom) def _print_euler(self, expr, exp=None): m, x = (expr.args[0], None) if len(expr.args) == 1 else expr.args tex = r"E_{%s}" % self._print(m) if exp is not None: tex = r"%s^{%s}" % (tex, exp) if x is not None: tex = r"%s\left(%s\right)" % (tex, self._print(x)) return tex def _print_catalan(self, expr, exp=None): tex = r"C_{%s}" % self._print(expr.args[0]) if exp is not None: tex = r"%s^{%s}" % (tex, exp) return tex def _print_UnifiedTransform(self, expr, s, inverse=False): return r"\mathcal{{{}}}{}_{{{}}}\left[{}\right]\left({}\right)".format(s, '^{-1}' if inverse else '', self._print(expr.args[1]), self._print(expr.args[0]), self._print(expr.args[2])) def _print_MellinTransform(self, expr): return self._print_UnifiedTransform(expr, 'M') def _print_InverseMellinTransform(self, expr): return self._print_UnifiedTransform(expr, 'M', True) def _print_LaplaceTransform(self, expr): return self._print_UnifiedTransform(expr, 'L') def _print_InverseLaplaceTransform(self, expr): return self._print_UnifiedTransform(expr, 'L', True) def _print_FourierTransform(self, expr): return self._print_UnifiedTransform(expr, 'F') def _print_InverseFourierTransform(self, expr): return self._print_UnifiedTransform(expr, 'F', True) def _print_SineTransform(self, expr): return self._print_UnifiedTransform(expr, 'SIN') def _print_InverseSineTransform(self, expr): return self._print_UnifiedTransform(expr, 'SIN', True) def _print_CosineTransform(self, expr): return self._print_UnifiedTransform(expr, 'COS') def _print_InverseCosineTransform(self, expr): return self._print_UnifiedTransform(expr, 'COS', True) def _print_DMP(self, p): try: if p.ring is not None: # TODO incorporate order return self._print(p.ring.to_sympy(p)) except SympifyError: pass return self._print(repr(p)) def _print_DMF(self, p): return self._print_DMP(p) def _print_Object(self, object): return self._print(Symbol(object.name)) def _print_LambertW(self, expr, exp=None): arg0 = self._print(expr.args[0]) exp = r"^{%s}" % (exp,) if exp is not None else "" if len(expr.args) == 1: result = r"W%s\left(%s\right)" % (exp, arg0) else: arg1 = self._print(expr.args[1]) result = "W{0}_{{{1}}}\\left({2}\\right)".format(exp, arg1, arg0) return result def _print_Expectation(self, expr): return r"\operatorname{{E}}\left[{}\right]".format(self._print(expr.args[0])) def _print_Variance(self, expr): return r"\operatorname{{Var}}\left({}\right)".format(self._print(expr.args[0])) def _print_Covariance(self, expr): return r"\operatorname{{Cov}}\left({}\right)".format(", ".join(self._print(arg) for arg in expr.args)) def _print_Probability(self, expr): return r"\operatorname{{P}}\left({}\right)".format(self._print(expr.args[0])) def _print_Morphism(self, morphism): domain = self._print(morphism.domain) codomain = self._print(morphism.codomain) return "%s\\rightarrow %s" % (domain, codomain) def _print_TransferFunction(self, expr): num, den = self._print(expr.num), self._print(expr.den) return r"\frac{%s}{%s}" % (num, den) def _print_Series(self, expr): args = list(expr.args) parens = lambda x: self.parenthesize(x, precedence_traditional(expr), False) return ' '.join(map(parens, args)) def _print_MIMOSeries(self, expr): from sympy.physics.control.lti import MIMOParallel args = list(expr.args)[::-1] parens = lambda x: self.parenthesize(x, precedence_traditional(expr), False) if isinstance(x, MIMOParallel) else self._print(x) return r"\cdot".join(map(parens, args)) def _print_Parallel(self, expr): return ' + '.join(map(self._print, expr.args)) def _print_MIMOParallel(self, expr): return ' + '.join(map(self._print, expr.args)) def _print_Feedback(self, expr): from sympy.physics.control import TransferFunction, Series num, tf = expr.sys1, TransferFunction(1, 1, expr.var) num_arg_list = list(num.args) if isinstance(num, Series) else [num] den_arg_list = list(expr.sys2.args) if \ isinstance(expr.sys2, Series) else [expr.sys2] den_term_1 = tf if isinstance(num, Series) and isinstance(expr.sys2, Series): den_term_2 = Series(*num_arg_list, *den_arg_list) elif isinstance(num, Series) and isinstance(expr.sys2, TransferFunction): if expr.sys2 == tf: den_term_2 = Series(*num_arg_list) else: den_term_2 = tf, Series(*num_arg_list, expr.sys2) elif isinstance(num, TransferFunction) and isinstance(expr.sys2, Series): if num == tf: den_term_2 = Series(*den_arg_list) else: den_term_2 = Series(num, *den_arg_list) else: if num == tf: den_term_2 = Series(*den_arg_list) elif expr.sys2 == tf: den_term_2 = Series(*num_arg_list) else: den_term_2 = Series(*num_arg_list, *den_arg_list) numer = self._print(num) denom_1 = self._print(den_term_1) denom_2 = self._print(den_term_2) _sign = "+" if expr.sign == -1 else "-" return r"\frac{%s}{%s %s %s}" % (numer, denom_1, _sign, denom_2) def _print_MIMOFeedback(self, expr): from sympy.physics.control import MIMOSeries inv_mat = self._print(MIMOSeries(expr.sys2, expr.sys1)) sys1 = self._print(expr.sys1) _sign = "+" if expr.sign == -1 else "-" return r"\left(I_{\tau} %s %s\right)^{-1} \cdot %s" % (_sign, inv_mat, sys1) def _print_TransferFunctionMatrix(self, expr): mat = self._print(expr._expr_mat) return r"%s_\tau" % mat def _print_DFT(self, expr): return r"\text{{{}}}_{{{}}}".format(expr.__class__.__name__, expr.n) _print_IDFT = _print_DFT def _print_NamedMorphism(self, morphism): pretty_name = self._print(Symbol(morphism.name)) pretty_morphism = self._print_Morphism(morphism) return "%s:%s" % (pretty_name, pretty_morphism) def _print_IdentityMorphism(self, morphism): from sympy.categories import NamedMorphism return self._print_NamedMorphism(NamedMorphism( morphism.domain, morphism.codomain, "id")) def _print_CompositeMorphism(self, morphism): # All components of the morphism have names and it is thus # possible to build the name of the composite. component_names_list = [self._print(Symbol(component.name)) for component in morphism.components] component_names_list.reverse() component_names = "\\circ ".join(component_names_list) + ":" pretty_morphism = self._print_Morphism(morphism) return component_names + pretty_morphism def _print_Category(self, morphism): return r"\mathbf{{{}}}".format(self._print(Symbol(morphism.name))) def _print_Diagram(self, diagram): if not diagram.premises: # This is an empty diagram. return self._print(S.EmptySet) latex_result = self._print(diagram.premises) if diagram.conclusions: latex_result += "\\Longrightarrow %s" % \ self._print(diagram.conclusions) return latex_result def _print_DiagramGrid(self, grid): latex_result = "\\begin{array}{%s}\n" % ("c" * grid.width) for i in range(grid.height): for j in range(grid.width): if grid[i, j]: latex_result += latex(grid[i, j]) latex_result += " " if j != grid.width - 1: latex_result += "& " if i != grid.height - 1: latex_result += "\\\\" latex_result += "\n" latex_result += "\\end{array}\n" return latex_result def _print_FreeModule(self, M): return '{{{}}}^{{{}}}'.format(self._print(M.ring), self._print(M.rank)) def _print_FreeModuleElement(self, m): # Print as row vector for convenience, for now. return r"\left[ {} \right]".format(",".join( '{' + self._print(x) + '}' for x in m)) def _print_SubModule(self, m): return r"\left\langle {} \right\rangle".format(",".join( '{' + self._print(x) + '}' for x in m.gens)) def _print_ModuleImplementedIdeal(self, m): return r"\left\langle {} \right\rangle".format(",".join( '{' + self._print(x) + '}' for [x] in m._module.gens)) def _print_Quaternion(self, expr): # TODO: This expression is potentially confusing, # shall we print it as `Quaternion( ... )`? s = [self.parenthesize(i, PRECEDENCE["Mul"], strict=True) for i in expr.args] a = [s[0]] + [i+" "+j for i, j in zip(s[1:], "ijk")] return " + ".join(a) def _print_QuotientRing(self, R): # TODO nicer fractions for few generators... return r"\frac{{{}}}{{{}}}".format(self._print(R.ring), self._print(R.base_ideal)) def _print_QuotientRingElement(self, x): return r"{{{}}} + {{{}}}".format(self._print(x.data), self._print(x.ring.base_ideal)) def _print_QuotientModuleElement(self, m): return r"{{{}}} + {{{}}}".format(self._print(m.data), self._print(m.module.killed_module)) def _print_QuotientModule(self, M): # TODO nicer fractions for few generators... return r"\frac{{{}}}{{{}}}".format(self._print(M.base), self._print(M.killed_module)) def _print_MatrixHomomorphism(self, h): return r"{{{}}} : {{{}}} \to {{{}}}".format(self._print(h._sympy_matrix()), self._print(h.domain), self._print(h.codomain)) def _print_Manifold(self, manifold): string = manifold.name.name if '{' in string: name, supers, subs = string, [], [] else: name, supers, subs = split_super_sub(string) name = translate(name) supers = [translate(sup) for sup in supers] subs = [translate(sub) for sub in subs] name = r'\text{%s}' % name if supers: name += "^{%s}" % " ".join(supers) if subs: name += "_{%s}" % " ".join(subs) return name def _print_Patch(self, patch): return r'\text{%s}_{%s}' % (self._print(patch.name), self._print(patch.manifold)) def _print_CoordSystem(self, coordsys): return r'\text{%s}^{\text{%s}}_{%s}' % ( self._print(coordsys.name), self._print(coordsys.patch.name), self._print(coordsys.manifold) ) def _print_CovarDerivativeOp(self, cvd): return r'\mathbb{\nabla}_{%s}' % self._print(cvd._wrt) def _print_BaseScalarField(self, field): string = field._coord_sys.symbols[field._index].name return r'\mathbf{{{}}}'.format(self._print(Symbol(string))) def _print_BaseVectorField(self, field): string = field._coord_sys.symbols[field._index].name return r'\partial_{{{}}}'.format(self._print(Symbol(string))) def _print_Differential(self, diff): field = diff._form_field if hasattr(field, '_coord_sys'): string = field._coord_sys.symbols[field._index].name return r'\operatorname{{d}}{}'.format(self._print(Symbol(string))) else: string = self._print(field) return r'\operatorname{{d}}\left({}\right)'.format(string) def _print_Tr(self, p): # TODO: Handle indices contents = self._print(p.args[0]) return r'\operatorname{{tr}}\left({}\right)'.format(contents) def _print_totient(self, expr, exp=None): if exp is not None: return r'\left(\phi\left(%s\right)\right)^{%s}' % \ (self._print(expr.args[0]), exp) return r'\phi\left(%s\right)' % self._print(expr.args[0]) def _print_reduced_totient(self, expr, exp=None): if exp is not None: return r'\left(\lambda\left(%s\right)\right)^{%s}' % \ (self._print(expr.args[0]), exp) return r'\lambda\left(%s\right)' % self._print(expr.args[0]) def _print_divisor_sigma(self, expr, exp=None): if len(expr.args) == 2: tex = r"_%s\left(%s\right)" % tuple(map(self._print, (expr.args[1], expr.args[0]))) else: tex = r"\left(%s\right)" % self._print(expr.args[0]) if exp is not None: return r"\sigma^{%s}%s" % (exp, tex) return r"\sigma%s" % tex def _print_udivisor_sigma(self, expr, exp=None): if len(expr.args) == 2: tex = r"_%s\left(%s\right)" % tuple(map(self._print, (expr.args[1], expr.args[0]))) else: tex = r"\left(%s\right)" % self._print(expr.args[0]) if exp is not None: return r"\sigma^*^{%s}%s" % (exp, tex) return r"\sigma^*%s" % tex def _print_primenu(self, expr, exp=None): if exp is not None: return r'\left(\nu\left(%s\right)\right)^{%s}' % \ (self._print(expr.args[0]), exp) return r'\nu\left(%s\right)' % self._print(expr.args[0]) def _print_primeomega(self, expr, exp=None): if exp is not None: return r'\left(\Omega\left(%s\right)\right)^{%s}' % \ (self._print(expr.args[0]), exp) return r'\Omega\left(%s\right)' % self._print(expr.args[0]) def _print_Str(self, s): return str(s.name) def _print_float(self, expr): return self._print(Float(expr)) def _print_int(self, expr): return str(expr) def _print_mpz(self, expr): return str(expr) def _print_mpq(self, expr): return str(expr) def _print_Predicate(self, expr): return r"\operatorname{{Q}}_{{\text{{{}}}}}".format(latex_escape(str(expr.name))) def _print_AppliedPredicate(self, expr): pred = expr.function args = expr.arguments pred_latex = self._print(pred) args_latex = ', '.join([self._print(a) for a in args]) return '%s(%s)' % (pred_latex, args_latex) def emptyPrinter(self, expr): # default to just printing as monospace, like would normally be shown s = super().emptyPrinter(expr) return r"\mathtt{\text{%s}}" % latex_escape(s) def translate(s: str) -> str: r''' Check for a modifier ending the string. If present, convert the modifier to latex and translate the rest recursively. Given a description of a Greek letter or other special character, return the appropriate latex. Let everything else pass as given. >>> from sympy.printing.latex import translate >>> translate('alphahatdotprime') "{\\dot{\\hat{\\alpha}}}'" ''' # Process the rest tex = tex_greek_dictionary.get(s) if tex: return tex elif s.lower() in greek_letters_set: return "\\" + s.lower() elif s in other_symbols: return "\\" + s else: # Process modifiers, if any, and recurse for key in sorted(modifier_dict.keys(), key=len, reverse=True): if s.lower().endswith(key) and len(s) > len(key): return modifier_dict[key](translate(s[:-len(key)])) return s @print_function(LatexPrinter) def latex(expr, **settings): r"""Convert the given expression to LaTeX string representation. Parameters ========== full_prec: boolean, optional If set to True, a floating point number is printed with full precision. fold_frac_powers : boolean, optional Emit ``^{p/q}`` instead of ``^{\frac{p}{q}}`` for fractional powers. fold_func_brackets : boolean, optional Fold function brackets where applicable. fold_short_frac : boolean, optional Emit ``p / q`` instead of ``\frac{p}{q}`` when the denominator is simple enough (at most two terms and no powers). The default value is ``True`` for inline mode, ``False`` otherwise. inv_trig_style : string, optional How inverse trig functions should be displayed. Can be one of ``'abbreviated'``, ``'full'``, or ``'power'``. Defaults to ``'abbreviated'``. itex : boolean, optional Specifies if itex-specific syntax is used, including emitting ``$$...$$``. ln_notation : boolean, optional If set to ``True``, ``\ln`` is used instead of default ``\log``. long_frac_ratio : float or None, optional The allowed ratio of the width of the numerator to the width of the denominator before the printer breaks off long fractions. If ``None`` (the default value), long fractions are not broken up. mat_delim : string, optional The delimiter to wrap around matrices. Can be one of ``'['``, ``'('``, or the empty string ``''``. Defaults to ``'['``. mat_str : string, optional Which matrix environment string to emit. ``'smallmatrix'``, ``'matrix'``, ``'array'``, etc. Defaults to ``'smallmatrix'`` for inline mode, ``'matrix'`` for matrices of no more than 10 columns, and ``'array'`` otherwise. mode: string, optional Specifies how the generated code will be delimited. ``mode`` can be one of ``'plain'``, ``'inline'``, ``'equation'`` or ``'equation*'``. If ``mode`` is set to ``'plain'``, then the resulting code will not be delimited at all (this is the default). If ``mode`` is set to ``'inline'`` then inline LaTeX ``$...$`` will be used. If ``mode`` is set to ``'equation'`` or ``'equation*'``, the resulting code will be enclosed in the ``equation`` or ``equation*`` environment (remember to import ``amsmath`` for ``equation*``), unless the ``itex`` option is set. In the latter case, the ``$$...$$`` syntax is used. mul_symbol : string or None, optional The symbol to use for multiplication. Can be one of ``None``, ``'ldot'``, ``'dot'``, or ``'times'``. order: string, optional Any of the supported monomial orderings (currently ``'lex'``, ``'grlex'``, or ``'grevlex'``), ``'old'``, and ``'none'``. This parameter does nothing for `~.Mul` objects. Setting order to ``'old'`` uses the compatibility ordering for ``~.Add`` defined in Printer. For very large expressions, set the ``order`` keyword to ``'none'`` if speed is a concern. symbol_names : dictionary of strings mapped to symbols, optional Dictionary of symbols and the custom strings they should be emitted as. root_notation : boolean, optional If set to ``False``, exponents of the form 1/n are printed in fractonal form. Default is ``True``, to print exponent in root form. mat_symbol_style : string, optional Can be either ``'plain'`` (default) or ``'bold'``. If set to ``'bold'``, a `~.MatrixSymbol` A will be printed as ``\mathbf{A}``, otherwise as ``A``. imaginary_unit : string, optional String to use for the imaginary unit. Defined options are ``'i'`` (default) and ``'j'``. Adding ``r`` or ``t`` in front gives ``\mathrm`` or ``\text``, so ``'ri'`` leads to ``\mathrm{i}`` which gives `\mathrm{i}`. gothic_re_im : boolean, optional If set to ``True``, `\Re` and `\Im` is used for ``re`` and ``im``, respectively. The default is ``False`` leading to `\operatorname{re}` and `\operatorname{im}`. decimal_separator : string, optional Specifies what separator to use to separate the whole and fractional parts of a floating point number as in `2.5` for the default, ``period`` or `2{,}5` when ``comma`` is specified. Lists, sets, and tuple are printed with semicolon separating the elements when ``comma`` is chosen. For example, [1; 2; 3] when ``comma`` is chosen and [1,2,3] for when ``period`` is chosen. parenthesize_super : boolean, optional If set to ``False``, superscripted expressions will not be parenthesized when powered. Default is ``True``, which parenthesizes the expression when powered. min: Integer or None, optional Sets the lower bound for the exponent to print floating point numbers in fixed-point format. max: Integer or None, optional Sets the upper bound for the exponent to print floating point numbers in fixed-point format. diff_operator: string, optional String to use for differential operator. Default is ``'d'``, to print in italic form. ``'rd'``, ``'td'`` are shortcuts for ``\mathrm{d}`` and ``\text{d}``. Notes ===== Not using a print statement for printing, results in double backslashes for latex commands since that's the way Python escapes backslashes in strings. >>> from sympy import latex, Rational >>> from sympy.abc import tau >>> latex((2*tau)**Rational(7,2)) '8 \\sqrt{2} \\tau^{\\frac{7}{2}}' >>> print(latex((2*tau)**Rational(7,2))) 8 \sqrt{2} \tau^{\frac{7}{2}} Examples ======== >>> from sympy import latex, pi, sin, asin, Integral, Matrix, Rational, log >>> from sympy.abc import x, y, mu, r, tau Basic usage: >>> print(latex((2*tau)**Rational(7,2))) 8 \sqrt{2} \tau^{\frac{7}{2}} ``mode`` and ``itex`` options: >>> print(latex((2*mu)**Rational(7,2), mode='plain')) 8 \sqrt{2} \mu^{\frac{7}{2}} >>> print(latex((2*tau)**Rational(7,2), mode='inline')) $8 \sqrt{2} \tau^{7 / 2}$ >>> print(latex((2*mu)**Rational(7,2), mode='equation*')) \begin{equation*}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation*} >>> print(latex((2*mu)**Rational(7,2), mode='equation')) \begin{equation}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation} >>> print(latex((2*mu)**Rational(7,2), mode='equation', itex=True)) $$8 \sqrt{2} \mu^{\frac{7}{2}}$$ >>> print(latex((2*mu)**Rational(7,2), mode='plain')) 8 \sqrt{2} \mu^{\frac{7}{2}} >>> print(latex((2*tau)**Rational(7,2), mode='inline')) $8 \sqrt{2} \tau^{7 / 2}$ >>> print(latex((2*mu)**Rational(7,2), mode='equation*')) \begin{equation*}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation*} >>> print(latex((2*mu)**Rational(7,2), mode='equation')) \begin{equation}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation} >>> print(latex((2*mu)**Rational(7,2), mode='equation', itex=True)) $$8 \sqrt{2} \mu^{\frac{7}{2}}$$ Fraction options: >>> print(latex((2*tau)**Rational(7,2), fold_frac_powers=True)) 8 \sqrt{2} \tau^{7/2} >>> print(latex((2*tau)**sin(Rational(7,2)))) \left(2 \tau\right)^{\sin{\left(\frac{7}{2} \right)}} >>> print(latex((2*tau)**sin(Rational(7,2)), fold_func_brackets=True)) \left(2 \tau\right)^{\sin {\frac{7}{2}}} >>> print(latex(3*x**2/y)) \frac{3 x^{2}}{y} >>> print(latex(3*x**2/y, fold_short_frac=True)) 3 x^{2} / y >>> print(latex(Integral(r, r)/2/pi, long_frac_ratio=2)) \frac{\int r\, dr}{2 \pi} >>> print(latex(Integral(r, r)/2/pi, long_frac_ratio=0)) \frac{1}{2 \pi} \int r\, dr Multiplication options: >>> print(latex((2*tau)**sin(Rational(7,2)), mul_symbol="times")) \left(2 \times \tau\right)^{\sin{\left(\frac{7}{2} \right)}} Trig options: >>> print(latex(asin(Rational(7,2)))) \operatorname{asin}{\left(\frac{7}{2} \right)} >>> print(latex(asin(Rational(7,2)), inv_trig_style="full")) \arcsin{\left(\frac{7}{2} \right)} >>> print(latex(asin(Rational(7,2)), inv_trig_style="power")) \sin^{-1}{\left(\frac{7}{2} \right)} Matrix options: >>> print(latex(Matrix(2, 1, [x, y]))) \left[\begin{matrix}x\\y\end{matrix}\right] >>> print(latex(Matrix(2, 1, [x, y]), mat_str = "array")) \left[\begin{array}{c}x\\y\end{array}\right] >>> print(latex(Matrix(2, 1, [x, y]), mat_delim="(")) \left(\begin{matrix}x\\y\end{matrix}\right) Custom printing of symbols: >>> print(latex(x**2, symbol_names={x: 'x_i'})) x_i^{2} Logarithms: >>> print(latex(log(10))) \log{\left(10 \right)} >>> print(latex(log(10), ln_notation=True)) \ln{\left(10 \right)} ``latex()`` also supports the builtin container types :class:`list`, :class:`tuple`, and :class:`dict`: >>> print(latex([2/x, y], mode='inline')) $\left[ 2 / x, \ y\right]$ Unsupported types are rendered as monospaced plaintext: >>> print(latex(int)) \mathtt{\text{<class 'int'>}} >>> print(latex("plain % text")) \mathtt{\text{plain \% text}} See :ref:`printer_method_example` for an example of how to override this behavior for your own types by implementing ``_latex``. .. versionchanged:: 1.7.0 Unsupported types no longer have their ``str`` representation treated as valid latex. """ return LatexPrinter(settings).doprint(expr) def print_latex(expr, **settings): """Prints LaTeX representation of the given expression. Takes the same settings as ``latex()``.""" print(latex(expr, **settings)) def multiline_latex(lhs, rhs, terms_per_line=1, environment="align*", use_dots=False, **settings): r""" This function generates a LaTeX equation with a multiline right-hand side in an ``align*``, ``eqnarray`` or ``IEEEeqnarray`` environment. Parameters ========== lhs : Expr Left-hand side of equation rhs : Expr Right-hand side of equation terms_per_line : integer, optional Number of terms per line to print. Default is 1. environment : "string", optional Which LaTeX wnvironment to use for the output. Options are "align*" (default), "eqnarray", and "IEEEeqnarray". use_dots : boolean, optional If ``True``, ``\\dots`` is added to the end of each line. Default is ``False``. Examples ======== >>> from sympy import multiline_latex, symbols, sin, cos, exp, log, I >>> x, y, alpha = symbols('x y alpha') >>> expr = sin(alpha*y) + exp(I*alpha) - cos(log(y)) >>> print(multiline_latex(x, expr)) \begin{align*} x = & e^{i \alpha} \\ & + \sin{\left(\alpha y \right)} \\ & - \cos{\left(\log{\left(y \right)} \right)} \end{align*} Using at most two terms per line: >>> print(multiline_latex(x, expr, 2)) \begin{align*} x = & e^{i \alpha} + \sin{\left(\alpha y \right)} \\ & - \cos{\left(\log{\left(y \right)} \right)} \end{align*} Using ``eqnarray`` and dots: >>> print(multiline_latex(x, expr, terms_per_line=2, environment="eqnarray", use_dots=True)) \begin{eqnarray} x & = & e^{i \alpha} + \sin{\left(\alpha y \right)} \dots\nonumber\\ & & - \cos{\left(\log{\left(y \right)} \right)} \end{eqnarray} Using ``IEEEeqnarray``: >>> print(multiline_latex(x, expr, environment="IEEEeqnarray")) \begin{IEEEeqnarray}{rCl} x & = & e^{i \alpha} \nonumber\\ & & + \sin{\left(\alpha y \right)} \nonumber\\ & & - \cos{\left(\log{\left(y \right)} \right)} \end{IEEEeqnarray} Notes ===== All optional parameters from ``latex`` can also be used. """ # Based on code from https://github.com/sympy/sympy/issues/3001 l = LatexPrinter(**settings) if environment == "eqnarray": result = r'\begin{eqnarray}' + '\n' first_term = '& = &' nonumber = r'\nonumber' end_term = '\n\\end{eqnarray}' doubleet = True elif environment == "IEEEeqnarray": result = r'\begin{IEEEeqnarray}{rCl}' + '\n' first_term = '& = &' nonumber = r'\nonumber' end_term = '\n\\end{IEEEeqnarray}' doubleet = True elif environment == "align*": result = r'\begin{align*}' + '\n' first_term = '= &' nonumber = '' end_term = '\n\\end{align*}' doubleet = False else: raise ValueError("Unknown environment: {}".format(environment)) dots = '' if use_dots: dots=r'\dots' terms = rhs.as_ordered_terms() n_terms = len(terms) term_count = 1 for i in range(n_terms): term = terms[i] term_start = '' term_end = '' sign = '+' if term_count > terms_per_line: if doubleet: term_start = '& & ' else: term_start = '& ' term_count = 1 if term_count == terms_per_line: # End of line if i < n_terms-1: # There are terms remaining term_end = dots + nonumber + r'\\' + '\n' else: term_end = '' if term.as_ordered_factors()[0] == -1: term = -1*term sign = r'-' if i == 0: # beginning if sign == '+': sign = '' result += r'{:s} {:s}{:s} {:s} {:s}'.format(l.doprint(lhs), first_term, sign, l.doprint(term), term_end) else: result += r'{:s}{:s} {:s} {:s}'.format(term_start, sign, l.doprint(term), term_end) term_count += 1 result += end_term return result
0bfe5c79f8497d3dd1272c31a9e979090be25180a45470c6cd8beeda6238cc78
"""Printing subsystem driver SymPy's printing system works the following way: Any expression can be passed to a designated Printer who then is responsible to return an adequate representation of that expression. **The basic concept is the following:** 1. Let the object print itself if it knows how. 2. Take the best fitting method defined in the printer. 3. As fall-back use the emptyPrinter method for the printer. Which Method is Responsible for Printing? ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The whole printing process is started by calling ``.doprint(expr)`` on the printer which you want to use. This method looks for an appropriate method which can print the given expression in the given style that the printer defines. While looking for the method, it follows these steps: 1. **Let the object print itself if it knows how.** The printer looks for a specific method in every object. The name of that method depends on the specific printer and is defined under ``Printer.printmethod``. For example, StrPrinter calls ``_sympystr`` and LatexPrinter calls ``_latex``. Look at the documentation of the printer that you want to use. The name of the method is specified there. This was the original way of doing printing in sympy. Every class had its own latex, mathml, str and repr methods, but it turned out that it is hard to produce a high quality printer, if all the methods are spread out that far. Therefore all printing code was combined into the different printers, which works great for built-in SymPy objects, but not that good for user defined classes where it is inconvenient to patch the printers. 2. **Take the best fitting method defined in the printer.** The printer loops through expr classes (class + its bases), and tries to dispatch the work to ``_print_<EXPR_CLASS>`` e.g., suppose we have the following class hierarchy:: Basic | Atom | Number | Rational then, for ``expr=Rational(...)``, the Printer will try to call printer methods in the order as shown in the figure below:: p._print(expr) | |-- p._print_Rational(expr) | |-- p._print_Number(expr) | |-- p._print_Atom(expr) | `-- p._print_Basic(expr) if ``._print_Rational`` method exists in the printer, then it is called, and the result is returned back. Otherwise, the printer tries to call ``._print_Number`` and so on. 3. **As a fall-back use the emptyPrinter method for the printer.** As fall-back ``self.emptyPrinter`` will be called with the expression. If not defined in the Printer subclass this will be the same as ``str(expr)``. .. _printer_example: Example of Custom Printer ^^^^^^^^^^^^^^^^^^^^^^^^^ In the example below, we have a printer which prints the derivative of a function in a shorter form. .. code-block:: python from sympy.core.symbol import Symbol from sympy.printing.latex import LatexPrinter, print_latex from sympy.core.function import UndefinedFunction, Function class MyLatexPrinter(LatexPrinter): \"\"\"Print derivative of a function of symbols in a shorter form. \"\"\" def _print_Derivative(self, expr): function, *vars = expr.args if not isinstance(type(function), UndefinedFunction) or \\ not all(isinstance(i, Symbol) for i in vars): return super()._print_Derivative(expr) # If you want the printer to work correctly for nested # expressions then use self._print() instead of str() or latex(). # See the example of nested modulo below in the custom printing # method section. return "{}_{{{}}}".format( self._print(Symbol(function.func.__name__)), ''.join(self._print(i) for i in vars)) def print_my_latex(expr): \"\"\" Most of the printers define their own wrappers for print(). These wrappers usually take printer settings. Our printer does not have any settings. \"\"\" print(MyLatexPrinter().doprint(expr)) y = Symbol("y") x = Symbol("x") f = Function("f") expr = f(x, y).diff(x, y) # Print the expression using the normal latex printer and our custom # printer. print_latex(expr) print_my_latex(expr) The output of the code above is:: \\frac{\\partial^{2}}{\\partial x\\partial y} f{\\left(x,y \\right)} f_{xy} .. _printer_method_example: Example of Custom Printing Method ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ In the example below, the latex printing of the modulo operator is modified. This is done by overriding the method ``_latex`` of ``Mod``. >>> from sympy import Symbol, Mod, Integer, print_latex >>> # Always use printer._print() >>> class ModOp(Mod): ... def _latex(self, printer): ... a, b = [printer._print(i) for i in self.args] ... return r"\\operatorname{Mod}{\\left(%s, %s\\right)}" % (a, b) Comparing the output of our custom operator to the builtin one: >>> x = Symbol('x') >>> m = Symbol('m') >>> print_latex(Mod(x, m)) x \\bmod m >>> print_latex(ModOp(x, m)) \\operatorname{Mod}{\\left(x, m\\right)} Common mistakes ~~~~~~~~~~~~~~~ It's important to always use ``self._print(obj)`` to print subcomponents of an expression when customizing a printer. Mistakes include: 1. Using ``self.doprint(obj)`` instead: >>> # This example does not work properly, as only the outermost call may use >>> # doprint. >>> class ModOpModeWrong(Mod): ... def _latex(self, printer): ... a, b = [printer.doprint(i) for i in self.args] ... return r"\\operatorname{Mod}{\\left(%s, %s\\right)}" % (a, b) This fails when the ``mode`` argument is passed to the printer: >>> print_latex(ModOp(x, m), mode='inline') # ok $\\operatorname{Mod}{\\left(x, m\\right)}$ >>> print_latex(ModOpModeWrong(x, m), mode='inline') # bad $\\operatorname{Mod}{\\left($x$, $m$\\right)}$ 2. Using ``str(obj)`` instead: >>> class ModOpNestedWrong(Mod): ... def _latex(self, printer): ... a, b = [str(i) for i in self.args] ... return r"\\operatorname{Mod}{\\left(%s, %s\\right)}" % (a, b) This fails on nested objects: >>> # Nested modulo. >>> print_latex(ModOp(ModOp(x, m), Integer(7))) # ok \\operatorname{Mod}{\\left(\\operatorname{Mod}{\\left(x, m\\right)}, 7\\right)} >>> print_latex(ModOpNestedWrong(ModOpNestedWrong(x, m), Integer(7))) # bad \\operatorname{Mod}{\\left(ModOpNestedWrong(x, m), 7\\right)} 3. Using ``LatexPrinter()._print(obj)`` instead. >>> from sympy.printing.latex import LatexPrinter >>> class ModOpSettingsWrong(Mod): ... def _latex(self, printer): ... a, b = [LatexPrinter()._print(i) for i in self.args] ... return r"\\operatorname{Mod}{\\left(%s, %s\\right)}" % (a, b) This causes all the settings to be discarded in the subobjects. As an example, the ``full_prec`` setting which shows floats to full precision is ignored: >>> from sympy import Float >>> print_latex(ModOp(Float(1) * x, m), full_prec=True) # ok \\operatorname{Mod}{\\left(1.00000000000000 x, m\\right)} >>> print_latex(ModOpSettingsWrong(Float(1) * x, m), full_prec=True) # bad \\operatorname{Mod}{\\left(1.0 x, m\\right)} """ import sys from typing import Any, Dict as tDict, Type import inspect from contextlib import contextmanager from functools import cmp_to_key, update_wrapper from sympy.core.add import Add from sympy.core.basic import Basic from sympy.core.core import BasicMeta from sympy.core.function import AppliedUndef, UndefinedFunction, Function @contextmanager def printer_context(printer, **kwargs): original = printer._context.copy() try: printer._context.update(kwargs) yield finally: printer._context = original class Printer: """ Generic printer Its job is to provide infrastructure for implementing new printers easily. If you want to define your custom Printer or your custom printing method for your custom class then see the example above: printer_example_ . """ _global_settings = {} # type: tDict[str, Any] _default_settings = {} # type: tDict[str, Any] printmethod = None # type: str @classmethod def _get_initial_settings(cls): settings = cls._default_settings.copy() for key, val in cls._global_settings.items(): if key in cls._default_settings: settings[key] = val return settings def __init__(self, settings=None): self._str = str self._settings = self._get_initial_settings() self._context = {} # mutable during printing if settings is not None: self._settings.update(settings) if len(self._settings) > len(self._default_settings): for key in self._settings: if key not in self._default_settings: raise TypeError("Unknown setting '%s'." % key) # _print_level is the number of times self._print() was recursively # called. See StrPrinter._print_Float() for an example of usage self._print_level = 0 @classmethod def set_global_settings(cls, **settings): """Set system-wide printing settings. """ for key, val in settings.items(): if val is not None: cls._global_settings[key] = val @property def order(self): if 'order' in self._settings: return self._settings['order'] else: raise AttributeError("No order defined.") def doprint(self, expr): """Returns printer's representation for expr (as a string)""" return self._str(self._print(expr)) def _print(self, expr, **kwargs) -> str: """Internal dispatcher Tries the following concepts to print an expression: 1. Let the object print itself if it knows how. 2. Take the best fitting method defined in the printer. 3. As fall-back use the emptyPrinter method for the printer. """ self._print_level += 1 try: # If the printer defines a name for a printing method # (Printer.printmethod) and the object knows for itself how it # should be printed, use that method. if (self.printmethod and hasattr(expr, self.printmethod) and not isinstance(expr, BasicMeta)): return getattr(expr, self.printmethod)(self, **kwargs) # See if the class of expr is known, or if one of its super # classes is known, and use that print function # Exception: ignore the subclasses of Undefined, so that, e.g., # Function('gamma') does not get dispatched to _print_gamma classes = type(expr).__mro__ if AppliedUndef in classes: classes = classes[classes.index(AppliedUndef):] if UndefinedFunction in classes: classes = classes[classes.index(UndefinedFunction):] # Another exception: if someone subclasses a known function, e.g., # gamma, and changes the name, then ignore _print_gamma if Function in classes: i = classes.index(Function) classes = tuple(c for c in classes[:i] if \ c.__name__ == classes[0].__name__ or \ c.__name__.endswith("Base")) + classes[i:] for cls in classes: printmethodname = '_print_' + cls.__name__ printmethod = getattr(self, printmethodname, None) if printmethod is not None: return printmethod(expr, **kwargs) # Unknown object, fall back to the emptyPrinter. return self.emptyPrinter(expr) finally: self._print_level -= 1 def emptyPrinter(self, expr): return str(expr) def _as_ordered_terms(self, expr, order=None): """A compatibility function for ordering terms in Add. """ order = order or self.order if order == 'old': return sorted(Add.make_args(expr), key=cmp_to_key(Basic._compare_pretty)) elif order == 'none': return list(expr.args) else: return expr.as_ordered_terms(order=order) class _PrintFunction: """ Function wrapper to replace ``**settings`` in the signature with printer defaults """ def __init__(self, f, print_cls: Type[Printer]): # find all the non-setting arguments params = list(inspect.signature(f).parameters.values()) assert params.pop(-1).kind == inspect.Parameter.VAR_KEYWORD self.__other_params = params self.__print_cls = print_cls update_wrapper(self, f) def __reduce__(self): # Since this is used as a decorator, it replaces the original function. # The default pickling will try to pickle self.__wrapped__ and fail # because the wrapped function can't be retrieved by name. return self.__wrapped__.__qualname__ def __call__(self, *args, **kwargs): return self.__wrapped__(*args, **kwargs) @property def __signature__(self) -> inspect.Signature: settings = self.__print_cls._get_initial_settings() return inspect.Signature( parameters=self.__other_params + [ inspect.Parameter(k, inspect.Parameter.KEYWORD_ONLY, default=v) for k, v in settings.items() ], return_annotation=self.__wrapped__.__annotations__.get('return', inspect.Signature.empty) # type:ignore ) def print_function(print_cls): """ A decorator to replace kwargs with the printer settings in __signature__ """ def decorator(f): if sys.version_info < (3, 9): # We have to create a subclass so that `help` actually shows the docstring in older Python versions. # IPython and Sphinx do not need this, only a raw Python console. cls = type(f'{f.__qualname__}_PrintFunction', (_PrintFunction,), dict(__doc__=f.__doc__)) else: cls = _PrintFunction return cls(f, print_cls) return decorator
042c78792746f0c43c652515d655847770b36d9e0888c89df934f13e857a1475
from .pycode import ( PythonCodePrinter, MpmathPrinter, ) from .numpy import NumPyPrinter # NumPyPrinter is imported for backward compatibility from sympy.core.sorting import default_sort_key __all__ = [ 'PythonCodePrinter', 'MpmathPrinter', # MpmathPrinter is published for backward compatibility 'NumPyPrinter', 'LambdaPrinter', 'NumPyPrinter', 'IntervalPrinter', 'lambdarepr', ] class LambdaPrinter(PythonCodePrinter): """ This printer converts expressions into strings that can be used by lambdify. """ printmethod = "_lambdacode" def _print_And(self, expr): result = ['('] for arg in sorted(expr.args, key=default_sort_key): result.extend(['(', self._print(arg), ')']) result.append(' and ') result = result[:-1] result.append(')') return ''.join(result) def _print_Or(self, expr): result = ['('] for arg in sorted(expr.args, key=default_sort_key): result.extend(['(', self._print(arg), ')']) result.append(' or ') result = result[:-1] result.append(')') return ''.join(result) def _print_Not(self, expr): result = ['(', 'not (', self._print(expr.args[0]), '))'] return ''.join(result) def _print_BooleanTrue(self, expr): return "True" def _print_BooleanFalse(self, expr): return "False" def _print_ITE(self, expr): result = [ '((', self._print(expr.args[1]), ') if (', self._print(expr.args[0]), ') else (', self._print(expr.args[2]), '))' ] return ''.join(result) def _print_NumberSymbol(self, expr): return str(expr) def _print_Pow(self, expr, **kwargs): # XXX Temporary workaround. Should Python math printer be # isolated from PythonCodePrinter? return super(PythonCodePrinter, self)._print_Pow(expr, **kwargs) # numexpr works by altering the string passed to numexpr.evaluate # rather than by populating a namespace. Thus a special printer... class NumExprPrinter(LambdaPrinter): # key, value pairs correspond to SymPy name and numexpr name # functions not appearing in this dict will raise a TypeError printmethod = "_numexprcode" _numexpr_functions = { 'sin' : 'sin', 'cos' : 'cos', 'tan' : 'tan', 'asin': 'arcsin', 'acos': 'arccos', 'atan': 'arctan', 'atan2' : 'arctan2', 'sinh' : 'sinh', 'cosh' : 'cosh', 'tanh' : 'tanh', 'asinh': 'arcsinh', 'acosh': 'arccosh', 'atanh': 'arctanh', 'ln' : 'log', 'log': 'log', 'exp': 'exp', 'sqrt' : 'sqrt', 'Abs' : 'abs', 'conjugate' : 'conj', 'im' : 'imag', 're' : 'real', 'where' : 'where', 'complex' : 'complex', 'contains' : 'contains', } module = 'numexpr' def _print_ImaginaryUnit(self, expr): return '1j' def _print_seq(self, seq, delimiter=', '): # simplified _print_seq taken from pretty.py s = [self._print(item) for item in seq] if s: return delimiter.join(s) else: return "" def _print_Function(self, e): func_name = e.func.__name__ nstr = self._numexpr_functions.get(func_name, None) if nstr is None: # check for implemented_function if hasattr(e, '_imp_'): return "(%s)" % self._print(e._imp_(*e.args)) else: raise TypeError("numexpr does not support function '%s'" % func_name) return "%s(%s)" % (nstr, self._print_seq(e.args)) def _print_Piecewise(self, expr): "Piecewise function printer" exprs = [self._print(arg.expr) for arg in expr.args] conds = [self._print(arg.cond) for arg in expr.args] # If [default_value, True] is a (expr, cond) sequence in a Piecewise object # it will behave the same as passing the 'default' kwarg to select() # *as long as* it is the last element in expr.args. # If this is not the case, it may be triggered prematurely. ans = [] parenthesis_count = 0 is_last_cond_True = False for cond, expr in zip(conds, exprs): if cond == 'True': ans.append(expr) is_last_cond_True = True break else: ans.append('where(%s, %s, ' % (cond, expr)) parenthesis_count += 1 if not is_last_cond_True: # See https://github.com/pydata/numexpr/issues/298 # # simplest way to put a nan but raises # 'RuntimeWarning: invalid value encountered in log' # # There are other ways to do this such as # # >>> import numexpr as ne # >>> nan = float('nan') # >>> ne.evaluate('where(x < 0, -1, nan)', {'x': [-1, 2, 3], 'nan':nan}) # array([-1., nan, nan]) # # That needs to be handled in the lambdified function though rather # than here in the printer. ans.append('log(-1)') return ''.join(ans) + ')' * parenthesis_count def _print_ITE(self, expr): from sympy.functions.elementary.piecewise import Piecewise return self._print(expr.rewrite(Piecewise)) def blacklisted(self, expr): raise TypeError("numexpr cannot be used with %s" % expr.__class__.__name__) # blacklist all Matrix printing _print_SparseRepMatrix = \ _print_MutableSparseMatrix = \ _print_ImmutableSparseMatrix = \ _print_Matrix = \ _print_DenseMatrix = \ _print_MutableDenseMatrix = \ _print_ImmutableMatrix = \ _print_ImmutableDenseMatrix = \ blacklisted # blacklist some Python expressions _print_list = \ _print_tuple = \ _print_Tuple = \ _print_dict = \ _print_Dict = \ blacklisted def _print_NumExprEvaluate(self, expr): evaluate = self._module_format(self.module +".evaluate") return "%s('%s', truediv=True)" % (evaluate, self._print(expr.expr)) def doprint(self, expr): from sympy.codegen.ast import CodegenAST from sympy.codegen.pynodes import NumExprEvaluate if not isinstance(expr, CodegenAST): expr = NumExprEvaluate(expr) return super().doprint(expr) def _print_Return(self, expr): from sympy.codegen.pynodes import NumExprEvaluate r, = expr.args if not isinstance(r, NumExprEvaluate): expr = expr.func(NumExprEvaluate(r)) return super()._print_Return(expr) def _print_Assignment(self, expr): from sympy.codegen.pynodes import NumExprEvaluate lhs, rhs, *args = expr.args if not isinstance(rhs, NumExprEvaluate): expr = expr.func(lhs, NumExprEvaluate(rhs), *args) return super()._print_Assignment(expr) def _print_CodeBlock(self, expr): from sympy.codegen.ast import CodegenAST from sympy.codegen.pynodes import NumExprEvaluate args = [ arg if isinstance(arg, CodegenAST) else NumExprEvaluate(arg) for arg in expr.args ] return super()._print_CodeBlock(self, expr.func(*args)) class IntervalPrinter(MpmathPrinter, LambdaPrinter): """Use ``lambda`` printer but print numbers as ``mpi`` intervals. """ def _print_Integer(self, expr): return "mpi('%s')" % super(PythonCodePrinter, self)._print_Integer(expr) def _print_Rational(self, expr): return "mpi('%s')" % super(PythonCodePrinter, self)._print_Rational(expr) def _print_Half(self, expr): return "mpi('%s')" % super(PythonCodePrinter, self)._print_Rational(expr) def _print_Pow(self, expr): return super(MpmathPrinter, self)._print_Pow(expr, rational=True) for k in NumExprPrinter._numexpr_functions: setattr(NumExprPrinter, '_print_%s' % k, NumExprPrinter._print_Function) def lambdarepr(expr, **settings): """ Returns a string usable for lambdifying. """ return LambdaPrinter(settings).doprint(expr)
91debb502e4d6085a28a9477cb2a2a8115958041ba3e52332c2a9da5389bc32b
from typing import Any, Dict as tDict, Set as tSet, Tuple as tTuple from functools import wraps from sympy.core import Add, Expr, Mul, Pow, S, sympify, Float from sympy.core.basic import Basic from sympy.core.expr import UnevaluatedExpr from sympy.core.function import Lambda from sympy.core.mul import _keep_coeff from sympy.core.sorting import default_sort_key from sympy.core.symbol import Symbol from sympy.functions.elementary.complexes import re from sympy.printing.str import StrPrinter from sympy.printing.precedence import precedence, PRECEDENCE class requires: """ Decorator for registering requirements on print methods. """ def __init__(self, **kwargs): self._req = kwargs def __call__(self, method): def _method_wrapper(self_, *args, **kwargs): for k, v in self._req.items(): getattr(self_, k).update(v) return method(self_, *args, **kwargs) return wraps(method)(_method_wrapper) class AssignmentError(Exception): """ Raised if an assignment variable for a loop is missing. """ pass def _convert_python_lists(arg): if isinstance(arg, list): from sympy.codegen.abstract_nodes import List return List(*(_convert_python_lists(e) for e in arg)) elif isinstance(arg, tuple): return tuple(_convert_python_lists(e) for e in arg) else: return arg class CodePrinter(StrPrinter): """ The base class for code-printing subclasses. """ _operators = { 'and': '&&', 'or': '||', 'not': '!', } _default_settings = { 'order': None, 'full_prec': 'auto', 'error_on_reserved': False, 'reserved_word_suffix': '_', 'human': True, 'inline': False, 'allow_unknown_functions': False, } # type: tDict[str, Any] # Functions which are "simple" to rewrite to other functions that # may be supported # function_to_rewrite : (function_to_rewrite_to, iterable_with_other_functions_required) _rewriteable_functions = { 'cot': ('tan', []), 'csc': ('sin', []), 'sec': ('cos', []), 'acot': ('atan', []), 'acsc': ('asin', []), 'asec': ('acos', []), 'coth': ('exp', []), 'csch': ('exp', []), 'sech': ('exp', []), 'acoth': ('log', []), 'acsch': ('log', []), 'asech': ('log', []), 'catalan': ('gamma', []), 'fibonacci': ('sqrt', []), 'lucas': ('sqrt', []), 'beta': ('gamma', []), 'sinc': ('sin', ['Piecewise']), 'Mod': ('floor', []), 'factorial': ('gamma', []), 'factorial2': ('gamma', ['Piecewise']), 'subfactorial': ('uppergamma', []), 'RisingFactorial': ('gamma', ['Piecewise']), 'FallingFactorial': ('gamma', ['Piecewise']), 'binomial': ('gamma', []), 'frac': ('floor', []), 'Max': ('Piecewise', []), 'Min': ('Piecewise', []), 'Heaviside': ('Piecewise', []), 'erf2': ('erf', []), 'erfc': ('erf', []), 'Li': ('li', []), 'Ei': ('li', []), 'dirichlet_eta': ('zeta', []), 'riemann_xi': ('zeta', ['gamma']), } def __init__(self, settings=None): super().__init__(settings=settings) if not hasattr(self, 'reserved_words'): self.reserved_words = set() def _handle_UnevaluatedExpr(self, expr): return expr.replace(re, lambda arg: arg if isinstance( arg, UnevaluatedExpr) and arg.args[0].is_real else re(arg)) def doprint(self, expr, assign_to=None): """ Print the expression as code. Parameters ---------- expr : Expression The expression to be printed. assign_to : Symbol, string, MatrixSymbol, list of strings or Symbols (optional) If provided, the printed code will set the expression to a variable or multiple variables with the name or names given in ``assign_to``. """ from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.codegen.ast import CodeBlock, Assignment def _handle_assign_to(expr, assign_to): if assign_to is None: return sympify(expr) if isinstance(assign_to, (list, tuple)): if len(expr) != len(assign_to): raise ValueError('Failed to assign an expression of length {} to {} variables'.format(len(expr), len(assign_to))) return CodeBlock(*[_handle_assign_to(lhs, rhs) for lhs, rhs in zip(expr, assign_to)]) if isinstance(assign_to, str): if expr.is_Matrix: assign_to = MatrixSymbol(assign_to, *expr.shape) else: assign_to = Symbol(assign_to) elif not isinstance(assign_to, Basic): raise TypeError("{} cannot assign to object of type {}".format( type(self).__name__, type(assign_to))) return Assignment(assign_to, expr) expr = _convert_python_lists(expr) expr = _handle_assign_to(expr, assign_to) # Remove re(...) nodes due to UnevaluatedExpr.is_real always is None: expr = self._handle_UnevaluatedExpr(expr) # keep a set of expressions that are not strictly translatable to Code # and number constants that must be declared and initialized self._not_supported = set() self._number_symbols = set() # type: tSet[tTuple[Expr, Float]] lines = self._print(expr).splitlines() # format the output if self._settings["human"]: frontlines = [] if self._not_supported: frontlines.append(self._get_comment( "Not supported in {}:".format(self.language))) for expr in sorted(self._not_supported, key=str): frontlines.append(self._get_comment(type(expr).__name__)) for name, value in sorted(self._number_symbols, key=str): frontlines.append(self._declare_number_const(name, value)) lines = frontlines + lines lines = self._format_code(lines) result = "\n".join(lines) else: lines = self._format_code(lines) num_syms = {(k, self._print(v)) for k, v in self._number_symbols} result = (num_syms, self._not_supported, "\n".join(lines)) self._not_supported = set() self._number_symbols = set() return result def _doprint_loops(self, expr, assign_to=None): # Here we print an expression that contains Indexed objects, they # correspond to arrays in the generated code. The low-level implementation # involves looping over array elements and possibly storing results in temporary # variables or accumulate it in the assign_to object. if self._settings.get('contract', True): from sympy.tensor import get_contraction_structure # Setup loops over non-dummy indices -- all terms need these indices = self._get_expression_indices(expr, assign_to) # Setup loops over dummy indices -- each term needs separate treatment dummies = get_contraction_structure(expr) else: indices = [] dummies = {None: (expr,)} openloop, closeloop = self._get_loop_opening_ending(indices) # terms with no summations first if None in dummies: text = StrPrinter.doprint(self, Add(*dummies[None])) else: # If all terms have summations we must initialize array to Zero text = StrPrinter.doprint(self, 0) # skip redundant assignments (where lhs == rhs) lhs_printed = self._print(assign_to) lines = [] if text != lhs_printed: lines.extend(openloop) if assign_to is not None: text = self._get_statement("%s = %s" % (lhs_printed, text)) lines.append(text) lines.extend(closeloop) # then terms with summations for d in dummies: if isinstance(d, tuple): indices = self._sort_optimized(d, expr) openloop_d, closeloop_d = self._get_loop_opening_ending( indices) for term in dummies[d]: if term in dummies and not ([list(f.keys()) for f in dummies[term]] == [[None] for f in dummies[term]]): # If one factor in the term has it's own internal # contractions, those must be computed first. # (temporary variables?) raise NotImplementedError( "FIXME: no support for contractions in factor yet") else: # We need the lhs expression as an accumulator for # the loops, i.e # # for (int d=0; d < dim; d++){ # lhs[] = lhs[] + term[][d] # } ^.................. the accumulator # # We check if the expression already contains the # lhs, and raise an exception if it does, as that # syntax is currently undefined. FIXME: What would be # a good interpretation? if assign_to is None: raise AssignmentError( "need assignment variable for loops") if term.has(assign_to): raise ValueError("FIXME: lhs present in rhs,\ this is undefined in CodePrinter") lines.extend(openloop) lines.extend(openloop_d) text = "%s = %s" % (lhs_printed, StrPrinter.doprint( self, assign_to + term)) lines.append(self._get_statement(text)) lines.extend(closeloop_d) lines.extend(closeloop) return "\n".join(lines) def _get_expression_indices(self, expr, assign_to): from sympy.tensor import get_indices rinds, junk = get_indices(expr) linds, junk = get_indices(assign_to) # support broadcast of scalar if linds and not rinds: rinds = linds if rinds != linds: raise ValueError("lhs indices must match non-dummy" " rhs indices in %s" % expr) return self._sort_optimized(rinds, assign_to) def _sort_optimized(self, indices, expr): from sympy.tensor.indexed import Indexed if not indices: return [] # determine optimized loop order by giving a score to each index # the index with the highest score are put in the innermost loop. score_table = {} for i in indices: score_table[i] = 0 arrays = expr.atoms(Indexed) for arr in arrays: for p, ind in enumerate(arr.indices): try: score_table[ind] += self._rate_index_position(p) except KeyError: pass return sorted(indices, key=lambda x: score_table[x]) def _rate_index_position(self, p): """function to calculate score based on position among indices This method is used to sort loops in an optimized order, see CodePrinter._sort_optimized() """ raise NotImplementedError("This function must be implemented by " "subclass of CodePrinter.") def _get_statement(self, codestring): """Formats a codestring with the proper line ending.""" raise NotImplementedError("This function must be implemented by " "subclass of CodePrinter.") def _get_comment(self, text): """Formats a text string as a comment.""" raise NotImplementedError("This function must be implemented by " "subclass of CodePrinter.") def _declare_number_const(self, name, value): """Declare a numeric constant at the top of a function""" raise NotImplementedError("This function must be implemented by " "subclass of CodePrinter.") def _format_code(self, lines): """Take in a list of lines of code, and format them accordingly. This may include indenting, wrapping long lines, etc...""" raise NotImplementedError("This function must be implemented by " "subclass of CodePrinter.") def _get_loop_opening_ending(self, indices): """Returns a tuple (open_lines, close_lines) containing lists of codelines""" raise NotImplementedError("This function must be implemented by " "subclass of CodePrinter.") def _print_Dummy(self, expr): if expr.name.startswith('Dummy_'): return '_' + expr.name else: return '%s_%d' % (expr.name, expr.dummy_index) def _print_CodeBlock(self, expr): return '\n'.join([self._print(i) for i in expr.args]) def _print_String(self, string): return str(string) def _print_QuotedString(self, arg): return '"%s"' % arg.text def _print_Comment(self, string): return self._get_comment(str(string)) def _print_Assignment(self, expr): from sympy.codegen.ast import Assignment from sympy.functions.elementary.piecewise import Piecewise from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.tensor.indexed import IndexedBase lhs = expr.lhs rhs = expr.rhs # We special case assignments that take multiple lines if isinstance(expr.rhs, Piecewise): # Here we modify Piecewise so each expression is now # an Assignment, and then continue on the print. expressions = [] conditions = [] for (e, c) in rhs.args: expressions.append(Assignment(lhs, e)) conditions.append(c) temp = Piecewise(*zip(expressions, conditions)) return self._print(temp) elif isinstance(lhs, MatrixSymbol): # Here we form an Assignment for each element in the array, # printing each one. lines = [] for (i, j) in self._traverse_matrix_indices(lhs): temp = Assignment(lhs[i, j], rhs[i, j]) code0 = self._print(temp) lines.append(code0) return "\n".join(lines) elif self._settings.get("contract", False) and (lhs.has(IndexedBase) or rhs.has(IndexedBase)): # Here we check if there is looping to be done, and if so # print the required loops. return self._doprint_loops(rhs, lhs) else: lhs_code = self._print(lhs) rhs_code = self._print(rhs) return self._get_statement("%s = %s" % (lhs_code, rhs_code)) def _print_AugmentedAssignment(self, expr): lhs_code = self._print(expr.lhs) rhs_code = self._print(expr.rhs) return self._get_statement("{} {} {}".format( *map(lambda arg: self._print(arg), [lhs_code, expr.op, rhs_code]))) def _print_FunctionCall(self, expr): return '%s(%s)' % ( expr.name, ', '.join(map(lambda arg: self._print(arg), expr.function_args))) def _print_Variable(self, expr): return self._print(expr.symbol) def _print_Symbol(self, expr): name = super()._print_Symbol(expr) if name in self.reserved_words: if self._settings['error_on_reserved']: msg = ('This expression includes the symbol "{}" which is a ' 'reserved keyword in this language.') raise ValueError(msg.format(name)) return name + self._settings['reserved_word_suffix'] else: return name def _can_print(self, name): """ Check if function ``name`` is either a known function or has its own printing method. Used to check if rewriting is possible.""" return name in self.known_functions or getattr(self, '_print_{}'.format(name), False) def _print_Function(self, expr): if expr.func.__name__ in self.known_functions: cond_func = self.known_functions[expr.func.__name__] func = None if isinstance(cond_func, str): func = cond_func else: for cond, func in cond_func: if cond(*expr.args): break if func is not None: try: return func(*[self.parenthesize(item, 0) for item in expr.args]) except TypeError: return "%s(%s)" % (func, self.stringify(expr.args, ", ")) elif hasattr(expr, '_imp_') and isinstance(expr._imp_, Lambda): # inlined function return self._print(expr._imp_(*expr.args)) elif expr.func.__name__ in self._rewriteable_functions: # Simple rewrite to supported function possible target_f, required_fs = self._rewriteable_functions[expr.func.__name__] if self._can_print(target_f) and all(self._can_print(f) for f in required_fs): return self._print(expr.rewrite(target_f)) if expr.is_Function and self._settings.get('allow_unknown_functions', False): return '%s(%s)' % (self._print(expr.func), ', '.join(map(self._print, expr.args))) else: return self._print_not_supported(expr) _print_Expr = _print_Function # Don't inherit the str-printer method for Heaviside to the code printers _print_Heaviside = None def _print_NumberSymbol(self, expr): if self._settings.get("inline", False): return self._print(Float(expr.evalf(self._settings["precision"]))) else: # A Number symbol that is not implemented here or with _printmethod # is registered and evaluated self._number_symbols.add((expr, Float(expr.evalf(self._settings["precision"])))) return str(expr) def _print_Catalan(self, expr): return self._print_NumberSymbol(expr) def _print_EulerGamma(self, expr): return self._print_NumberSymbol(expr) def _print_GoldenRatio(self, expr): return self._print_NumberSymbol(expr) def _print_TribonacciConstant(self, expr): return self._print_NumberSymbol(expr) def _print_Exp1(self, expr): return self._print_NumberSymbol(expr) def _print_Pi(self, expr): return self._print_NumberSymbol(expr) def _print_And(self, expr): PREC = precedence(expr) return (" %s " % self._operators['and']).join(self.parenthesize(a, PREC) for a in sorted(expr.args, key=default_sort_key)) def _print_Or(self, expr): PREC = precedence(expr) return (" %s " % self._operators['or']).join(self.parenthesize(a, PREC) for a in sorted(expr.args, key=default_sort_key)) def _print_Xor(self, expr): if self._operators.get('xor') is None: return self._print(expr.to_nnf()) PREC = precedence(expr) return (" %s " % self._operators['xor']).join(self.parenthesize(a, PREC) for a in expr.args) def _print_Equivalent(self, expr): if self._operators.get('equivalent') is None: return self._print(expr.to_nnf()) PREC = precedence(expr) return (" %s " % self._operators['equivalent']).join(self.parenthesize(a, PREC) for a in expr.args) def _print_Not(self, expr): PREC = precedence(expr) return self._operators['not'] + self.parenthesize(expr.args[0], PREC) def _print_BooleanFunction(self, expr): return self._print(expr.to_nnf()) def _print_Mul(self, expr): prec = precedence(expr) c, e = expr.as_coeff_Mul() if c < 0: expr = _keep_coeff(-c, e) sign = "-" else: sign = "" a = [] # items in the numerator b = [] # items that are in the denominator (if any) pow_paren = [] # Will collect all pow with more than one base element and exp = -1 if self.order not in ('old', 'none'): args = expr.as_ordered_factors() else: # use make_args in case expr was something like -x -> x args = Mul.make_args(expr) # Gather args for numerator/denominator for item in args: if item.is_commutative and item.is_Pow and item.exp.is_Rational and item.exp.is_negative: if item.exp != -1: b.append(Pow(item.base, -item.exp, evaluate=False)) else: if len(item.args[0].args) != 1 and isinstance(item.base, Mul): # To avoid situations like #14160 pow_paren.append(item) b.append(Pow(item.base, -item.exp)) else: a.append(item) a = a or [S.One] if len(a) == 1 and sign == "-": # Unary minus does not have a SymPy class, and hence there's no # precedence weight associated with it, Python's unary minus has # an operator precedence between multiplication and exponentiation, # so we use this to compute a weight. a_str = [self.parenthesize(a[0], 0.5*(PRECEDENCE["Pow"]+PRECEDENCE["Mul"]))] else: a_str = [self.parenthesize(x, prec) for x in a] b_str = [self.parenthesize(x, prec) for x in b] # To parenthesize Pow with exp = -1 and having more than one Symbol for item in pow_paren: if item.base in b: b_str[b.index(item.base)] = "(%s)" % b_str[b.index(item.base)] if not b: return sign + '*'.join(a_str) elif len(b) == 1: return sign + '*'.join(a_str) + "/" + b_str[0] else: return sign + '*'.join(a_str) + "/(%s)" % '*'.join(b_str) def _print_not_supported(self, expr): try: self._not_supported.add(expr) except TypeError: # not hashable pass return self.emptyPrinter(expr) # The following can not be simply translated into C or Fortran _print_Basic = _print_not_supported _print_ComplexInfinity = _print_not_supported _print_Derivative = _print_not_supported _print_ExprCondPair = _print_not_supported _print_GeometryEntity = _print_not_supported _print_Infinity = _print_not_supported _print_Integral = _print_not_supported _print_Interval = _print_not_supported _print_AccumulationBounds = _print_not_supported _print_Limit = _print_not_supported _print_MatrixBase = _print_not_supported _print_DeferredVector = _print_not_supported _print_NaN = _print_not_supported _print_NegativeInfinity = _print_not_supported _print_Order = _print_not_supported _print_RootOf = _print_not_supported _print_RootsOf = _print_not_supported _print_RootSum = _print_not_supported _print_Uniform = _print_not_supported _print_Unit = _print_not_supported _print_Wild = _print_not_supported _print_WildFunction = _print_not_supported _print_Relational = _print_not_supported # Code printer functions. These are included in this file so that they can be # imported in the top-level __init__.py without importing the sympy.codegen # module. def ccode(expr, assign_to=None, standard='c99', **settings): """Converts an expr to a string of c code Parameters ========== expr : Expr A SymPy expression to be converted. assign_to : optional When given, the argument is used as the name of the variable to which the expression is assigned. Can be a string, ``Symbol``, ``MatrixSymbol``, or ``Indexed`` type. This is helpful in case of line-wrapping, or for expressions that generate multi-line statements. standard : str, optional String specifying the standard. If your compiler supports a more modern standard you may set this to 'c99' to allow the printer to use more math functions. [default='c89']. precision : integer, optional The precision for numbers such as pi [default=17]. user_functions : dict, optional A dictionary where the keys are string representations of either ``FunctionClass`` or ``UndefinedFunction`` instances and the values are their desired C string representations. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, cfunction_string)] or [(argument_test, cfunction_formater)]. See below for examples. dereference : iterable, optional An iterable of symbols that should be dereferenced in the printed code expression. These would be values passed by address to the function. For example, if ``dereference=[a]``, the resulting code would print ``(*a)`` instead of ``a``. human : bool, optional If True, the result is a single string that may contain some constant declarations for the number symbols. If False, the same information is returned in a tuple of (symbols_to_declare, not_supported_functions, code_text). [default=True]. contract: bool, optional If True, ``Indexed`` instances are assumed to obey tensor contraction rules and the corresponding nested loops over indices are generated. Setting contract=False will not generate loops, instead the user is responsible to provide values for the indices in the code. [default=True]. Examples ======== >>> from sympy import ccode, symbols, Rational, sin, ceiling, Abs, Function >>> x, tau = symbols("x, tau") >>> expr = (2*tau)**Rational(7, 2) >>> ccode(expr) '8*M_SQRT2*pow(tau, 7.0/2.0)' >>> ccode(expr, math_macros={}) '8*sqrt(2)*pow(tau, 7.0/2.0)' >>> ccode(sin(x), assign_to="s") 's = sin(x);' >>> from sympy.codegen.ast import real, float80 >>> ccode(expr, type_aliases={real: float80}) '8*M_SQRT2l*powl(tau, 7.0L/2.0L)' Simple custom printing can be defined for certain types by passing a dictionary of {"type" : "function"} to the ``user_functions`` kwarg. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, cfunction_string)]. >>> custom_functions = { ... "ceiling": "CEIL", ... "Abs": [(lambda x: not x.is_integer, "fabs"), ... (lambda x: x.is_integer, "ABS")], ... "func": "f" ... } >>> func = Function('func') >>> ccode(func(Abs(x) + ceiling(x)), standard='C89', user_functions=custom_functions) 'f(fabs(x) + CEIL(x))' or if the C-function takes a subset of the original arguments: >>> ccode(2**x + 3**x, standard='C99', user_functions={'Pow': [ ... (lambda b, e: b == 2, lambda b, e: 'exp2(%s)' % e), ... (lambda b, e: b != 2, 'pow')]}) 'exp2(x) + pow(3, x)' ``Piecewise`` expressions are converted into conditionals. If an ``assign_to`` variable is provided an if statement is created, otherwise the ternary operator is used. Note that if the ``Piecewise`` lacks a default term, represented by ``(expr, True)`` then an error will be thrown. This is to prevent generating an expression that may not evaluate to anything. >>> from sympy import Piecewise >>> expr = Piecewise((x + 1, x > 0), (x, True)) >>> print(ccode(expr, tau, standard='C89')) if (x > 0) { tau = x + 1; } else { tau = x; } Support for loops is provided through ``Indexed`` types. With ``contract=True`` these expressions will be turned into loops, whereas ``contract=False`` will just print the assignment expression that should be looped over: >>> from sympy import Eq, IndexedBase, Idx >>> len_y = 5 >>> y = IndexedBase('y', shape=(len_y,)) >>> t = IndexedBase('t', shape=(len_y,)) >>> Dy = IndexedBase('Dy', shape=(len_y-1,)) >>> i = Idx('i', len_y-1) >>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i])) >>> ccode(e.rhs, assign_to=e.lhs, contract=False, standard='C89') 'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);' Matrices are also supported, but a ``MatrixSymbol`` of the same dimensions must be provided to ``assign_to``. Note that any expression that can be generated normally can also exist inside a Matrix: >>> from sympy import Matrix, MatrixSymbol >>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)]) >>> A = MatrixSymbol('A', 3, 1) >>> print(ccode(mat, A, standard='C89')) A[0] = pow(x, 2); if (x > 0) { A[1] = x + 1; } else { A[1] = x; } A[2] = sin(x); """ from sympy.printing.c import c_code_printers return c_code_printers[standard.lower()](settings).doprint(expr, assign_to) def print_ccode(expr, **settings): """Prints C representation of the given expression.""" print(ccode(expr, **settings)) def fcode(expr, assign_to=None, **settings): """Converts an expr to a string of fortran code Parameters ========== expr : Expr A SymPy expression to be converted. assign_to : optional When given, the argument is used as the name of the variable to which the expression is assigned. Can be a string, ``Symbol``, ``MatrixSymbol``, or ``Indexed`` type. This is helpful in case of line-wrapping, or for expressions that generate multi-line statements. precision : integer, optional DEPRECATED. Use type_mappings instead. The precision for numbers such as pi [default=17]. user_functions : dict, optional A dictionary where keys are ``FunctionClass`` instances and values are their string representations. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, cfunction_string)]. See below for examples. human : bool, optional If True, the result is a single string that may contain some constant declarations for the number symbols. If False, the same information is returned in a tuple of (symbols_to_declare, not_supported_functions, code_text). [default=True]. contract: bool, optional If True, ``Indexed`` instances are assumed to obey tensor contraction rules and the corresponding nested loops over indices are generated. Setting contract=False will not generate loops, instead the user is responsible to provide values for the indices in the code. [default=True]. source_format : optional The source format can be either 'fixed' or 'free'. [default='fixed'] standard : integer, optional The Fortran standard to be followed. This is specified as an integer. Acceptable standards are 66, 77, 90, 95, 2003, and 2008. Default is 77. Note that currently the only distinction internally is between standards before 95, and those 95 and after. This may change later as more features are added. name_mangling : bool, optional If True, then the variables that would become identical in case-insensitive Fortran are mangled by appending different number of ``_`` at the end. If False, SymPy Will not interfere with naming of variables. [default=True] Examples ======== >>> from sympy import fcode, symbols, Rational, sin, ceiling, floor >>> x, tau = symbols("x, tau") >>> fcode((2*tau)**Rational(7, 2)) ' 8*sqrt(2.0d0)*tau**(7.0d0/2.0d0)' >>> fcode(sin(x), assign_to="s") ' s = sin(x)' Custom printing can be defined for certain types by passing a dictionary of "type" : "function" to the ``user_functions`` kwarg. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, cfunction_string)]. >>> custom_functions = { ... "ceiling": "CEIL", ... "floor": [(lambda x: not x.is_integer, "FLOOR1"), ... (lambda x: x.is_integer, "FLOOR2")] ... } >>> fcode(floor(x) + ceiling(x), user_functions=custom_functions) ' CEIL(x) + FLOOR1(x)' ``Piecewise`` expressions are converted into conditionals. If an ``assign_to`` variable is provided an if statement is created, otherwise the ternary operator is used. Note that if the ``Piecewise`` lacks a default term, represented by ``(expr, True)`` then an error will be thrown. This is to prevent generating an expression that may not evaluate to anything. >>> from sympy import Piecewise >>> expr = Piecewise((x + 1, x > 0), (x, True)) >>> print(fcode(expr, tau)) if (x > 0) then tau = x + 1 else tau = x end if Support for loops is provided through ``Indexed`` types. With ``contract=True`` these expressions will be turned into loops, whereas ``contract=False`` will just print the assignment expression that should be looped over: >>> from sympy import Eq, IndexedBase, Idx >>> len_y = 5 >>> y = IndexedBase('y', shape=(len_y,)) >>> t = IndexedBase('t', shape=(len_y,)) >>> Dy = IndexedBase('Dy', shape=(len_y-1,)) >>> i = Idx('i', len_y-1) >>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i])) >>> fcode(e.rhs, assign_to=e.lhs, contract=False) ' Dy(i) = (y(i + 1) - y(i))/(t(i + 1) - t(i))' Matrices are also supported, but a ``MatrixSymbol`` of the same dimensions must be provided to ``assign_to``. Note that any expression that can be generated normally can also exist inside a Matrix: >>> from sympy import Matrix, MatrixSymbol >>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)]) >>> A = MatrixSymbol('A', 3, 1) >>> print(fcode(mat, A)) A(1, 1) = x**2 if (x > 0) then A(2, 1) = x + 1 else A(2, 1) = x end if A(3, 1) = sin(x) """ from sympy.printing.fortran import FCodePrinter return FCodePrinter(settings).doprint(expr, assign_to) def print_fcode(expr, **settings): """Prints the Fortran representation of the given expression. See fcode for the meaning of the optional arguments. """ print(fcode(expr, **settings)) def cxxcode(expr, assign_to=None, standard='c++11', **settings): """ C++ equivalent of :func:`~.ccode`. """ from sympy.printing.cxx import cxx_code_printers return cxx_code_printers[standard.lower()](settings).doprint(expr, assign_to)
8bdd32900c49c7c5787fe6a960ad367c186105686877f212463b2348fe895537
""" Maple code printer The MapleCodePrinter converts single SymPy expressions into single Maple expressions, using the functions defined in the Maple objects where possible. FIXME: This module is still under actively developed. Some functions may be not completed. """ from sympy.core import S from sympy.core.numbers import Integer, IntegerConstant from sympy.printing.codeprinter import CodePrinter from sympy.printing.precedence import precedence, PRECEDENCE import sympy _known_func_same_name = ( 'sin', 'cos', 'tan', 'sec', 'csc', 'cot', 'sinh', 'cosh', 'tanh', 'sech', 'csch', 'coth', 'exp', 'floor', 'factorial', 'bernoulli', 'euler', 'fibonacci', 'gcd', 'lcm', 'conjugate', 'Ci', 'Chi', 'Ei', 'Li', 'Si', 'Shi', 'erf', 'erfc', 'harmonic', 'LambertW', 'sqrt', # For automatic rewrites ) known_functions = { # SymPy -> Maple 'Abs': 'abs', 'log': 'ln', 'asin': 'arcsin', 'acos': 'arccos', 'atan': 'arctan', 'asec': 'arcsec', 'acsc': 'arccsc', 'acot': 'arccot', 'asinh': 'arcsinh', 'acosh': 'arccosh', 'atanh': 'arctanh', 'asech': 'arcsech', 'acsch': 'arccsch', 'acoth': 'arccoth', 'ceiling': 'ceil', 'Max' : 'max', 'Min' : 'min', 'factorial2': 'doublefactorial', 'RisingFactorial': 'pochhammer', 'besseli': 'BesselI', 'besselj': 'BesselJ', 'besselk': 'BesselK', 'bessely': 'BesselY', 'hankelh1': 'HankelH1', 'hankelh2': 'HankelH2', 'airyai': 'AiryAi', 'airybi': 'AiryBi', 'appellf1': 'AppellF1', 'fresnelc': 'FresnelC', 'fresnels': 'FresnelS', 'lerchphi' : 'LerchPhi', } for _func in _known_func_same_name: known_functions[_func] = _func number_symbols = { # SymPy -> Maple S.Pi: 'Pi', S.Exp1: 'exp(1)', S.Catalan: 'Catalan', S.EulerGamma: 'gamma', S.GoldenRatio: '(1/2 + (1/2)*sqrt(5))' } spec_relational_ops = { # SymPy -> Maple '==': '=', '!=': '<>' } not_supported_symbol = [ S.ComplexInfinity ] class MapleCodePrinter(CodePrinter): """ Printer which converts a SymPy expression into a maple code. """ printmethod = "_maple" language = "maple" _default_settings = { 'order': None, 'full_prec': 'auto', 'human': True, 'inline': True, 'allow_unknown_functions': True, } def __init__(self, settings=None): if settings is None: settings = {} super().__init__(settings) self.known_functions = dict(known_functions) userfuncs = settings.get('user_functions', {}) self.known_functions.update(userfuncs) def _get_statement(self, codestring): return "%s;" % codestring def _get_comment(self, text): return "# {}".format(text) def _declare_number_const(self, name, value): return "{} := {};".format(name, value.evalf(self._settings['precision'])) def _format_code(self, lines): return lines def _print_tuple(self, expr): return self._print(list(expr)) def _print_Tuple(self, expr): return self._print(list(expr)) def _print_Assignment(self, expr): lhs = self._print(expr.lhs) rhs = self._print(expr.rhs) return "{lhs} := {rhs}".format(lhs=lhs, rhs=rhs) def _print_Pow(self, expr, **kwargs): PREC = precedence(expr) if expr.exp == -1: return '1/%s' % (self.parenthesize(expr.base, PREC)) elif expr.exp in (0.5, S.Half): return 'sqrt(%s)' % self._print(expr.base) elif expr.exp in (-0.5, -S.Half): return '1/sqrt(%s)' % self._print(expr.base) else: return '{base}^{exp}'.format( base=self.parenthesize(expr.base, PREC), exp=self.parenthesize(expr.exp, PREC)) def _print_Piecewise(self, expr): if (expr.args[-1].cond is not True) and (expr.args[-1].cond != S.BooleanTrue): # We need the last conditional to be a True, otherwise the resulting # function may not return a result. raise ValueError("All Piecewise expressions must contain an " "(expr, True) statement to be used as a default " "condition. Without one, the generated " "expression may not evaluate to anything under " "some condition.") _coup_list = [ ("{c}, {e}".format(c=self._print(c), e=self._print(e)) if c is not True and c is not S.BooleanTrue else "{e}".format( e=self._print(e))) for e, c in expr.args] _inbrace = ', '.join(_coup_list) return 'piecewise({_inbrace})'.format(_inbrace=_inbrace) def _print_Rational(self, expr): p, q = int(expr.p), int(expr.q) return "{p}/{q}".format(p=str(p), q=str(q)) def _print_Relational(self, expr): PREC=precedence(expr) lhs_code = self.parenthesize(expr.lhs, PREC) rhs_code = self.parenthesize(expr.rhs, PREC) op = expr.rel_op if op in spec_relational_ops: op = spec_relational_ops[op] return "{lhs} {rel_op} {rhs}".format(lhs=lhs_code, rel_op=op, rhs=rhs_code) def _print_NumberSymbol(self, expr): return number_symbols[expr] def _print_NegativeInfinity(self, expr): return '-infinity' def _print_Infinity(self, expr): return 'infinity' def _print_Idx(self, expr): return self._print(expr.label) def _print_BooleanTrue(self, expr): return "true" def _print_BooleanFalse(self, expr): return "false" def _print_bool(self, expr): return 'true' if expr else 'false' def _print_NaN(self, expr): return 'undefined' def _get_matrix(self, expr, sparse=False): if S.Zero in expr.shape: _strM = 'Matrix([], storage = {storage})'.format( storage='sparse' if sparse else 'rectangular') else: _strM = 'Matrix({list}, storage = {storage})'.format( list=self._print(expr.tolist()), storage='sparse' if sparse else 'rectangular') return _strM def _print_MatrixElement(self, expr): return "{parent}[{i_maple}, {j_maple}]".format( parent=self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True), i_maple=self._print(expr.i + 1), j_maple=self._print(expr.j + 1)) def _print_MatrixBase(self, expr): return self._get_matrix(expr, sparse=False) def _print_SparseRepMatrix(self, expr): return self._get_matrix(expr, sparse=True) def _print_Identity(self, expr): if isinstance(expr.rows, (Integer, IntegerConstant)): return self._print(sympy.SparseMatrix(expr)) else: return "Matrix({var_size}, shape = identity)".format(var_size=self._print(expr.rows)) def _print_MatMul(self, expr): PREC=precedence(expr) _fact_list = list(expr.args) _const = None if not isinstance(_fact_list[0], (sympy.MatrixBase, sympy.MatrixExpr, sympy.MatrixSlice, sympy.MatrixSymbol)): _const, _fact_list = _fact_list[0], _fact_list[1:] if _const is None or _const == 1: return '.'.join(self.parenthesize(_m, PREC) for _m in _fact_list) else: return '{c}*{m}'.format(c=_const, m='.'.join(self.parenthesize(_m, PREC) for _m in _fact_list)) def _print_MatPow(self, expr): # This function requires LinearAlgebra Function in Maple return 'MatrixPower({A}, {n})'.format(A=self._print(expr.base), n=self._print(expr.exp)) def _print_HadamardProduct(self, expr): PREC = precedence(expr) _fact_list = list(expr.args) return '*'.join(self.parenthesize(_m, PREC) for _m in _fact_list) def _print_Derivative(self, expr): _f, (_var, _order) = expr.args if _order != 1: _second_arg = '{var}${order}'.format(var=self._print(_var), order=self._print(_order)) else: _second_arg = '{var}'.format(var=self._print(_var)) return 'diff({func_expr}, {sec_arg})'.format(func_expr=self._print(_f), sec_arg=_second_arg) def maple_code(expr, assign_to=None, **settings): r"""Converts ``expr`` to a string of Maple code. Parameters ========== expr : Expr A SymPy expression to be converted. assign_to : optional When given, the argument is used as the name of the variable to which the expression is assigned. Can be a string, ``Symbol``, ``MatrixSymbol``, or ``Indexed`` type. This can be helpful for expressions that generate multi-line statements. precision : integer, optional The precision for numbers such as pi [default=16]. user_functions : dict, optional A dictionary where keys are ``FunctionClass`` instances and values are their string representations. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, cfunction_string)]. See below for examples. human : bool, optional If True, the result is a single string that may contain some constant declarations for the number symbols. If False, the same information is returned in a tuple of (symbols_to_declare, not_supported_functions, code_text). [default=True]. contract: bool, optional If True, ``Indexed`` instances are assumed to obey tensor contraction rules and the corresponding nested loops over indices are generated. Setting contract=False will not generate loops, instead the user is responsible to provide values for the indices in the code. [default=True]. inline: bool, optional If True, we try to create single-statement code instead of multiple statements. [default=True]. """ return MapleCodePrinter(settings).doprint(expr, assign_to) def print_maple_code(expr, **settings): """Prints the Maple representation of the given expression. See :func:`maple_code` for the meaning of the optional arguments. Examples ======== >>> from sympy import print_maple_code, symbols >>> x, y = symbols('x y') >>> print_maple_code(x, assign_to=y) y := x """ print(maple_code(expr, **settings))
815887c3bcb9abfe945773184c707732368eea4e621056220f351c1f2a82f27a
from typing import Any, Dict as tDict from sympy.external import import_module from sympy.printing.printer import Printer from sympy.utilities.iterables import is_sequence import sympy from functools import partial aesara = import_module('aesara') if aesara: aes = aesara.scalar aet = aesara.tensor from aesara.tensor import nlinalg from aesara.tensor.elemwise import Elemwise from aesara.tensor.elemwise import DimShuffle mapping = { sympy.Add: aet.add, sympy.Mul: aet.mul, sympy.Abs: aet.abs_, sympy.sign: aet.sgn, sympy.ceiling: aet.ceil, sympy.floor: aet.floor, sympy.log: aet.log, sympy.exp: aet.exp, sympy.sqrt: aet.sqrt, sympy.cos: aet.cos, sympy.acos: aet.arccos, sympy.sin: aet.sin, sympy.asin: aet.arcsin, sympy.tan: aet.tan, sympy.atan: aet.arctan, sympy.atan2: aet.arctan2, sympy.cosh: aet.cosh, sympy.acosh: aet.arccosh, sympy.sinh: aet.sinh, sympy.asinh: aet.arcsinh, sympy.tanh: aet.tanh, sympy.atanh: aet.arctanh, sympy.re: aet.real, sympy.im: aet.imag, sympy.arg: aet.angle, sympy.erf: aet.erf, sympy.gamma: aet.gamma, sympy.loggamma: aet.gammaln, sympy.Pow: aet.pow, sympy.Eq: aet.eq, sympy.StrictGreaterThan: aet.gt, sympy.StrictLessThan: aet.lt, sympy.LessThan: aet.le, sympy.GreaterThan: aet.ge, sympy.And: aet.and_, # bitwise sympy.Or: aet.or_, # bitwise sympy.Not: aet.invert, # bitwise sympy.Xor: aet.xor, # bitwise sympy.Max: aet.maximum, # Sympy accept >2 inputs, Aesara only 2 sympy.Min: aet.minimum, # Sympy accept >2 inputs, Aesara only 2 sympy.conjugate: aet.conj, sympy.core.numbers.ImaginaryUnit: lambda:aet.complex(0,1), # Matrices sympy.MatAdd: Elemwise(aes.add), sympy.HadamardProduct: Elemwise(aes.mul), sympy.Trace: nlinalg.trace, sympy.Determinant : nlinalg.det, sympy.Inverse: nlinalg.matrix_inverse, sympy.Transpose: DimShuffle((False, False), [1, 0]), } class AesaraPrinter(Printer): """ Code printer which creates Aesara symbolic expression graphs. Parameters ========== cache : dict Cache dictionary to use. If None (default) will use the global cache. To create a printer which does not depend on or alter global state pass an empty dictionary. Note: the dictionary is not copied on initialization of the printer and will be updated in-place, so using the same dict object when creating multiple printers or making multiple calls to :func:`.aesara_code` or :func:`.aesara_function` means the cache is shared between all these applications. Attributes ========== cache : dict A cache of Aesara variables which have been created for SymPy symbol-like objects (e.g. :class:`sympy.core.symbol.Symbol` or :class:`sympy.matrices.expressions.MatrixSymbol`). This is used to ensure that all references to a given symbol in an expression (or multiple expressions) are printed as the same Aesara variable, which is created only once. Symbols are differentiated only by name and type. The format of the cache's contents should be considered opaque to the user. """ printmethod = "_aesara" def __init__(self, *args, **kwargs): self.cache = kwargs.pop('cache', {}) super().__init__(*args, **kwargs) def _get_key(self, s, name=None, dtype=None, broadcastable=None): """ Get the cache key for a SymPy object. Parameters ========== s : sympy.core.basic.Basic SymPy object to get key for. name : str Name of object, if it does not have a ``name`` attribute. """ if name is None: name = s.name return (name, type(s), s.args, dtype, broadcastable) def _get_or_create(self, s, name=None, dtype=None, broadcastable=None): """ Get the Aesara variable for a SymPy symbol from the cache, or create it if it does not exist. """ # Defaults if name is None: name = s.name if dtype is None: dtype = 'floatX' if broadcastable is None: broadcastable = () key = self._get_key(s, name, dtype=dtype, broadcastable=broadcastable) if key in self.cache: return self.cache[key] value = aet.tensor(name=name, dtype=dtype, broadcastable=broadcastable) self.cache[key] = value return value def _print_Symbol(self, s, **kwargs): dtype = kwargs.get('dtypes', {}).get(s) bc = kwargs.get('broadcastables', {}).get(s) return self._get_or_create(s, dtype=dtype, broadcastable=bc) def _print_AppliedUndef(self, s, **kwargs): name = str(type(s)) + '_' + str(s.args[0]) dtype = kwargs.get('dtypes', {}).get(s) bc = kwargs.get('broadcastables', {}).get(s) return self._get_or_create(s, name=name, dtype=dtype, broadcastable=bc) def _print_Basic(self, expr, **kwargs): op = mapping[type(expr)] children = [self._print(arg, **kwargs) for arg in expr.args] return op(*children) def _print_Number(self, n, **kwargs): # Integers already taken care of below, interpret as float return float(n.evalf()) def _print_MatrixSymbol(self, X, **kwargs): dtype = kwargs.get('dtypes', {}).get(X) return self._get_or_create(X, dtype=dtype, broadcastable=(None, None)) def _print_DenseMatrix(self, X, **kwargs): if not hasattr(aet, 'stacklists'): raise NotImplementedError( "Matrix translation not yet supported in this version of Aesara") return aet.stacklists([ [self._print(arg, **kwargs) for arg in L] for L in X.tolist() ]) _print_ImmutableMatrix = _print_ImmutableDenseMatrix = _print_DenseMatrix def _print_MatMul(self, expr, **kwargs): children = [self._print(arg, **kwargs) for arg in expr.args] result = children[0] for child in children[1:]: result = aet.dot(result, child) return result def _print_MatPow(self, expr, **kwargs): children = [self._print(arg, **kwargs) for arg in expr.args] result = 1 if isinstance(children[1], int) and children[1] > 0: for i in range(children[1]): result = aet.dot(result, children[0]) else: raise NotImplementedError('''Only non-negative integer powers of matrices can be handled by Aesara at the moment''') return result def _print_MatrixSlice(self, expr, **kwargs): parent = self._print(expr.parent, **kwargs) rowslice = self._print(slice(*expr.rowslice), **kwargs) colslice = self._print(slice(*expr.colslice), **kwargs) return parent[rowslice, colslice] def _print_BlockMatrix(self, expr, **kwargs): nrows, ncols = expr.blocks.shape blocks = [[self._print(expr.blocks[r, c], **kwargs) for c in range(ncols)] for r in range(nrows)] return aet.join(0, *[aet.join(1, *row) for row in blocks]) def _print_slice(self, expr, **kwargs): return slice(*[self._print(i, **kwargs) if isinstance(i, sympy.Basic) else i for i in (expr.start, expr.stop, expr.step)]) def _print_Pi(self, expr, **kwargs): return 3.141592653589793 def _print_Piecewise(self, expr, **kwargs): import numpy as np e, cond = expr.args[0].args # First condition and corresponding value # Print conditional expression and value for first condition p_cond = self._print(cond, **kwargs) p_e = self._print(e, **kwargs) # One condition only if len(expr.args) == 1: # Return value if condition else NaN return aet.switch(p_cond, p_e, np.nan) # Return value_1 if condition_1 else evaluate remaining conditions p_remaining = self._print(sympy.Piecewise(*expr.args[1:]), **kwargs) return aet.switch(p_cond, p_e, p_remaining) def _print_Rational(self, expr, **kwargs): return aet.true_div(self._print(expr.p, **kwargs), self._print(expr.q, **kwargs)) def _print_Integer(self, expr, **kwargs): return expr.p def _print_factorial(self, expr, **kwargs): return self._print(sympy.gamma(expr.args[0] + 1), **kwargs) def _print_Derivative(self, deriv, **kwargs): from aesara.gradient import Rop rv = self._print(deriv.expr, **kwargs) for var in deriv.variables: var = self._print(var, **kwargs) rv = Rop(rv, var, aet.ones_like(var)) return rv def emptyPrinter(self, expr): return expr def doprint(self, expr, dtypes=None, broadcastables=None): """ Convert a SymPy expression to a Aesara graph variable. The ``dtypes`` and ``broadcastables`` arguments are used to specify the data type, dimension, and broadcasting behavior of the Aesara variables corresponding to the free symbols in ``expr``. Each is a mapping from SymPy symbols to the value of the corresponding argument to ``aesara.tensor.var.TensorVariable``. See the corresponding `documentation page`__ for more information on broadcasting in Aesara. .. __: https://aesara.readthedocs.io/en/latest/tutorial/broadcasting.html Parameters ========== expr : sympy.core.expr.Expr SymPy expression to print. dtypes : dict Mapping from SymPy symbols to Aesara datatypes to use when creating new Aesara variables for those symbols. Corresponds to the ``dtype`` argument to ``aesara.tensor.var.TensorVariable``. Defaults to ``'floatX'`` for symbols not included in the mapping. broadcastables : dict Mapping from SymPy symbols to the value of the ``broadcastable`` argument to ``aesara.tensor.var.TensorVariable`` to use when creating Aesara variables for those symbols. Defaults to the empty tuple for symbols not included in the mapping (resulting in a scalar). Returns ======= aesara.graph.basic.Variable A variable corresponding to the expression's value in a Aesara symbolic expression graph. """ if dtypes is None: dtypes = {} if broadcastables is None: broadcastables = {} return self._print(expr, dtypes=dtypes, broadcastables=broadcastables) global_cache = {} # type: tDict[Any, Any] def aesara_code(expr, cache=None, **kwargs): """ Convert a SymPy expression into a Aesara graph variable. Parameters ========== expr : sympy.core.expr.Expr SymPy expression object to convert. cache : dict Cached Aesara variables (see :class:`AesaraPrinter.cache <AesaraPrinter>`). Defaults to the module-level global cache. dtypes : dict Passed to :meth:`.AesaraPrinter.doprint`. broadcastables : dict Passed to :meth:`.AesaraPrinter.doprint`. Returns ======= aesara.graph.basic.Variable A variable corresponding to the expression's value in a Aesara symbolic expression graph. """ if not aesara: raise ImportError("aesara is required for aesara_code") if cache is None: cache = global_cache return AesaraPrinter(cache=cache, settings={}).doprint(expr, **kwargs) def dim_handling(inputs, dim=None, dims=None, broadcastables=None): r""" Get value of ``broadcastables`` argument to :func:`.aesara_code` from keyword arguments to :func:`.aesara_function`. Included for backwards compatibility. Parameters ========== inputs Sequence of input symbols. dim : int Common number of dimensions for all inputs. Overrides other arguments if given. dims : dict Mapping from input symbols to number of dimensions. Overrides ``broadcastables`` argument if given. broadcastables : dict Explicit value of ``broadcastables`` argument to :meth:`.AesaraPrinter.doprint`. If not None function will return this value unchanged. Returns ======= dict Dictionary mapping elements of ``inputs`` to their "broadcastable" values (tuple of ``bool``\ s). """ if dim is not None: return {s: (False,) * dim for s in inputs} if dims is not None: maxdim = max(dims.values()) return { s: (False,) * d + (True,) * (maxdim - d) for s, d in dims.items() } if broadcastables is not None: return broadcastables return {} def aesara_function(inputs, outputs, scalar=False, *, dim=None, dims=None, broadcastables=None, **kwargs): """ Create a Aesara function from SymPy expressions. The inputs and outputs are converted to Aesara variables using :func:`.aesara_code` and then passed to ``aesara.function``. Parameters ========== inputs Sequence of symbols which constitute the inputs of the function. outputs Sequence of expressions which constitute the outputs(s) of the function. The free symbols of each expression must be a subset of ``inputs``. scalar : bool Convert 0-dimensional arrays in output to scalars. This will return a Python wrapper function around the Aesara function object. cache : dict Cached Aesara variables (see :class:`AesaraPrinter.cache <AesaraPrinter>`). Defaults to the module-level global cache. dtypes : dict Passed to :meth:`.AesaraPrinter.doprint`. broadcastables : dict Passed to :meth:`.AesaraPrinter.doprint`. dims : dict Alternative to ``broadcastables`` argument. Mapping from elements of ``inputs`` to integers indicating the dimension of their associated arrays/tensors. Overrides ``broadcastables`` argument if given. dim : int Another alternative to the ``broadcastables`` argument. Common number of dimensions to use for all arrays/tensors. ``aesara_function([x, y], [...], dim=2)`` is equivalent to using ``broadcastables={x: (False, False), y: (False, False)}``. Returns ======= callable A callable object which takes values of ``inputs`` as positional arguments and returns an output array for each of the expressions in ``outputs``. If ``outputs`` is a single expression the function will return a Numpy array, if it is a list of multiple expressions the function will return a list of arrays. See description of the ``squeeze`` argument above for the behavior when a single output is passed in a list. The returned object will either be an instance of ``aesara.compile.function.types.Function`` or a Python wrapper function around one. In both cases, the returned value will have a ``aesara_function`` attribute which points to the return value of ``aesara.function``. Examples ======== >>> from sympy.abc import x, y, z >>> from sympy.printing.aesaracode import aesara_function A simple function with one input and one output: >>> f1 = aesara_function([x], [x**2 - 1], scalar=True) >>> f1(3) 8.0 A function with multiple inputs and one output: >>> f2 = aesara_function([x, y, z], [(x**z + y**z)**(1/z)], scalar=True) >>> f2(3, 4, 2) 5.0 A function with multiple inputs and multiple outputs: >>> f3 = aesara_function([x, y], [x**2 + y**2, x**2 - y**2], scalar=True) >>> f3(2, 3) [13.0, -5.0] See also ======== dim_handling """ if not aesara: raise ImportError("Aesara is required for aesara_function") # Pop off non-aesara keyword args cache = kwargs.pop('cache', {}) dtypes = kwargs.pop('dtypes', {}) broadcastables = dim_handling( inputs, dim=dim, dims=dims, broadcastables=broadcastables, ) # Print inputs/outputs code = partial(aesara_code, cache=cache, dtypes=dtypes, broadcastables=broadcastables) tinputs = list(map(code, inputs)) toutputs = list(map(code, outputs)) #fix constant expressions as variables toutputs = [output if isinstance(output, aesara.graph.basic.Variable) else aet.as_tensor_variable(output) for output in toutputs] if len(toutputs) == 1: toutputs = toutputs[0] # Compile aesara func func = aesara.function(tinputs, toutputs, **kwargs) is_0d = [len(o.variable.broadcastable) == 0 for o in func.outputs] # No wrapper required if not scalar or not any(is_0d): func.aesara_function = func return func # Create wrapper to convert 0-dimensional outputs to scalars def wrapper(*args): out = func(*args) # out can be array(1.0) or [array(1.0), array(2.0)] if is_sequence(out): return [o[()] if is_0d[i] else o for i, o in enumerate(out)] else: return out[()] wrapper.__wrapped__ = func wrapper.__doc__ = func.__doc__ wrapper.aesara_function = func return wrapper
5b427bf7c67105d9497ab71f7c11a73434e9ec9dad31d21842413f2888b28b7b
from sympy.core.basic import Basic from sympy.core.expr import Expr from sympy.core.symbol import Symbol from sympy.core.numbers import Integer, Rational, Float from sympy.printing.repr import srepr __all__ = ['dotprint'] default_styles = ( (Basic, {'color': 'blue', 'shape': 'ellipse'}), (Expr, {'color': 'black'}) ) slotClasses = (Symbol, Integer, Rational, Float) def purestr(x, with_args=False): """A string that follows ```obj = type(obj)(*obj.args)``` exactly. Parameters ========== with_args : boolean, optional If ``True``, there will be a second argument for the return value, which is a tuple containing ``purestr`` applied to each of the subnodes. If ``False``, there will not be a second argument for the return. Default is ``False`` Examples ======== >>> from sympy import Float, Symbol, MatrixSymbol >>> from sympy import Integer # noqa: F401 >>> from sympy.core.symbol import Str # noqa: F401 >>> from sympy.printing.dot import purestr Applying ``purestr`` for basic symbolic object: >>> code = purestr(Symbol('x')) >>> code "Symbol('x')" >>> eval(code) == Symbol('x') True For basic numeric object: >>> purestr(Float(2)) "Float('2.0', precision=53)" For matrix symbol: >>> code = purestr(MatrixSymbol('x', 2, 2)) >>> code "MatrixSymbol(Str('x'), Integer(2), Integer(2))" >>> eval(code) == MatrixSymbol('x', 2, 2) True With ``with_args=True``: >>> purestr(Float(2), with_args=True) ("Float('2.0', precision=53)", ()) >>> purestr(MatrixSymbol('x', 2, 2), with_args=True) ("MatrixSymbol(Str('x'), Integer(2), Integer(2))", ("Str('x')", 'Integer(2)', 'Integer(2)')) """ sargs = () if not isinstance(x, Basic): rv = str(x) elif not x.args: rv = srepr(x) else: args = x.args sargs = tuple(map(purestr, args)) rv = "%s(%s)"%(type(x).__name__, ', '.join(sargs)) if with_args: rv = rv, sargs return rv def styleof(expr, styles=default_styles): """ Merge style dictionaries in order Examples ======== >>> from sympy import Symbol, Basic, Expr, S >>> from sympy.printing.dot import styleof >>> styles = [(Basic, {'color': 'blue', 'shape': 'ellipse'}), ... (Expr, {'color': 'black'})] >>> styleof(Basic(S(1)), styles) {'color': 'blue', 'shape': 'ellipse'} >>> x = Symbol('x') >>> styleof(x + 1, styles) # this is an Expr {'color': 'black', 'shape': 'ellipse'} """ style = {} for typ, sty in styles: if isinstance(expr, typ): style.update(sty) return style def attrprint(d, delimiter=', '): """ Print a dictionary of attributes Examples ======== >>> from sympy.printing.dot import attrprint >>> print(attrprint({'color': 'blue', 'shape': 'ellipse'})) "color"="blue", "shape"="ellipse" """ return delimiter.join('"%s"="%s"'%item for item in sorted(d.items())) def dotnode(expr, styles=default_styles, labelfunc=str, pos=(), repeat=True): """ String defining a node Examples ======== >>> from sympy.printing.dot import dotnode >>> from sympy.abc import x >>> print(dotnode(x)) "Symbol('x')_()" ["color"="black", "label"="x", "shape"="ellipse"]; """ style = styleof(expr, styles) if isinstance(expr, Basic) and not expr.is_Atom: label = str(expr.__class__.__name__) else: label = labelfunc(expr) style['label'] = label expr_str = purestr(expr) if repeat: expr_str += '_%s' % str(pos) return '"%s" [%s];' % (expr_str, attrprint(style)) def dotedges(expr, atom=lambda x: not isinstance(x, Basic), pos=(), repeat=True): """ List of strings for all expr->expr.arg pairs See the docstring of dotprint for explanations of the options. Examples ======== >>> from sympy.printing.dot import dotedges >>> from sympy.abc import x >>> for e in dotedges(x+2): ... print(e) "Add(Integer(2), Symbol('x'))_()" -> "Integer(2)_(0,)"; "Add(Integer(2), Symbol('x'))_()" -> "Symbol('x')_(1,)"; """ if atom(expr): return [] else: expr_str, arg_strs = purestr(expr, with_args=True) if repeat: expr_str += '_%s' % str(pos) arg_strs = ['%s_%s' % (a, str(pos + (i,))) for i, a in enumerate(arg_strs)] return ['"%s" -> "%s";' % (expr_str, a) for a in arg_strs] template = \ """digraph{ # Graph style %(graphstyle)s ######### # Nodes # ######### %(nodes)s ######### # Edges # ######### %(edges)s }""" _graphstyle = {'rankdir': 'TD', 'ordering': 'out'} def dotprint(expr, styles=default_styles, atom=lambda x: not isinstance(x, Basic), maxdepth=None, repeat=True, labelfunc=str, **kwargs): """DOT description of a SymPy expression tree Parameters ========== styles : list of lists composed of (Class, mapping), optional Styles for different classes. The default is .. code-block:: python ( (Basic, {'color': 'blue', 'shape': 'ellipse'}), (Expr, {'color': 'black'}) ) atom : function, optional Function used to determine if an arg is an atom. A good choice is ``lambda x: not x.args``. The default is ``lambda x: not isinstance(x, Basic)``. maxdepth : integer, optional The maximum depth. The default is ``None``, meaning no limit. repeat : boolean, optional Whether to use different nodes for common subexpressions. The default is ``True``. For example, for ``x + x*y`` with ``repeat=True``, it will have two nodes for ``x``; with ``repeat=False``, it will have one node. .. warning:: Even if a node appears twice in the same object like ``x`` in ``Pow(x, x)``, it will still only appear once. Hence, with ``repeat=False``, the number of arrows out of an object might not equal the number of args it has. labelfunc : function, optional A function to create a label for a given leaf node. The default is ``str``. Another good option is ``srepr``. For example with ``str``, the leaf nodes of ``x + 1`` are labeled, ``x`` and ``1``. With ``srepr``, they are labeled ``Symbol('x')`` and ``Integer(1)``. **kwargs : optional Additional keyword arguments are included as styles for the graph. Examples ======== >>> from sympy import dotprint >>> from sympy.abc import x >>> print(dotprint(x+2)) # doctest: +NORMALIZE_WHITESPACE digraph{ <BLANKLINE> # Graph style "ordering"="out" "rankdir"="TD" <BLANKLINE> ######### # Nodes # ######### <BLANKLINE> "Add(Integer(2), Symbol('x'))_()" ["color"="black", "label"="Add", "shape"="ellipse"]; "Integer(2)_(0,)" ["color"="black", "label"="2", "shape"="ellipse"]; "Symbol('x')_(1,)" ["color"="black", "label"="x", "shape"="ellipse"]; <BLANKLINE> ######### # Edges # ######### <BLANKLINE> "Add(Integer(2), Symbol('x'))_()" -> "Integer(2)_(0,)"; "Add(Integer(2), Symbol('x'))_()" -> "Symbol('x')_(1,)"; } """ # repeat works by adding a signature tuple to the end of each node for its # position in the graph. For example, for expr = Add(x, Pow(x, 2)), the x in the # Pow will have the tuple (1, 0), meaning it is expr.args[1].args[0]. graphstyle = _graphstyle.copy() graphstyle.update(kwargs) nodes = [] edges = [] def traverse(e, depth, pos=()): nodes.append(dotnode(e, styles, labelfunc=labelfunc, pos=pos, repeat=repeat)) if maxdepth and depth >= maxdepth: return edges.extend(dotedges(e, atom=atom, pos=pos, repeat=repeat)) [traverse(arg, depth+1, pos + (i,)) for i, arg in enumerate(e.args) if not atom(arg)] traverse(expr, 0) return template%{'graphstyle': attrprint(graphstyle, delimiter='\n'), 'nodes': '\n'.join(nodes), 'edges': '\n'.join(edges)}
07e8c20064ef1ffbee1368cf5b75e6e3a98716e0c67f322e57e9a24b5ad1120c
import os from os.path import join import shutil import tempfile try: from subprocess import STDOUT, CalledProcessError, check_output except ImportError: pass from sympy.utilities.decorator import doctest_depends_on from sympy.utilities.misc import debug from .latex import latex __doctest_requires__ = {('preview',): ['pyglet']} def _check_output_no_window(*args, **kwargs): # Avoid showing a cmd.exe window when running this # on Windows if os.name == 'nt': creation_flag = 0x08000000 # CREATE_NO_WINDOW else: creation_flag = 0 # Default value return check_output(*args, creationflags=creation_flag, **kwargs) def system_default_viewer(fname, fmt): """ Open fname with the default system viewer. In practice, it is impossible for python to know when the system viewer is done. For this reason, we ensure the passed file will not be deleted under it, and this function does not attempt to block. """ # copy to a new temporary file that will not be deleted with tempfile.NamedTemporaryFile(prefix='sympy-preview-', suffix=os.path.splitext(fname)[1], delete=False) as temp_f: with open(fname, 'rb') as f: shutil.copyfileobj(f, temp_f) import platform if platform.system() == 'Darwin': import subprocess subprocess.call(('open', temp_f.name)) elif platform.system() == 'Windows': os.startfile(temp_f.name) else: import subprocess subprocess.call(('xdg-open', temp_f.name)) def pyglet_viewer(fname, fmt): try: from pyglet import window, image, gl from pyglet.window import key from pyglet.image.codecs import ImageDecodeException except ImportError: raise ImportError("pyglet is required for preview.\n visit http://www.pyglet.org/") try: img = image.load(fname) except ImageDecodeException: raise ValueError("pyglet preview does not work for '{}' files.".format(fmt)) offset = 25 config = gl.Config(double_buffer=False) win = window.Window( width=img.width + 2*offset, height=img.height + 2*offset, caption="SymPy", resizable=False, config=config ) win.set_vsync(False) try: def on_close(): win.has_exit = True win.on_close = on_close def on_key_press(symbol, modifiers): if symbol in [key.Q, key.ESCAPE]: on_close() win.on_key_press = on_key_press def on_expose(): gl.glClearColor(1.0, 1.0, 1.0, 1.0) gl.glClear(gl.GL_COLOR_BUFFER_BIT) img.blit( (win.width - img.width) / 2, (win.height - img.height) / 2 ) win.on_expose = on_expose while not win.has_exit: win.dispatch_events() win.flip() except KeyboardInterrupt: pass win.close() def _get_latex_main(expr, *, preamble=None, packages=(), extra_preamble=None, euler=True, fontsize=None, **latex_settings): """ Generate string of a LaTeX document rendering ``expr``. """ if preamble is None: actual_packages = packages + ("amsmath", "amsfonts") if euler: actual_packages += ("euler",) package_includes = "\n" + "\n".join(["\\usepackage{%s}" % p for p in actual_packages]) if extra_preamble: package_includes += extra_preamble if not fontsize: fontsize = "12pt" elif isinstance(fontsize, int): fontsize = "{}pt".format(fontsize) preamble = r"""\documentclass[varwidth,%s]{standalone} %s \begin{document} """ % (fontsize, package_includes) else: if packages or extra_preamble: raise ValueError("The \"packages\" or \"extra_preamble\" keywords" "must not be set if a " "custom LaTeX preamble was specified") if isinstance(expr, str): latex_string = expr else: latex_string = ('$\\displaystyle ' + latex(expr, mode='plain', **latex_settings) + '$') return preamble + '\n' + latex_string + '\n\n' + r"\end{document}" @doctest_depends_on(exe=('latex', 'dvipng'), modules=('pyglet',), disable_viewers=('evince', 'gimp', 'superior-dvi-viewer')) def preview(expr, output='png', viewer=None, euler=True, packages=(), filename=None, outputbuffer=None, preamble=None, dvioptions=None, outputTexFile=None, extra_preamble=None, fontsize=None, **latex_settings): r""" View expression or LaTeX markup in PNG, DVI, PostScript or PDF form. If the expr argument is an expression, it will be exported to LaTeX and then compiled using the available TeX distribution. The first argument, 'expr', may also be a LaTeX string. The function will then run the appropriate viewer for the given output format or use the user defined one. By default png output is generated. By default pretty Euler fonts are used for typesetting (they were used to typeset the well known "Concrete Mathematics" book). For that to work, you need the 'eulervm.sty' LaTeX style (in Debian/Ubuntu, install the texlive-fonts-extra package). If you prefer default AMS fonts or your system lacks 'eulervm' LaTeX package then unset the 'euler' keyword argument. To use viewer auto-detection, lets say for 'png' output, issue >>> from sympy import symbols, preview, Symbol >>> x, y = symbols("x,y") >>> preview(x + y, output='png') This will choose 'pyglet' by default. To select a different one, do >>> preview(x + y, output='png', viewer='gimp') The 'png' format is considered special. For all other formats the rules are slightly different. As an example we will take 'dvi' output format. If you would run >>> preview(x + y, output='dvi') then 'view' will look for available 'dvi' viewers on your system (predefined in the function, so it will try evince, first, then kdvi and xdvi). If nothing is found, it will fall back to using a system file association (via ``open`` and ``xdg-open``). To always use your system file association without searching for the above readers, use >>> from sympy.printing.preview import system_default_viewer >>> preview(x + y, output='dvi', viewer=system_default_viewer) If this still does not find the viewer you want, it can be set explicitly. >>> preview(x + y, output='dvi', viewer='superior-dvi-viewer') This will skip auto-detection and will run user specified 'superior-dvi-viewer'. If ``view`` fails to find it on your system it will gracefully raise an exception. You may also enter ``'file'`` for the viewer argument. Doing so will cause this function to return a file object in read-only mode, if ``filename`` is unset. However, if it was set, then 'preview' writes the genereted file to this filename instead. There is also support for writing to a ``io.BytesIO`` like object, which needs to be passed to the ``outputbuffer`` argument. >>> from io import BytesIO >>> obj = BytesIO() >>> preview(x + y, output='png', viewer='BytesIO', ... outputbuffer=obj) The LaTeX preamble can be customized by setting the 'preamble' keyword argument. This can be used, e.g., to set a different font size, use a custom documentclass or import certain set of LaTeX packages. >>> preamble = "\\documentclass[10pt]{article}\n" \ ... "\\usepackage{amsmath,amsfonts}\\begin{document}" >>> preview(x + y, output='png', preamble=preamble) It is also possible to use the standard preamble and provide additional information to the preamble using the ``extra_preamble`` keyword argument. >>> from sympy import sin >>> extra_preamble = "\\renewcommand{\\sin}{\\cos}" >>> preview(sin(x), output='png', extra_preamble=extra_preamble) If the value of 'output' is different from 'dvi' then command line options can be set ('dvioptions' argument) for the execution of the 'dvi'+output conversion tool. These options have to be in the form of a list of strings (see ``subprocess.Popen``). Additional keyword args will be passed to the :func:`~sympy.printing.latex.latex` call, e.g., the ``symbol_names`` flag. >>> phidd = Symbol('phidd') >>> preview(phidd, symbol_names={phidd: r'\ddot{\varphi}'}) For post-processing the generated TeX File can be written to a file by passing the desired filename to the 'outputTexFile' keyword argument. To write the TeX code to a file named ``"sample.tex"`` and run the default png viewer to display the resulting bitmap, do >>> preview(x + y, outputTexFile="sample.tex") """ # pyglet is the default for png if viewer is None and output == "png": try: import pyglet # noqa: F401 except ImportError: pass else: viewer = pyglet_viewer # look up a known application if viewer is None: # sorted in order from most pretty to most ugly # very discussable, but indeed 'gv' looks awful :) candidates = { "dvi": [ "evince", "okular", "kdvi", "xdvi" ], "ps": [ "evince", "okular", "gsview", "gv" ], "pdf": [ "evince", "okular", "kpdf", "acroread", "xpdf", "gv" ], } for candidate in candidates.get(output, []): path = shutil.which(candidate) if path is not None: viewer = path break # otherwise, use the system default for file association if viewer is None: viewer = system_default_viewer if viewer == "file": if filename is None: raise ValueError("filename has to be specified if viewer=\"file\"") elif viewer == "BytesIO": if outputbuffer is None: raise ValueError("outputbuffer has to be a BytesIO " "compatible object if viewer=\"BytesIO\"") elif not callable(viewer) and not shutil.which(viewer): raise OSError("Unrecognized viewer: %s" % viewer) latex_main = _get_latex_main(expr, preamble=preamble, packages=packages, euler=euler, extra_preamble=extra_preamble, fontsize=fontsize, **latex_settings) debug("Latex code:") debug(latex_main) with tempfile.TemporaryDirectory() as workdir: with open(join(workdir, 'texput.tex'), 'w', encoding='utf-8') as fh: fh.write(latex_main) if outputTexFile is not None: shutil.copyfile(join(workdir, 'texput.tex'), outputTexFile) if not shutil.which('latex'): raise RuntimeError("latex program is not installed") try: _check_output_no_window( ['latex', '-halt-on-error', '-interaction=nonstopmode', 'texput.tex'], cwd=workdir, stderr=STDOUT) except CalledProcessError as e: raise RuntimeError( "'latex' exited abnormally with the following output:\n%s" % e.output) src = "texput.%s" % (output) if output != "dvi": # in order of preference commandnames = { "ps": ["dvips"], "pdf": ["dvipdfmx", "dvipdfm", "dvipdf"], "png": ["dvipng"], "svg": ["dvisvgm"], } try: cmd_variants = commandnames[output] except KeyError: raise ValueError("Invalid output format: %s" % output) from None # find an appropriate command for cmd_variant in cmd_variants: cmd_path = shutil.which(cmd_variant) if cmd_path: cmd = [cmd_path] break else: if len(cmd_variants) > 1: raise RuntimeError("None of %s are installed" % ", ".join(cmd_variants)) else: raise RuntimeError("%s is not installed" % cmd_variants[0]) defaultoptions = { "dvipng": ["-T", "tight", "-z", "9", "--truecolor"], "dvisvgm": ["--no-fonts"], } commandend = { "dvips": ["-o", src, "texput.dvi"], "dvipdf": ["texput.dvi", src], "dvipdfm": ["-o", src, "texput.dvi"], "dvipdfmx": ["-o", src, "texput.dvi"], "dvipng": ["-o", src, "texput.dvi"], "dvisvgm": ["-o", src, "texput.dvi"], } if dvioptions is not None: cmd.extend(dvioptions) else: cmd.extend(defaultoptions.get(cmd_variant, [])) cmd.extend(commandend[cmd_variant]) try: _check_output_no_window(cmd, cwd=workdir, stderr=STDOUT) except CalledProcessError as e: raise RuntimeError( "'%s' exited abnormally with the following output:\n%s" % (' '.join(cmd), e.output)) if viewer == "file": shutil.move(join(workdir, src), filename) elif viewer == "BytesIO": with open(join(workdir, src), 'rb') as fh: outputbuffer.write(fh.read()) elif callable(viewer): viewer(join(workdir, src), fmt=output) else: try: _check_output_no_window( [viewer, src], cwd=workdir, stderr=STDOUT) except CalledProcessError as e: raise RuntimeError( "'%s %s' exited abnormally with the following output:\n%s" % (viewer, src, e.output))
b650e92af44fce269d8e569ddbfae1b88c844d21c0c665f1a89fa54c36f9ceb1
""" Julia code printer The `JuliaCodePrinter` converts SymPy expressions into Julia expressions. A complete code generator, which uses `julia_code` extensively, can be found in `sympy.utilities.codegen`. The `codegen` module can be used to generate complete source code files. """ from typing import Any, Dict as tDict from sympy.core import Mul, Pow, S, Rational from sympy.core.mul import _keep_coeff from sympy.printing.codeprinter import CodePrinter from sympy.printing.precedence import precedence, PRECEDENCE from re import search # List of known functions. First, those that have the same name in # SymPy and Julia. This is almost certainly incomplete! known_fcns_src1 = ["sin", "cos", "tan", "cot", "sec", "csc", "asin", "acos", "atan", "acot", "asec", "acsc", "sinh", "cosh", "tanh", "coth", "sech", "csch", "asinh", "acosh", "atanh", "acoth", "asech", "acsch", "sinc", "atan2", "sign", "floor", "log", "exp", "cbrt", "sqrt", "erf", "erfc", "erfi", "factorial", "gamma", "digamma", "trigamma", "polygamma", "beta", "airyai", "airyaiprime", "airybi", "airybiprime", "besselj", "bessely", "besseli", "besselk", "erfinv", "erfcinv"] # These functions have different names ("SymPy": "Julia"), more # generally a mapping to (argument_conditions, julia_function). known_fcns_src2 = { "Abs": "abs", "ceiling": "ceil", "conjugate": "conj", "hankel1": "hankelh1", "hankel2": "hankelh2", "im": "imag", "re": "real" } class JuliaCodePrinter(CodePrinter): """ A printer to convert expressions to strings of Julia code. """ printmethod = "_julia" language = "Julia" _operators = { 'and': '&&', 'or': '||', 'not': '!', } _default_settings = { 'order': None, 'full_prec': 'auto', 'precision': 17, 'user_functions': {}, 'human': True, 'allow_unknown_functions': False, 'contract': True, 'inline': True, } # type: tDict[str, Any] # Note: contract is for expressing tensors as loops (if True), or just # assignment (if False). FIXME: this should be looked a more carefully # for Julia. def __init__(self, settings={}): super().__init__(settings) self.known_functions = dict(zip(known_fcns_src1, known_fcns_src1)) self.known_functions.update(dict(known_fcns_src2)) userfuncs = settings.get('user_functions', {}) self.known_functions.update(userfuncs) def _rate_index_position(self, p): return p*5 def _get_statement(self, codestring): return "%s" % codestring def _get_comment(self, text): return "# {}".format(text) def _declare_number_const(self, name, value): return "const {} = {}".format(name, value) def _format_code(self, lines): return self.indent_code(lines) def _traverse_matrix_indices(self, mat): # Julia uses Fortran order (column-major) rows, cols = mat.shape return ((i, j) for j in range(cols) for i in range(rows)) def _get_loop_opening_ending(self, indices): open_lines = [] close_lines = [] for i in indices: # Julia arrays start at 1 and end at dimension var, start, stop = map(self._print, [i.label, i.lower + 1, i.upper + 1]) open_lines.append("for %s = %s:%s" % (var, start, stop)) close_lines.append("end") return open_lines, close_lines def _print_Mul(self, expr): # print complex numbers nicely in Julia if (expr.is_number and expr.is_imaginary and expr.as_coeff_Mul()[0].is_integer): return "%sim" % self._print(-S.ImaginaryUnit*expr) # cribbed from str.py prec = precedence(expr) c, e = expr.as_coeff_Mul() if c < 0: expr = _keep_coeff(-c, e) sign = "-" else: sign = "" a = [] # items in the numerator b = [] # items that are in the denominator (if any) pow_paren = [] # Will collect all pow with more than one base element and exp = -1 if self.order not in ('old', 'none'): args = expr.as_ordered_factors() else: # use make_args in case expr was something like -x -> x args = Mul.make_args(expr) # Gather args for numerator/denominator for item in args: if (item.is_commutative and item.is_Pow and item.exp.is_Rational and item.exp.is_negative): if item.exp != -1: b.append(Pow(item.base, -item.exp, evaluate=False)) else: if len(item.args[0].args) != 1 and isinstance(item.base, Mul): # To avoid situations like #14160 pow_paren.append(item) b.append(Pow(item.base, -item.exp)) elif item.is_Rational and item is not S.Infinity and item.p == 1: # Save the Rational type in julia Unless the numerator is 1. # For example: # julia_code(Rational(3, 7)*x) --> (3 // 7) * x # julia_code(x/3) --> x / 3 but not x * (1 // 3) b.append(Rational(item.q)) else: a.append(item) a = a or [S.One] a_str = [self.parenthesize(x, prec) for x in a] b_str = [self.parenthesize(x, prec) for x in b] # To parenthesize Pow with exp = -1 and having more than one Symbol for item in pow_paren: if item.base in b: b_str[b.index(item.base)] = "(%s)" % b_str[b.index(item.base)] # from here it differs from str.py to deal with "*" and ".*" def multjoin(a, a_str): # here we probably are assuming the constants will come first r = a_str[0] for i in range(1, len(a)): mulsym = '*' if a[i-1].is_number else '.*' r = "%s %s %s" % (r, mulsym, a_str[i]) return r if not b: return sign + multjoin(a, a_str) elif len(b) == 1: divsym = '/' if b[0].is_number else './' return "%s %s %s" % (sign+multjoin(a, a_str), divsym, b_str[0]) else: divsym = '/' if all(bi.is_number for bi in b) else './' return "%s %s (%s)" % (sign + multjoin(a, a_str), divsym, multjoin(b, b_str)) def _print_Relational(self, expr): lhs_code = self._print(expr.lhs) rhs_code = self._print(expr.rhs) op = expr.rel_op return "{} {} {}".format(lhs_code, op, rhs_code) def _print_Pow(self, expr): powsymbol = '^' if all(x.is_number for x in expr.args) else '.^' PREC = precedence(expr) if expr.exp == S.Half: return "sqrt(%s)" % self._print(expr.base) if expr.is_commutative: if expr.exp == -S.Half: sym = '/' if expr.base.is_number else './' return "1 %s sqrt(%s)" % (sym, self._print(expr.base)) if expr.exp == -S.One: sym = '/' if expr.base.is_number else './' return "1 %s %s" % (sym, self.parenthesize(expr.base, PREC)) return '%s %s %s' % (self.parenthesize(expr.base, PREC), powsymbol, self.parenthesize(expr.exp, PREC)) def _print_MatPow(self, expr): PREC = precedence(expr) return '%s ^ %s' % (self.parenthesize(expr.base, PREC), self.parenthesize(expr.exp, PREC)) def _print_Pi(self, expr): if self._settings["inline"]: return "pi" else: return super()._print_NumberSymbol(expr) def _print_ImaginaryUnit(self, expr): return "im" def _print_Exp1(self, expr): if self._settings["inline"]: return "e" else: return super()._print_NumberSymbol(expr) def _print_EulerGamma(self, expr): if self._settings["inline"]: return "eulergamma" else: return super()._print_NumberSymbol(expr) def _print_Catalan(self, expr): if self._settings["inline"]: return "catalan" else: return super()._print_NumberSymbol(expr) def _print_GoldenRatio(self, expr): if self._settings["inline"]: return "golden" else: return super()._print_NumberSymbol(expr) def _print_Assignment(self, expr): from sympy.codegen.ast import Assignment from sympy.functions.elementary.piecewise import Piecewise from sympy.tensor.indexed import IndexedBase # Copied from codeprinter, but remove special MatrixSymbol treatment lhs = expr.lhs rhs = expr.rhs # We special case assignments that take multiple lines if not self._settings["inline"] and isinstance(expr.rhs, Piecewise): # Here we modify Piecewise so each expression is now # an Assignment, and then continue on the print. expressions = [] conditions = [] for (e, c) in rhs.args: expressions.append(Assignment(lhs, e)) conditions.append(c) temp = Piecewise(*zip(expressions, conditions)) return self._print(temp) if self._settings["contract"] and (lhs.has(IndexedBase) or rhs.has(IndexedBase)): # Here we check if there is looping to be done, and if so # print the required loops. return self._doprint_loops(rhs, lhs) else: lhs_code = self._print(lhs) rhs_code = self._print(rhs) return self._get_statement("%s = %s" % (lhs_code, rhs_code)) def _print_Infinity(self, expr): return 'Inf' def _print_NegativeInfinity(self, expr): return '-Inf' def _print_NaN(self, expr): return 'NaN' def _print_list(self, expr): return 'Any[' + ', '.join(self._print(a) for a in expr) + ']' def _print_tuple(self, expr): if len(expr) == 1: return "(%s,)" % self._print(expr[0]) else: return "(%s)" % self.stringify(expr, ", ") _print_Tuple = _print_tuple def _print_BooleanTrue(self, expr): return "true" def _print_BooleanFalse(self, expr): return "false" def _print_bool(self, expr): return str(expr).lower() # Could generate quadrature code for definite Integrals? #_print_Integral = _print_not_supported def _print_MatrixBase(self, A): # Handle zero dimensions: if S.Zero in A.shape: return 'zeros(%s, %s)' % (A.rows, A.cols) elif (A.rows, A.cols) == (1, 1): return "[%s]" % A[0, 0] elif A.rows == 1: return "[%s]" % A.table(self, rowstart='', rowend='', colsep=' ') elif A.cols == 1: # note .table would unnecessarily equispace the rows return "[%s]" % ", ".join([self._print(a) for a in A]) return "[%s]" % A.table(self, rowstart='', rowend='', rowsep=';\n', colsep=' ') def _print_SparseRepMatrix(self, A): from sympy.matrices import Matrix L = A.col_list(); # make row vectors of the indices and entries I = Matrix([k[0] + 1 for k in L]) J = Matrix([k[1] + 1 for k in L]) AIJ = Matrix([k[2] for k in L]) return "sparse(%s, %s, %s, %s, %s)" % (self._print(I), self._print(J), self._print(AIJ), A.rows, A.cols) def _print_MatrixElement(self, expr): return self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) \ + '[%s,%s]' % (expr.i + 1, expr.j + 1) def _print_MatrixSlice(self, expr): def strslice(x, lim): l = x[0] + 1 h = x[1] step = x[2] lstr = self._print(l) hstr = 'end' if h == lim else self._print(h) if step == 1: if l == 1 and h == lim: return ':' if l == h: return lstr else: return lstr + ':' + hstr else: return ':'.join((lstr, self._print(step), hstr)) return (self._print(expr.parent) + '[' + strslice(expr.rowslice, expr.parent.shape[0]) + ',' + strslice(expr.colslice, expr.parent.shape[1]) + ']') def _print_Indexed(self, expr): inds = [ self._print(i) for i in expr.indices ] return "%s[%s]" % (self._print(expr.base.label), ",".join(inds)) def _print_Idx(self, expr): return self._print(expr.label) def _print_Identity(self, expr): return "eye(%s)" % self._print(expr.shape[0]) def _print_HadamardProduct(self, expr): return ' .* '.join([self.parenthesize(arg, precedence(expr)) for arg in expr.args]) def _print_HadamardPower(self, expr): PREC = precedence(expr) return '.**'.join([ self.parenthesize(expr.base, PREC), self.parenthesize(expr.exp, PREC) ]) def _print_Rational(self, expr): if expr.q == 1: return str(expr.p) return "%s // %s" % (expr.p, expr.q) # Note: as of 2022, Julia doesn't have spherical Bessel functions def _print_jn(self, expr): from sympy.functions import sqrt, besselj x = expr.argument expr2 = sqrt(S.Pi/(2*x))*besselj(expr.order + S.Half, x) return self._print(expr2) def _print_yn(self, expr): from sympy.functions import sqrt, bessely x = expr.argument expr2 = sqrt(S.Pi/(2*x))*bessely(expr.order + S.Half, x) return self._print(expr2) def _print_Piecewise(self, expr): if expr.args[-1].cond != True: # We need the last conditional to be a True, otherwise the resulting # function may not return a result. raise ValueError("All Piecewise expressions must contain an " "(expr, True) statement to be used as a default " "condition. Without one, the generated " "expression may not evaluate to anything under " "some condition.") lines = [] if self._settings["inline"]: # Express each (cond, expr) pair in a nested Horner form: # (condition) .* (expr) + (not cond) .* (<others>) # Expressions that result in multiple statements won't work here. ecpairs = ["({}) ? ({}) :".format (self._print(c), self._print(e)) for e, c in expr.args[:-1]] elast = " (%s)" % self._print(expr.args[-1].expr) pw = "\n".join(ecpairs) + elast # Note: current need these outer brackets for 2*pw. Would be # nicer to teach parenthesize() to do this for us when needed! return "(" + pw + ")" else: for i, (e, c) in enumerate(expr.args): if i == 0: lines.append("if (%s)" % self._print(c)) elif i == len(expr.args) - 1 and c == True: lines.append("else") else: lines.append("elseif (%s)" % self._print(c)) code0 = self._print(e) lines.append(code0) if i == len(expr.args) - 1: lines.append("end") return "\n".join(lines) def _print_MatMul(self, expr): c, m = expr.as_coeff_mmul() sign = "" if c.is_number: re, im = c.as_real_imag() if im.is_zero and re.is_negative: expr = _keep_coeff(-c, m) sign = "-" elif re.is_zero and im.is_negative: expr = _keep_coeff(-c, m) sign = "-" return sign + ' * '.join( (self.parenthesize(arg, precedence(expr)) for arg in expr.args) ) def indent_code(self, code): """Accepts a string of code or a list of code lines""" # code mostly copied from ccode if isinstance(code, str): code_lines = self.indent_code(code.splitlines(True)) return ''.join(code_lines) tab = " " inc_regex = ('^function ', '^if ', '^elseif ', '^else$', '^for ') dec_regex = ('^end$', '^elseif ', '^else$') # pre-strip left-space from the code code = [ line.lstrip(' \t') for line in code ] increase = [ int(any(search(re, line) for re in inc_regex)) for line in code ] decrease = [ int(any(search(re, line) for re in dec_regex)) for line in code ] pretty = [] level = 0 for n, line in enumerate(code): if line in ('', '\n'): pretty.append(line) continue level -= decrease[n] pretty.append("%s%s" % (tab*level, line)) level += increase[n] return pretty def julia_code(expr, assign_to=None, **settings): r"""Converts `expr` to a string of Julia code. Parameters ========== expr : Expr A SymPy expression to be converted. assign_to : optional When given, the argument is used as the name of the variable to which the expression is assigned. Can be a string, ``Symbol``, ``MatrixSymbol``, or ``Indexed`` type. This can be helpful for expressions that generate multi-line statements. precision : integer, optional The precision for numbers such as pi [default=16]. user_functions : dict, optional A dictionary where keys are ``FunctionClass`` instances and values are their string representations. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, cfunction_string)]. See below for examples. human : bool, optional If True, the result is a single string that may contain some constant declarations for the number symbols. If False, the same information is returned in a tuple of (symbols_to_declare, not_supported_functions, code_text). [default=True]. contract: bool, optional If True, ``Indexed`` instances are assumed to obey tensor contraction rules and the corresponding nested loops over indices are generated. Setting contract=False will not generate loops, instead the user is responsible to provide values for the indices in the code. [default=True]. inline: bool, optional If True, we try to create single-statement code instead of multiple statements. [default=True]. Examples ======== >>> from sympy import julia_code, symbols, sin, pi >>> x = symbols('x') >>> julia_code(sin(x).series(x).removeO()) 'x .^ 5 / 120 - x .^ 3 / 6 + x' >>> from sympy import Rational, ceiling >>> x, y, tau = symbols("x, y, tau") >>> julia_code((2*tau)**Rational(7, 2)) '8 * sqrt(2) * tau .^ (7 // 2)' Note that element-wise (Hadamard) operations are used by default between symbols. This is because its possible in Julia to write "vectorized" code. It is harmless if the values are scalars. >>> julia_code(sin(pi*x*y), assign_to="s") 's = sin(pi * x .* y)' If you need a matrix product "*" or matrix power "^", you can specify the symbol as a ``MatrixSymbol``. >>> from sympy import Symbol, MatrixSymbol >>> n = Symbol('n', integer=True, positive=True) >>> A = MatrixSymbol('A', n, n) >>> julia_code(3*pi*A**3) '(3 * pi) * A ^ 3' This class uses several rules to decide which symbol to use a product. Pure numbers use "*", Symbols use ".*" and MatrixSymbols use "*". A HadamardProduct can be used to specify componentwise multiplication ".*" of two MatrixSymbols. There is currently there is no easy way to specify scalar symbols, so sometimes the code might have some minor cosmetic issues. For example, suppose x and y are scalars and A is a Matrix, then while a human programmer might write "(x^2*y)*A^3", we generate: >>> julia_code(x**2*y*A**3) '(x .^ 2 .* y) * A ^ 3' Matrices are supported using Julia inline notation. When using ``assign_to`` with matrices, the name can be specified either as a string or as a ``MatrixSymbol``. The dimensions must align in the latter case. >>> from sympy import Matrix, MatrixSymbol >>> mat = Matrix([[x**2, sin(x), ceiling(x)]]) >>> julia_code(mat, assign_to='A') 'A = [x .^ 2 sin(x) ceil(x)]' ``Piecewise`` expressions are implemented with logical masking by default. Alternatively, you can pass "inline=False" to use if-else conditionals. Note that if the ``Piecewise`` lacks a default term, represented by ``(expr, True)`` then an error will be thrown. This is to prevent generating an expression that may not evaluate to anything. >>> from sympy import Piecewise >>> pw = Piecewise((x + 1, x > 0), (x, True)) >>> julia_code(pw, assign_to=tau) 'tau = ((x > 0) ? (x + 1) : (x))' Note that any expression that can be generated normally can also exist inside a Matrix: >>> mat = Matrix([[x**2, pw, sin(x)]]) >>> julia_code(mat, assign_to='A') 'A = [x .^ 2 ((x > 0) ? (x + 1) : (x)) sin(x)]' Custom printing can be defined for certain types by passing a dictionary of "type" : "function" to the ``user_functions`` kwarg. Alternatively, the dictionary value can be a list of tuples i.e., [(argument_test, cfunction_string)]. This can be used to call a custom Julia function. >>> from sympy import Function >>> f = Function('f') >>> g = Function('g') >>> custom_functions = { ... "f": "existing_julia_fcn", ... "g": [(lambda x: x.is_Matrix, "my_mat_fcn"), ... (lambda x: not x.is_Matrix, "my_fcn")] ... } >>> mat = Matrix([[1, x]]) >>> julia_code(f(x) + g(x) + g(mat), user_functions=custom_functions) 'existing_julia_fcn(x) + my_fcn(x) + my_mat_fcn([1 x])' Support for loops is provided through ``Indexed`` types. With ``contract=True`` these expressions will be turned into loops, whereas ``contract=False`` will just print the assignment expression that should be looped over: >>> from sympy import Eq, IndexedBase, Idx >>> len_y = 5 >>> y = IndexedBase('y', shape=(len_y,)) >>> t = IndexedBase('t', shape=(len_y,)) >>> Dy = IndexedBase('Dy', shape=(len_y-1,)) >>> i = Idx('i', len_y-1) >>> e = Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i])) >>> julia_code(e.rhs, assign_to=e.lhs, contract=False) 'Dy[i] = (y[i + 1] - y[i]) ./ (t[i + 1] - t[i])' """ return JuliaCodePrinter(settings).doprint(expr, assign_to) def print_julia_code(expr, **settings): """Prints the Julia representation of the given expression. See `julia_code` for the meaning of the optional arguments. """ print(julia_code(expr, **settings))
3cc0a86a0184244da05c2741d7ea4bec37e51c0a3a9656f7e526718a8f749df7
"""Integration method that emulates by-hand techniques. This module also provides functionality to get the steps used to evaluate a particular integral, in the ``integral_steps`` function. This will return nested namedtuples representing the integration rules used. The ``manualintegrate`` function computes the integral using those steps given an integrand; given the steps, ``_manualintegrate`` will evaluate them. The integrator can be extended with new heuristics and evaluation techniques. To do so, write a function that accepts an ``IntegralInfo`` object and returns either a namedtuple representing a rule or ``None``. Then, write another function that accepts the namedtuple's fields and returns the antiderivative, and decorate it with ``@evaluates(namedtuple_type)``. If the new technique requires a new match, add the key and call to the antiderivative function to integral_steps. To enable simple substitutions, add the match to find_substitutions. """ from __future__ import annotations from typing import NamedTuple, Type, Callable from collections import namedtuple, defaultdict from collections.abc import Mapping from functools import reduce from sympy.core.add import Add from sympy.core.cache import cacheit from sympy.core.containers import Dict from sympy.core.expr import Expr from sympy.core.function import Derivative from sympy.core.logic import fuzzy_not from sympy.core.mul import Mul from sympy.core.numbers import Integer, Number, E from sympy.core.power import Pow from sympy.core.relational import Eq, Ne from sympy.core.singleton import S from sympy.core.symbol import Dummy, Symbol, Wild from sympy.functions.elementary.complexes import Abs from sympy.functions.elementary.exponential import exp, log from sympy.functions.elementary.hyperbolic import (HyperbolicFunction, csch, cosh, coth, sech, sinh, tanh, asinh, atanh) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import (TrigonometricFunction, cos, sin, tan, cot, csc, sec, acos, asin, atan, acot, acsc, asec) from sympy.functions.special.delta_functions import Heaviside, DiracDelta from sympy.functions.special.error_functions import (erf, erfi, fresnelc, fresnels, Ci, Chi, Si, Shi, Ei, li) from sympy.functions.special.gamma_functions import uppergamma from sympy.functions.special.elliptic_integrals import elliptic_e, elliptic_f from sympy.functions.special.polynomials import (chebyshevt, chebyshevu, legendre, hermite, laguerre, assoc_laguerre, gegenbauer, jacobi, OrthogonalPolynomial) from sympy.functions.special.zeta_functions import polylog from .integrals import Integral from sympy.logic.boolalg import And from sympy.ntheory.factor_ import primefactors from sympy.polys.polytools import degree, lcm_list, gcd_list, Poly from sympy.simplify.radsimp import fraction from sympy.simplify.simplify import simplify from sympy.solvers.solvers import solve from sympy.strategies.core import switch, do_one, null_safe, condition from sympy.utilities.iterables import iterable from sympy.utilities.misc import debug def Rule(name, props=""): # GOTCHA: namedtuple class name not considered! def __eq__(self, other): return self.__class__ == other.__class__ and tuple.__eq__(self, other) __neq__ = lambda self, other: not __eq__(self, other) cls = namedtuple(name, props + " context symbol") cls.__eq__ = __eq__ cls.__ne__ = __neq__ return cls ConstantRule = Rule("ConstantRule", "constant") ConstantTimesRule = Rule("ConstantTimesRule", "constant other substep") PowerRule = Rule("PowerRule", "base exp") AddRule = Rule("AddRule", "substeps") URule = Rule("URule", "u_var u_func constant substep") PartsRule = Rule("PartsRule", "u dv v_step second_step") CyclicPartsRule = Rule("CyclicPartsRule", "parts_rules coefficient") TrigRule = Rule("TrigRule", "func arg") HyperbolicRule = Rule("HyperbolicRule", "func arg") ExpRule = Rule("ExpRule", "base exp") ReciprocalRule = Rule("ReciprocalRule", "func") ArcsinRule = Rule("ArcsinRule") ArcsinhRule = Rule("ArcsinhRule") ReciprocalSqrtQuadraticRule = Rule("ReciprocalSqrtQuadraticRule", "a b c") SqrtQuadraticDenomRule = Rule("SqrtQuadraticDenomRule", "a b c coeffs") SqrtQuadraticRule = Rule("SqrtQuadraticRule", "a b c") AlternativeRule = Rule("AlternativeRule", "alternatives") DontKnowRule = Rule("DontKnowRule") DerivativeRule = Rule("DerivativeRule") RewriteRule = Rule("RewriteRule", "rewritten substep") CompleteSquareRule = Rule("CompleteSquareRule", "rewritten substep") PiecewiseRule = Rule("PiecewiseRule", "subfunctions") HeavisideRule = Rule("HeavisideRule", "harg ibnd substep") DiracDeltaRule = Rule("DiracDeltaRule", "n a b") TrigSubstitutionRule = Rule("TrigSubstitutionRule", "theta func rewritten substep restriction") ArctanRule = Rule("ArctanRule", "a b c") ArctanhRule = Rule("ArctanhRule", "a b c") JacobiRule = Rule("JacobiRule", "n a b") GegenbauerRule = Rule("GegenbauerRule", "n a") ChebyshevTRule = Rule("ChebyshevTRule", "n") ChebyshevURule = Rule("ChebyshevURule", "n") LegendreRule = Rule("LegendreRule", "n") HermiteRule = Rule("HermiteRule", "n") LaguerreRule = Rule("LaguerreRule", "n") AssocLaguerreRule = Rule("AssocLaguerreRule", "n a") CiRule = Rule("CiRule", "a b") ChiRule = Rule("ChiRule", "a b") EiRule = Rule("EiRule", "a b") SiRule = Rule("SiRule", "a b") ShiRule = Rule("ShiRule", "a b") ErfRule = Rule("ErfRule", "a b c") FresnelCRule = Rule("FresnelCRule", "a b c") FresnelSRule = Rule("FresnelSRule", "a b c") LiRule = Rule("LiRule", "a b") PolylogRule = Rule("PolylogRule", "a b") UpperGammaRule = Rule("UpperGammaRule", "a e") EllipticFRule = Rule("EllipticFRule", "a d") EllipticERule = Rule("EllipticERule", "a d") class IntegralInfo(NamedTuple): integrand: Expr symbol: Symbol evaluators = {} def evaluates(rule): def _evaluates(func): func.rule = rule evaluators[rule] = func return func return _evaluates def contains_dont_know(rule): if isinstance(rule, DontKnowRule): return True if not isinstance(rule, tuple): return False for val in rule: if isinstance(val, tuple): if contains_dont_know(val): return True elif isinstance(val, list): if any(contains_dont_know(i) for i in val): return True return False def manual_diff(f, symbol): """Derivative of f in form expected by find_substitutions SymPy's derivatives for some trig functions (like cot) are not in a form that works well with finding substitutions; this replaces the derivatives for those particular forms with something that works better. """ if f.args: arg = f.args[0] if isinstance(f, tan): return arg.diff(symbol) * sec(arg)**2 elif isinstance(f, cot): return -arg.diff(symbol) * csc(arg)**2 elif isinstance(f, sec): return arg.diff(symbol) * sec(arg) * tan(arg) elif isinstance(f, csc): return -arg.diff(symbol) * csc(arg) * cot(arg) elif isinstance(f, Add): return sum([manual_diff(arg, symbol) for arg in f.args]) elif isinstance(f, Mul): if len(f.args) == 2 and isinstance(f.args[0], Number): return f.args[0] * manual_diff(f.args[1], symbol) return f.diff(symbol) def manual_subs(expr, *args): """ A wrapper for `expr.subs(*args)` with additional logic for substitution of invertible functions. """ if len(args) == 1: sequence = args[0] if isinstance(sequence, (Dict, Mapping)): sequence = sequence.items() elif not iterable(sequence): raise ValueError("Expected an iterable of (old, new) pairs") elif len(args) == 2: sequence = [args] else: raise ValueError("subs accepts either 1 or 2 arguments") new_subs = [] for old, new in sequence: if isinstance(old, log): # If log(x) = y, then exp(a*log(x)) = exp(a*y) # that is, x**a = exp(a*y). Replace nontrivial powers of x # before subs turns them into `exp(y)**a`, but # do not replace x itself yet, to avoid `log(exp(y))`. x0 = old.args[0] expr = expr.replace(lambda x: x.is_Pow and x.base == x0, lambda x: exp(x.exp*new)) new_subs.append((x0, exp(new))) return expr.subs(list(sequence) + new_subs) # Method based on that on SIN, described in "Symbolic Integration: The # Stormy Decade" inverse_trig_functions = (atan, asin, acos, acot, acsc, asec) def find_substitutions(integrand, symbol, u_var): results = [] def test_subterm(u, u_diff): if u_diff == 0: return False substituted = integrand / u_diff debug("substituted: {}, u: {}, u_var: {}".format(substituted, u, u_var)) substituted = manual_subs(substituted, u, u_var).cancel() if symbol in substituted.free_symbols: return False # avoid increasing the degree of a rational function if integrand.is_rational_function(symbol) and substituted.is_rational_function(u_var): deg_before = max([degree(t, symbol) for t in integrand.as_numer_denom()]) deg_after = max([degree(t, u_var) for t in substituted.as_numer_denom()]) if deg_after > deg_before: return False return substituted.as_independent(u_var, as_Add=False) def exp_subterms(term: Expr): linear_coeffs = [] terms = [] n = Wild('n', properties=[lambda n: n.is_Integer]) for exp_ in term.find(exp): arg = exp_.args[0] if symbol not in arg.free_symbols: continue match = arg.match(n*symbol) if match: linear_coeffs.append(match[n]) else: terms.append(exp_) if linear_coeffs: terms.append(exp(gcd_list(linear_coeffs)*symbol)) return terms def possible_subterms(term): if isinstance(term, (TrigonometricFunction, HyperbolicFunction, *inverse_trig_functions, exp, log, Heaviside)): return [term.args[0]] elif isinstance(term, (chebyshevt, chebyshevu, legendre, hermite, laguerre)): return [term.args[1]] elif isinstance(term, (gegenbauer, assoc_laguerre)): return [term.args[2]] elif isinstance(term, jacobi): return [term.args[3]] elif isinstance(term, Mul): r = [] for u in term.args: r.append(u) r.extend(possible_subterms(u)) return r elif isinstance(term, Pow): r = [arg for arg in term.args if arg.has(symbol)] if term.exp.is_Integer: r.extend([term.base**d for d in primefactors(term.exp) if 1 < d < abs(term.args[1])]) if term.base.is_Add: r.extend([t for t in possible_subterms(term.base) if t.is_Pow]) return r elif isinstance(term, Add): r = [] for arg in term.args: r.append(arg) r.extend(possible_subterms(arg)) return r return [] for u in list(dict.fromkeys(possible_subterms(integrand) + exp_subterms(integrand))): if u == symbol: continue u_diff = manual_diff(u, symbol) new_integrand = test_subterm(u, u_diff) if new_integrand is not False: constant, new_integrand = new_integrand if new_integrand == integrand.subs(symbol, u_var): continue substitution = (u, constant, new_integrand) if substitution not in results: results.append(substitution) return results def rewriter(condition, rewrite): """Strategy that rewrites an integrand.""" def _rewriter(integral): integrand, symbol = integral debug("Integral: {} is rewritten with {} on symbol: {}".format(integrand, rewrite, symbol)) if condition(*integral): rewritten = rewrite(*integral) if rewritten != integrand: substep = integral_steps(rewritten, symbol) if not isinstance(substep, DontKnowRule) and substep: return RewriteRule( rewritten, substep, integrand, symbol) return _rewriter def proxy_rewriter(condition, rewrite): """Strategy that rewrites an integrand based on some other criteria.""" def _proxy_rewriter(criteria): criteria, integral = criteria integrand, symbol = integral debug("Integral: {} is rewritten with {} on symbol: {} and criteria: {}".format(integrand, rewrite, symbol, criteria)) args = criteria + list(integral) if condition(*args): rewritten = rewrite(*args) if rewritten != integrand: return RewriteRule( rewritten, integral_steps(rewritten, symbol), integrand, symbol) return _proxy_rewriter def multiplexer(conditions): """Apply the rule that matches the condition, else None""" def multiplexer_rl(expr): for key, rule in conditions.items(): if key(expr): return rule(expr) return multiplexer_rl def alternatives(*rules): """Strategy that makes an AlternativeRule out of multiple possible results.""" def _alternatives(integral): alts = [] count = 0 debug("List of Alternative Rules") for rule in rules: count = count + 1 debug("Rule {}: {}".format(count, rule)) result = rule(integral) if (result and not isinstance(result, DontKnowRule) and result != integral and result not in alts): alts.append(result) if len(alts) == 1: return alts[0] elif alts: doable = [rule for rule in alts if not contains_dont_know(rule)] if doable: return AlternativeRule(doable, *integral) else: return AlternativeRule(alts, *integral) return _alternatives def constant_rule(integral): return ConstantRule(integral.integrand, *integral) def power_rule(integral): integrand, symbol = integral base, expt = integrand.as_base_exp() if symbol not in expt.free_symbols and isinstance(base, Symbol): if simplify(expt + 1) == 0: return ReciprocalRule(base, integrand, symbol) return PowerRule(base, expt, integrand, symbol) elif symbol not in base.free_symbols and isinstance(expt, Symbol): rule = ExpRule(base, expt, integrand, symbol) if fuzzy_not(log(base).is_zero): return rule elif log(base).is_zero: return ConstantRule(1, 1, symbol) return PiecewiseRule([ (rule, Ne(log(base), 0)), (ConstantRule(1, 1, symbol), True) ], integrand, symbol) def exp_rule(integral): integrand, symbol = integral if isinstance(integrand.args[0], Symbol): return ExpRule(E, integrand.args[0], integrand, symbol) def orthogonal_poly_rule(integral): orthogonal_poly_classes = { jacobi: JacobiRule, gegenbauer: GegenbauerRule, chebyshevt: ChebyshevTRule, chebyshevu: ChebyshevURule, legendre: LegendreRule, hermite: HermiteRule, laguerre: LaguerreRule, assoc_laguerre: AssocLaguerreRule } orthogonal_poly_var_index = { jacobi: 3, gegenbauer: 2, assoc_laguerre: 2 } integrand, symbol = integral for klass in orthogonal_poly_classes: if isinstance(integrand, klass): var_index = orthogonal_poly_var_index.get(klass, 1) if (integrand.args[var_index] is symbol and not any(v.has(symbol) for v in integrand.args[:var_index])): args = integrand.args[:var_index] + (integrand, symbol) return orthogonal_poly_classes[klass](*args) _special_function_patterns: list[tuple[Type, Expr, Callable | None, tuple]] = [] _wilds = [] _symbol = Dummy('x') def special_function_rule(integral): integrand, symbol = integral if not _special_function_patterns: a = Wild('a', exclude=[_symbol], properties=[lambda x: not x.is_zero]) b = Wild('b', exclude=[_symbol]) c = Wild('c', exclude=[_symbol]) d = Wild('d', exclude=[_symbol], properties=[lambda x: not x.is_zero]) e = Wild('e', exclude=[_symbol], properties=[ lambda x: not (x.is_nonnegative and x.is_integer)]) _wilds.extend((a, b, c, d, e)) # patterns consist of a SymPy class, a wildcard expr, an optional # condition coded as a lambda (when Wild properties are not enough), # followed by an applicable rule linear_pattern = a*_symbol + b quadratic_pattern = a*_symbol**2 + b*_symbol + c _special_function_patterns.extend(( (Mul, exp(linear_pattern, evaluate=False)/_symbol, None, EiRule), (Mul, cos(linear_pattern, evaluate=False)/_symbol, None, CiRule), (Mul, cosh(linear_pattern, evaluate=False)/_symbol, None, ChiRule), (Mul, sin(linear_pattern, evaluate=False)/_symbol, None, SiRule), (Mul, sinh(linear_pattern, evaluate=False)/_symbol, None, ShiRule), (Pow, 1/log(linear_pattern, evaluate=False), None, LiRule), (exp, exp(quadratic_pattern, evaluate=False), None, ErfRule), (sin, sin(quadratic_pattern, evaluate=False), None, FresnelSRule), (cos, cos(quadratic_pattern, evaluate=False), None, FresnelCRule), (Mul, _symbol**e*exp(a*_symbol, evaluate=False), None, UpperGammaRule), (Mul, polylog(b, a*_symbol, evaluate=False)/_symbol, None, PolylogRule), (Pow, 1/sqrt(a - d*sin(_symbol, evaluate=False)**2), lambda a, d: a != d, EllipticFRule), (Pow, sqrt(a - d*sin(_symbol, evaluate=False)**2), lambda a, d: a != d, EllipticERule), )) _integrand = integrand.subs(symbol, _symbol) for type_, pattern, constraint, rule in _special_function_patterns: if isinstance(_integrand, type_): match = _integrand.match(pattern) if match: wild_vals = tuple(match.get(w) for w in _wilds if match.get(w) is not None) if constraint is None or constraint(*wild_vals): args = wild_vals + (integrand, symbol) return rule(*args) def _add_degenerate_step(generic_cond, generic_step, degenerate_step): if degenerate_step is None: return generic_step if isinstance(generic_step, PiecewiseRule): subfunctions = [(substep, (cond & generic_cond).simplify()) for substep, cond in generic_step.subfunctions] else: subfunctions = [(generic_step, generic_cond)] if isinstance(degenerate_step, PiecewiseRule): subfunctions += degenerate_step.subfunctions else: subfunctions.append((degenerate_step, S.true)) return PiecewiseRule(subfunctions, generic_step.context, generic_step.symbol) def inverse_trig_rule(integral: IntegralInfo, degenerate=True): """ Set degenerate=False on recursive call where coefficient of quadratic term is assumed non-zero. """ integrand, symbol = integral base, exp = integrand.as_base_exp() a = Wild('a', exclude=[symbol]) b = Wild('b', exclude=[symbol]) c = Wild('c', exclude=[symbol, 0]) match = base.match(a + b*symbol + c*symbol**2) if not match: return def make_inverse_trig(RuleClass, a, sign_a, c, sign_c, h): u_var = Dummy("u") rewritten = 1/sqrt(sign_a*a + sign_c*c*(symbol-h)**2) # a>0, c>0 quadratic_base = sqrt(c/a)*(symbol-h) constant = 1/sqrt(c) u_func = None if quadratic_base is not symbol: u_func = quadratic_base quadratic_base = u_var standard_form = 1/sqrt(sign_a + sign_c*quadratic_base**2) substep = RuleClass(standard_form, quadratic_base) if constant != 1: substep = ConstantTimesRule(constant, standard_form, substep, constant*standard_form, symbol) if u_func is not None: substep = URule(u_var, u_func, None, substep, rewritten, symbol) if h != 0: substep = CompleteSquareRule(rewritten, substep, integrand, symbol) return substep a, b, c = [match.get(i, S.Zero) for i in (a, b, c)] generic_cond = Ne(c, 0) if not degenerate or generic_cond is S.true: degenerate_step = None elif b.is_zero: degenerate_step = ConstantRule(a ** exp, a ** exp, symbol) else: degenerate_step = sqrt_linear_rule(IntegralInfo((a + b * symbol) ** exp, symbol)) if simplify(2*exp + 1) == 0: h, k = -b/(2*c), a - b**2/(4*c) # rewrite base to k + c*(symbol-h)**2 step = general_rule = ReciprocalSqrtQuadraticRule(a, b, c, integrand, symbol) if k.is_real and c.is_real: # list of ((rule, base_exp, a, sign_a, b, sign_b), condition) possibilities = [] for args, cond in ( # don't apply ArccoshRule to x**2-1 ((ArcsinRule, k, 1, -c, -1, h), And(k > 0, c < 0)), # 1-x**2 ((ArcsinhRule, k, 1, c, 1, h), And(k > 0, c > 0)), # 1+x**2 ): if cond is S.true: return make_inverse_trig(*args) if cond is not S.false: possibilities.append((args, cond)) if possibilities: rules = [(make_inverse_trig(*args), cond) for args, cond in possibilities] if not k.is_positive: # conditions are not thorough, need fall back rule rules.append((general_rule, S.true)) step = PiecewiseRule(rules, integrand, symbol) else: step = general_rule return _add_degenerate_step(generic_cond, step, degenerate_step) if exp == S.Half: step = SqrtQuadraticRule(a, b, c, integrand, symbol) return _add_degenerate_step(generic_cond, step, degenerate_step) def add_rule(integral): integrand, symbol = integral results = [integral_steps(g, symbol) for g in integrand.as_ordered_terms()] return None if None in results else AddRule(results, integrand, symbol) def mul_rule(integral: IntegralInfo): integrand, symbol = integral # Constant times function case coeff, f = integrand.as_independent(symbol) if coeff != 1: next_step = integral_steps(f, symbol) if next_step is not None: return ConstantTimesRule(coeff, f, next_step, integrand, symbol) def _parts_rule(integrand, symbol): # LIATE rule: # log, inverse trig, algebraic, trigonometric, exponential def pull_out_algebraic(integrand): integrand = integrand.cancel().together() # iterating over Piecewise args would not work here algebraic = ([] if isinstance(integrand, Piecewise) or not integrand.is_Mul else [arg for arg in integrand.args if arg.is_algebraic_expr(symbol)]) if algebraic: u = Mul(*algebraic) dv = (integrand / u).cancel() return u, dv def pull_out_u(*functions): def pull_out_u_rl(integrand): if any(integrand.has(f) for f in functions): args = [arg for arg in integrand.args if any(isinstance(arg, cls) for cls in functions)] if args: u = reduce(lambda a,b: a*b, args) dv = integrand / u return u, dv return pull_out_u_rl liate_rules = [pull_out_u(log), pull_out_u(*inverse_trig_functions), pull_out_algebraic, pull_out_u(sin, cos), pull_out_u(exp)] dummy = Dummy("temporary") # we can integrate log(x) and atan(x) by setting dv = 1 if isinstance(integrand, (log, *inverse_trig_functions)): integrand = dummy * integrand for index, rule in enumerate(liate_rules): result = rule(integrand) if result: u, dv = result # Don't pick u to be a constant if possible if symbol not in u.free_symbols and not u.has(dummy): return u = u.subs(dummy, 1) dv = dv.subs(dummy, 1) # Don't pick a non-polynomial algebraic to be differentiated if rule == pull_out_algebraic and not u.is_polynomial(symbol): return # Don't trade one logarithm for another if isinstance(u, log): rec_dv = 1/dv if (rec_dv.is_polynomial(symbol) and degree(rec_dv, symbol) == 1): return # Can integrate a polynomial times OrthogonalPolynomial if rule == pull_out_algebraic: if dv.is_Derivative or dv.has(TrigonometricFunction) or \ isinstance(dv, OrthogonalPolynomial): v_step = integral_steps(dv, symbol) if contains_dont_know(v_step): return else: du = u.diff(symbol) v = _manualintegrate(v_step) return u, dv, v, du, v_step # make sure dv is amenable to integration accept = False if index < 2: # log and inverse trig are usually worth trying accept = True elif (rule == pull_out_algebraic and dv.args and all(isinstance(a, (sin, cos, exp)) for a in dv.args)): accept = True else: for lrule in liate_rules[index + 1:]: r = lrule(integrand) if r and r[0].subs(dummy, 1).equals(dv): accept = True break if accept: du = u.diff(symbol) v_step = integral_steps(simplify(dv), symbol) if not contains_dont_know(v_step): v = _manualintegrate(v_step) return u, dv, v, du, v_step def parts_rule(integral): integrand, symbol = integral constant, integrand = integrand.as_coeff_Mul() result = _parts_rule(integrand, symbol) steps = [] if result: u, dv, v, du, v_step = result debug("u : {}, dv : {}, v : {}, du : {}, v_step: {}".format(u, dv, v, du, v_step)) steps.append(result) if isinstance(v, Integral): return # Set a limit on the number of times u can be used if isinstance(u, (sin, cos, exp, sinh, cosh)): cachekey = u.xreplace({symbol: _cache_dummy}) if _parts_u_cache[cachekey] > 2: return _parts_u_cache[cachekey] += 1 # Try cyclic integration by parts a few times for _ in range(4): debug("Cyclic integration {} with v: {}, du: {}, integrand: {}".format(_, v, du, integrand)) coefficient = ((v * du) / integrand).cancel() if coefficient == 1: break if symbol not in coefficient.free_symbols: rule = CyclicPartsRule( [PartsRule(u, dv, v_step, None, None, None) for (u, dv, v, du, v_step) in steps], (-1) ** len(steps) * coefficient, integrand, symbol ) if (constant != 1) and rule: rule = ConstantTimesRule(constant, integrand, rule, constant * integrand, symbol) return rule # _parts_rule is sensitive to constants, factor it out next_constant, next_integrand = (v * du).as_coeff_Mul() result = _parts_rule(next_integrand, symbol) if result: u, dv, v, du, v_step = result u *= next_constant du *= next_constant steps.append((u, dv, v, du, v_step)) else: break def make_second_step(steps, integrand): if steps: u, dv, v, du, v_step = steps[0] return PartsRule(u, dv, v_step, make_second_step(steps[1:], v * du), integrand, symbol) return integral_steps(integrand, symbol) if steps: u, dv, v, du, v_step = steps[0] rule = PartsRule(u, dv, v_step, make_second_step(steps[1:], v * du), integrand, symbol) if (constant != 1) and rule: rule = ConstantTimesRule(constant, integrand, rule, constant * integrand, symbol) return rule def trig_rule(integral): integrand, symbol = integral if isinstance(integrand, (sin, cos)): arg = integrand.args[0] if not isinstance(arg, Symbol): return # perhaps a substitution can deal with it if isinstance(integrand, sin): func = 'sin' else: func = 'cos' return TrigRule(func, arg, integrand, symbol) if integrand == sec(symbol)**2: return TrigRule('sec**2', symbol, integrand, symbol) elif integrand == csc(symbol)**2: return TrigRule('csc**2', symbol, integrand, symbol) if isinstance(integrand, tan): rewritten = sin(*integrand.args) / cos(*integrand.args) elif isinstance(integrand, cot): rewritten = cos(*integrand.args) / sin(*integrand.args) elif isinstance(integrand, sec): arg = integrand.args[0] rewritten = ((sec(arg)**2 + tan(arg) * sec(arg)) / (sec(arg) + tan(arg))) elif isinstance(integrand, csc): arg = integrand.args[0] rewritten = ((csc(arg)**2 + cot(arg) * csc(arg)) / (csc(arg) + cot(arg))) else: return return RewriteRule( rewritten, integral_steps(rewritten, symbol), integrand, symbol ) def trig_product_rule(integral): integrand, symbol = integral sectan = sec(symbol) * tan(symbol) q = integrand / sectan if symbol not in q.free_symbols: rule = TrigRule('sec*tan', symbol, sectan, symbol) if q != 1 and rule: rule = ConstantTimesRule(q, sectan, rule, integrand, symbol) return rule csccot = -csc(symbol) * cot(symbol) q = integrand / csccot if symbol not in q.free_symbols: rule = TrigRule('csc*cot', symbol, csccot, symbol) if q != 1 and rule: rule = ConstantTimesRule(q, csccot, rule, integrand, symbol) return rule def quadratic_denom_rule(integral): integrand, symbol = integral a = Wild('a', exclude=[symbol]) b = Wild('b', exclude=[symbol]) c = Wild('c', exclude=[symbol]) match = integrand.match(a / (b * symbol ** 2 + c)) if match: a, b, c = match[a], match[b], match[c] general_rule = ArctanRule(a, b, c, integrand, symbol) if b.is_extended_real and c.is_extended_real: positive_cond = c/b > 0 if positive_cond is S.true: return general_rule coeff = a/(2*sqrt(-c)*sqrt(b)) constant = sqrt(-c/b) r1 = 1/(symbol-constant) r2 = 1/(symbol+constant) log_steps = [ReciprocalRule(symbol-constant, r1, symbol), ConstantTimesRule(-1, r2, ReciprocalRule(symbol+constant, r2, symbol), -r2, symbol)] rewritten = sub = r1 - r2 negative_step = AddRule(log_steps, sub, symbol) if coeff != 1: rewritten = Mul(coeff, sub, evaluate=False) negative_step = ConstantTimesRule(coeff, sub, negative_step, rewritten, symbol) negative_step = RewriteRule(rewritten, negative_step, integrand, symbol) if positive_cond is S.false: return negative_step return PiecewiseRule([(general_rule, positive_cond), (negative_step, S.true)], integrand, symbol) return general_rule d = Wild('d', exclude=[symbol]) match2 = integrand.match(a / (b * symbol ** 2 + c * symbol + d)) if match2: b, c = match2[b], match2[c] if b.is_zero: return u = Dummy('u') u_func = symbol + c/(2*b) integrand2 = integrand.subs(symbol, u - c / (2*b)) next_step = integral_steps(integrand2, u) if next_step: return URule(u, u_func, None, next_step, integrand2, symbol) else: return e = Wild('e', exclude=[symbol]) match3 = integrand.match((a* symbol + b) / (c * symbol ** 2 + d * symbol + e)) if match3: a, b, c, d, e = match3[a], match3[b], match3[c], match3[d], match3[e] if c.is_zero: return denominator = c * symbol**2 + d * symbol + e const = a/(2*c) numer1 = (2*c*symbol+d) numer2 = - const*d + b u = Dummy('u') step1 = URule(u, denominator, const, integral_steps(u**(-1), u), integrand, symbol) if const != 1: step1 = ConstantTimesRule(const, numer1/denominator, step1, const*numer1/denominator, symbol) if numer2.is_zero: return step1 step2 = integral_steps(numer2/denominator, symbol) substeps = AddRule([step1, step2], integrand, symbol) rewriten = const*numer1/denominator+numer2/denominator return RewriteRule(rewriten, substeps, integrand, symbol) return def sqrt_linear_rule(integral: IntegralInfo): """ Substitute common (a+b*x)**(1/n) """ integrand, x = integral a = Wild('a', exclude=[x]) b = Wild('b', exclude=[x, 0]) a0 = b0 = 0 bases, qs, bs = [], [], [] for pow_ in integrand.find(Pow): # collect all (a+b*x)**(p/q) base, exp_ = pow_.base, pow_.exp if exp_.is_Integer or x not in base.free_symbols: # skip 1/x and sqrt(2) continue if not exp_.is_Rational: # exclude x**pi return match = base.match(a+b*x) if not match: # skip non-linear continue # for sqrt(x+sqrt(x)), although base is non-linear, we can still substitute sqrt(x) a1, b1 = match[a], match[b] if a0*b1 != a1*b0 or not (b0/b1).is_nonnegative: # cannot transform sqrt(x) to sqrt(x+1) or sqrt(-x) return if b0 == 0 or (b0/b1 > 1) is S.true: # choose the latter of sqrt(2*x) and sqrt(x) as representative a0, b0 = a1, b1 bases.append(base) bs.append(b1) qs.append(exp_.q) if b0 == 0: # no such pattern found return q0: Integer = lcm_list(qs) u_x = (a0 + b0*x)**(1/q0) u = Dummy("u") substituted = integrand.subs({base**(S.One/q): (b/b0)**(S.One/q)*u**(q0/q) for base, b, q in zip(bases, bs, qs)}).subs(x, (u**q0-a0)/b0) substep = integral_steps(substituted*u**(q0-1)*q0/b0, u) if not contains_dont_know(substep): step = URule(u, u_x, None, substep, integrand, x) generic_cond = Ne(b0, 0) if generic_cond is not S.true: # possible degenerate case simplified = integrand.subs({b: 0 for b in bs}) degenerate_step = integral_steps(simplified, x) step = PiecewiseRule([(step, generic_cond), (degenerate_step, S.true)], integrand, x) return step def sqrt_quadratic_rule(integral: IntegralInfo, degenerate=True): integrand, x = integral a = Wild('a', exclude=[x]) b = Wild('b', exclude=[x]) c = Wild('c', exclude=[x, 0]) f = Wild('f') n = Wild('n', properties=[lambda n: n.is_Integer and n.is_odd]) match = integrand.match(f*sqrt(a+b*x+c*x**2)**n) if not match: return a, b, c, f, n = match[a], match[b], match[c], match[f], match[n] f_poly = f.as_poly(x) if f_poly is None: return generic_cond = Ne(c, 0) if not degenerate or generic_cond is S.true: degenerate_step = None elif b.is_zero: degenerate_step = integral_steps(f*sqrt(a)**n, x) else: degenerate_step = sqrt_linear_rule(IntegralInfo(f*sqrt(a+b*x)**n, x)) def sqrt_quadratic_denom_rule(numer_poly: Poly, integrand: Expr): denom = sqrt(a+b*x+c*x**2) deg = numer_poly.degree() if deg <= 1: # integrand == (d+e*x)/sqrt(a+b*x+c*x**2) e, d = numer_poly.all_coeffs() if deg == 1 else (S.Zero, numer_poly.as_expr()) # rewrite numerator to A*(2*c*x+b) + B A = e/(2*c) B = d-A*b pre_substitute = (2*c*x+b)/denom constant_step = linear_step = None if A != 0: u = Dummy("u") pow_rule = PowerRule(u, -S.Half, 1/sqrt(u), u) linear_step = URule(u, a+b*x+c*x**2, None, pow_rule, pre_substitute, x) if A != 1: linear_step = ConstantTimesRule(A, pre_substitute, linear_step, A*pre_substitute, x) if B != 0: constant_step = inverse_trig_rule(IntegralInfo(1/denom, x), degenerate=False) if B != 1: constant_step = ConstantTimesRule(B, 1/denom, constant_step, B/denom, x) if linear_step and constant_step: add = Add(A*pre_substitute, B/denom, evaluate=False) step = RewriteRule(add, AddRule([linear_step, constant_step], add, x), integrand, x) else: step = linear_step or constant_step else: coeffs = numer_poly.all_coeffs() step = SqrtQuadraticDenomRule(a, b, c, coeffs, integrand, x) return step if n > 0: # rewrite poly * sqrt(s)**(2*k-1) to poly*s**k / sqrt(s) numer_poly = f_poly * (a+b*x+c*x**2)**((n+1)/2) rewritten = numer_poly.as_expr()/sqrt(a+b*x+c*x**2) substep = sqrt_quadratic_denom_rule(numer_poly, rewritten) generic_step = RewriteRule(rewritten, substep, integrand, x) elif n == -1: generic_step = sqrt_quadratic_denom_rule(f_poly, integrand) else: return # todo: handle n < -1 case return _add_degenerate_step(generic_cond, generic_step, degenerate_step) def hyperbolic_rule(integral: tuple[Expr, Symbol]): integrand, symbol = integral if isinstance(integrand, HyperbolicFunction) and integrand.args[0] == symbol: if integrand.func == sinh: return HyperbolicRule('sinh', symbol, integrand, symbol) if integrand.func == cosh: return HyperbolicRule('cosh', symbol, integrand, symbol) u = Dummy('u') if integrand.func == tanh: rewritten = sinh(symbol)/cosh(symbol) return RewriteRule(rewritten, URule(u, cosh(symbol), None, ReciprocalRule(u, 1/u, u), rewritten, symbol), integrand, symbol) if integrand.func == coth: rewritten = cosh(symbol)/sinh(symbol) return RewriteRule(rewritten, URule(u, sinh(symbol), None, ReciprocalRule(u, 1/u, u), rewritten, symbol), integrand, symbol) else: rewritten = integrand.rewrite(tanh) if integrand.func == sech: return RewriteRule(rewritten, URule(u, tanh(symbol/2), None, ArctanRule(S(2), S.One, S.One, 2/(u**2 + 1), u), rewritten, symbol), integrand, symbol) if integrand.func == csch: return RewriteRule(rewritten, URule(u, tanh(symbol/2), None, ReciprocalRule(u, 1/u, u), rewritten, symbol), integrand, symbol) @cacheit def make_wilds(symbol): a = Wild('a', exclude=[symbol]) b = Wild('b', exclude=[symbol]) m = Wild('m', exclude=[symbol], properties=[lambda n: isinstance(n, Integer)]) n = Wild('n', exclude=[symbol], properties=[lambda n: isinstance(n, Integer)]) return a, b, m, n @cacheit def sincos_pattern(symbol): a, b, m, n = make_wilds(symbol) pattern = sin(a*symbol)**m * cos(b*symbol)**n return pattern, a, b, m, n @cacheit def tansec_pattern(symbol): a, b, m, n = make_wilds(symbol) pattern = tan(a*symbol)**m * sec(b*symbol)**n return pattern, a, b, m, n @cacheit def cotcsc_pattern(symbol): a, b, m, n = make_wilds(symbol) pattern = cot(a*symbol)**m * csc(b*symbol)**n return pattern, a, b, m, n @cacheit def heaviside_pattern(symbol): m = Wild('m', exclude=[symbol]) b = Wild('b', exclude=[symbol]) g = Wild('g') pattern = Heaviside(m*symbol + b) * g return pattern, m, b, g def uncurry(func): def uncurry_rl(args): return func(*args) return uncurry_rl def trig_rewriter(rewrite): def trig_rewriter_rl(args): a, b, m, n, integrand, symbol = args rewritten = rewrite(a, b, m, n, integrand, symbol) if rewritten != integrand: return RewriteRule( rewritten, integral_steps(rewritten, symbol), integrand, symbol) return trig_rewriter_rl sincos_botheven_condition = uncurry( lambda a, b, m, n, i, s: m.is_even and n.is_even and m.is_nonnegative and n.is_nonnegative) sincos_botheven = trig_rewriter( lambda a, b, m, n, i, symbol: ( (((1 - cos(2*a*symbol)) / 2) ** (m / 2)) * (((1 + cos(2*b*symbol)) / 2) ** (n / 2)) )) sincos_sinodd_condition = uncurry(lambda a, b, m, n, i, s: m.is_odd and m >= 3) sincos_sinodd = trig_rewriter( lambda a, b, m, n, i, symbol: ( (1 - cos(a*symbol)**2)**((m - 1) / 2) * sin(a*symbol) * cos(b*symbol) ** n)) sincos_cosodd_condition = uncurry(lambda a, b, m, n, i, s: n.is_odd and n >= 3) sincos_cosodd = trig_rewriter( lambda a, b, m, n, i, symbol: ( (1 - sin(b*symbol)**2)**((n - 1) / 2) * cos(b*symbol) * sin(a*symbol) ** m)) tansec_seceven_condition = uncurry(lambda a, b, m, n, i, s: n.is_even and n >= 4) tansec_seceven = trig_rewriter( lambda a, b, m, n, i, symbol: ( (1 + tan(b*symbol)**2) ** (n/2 - 1) * sec(b*symbol)**2 * tan(a*symbol) ** m )) tansec_tanodd_condition = uncurry(lambda a, b, m, n, i, s: m.is_odd) tansec_tanodd = trig_rewriter( lambda a, b, m, n, i, symbol: ( (sec(a*symbol)**2 - 1) ** ((m - 1) / 2) * tan(a*symbol) * sec(b*symbol) ** n )) tan_tansquared_condition = uncurry(lambda a, b, m, n, i, s: m == 2 and n == 0) tan_tansquared = trig_rewriter( lambda a, b, m, n, i, symbol: ( sec(a*symbol)**2 - 1)) cotcsc_csceven_condition = uncurry(lambda a, b, m, n, i, s: n.is_even and n >= 4) cotcsc_csceven = trig_rewriter( lambda a, b, m, n, i, symbol: ( (1 + cot(b*symbol)**2) ** (n/2 - 1) * csc(b*symbol)**2 * cot(a*symbol) ** m )) cotcsc_cotodd_condition = uncurry(lambda a, b, m, n, i, s: m.is_odd) cotcsc_cotodd = trig_rewriter( lambda a, b, m, n, i, symbol: ( (csc(a*symbol)**2 - 1) ** ((m - 1) / 2) * cot(a*symbol) * csc(b*symbol) ** n )) def trig_sincos_rule(integral): integrand, symbol = integral if any(integrand.has(f) for f in (sin, cos)): pattern, a, b, m, n = sincos_pattern(symbol) match = integrand.match(pattern) if not match: return return multiplexer({ sincos_botheven_condition: sincos_botheven, sincos_sinodd_condition: sincos_sinodd, sincos_cosodd_condition: sincos_cosodd })(tuple( [match.get(i, S.Zero) for i in (a, b, m, n)] + [integrand, symbol])) def trig_tansec_rule(integral): integrand, symbol = integral integrand = integrand.subs({ 1 / cos(symbol): sec(symbol) }) if any(integrand.has(f) for f in (tan, sec)): pattern, a, b, m, n = tansec_pattern(symbol) match = integrand.match(pattern) if not match: return return multiplexer({ tansec_tanodd_condition: tansec_tanodd, tansec_seceven_condition: tansec_seceven, tan_tansquared_condition: tan_tansquared })(tuple( [match.get(i, S.Zero) for i in (a, b, m, n)] + [integrand, symbol])) def trig_cotcsc_rule(integral): integrand, symbol = integral integrand = integrand.subs({ 1 / sin(symbol): csc(symbol), 1 / tan(symbol): cot(symbol), cos(symbol) / tan(symbol): cot(symbol) }) if any(integrand.has(f) for f in (cot, csc)): pattern, a, b, m, n = cotcsc_pattern(symbol) match = integrand.match(pattern) if not match: return return multiplexer({ cotcsc_cotodd_condition: cotcsc_cotodd, cotcsc_csceven_condition: cotcsc_csceven })(tuple( [match.get(i, S.Zero) for i in (a, b, m, n)] + [integrand, symbol])) def trig_sindouble_rule(integral): integrand, symbol = integral a = Wild('a', exclude=[sin(2*symbol)]) match = integrand.match(sin(2*symbol)*a) if match: sin_double = 2*sin(symbol)*cos(symbol)/sin(2*symbol) return integral_steps(integrand * sin_double, symbol) def trig_powers_products_rule(integral): return do_one(null_safe(trig_sincos_rule), null_safe(trig_tansec_rule), null_safe(trig_cotcsc_rule), null_safe(trig_sindouble_rule))(integral) def trig_substitution_rule(integral): integrand, symbol = integral A = Wild('a', exclude=[0, symbol]) B = Wild('b', exclude=[0, symbol]) theta = Dummy("theta") target_pattern = A + B*symbol**2 matches = integrand.find(target_pattern) for expr in matches: match = expr.match(target_pattern) a = match.get(A, S.Zero) b = match.get(B, S.Zero) a_positive = ((a.is_number and a > 0) or a.is_positive) b_positive = ((b.is_number and b > 0) or b.is_positive) a_negative = ((a.is_number and a < 0) or a.is_negative) b_negative = ((b.is_number and b < 0) or b.is_negative) x_func = None if a_positive and b_positive: # a**2 + b*x**2. Assume sec(theta) > 0, -pi/2 < theta < pi/2 x_func = (sqrt(a)/sqrt(b)) * tan(theta) # Do not restrict the domain: tan(theta) takes on any real # value on the interval -pi/2 < theta < pi/2 so x takes on # any value restriction = True elif a_positive and b_negative: # a**2 - b*x**2. Assume cos(theta) > 0, -pi/2 < theta < pi/2 constant = sqrt(a)/sqrt(-b) x_func = constant * sin(theta) restriction = And(symbol > -constant, symbol < constant) elif a_negative and b_positive: # b*x**2 - a**2. Assume sin(theta) > 0, 0 < theta < pi constant = sqrt(-a)/sqrt(b) x_func = constant * sec(theta) restriction = And(symbol > -constant, symbol < constant) if x_func: # Manually simplify sqrt(trig(theta)**2) to trig(theta) # Valid due to assumed domain restriction substitutions = {} for f in [sin, cos, tan, sec, csc, cot]: substitutions[sqrt(f(theta)**2)] = f(theta) substitutions[sqrt(f(theta)**(-2))] = 1/f(theta) replaced = integrand.subs(symbol, x_func).trigsimp() replaced = manual_subs(replaced, substitutions) if not replaced.has(symbol): replaced *= manual_diff(x_func, theta) replaced = replaced.trigsimp() secants = replaced.find(1/cos(theta)) if secants: replaced = replaced.xreplace({ 1/cos(theta): sec(theta) }) substep = integral_steps(replaced, theta) if not contains_dont_know(substep): return TrigSubstitutionRule( theta, x_func, replaced, substep, restriction, integrand, symbol) def heaviside_rule(integral): integrand, symbol = integral pattern, m, b, g = heaviside_pattern(symbol) match = integrand.match(pattern) if match and 0 != match[g]: # f = Heaviside(m*x + b)*g v_step = integral_steps(match[g], symbol) result = _manualintegrate(v_step) m, b = match[m], match[b] return HeavisideRule(m*symbol + b, -b/m, result, integrand, symbol) def dirac_delta_rule(integral: IntegralInfo): integrand, x = integral if len(integrand.args) == 1: n = S.Zero else: n = integrand.args[1] if not n.is_Integer or n < 0: return a, b = Wild('a', exclude=[x]), Wild('b', exclude=[x, 0]) match = integrand.args[0].match(a+b*x) if not match: return a, b = match[a], match[b] generic_cond = Ne(b, 0) if generic_cond is S.true: degenerate_step = None else: degenerate_step = ConstantRule(DiracDelta(a, n), integrand, x) generic_step = DiracDeltaRule(n, a, b, integrand, x) return _add_degenerate_step(generic_cond, generic_step, degenerate_step) def substitution_rule(integral): integrand, symbol = integral u_var = Dummy("u") substitutions = find_substitutions(integrand, symbol, u_var) count = 0 if substitutions: debug("List of Substitution Rules") ways = [] for u_func, c, substituted in substitutions: subrule = integral_steps(substituted, u_var) count = count + 1 debug("Rule {}: {}".format(count, subrule)) if contains_dont_know(subrule): continue if simplify(c - 1) != 0: _, denom = c.as_numer_denom() if subrule: subrule = ConstantTimesRule(c, substituted, subrule, c * substituted, u_var) if denom.free_symbols: piecewise = [] could_be_zero = [] if isinstance(denom, Mul): could_be_zero = denom.args else: could_be_zero.append(denom) for expr in could_be_zero: if not fuzzy_not(expr.is_zero): substep = integral_steps(manual_subs(integrand, expr, 0), symbol) if substep: piecewise.append(( substep, Eq(expr, 0) )) piecewise.append((subrule, True)) subrule = PiecewiseRule(piecewise, substituted, symbol) ways.append(URule(u_var, u_func, c, subrule, integrand, symbol)) if len(ways) > 1: return AlternativeRule(ways, integrand, symbol) elif ways: return ways[0] partial_fractions_rule = rewriter( lambda integrand, symbol: integrand.is_rational_function(), lambda integrand, symbol: integrand.apart(symbol)) cancel_rule = rewriter( # lambda integrand, symbol: integrand.is_algebraic_expr(), # lambda integrand, symbol: isinstance(integrand, Mul), lambda integrand, symbol: True, lambda integrand, symbol: integrand.cancel()) distribute_expand_rule = rewriter( lambda integrand, symbol: ( all(arg.is_Pow or arg.is_polynomial(symbol) for arg in integrand.args) or isinstance(integrand, Pow) or isinstance(integrand, Mul)), lambda integrand, symbol: integrand.expand()) trig_expand_rule = rewriter( # If there are trig functions with different arguments, expand them lambda integrand, symbol: ( len({a.args[0] for a in integrand.atoms(TrigonometricFunction)}) > 1), lambda integrand, symbol: integrand.expand(trig=True)) def derivative_rule(integral): integrand = integral[0] diff_variables = integrand.variables undifferentiated_function = integrand.expr integrand_variables = undifferentiated_function.free_symbols if integral.symbol in integrand_variables: if integral.symbol in diff_variables: return DerivativeRule(*integral) else: return DontKnowRule(integrand, integral.symbol) else: return ConstantRule(integral.integrand, *integral) def rewrites_rule(integral): integrand, symbol = integral if integrand.match(1/cos(symbol)): rewritten = integrand.subs(1/cos(symbol), sec(symbol)) return RewriteRule(rewritten, integral_steps(rewritten, symbol), integrand, symbol) def fallback_rule(integral): return DontKnowRule(*integral) # Cache is used to break cyclic integrals. # Need to use the same dummy variable in cached expressions for them to match. # Also record "u" of integration by parts, to avoid infinite repetition. _integral_cache: dict[Expr, Expr | None] = {} _parts_u_cache: dict[Expr, int] = defaultdict(int) _cache_dummy = Dummy("z") def integral_steps(integrand, symbol, **options): """Returns the steps needed to compute an integral. Explanation =========== This function attempts to mirror what a student would do by hand as closely as possible. SymPy Gamma uses this to provide a step-by-step explanation of an integral. The code it uses to format the results of this function can be found at https://github.com/sympy/sympy_gamma/blob/master/app/logic/intsteps.py. Examples ======== >>> from sympy import exp, sin >>> from sympy.integrals.manualintegrate import integral_steps >>> from sympy.abc import x >>> print(repr(integral_steps(exp(x) / (1 + exp(2 * x)), x))) \ # doctest: +NORMALIZE_WHITESPACE URule(u_var=_u, u_func=exp(x), constant=1, substep=ArctanRule(a=1, b=1, c=1, context=1/(_u**2 + 1), symbol=_u), context=exp(x)/(exp(2*x) + 1), symbol=x) >>> print(repr(integral_steps(sin(x), x))) \ # doctest: +NORMALIZE_WHITESPACE TrigRule(func='sin', arg=x, context=sin(x), symbol=x) >>> print(repr(integral_steps((x**2 + 3)**2, x))) \ # doctest: +NORMALIZE_WHITESPACE RewriteRule(rewritten=x**4 + 6*x**2 + 9, substep=AddRule(substeps=[PowerRule(base=x, exp=4, context=x**4, symbol=x), ConstantTimesRule(constant=6, other=x**2, substep=PowerRule(base=x, exp=2, context=x**2, symbol=x), context=6*x**2, symbol=x), ConstantRule(constant=9, context=9, symbol=x)], context=x**4 + 6*x**2 + 9, symbol=x), context=(x**2 + 3)**2, symbol=x) Returns ======= rule : namedtuple The first step; most rules have substeps that must also be considered. These substeps can be evaluated using ``manualintegrate`` to obtain a result. """ cachekey = integrand.xreplace({symbol: _cache_dummy}) if cachekey in _integral_cache: if _integral_cache[cachekey] is None: # Stop this attempt, because it leads around in a loop return DontKnowRule(integrand, symbol) else: # TODO: This is for future development, as currently # _integral_cache gets no values other than None return (_integral_cache[cachekey].xreplace(_cache_dummy, symbol), symbol) else: _integral_cache[cachekey] = None integral = IntegralInfo(integrand, symbol) def key(integral): integrand = integral.integrand if symbol not in integrand.free_symbols: return Number for cls in (Symbol, TrigonometricFunction, OrthogonalPolynomial): if isinstance(integrand, cls): return cls return type(integrand) def integral_is_subclass(*klasses): def _integral_is_subclass(integral): k = key(integral) return k and issubclass(k, klasses) return _integral_is_subclass result = do_one( null_safe(special_function_rule), null_safe(switch(key, { Pow: do_one(null_safe(power_rule), null_safe(inverse_trig_rule), null_safe(sqrt_linear_rule), null_safe(quadratic_denom_rule)), Symbol: power_rule, exp: exp_rule, Add: add_rule, Mul: do_one(null_safe(mul_rule), null_safe(trig_product_rule), null_safe(heaviside_rule), null_safe(quadratic_denom_rule), null_safe(sqrt_linear_rule), null_safe(sqrt_quadratic_rule)), Derivative: derivative_rule, TrigonometricFunction: trig_rule, Heaviside: heaviside_rule, DiracDelta: dirac_delta_rule, OrthogonalPolynomial: orthogonal_poly_rule, Number: constant_rule })), do_one( null_safe(trig_rule), null_safe(hyperbolic_rule), null_safe(alternatives( rewrites_rule, substitution_rule, condition( integral_is_subclass(Mul, Pow), partial_fractions_rule), condition( integral_is_subclass(Mul, Pow), cancel_rule), condition( integral_is_subclass(Mul, log, *inverse_trig_functions), parts_rule), condition( integral_is_subclass(Mul, Pow), distribute_expand_rule), trig_powers_products_rule, trig_expand_rule )), null_safe(trig_substitution_rule) ), fallback_rule)(integral) del _integral_cache[cachekey] return result @evaluates(ConstantRule) def eval_constant(constant, integrand, symbol): return constant * symbol @evaluates(ConstantTimesRule) def eval_constanttimes(constant, other, substep, integrand, symbol): return constant * _manualintegrate(substep) @evaluates(PowerRule) def eval_power(base, exp, integrand, symbol): return Piecewise( ((base**(exp + 1))/(exp + 1), Ne(exp, -1)), (log(base), True), ) @evaluates(ExpRule) def eval_exp(base, exp, integrand, symbol): return integrand / log(base) @evaluates(AddRule) def eval_add(substeps, integrand, symbol): return sum(map(_manualintegrate, substeps)) @evaluates(URule) def eval_u(u_var, u_func, constant, substep, integrand, symbol): result = _manualintegrate(substep) if u_func.is_Pow and u_func.exp == -1: # avoid needless -log(1/x) from substitution result = result.subs(log(u_var), -log(u_func.base)) return result.subs(u_var, u_func) @evaluates(PartsRule) def eval_parts(u, dv, v_step, second_step, integrand, symbol): v = _manualintegrate(v_step) return u * v - _manualintegrate(second_step) @evaluates(CyclicPartsRule) def eval_cyclicparts(parts_rules, coefficient, integrand, symbol): coefficient = 1 - coefficient result = [] sign = 1 for rule in parts_rules: result.append(sign * rule.u * _manualintegrate(rule.v_step)) sign *= -1 return Add(*result) / coefficient @evaluates(TrigRule) def eval_trig(func, arg, integrand, symbol): if func == 'sin': return -cos(arg) elif func == 'cos': return sin(arg) elif func == 'sec*tan': return sec(arg) elif func == 'csc*cot': return csc(arg) elif func == 'sec**2': return tan(arg) elif func == 'csc**2': return -cot(arg) @evaluates(HyperbolicRule) def eval_hyperbolic(func: str, arg: Expr, integrand, symbol): if func == 'sinh': return cosh(arg) if func == 'cosh': return sinh(arg) @evaluates(ArctanRule) def eval_arctan(a, b, c, integrand, symbol): return a / b * 1 / sqrt(c / b) * atan(symbol / sqrt(c / b)) @evaluates(ArctanhRule) def eval_arctanh(a, b, c, integrand, symbol): return - a / b * 1 / sqrt(-c / b) * atanh(symbol / sqrt(-c / b)) @evaluates(ReciprocalRule) def eval_reciprocal(func, integrand, symbol): return log(func) @evaluates(ArcsinRule) def eval_arcsin(integrand, symbol): return asin(symbol) @evaluates(ArcsinhRule) def eval_arcsinh(integrand, x): return asinh(x) @evaluates(ReciprocalSqrtQuadraticRule) def eval_reciprocal_sqrt_quadratic(a, b, c, integrand, x): return log(2*sqrt(c)*sqrt(a+b*x+c*x**2)+b+2*c*x)/sqrt(c) @evaluates(SqrtQuadraticDenomRule) def eval_sqrt_quadratic_denom(a, b, c, coeffs: list[Expr], integrand, x): # Integrate poly/sqrt(a+b*x+c*x**2) using recursion. # coeffs are coefficients of the polynomial. # Let I_n = x**n/sqrt(a+b*x+c*x**2), then # I_n = A * x**(n-1)*sqrt(a+b*x+c*x**2) - B * I_{n-1} - C * I_{n-2} # where A = 1/(n*c), B = (2*n-1)*b/(2*n*c), C = (n-1)*a/(n*c) # See https://github.com/sympy/sympy/pull/23608 for proof. result_coeffs = [] coeffs = coeffs.copy() for i in range(len(coeffs)-2): n = len(coeffs)-1-i coeff = coeffs[i]/(c*n) result_coeffs.append(coeff) coeffs[i+1] -= (2*n-1)*b/2*coeff coeffs[i+2] -= (n-1)*a*coeff d, e = coeffs[-1], coeffs[-2] s = sqrt(a+b*x+c*x**2) constant = d-b*e/(2*c) if constant == 0: I0 = 0 else: step = inverse_trig_rule(IntegralInfo(1/s, x), degenerate=False) I0 = constant*_manualintegrate(step) return Add(*(result_coeffs[i]*x**(len(coeffs)-2-i) for i in range(len(result_coeffs))), e/c)*s + I0 @evaluates(SqrtQuadraticRule) def eval_sqrt_quadratic(a, b, c, integrand, x): step = sqrt_quadratic_rule(IntegralInfo(integrand, x), degenerate=False) return _manualintegrate(step) @evaluates(AlternativeRule) def eval_alternative(alternatives, integrand, symbol): return _manualintegrate(alternatives[0]) @evaluates(CompleteSquareRule) @evaluates(RewriteRule) def eval_rewrite(rewritten, substep, integrand, symbol): return _manualintegrate(substep) @evaluates(PiecewiseRule) def eval_piecewise(substeps, integrand, symbol): return Piecewise(*[(_manualintegrate(substep), cond) for substep, cond in substeps]) @evaluates(TrigSubstitutionRule) def eval_trigsubstitution(theta, func, rewritten, substep, restriction, integrand, symbol): func = func.subs(sec(theta), 1/cos(theta)) func = func.subs(csc(theta), 1/sin(theta)) func = func.subs(cot(theta), 1/tan(theta)) trig_function = list(func.find(TrigonometricFunction)) assert len(trig_function) == 1 trig_function = trig_function[0] relation = solve(symbol - func, trig_function) assert len(relation) == 1 numer, denom = fraction(relation[0]) if isinstance(trig_function, sin): opposite = numer hypotenuse = denom adjacent = sqrt(denom**2 - numer**2) inverse = asin(relation[0]) elif isinstance(trig_function, cos): adjacent = numer hypotenuse = denom opposite = sqrt(denom**2 - numer**2) inverse = acos(relation[0]) elif isinstance(trig_function, tan): opposite = numer adjacent = denom hypotenuse = sqrt(denom**2 + numer**2) inverse = atan(relation[0]) substitution = [ (sin(theta), opposite/hypotenuse), (cos(theta), adjacent/hypotenuse), (tan(theta), opposite/adjacent), (theta, inverse) ] return Piecewise( (_manualintegrate(substep).subs(substitution).trigsimp(), restriction) ) @evaluates(DerivativeRule) def eval_derivativerule(integrand, symbol): # isinstance(integrand, Derivative) should be True variable_count = list(integrand.variable_count) for i, (var, count) in enumerate(variable_count): if var == symbol: variable_count[i] = (var, count-1) break return Derivative(integrand.expr, *variable_count) @evaluates(HeavisideRule) def eval_heaviside(harg, ibnd, substep, integrand, symbol): # If we are integrating over x and the integrand has the form # Heaviside(m*x+b)*g(x) == Heaviside(harg)*g(symbol) # then there needs to be continuity at -b/m == ibnd, # so we subtract the appropriate term. return Heaviside(harg)*(substep - substep.subs(symbol, ibnd)) @evaluates(DiracDeltaRule) def eval_dirac_delta(n, a, b, integrand, x): if n == 0: return Heaviside(a+b*x)/b return DiracDelta(a+b*x, n-1)/b @evaluates(JacobiRule) def eval_jacobi(n, a, b, integrand, symbol): return Piecewise( (2*jacobi(n + 1, a - 1, b - 1, symbol)/(n + a + b), Ne(n + a + b, 0)), (symbol, Eq(n, 0)), ((a + b + 2)*symbol**2/4 + (a - b)*symbol/2, Eq(n, 1))) @evaluates(GegenbauerRule) def eval_gegenbauer(n, a, integrand, symbol): return Piecewise( (gegenbauer(n + 1, a - 1, symbol)/(2*(a - 1)), Ne(a, 1)), (chebyshevt(n + 1, symbol)/(n + 1), Ne(n, -1)), (S.Zero, True)) @evaluates(ChebyshevTRule) def eval_chebyshevt(n, integrand, symbol): return Piecewise(((chebyshevt(n + 1, symbol)/(n + 1) - chebyshevt(n - 1, symbol)/(n - 1))/2, Ne(Abs(n), 1)), (symbol**2/2, True)) @evaluates(ChebyshevURule) def eval_chebyshevu(n, integrand, symbol): return Piecewise( (chebyshevt(n + 1, symbol)/(n + 1), Ne(n, -1)), (S.Zero, True)) @evaluates(LegendreRule) def eval_legendre(n, integrand, symbol): return (legendre(n + 1, symbol) - legendre(n - 1, symbol))/(2*n + 1) @evaluates(HermiteRule) def eval_hermite(n, integrand, symbol): return hermite(n + 1, symbol)/(2*(n + 1)) @evaluates(LaguerreRule) def eval_laguerre(n, integrand, symbol): return laguerre(n, symbol) - laguerre(n + 1, symbol) @evaluates(AssocLaguerreRule) def eval_assoclaguerre(n, a, integrand, symbol): return -assoc_laguerre(n + 1, a - 1, symbol) @evaluates(CiRule) def eval_ci(a, b, integrand, symbol): return cos(b)*Ci(a*symbol) - sin(b)*Si(a*symbol) @evaluates(ChiRule) def eval_chi(a, b, integrand, symbol): return cosh(b)*Chi(a*symbol) + sinh(b)*Shi(a*symbol) @evaluates(EiRule) def eval_ei(a, b, integrand, symbol): return exp(b)*Ei(a*symbol) @evaluates(SiRule) def eval_si(a, b, integrand, symbol): return sin(b)*Ci(a*symbol) + cos(b)*Si(a*symbol) @evaluates(ShiRule) def eval_shi(a, b, integrand, symbol): return sinh(b)*Chi(a*symbol) + cosh(b)*Shi(a*symbol) @evaluates(ErfRule) def eval_erf(a, b, c, integrand, symbol): if a.is_extended_real: return Piecewise( (sqrt(S.Pi/(-a))/2 * exp(c - b**2/(4*a)) * erf((-2*a*symbol - b)/(2*sqrt(-a))), a < 0), (sqrt(S.Pi/a)/2 * exp(c - b**2/(4*a)) * erfi((2*a*symbol + b)/(2*sqrt(a))), True)) else: return sqrt(S.Pi/a)/2 * exp(c - b**2/(4*a)) * \ erfi((2*a*symbol + b)/(2*sqrt(a))) @evaluates(FresnelCRule) def eval_fresnelc(a, b, c, integrand, symbol): return sqrt(S.Pi/(2*a)) * ( cos(b**2/(4*a) - c)*fresnelc((2*a*symbol + b)/sqrt(2*a*S.Pi)) + sin(b**2/(4*a) - c)*fresnels((2*a*symbol + b)/sqrt(2*a*S.Pi))) @evaluates(FresnelSRule) def eval_fresnels(a, b, c, integrand, symbol): return sqrt(S.Pi/(2*a)) * ( cos(b**2/(4*a) - c)*fresnels((2*a*symbol + b)/sqrt(2*a*S.Pi)) - sin(b**2/(4*a) - c)*fresnelc((2*a*symbol + b)/sqrt(2*a*S.Pi))) @evaluates(LiRule) def eval_li(a, b, integrand, symbol): return li(a*symbol + b)/a @evaluates(PolylogRule) def eval_polylog(a, b, integrand, symbol): return polylog(b + 1, a*symbol) @evaluates(UpperGammaRule) def eval_uppergamma(a, e, integrand, symbol): return symbol**e * (-a*symbol)**(-e) * uppergamma(e + 1, -a*symbol)/a @evaluates(EllipticFRule) def eval_elliptic_f(a, d, integrand, symbol): return elliptic_f(symbol, d/a)/sqrt(a) @evaluates(EllipticERule) def eval_elliptic_e(a, d, integrand, symbol): return elliptic_e(symbol, d/a)*sqrt(a) @evaluates(DontKnowRule) def eval_dontknowrule(integrand, symbol): return Integral(integrand, symbol) def _manualintegrate(rule): evaluator = evaluators.get(rule.__class__) if not evaluator: raise ValueError("Cannot evaluate rule %s" % repr(rule)) return evaluator(*rule) def manualintegrate(f, var): """manualintegrate(f, var) Explanation =========== Compute indefinite integral of a single variable using an algorithm that resembles what a student would do by hand. Unlike :func:`~.integrate`, var can only be a single symbol. Examples ======== >>> from sympy import sin, cos, tan, exp, log, integrate >>> from sympy.integrals.manualintegrate import manualintegrate >>> from sympy.abc import x >>> manualintegrate(1 / x, x) log(x) >>> integrate(1/x) log(x) >>> manualintegrate(log(x), x) x*log(x) - x >>> integrate(log(x)) x*log(x) - x >>> manualintegrate(exp(x) / (1 + exp(2 * x)), x) atan(exp(x)) >>> integrate(exp(x) / (1 + exp(2 * x))) RootSum(4*_z**2 + 1, Lambda(_i, _i*log(2*_i + exp(x)))) >>> manualintegrate(cos(x)**4 * sin(x), x) -cos(x)**5/5 >>> integrate(cos(x)**4 * sin(x), x) -cos(x)**5/5 >>> manualintegrate(cos(x)**4 * sin(x)**3, x) cos(x)**7/7 - cos(x)**5/5 >>> integrate(cos(x)**4 * sin(x)**3, x) cos(x)**7/7 - cos(x)**5/5 >>> manualintegrate(tan(x), x) -log(cos(x)) >>> integrate(tan(x), x) -log(cos(x)) See Also ======== sympy.integrals.integrals.integrate sympy.integrals.integrals.Integral.doit sympy.integrals.integrals.Integral """ result = _manualintegrate(integral_steps(f, var)) # Clear the cache of u-parts _parts_u_cache.clear() # If we got Piecewise with two parts, put generic first if isinstance(result, Piecewise) and len(result.args) == 2: cond = result.args[0][1] if isinstance(cond, Eq) and result.args[1][1] == True: result = result.func( (result.args[1][0], Ne(*cond.args)), (result.args[0][0], True)) return result
05e814729516f7a158f5ff189f48c78cad0b8c290cdbc3670958394bd7135b05
from sympy.functions import SingularityFunction, DiracDelta from sympy.integrals import integrate def singularityintegrate(f, x): """ This function handles the indefinite integrations of Singularity functions. The ``integrate`` function calls this function internally whenever an instance of SingularityFunction is passed as argument. Explanation =========== The idea for integration is the following: - If we are dealing with a SingularityFunction expression, i.e. ``SingularityFunction(x, a, n)``, we just return ``SingularityFunction(x, a, n + 1)/(n + 1)`` if ``n >= 0`` and ``SingularityFunction(x, a, n + 1)`` if ``n < 0``. - If the node is a multiplication or power node having a SingularityFunction term we rewrite the whole expression in terms of Heaviside and DiracDelta and then integrate the output. Lastly, we rewrite the output of integration back in terms of SingularityFunction. - If none of the above case arises, we return None. Examples ======== >>> from sympy.integrals.singularityfunctions import singularityintegrate >>> from sympy import SingularityFunction, symbols, Function >>> x, a, n, y = symbols('x a n y') >>> f = Function('f') >>> singularityintegrate(SingularityFunction(x, a, 3), x) SingularityFunction(x, a, 4)/4 >>> singularityintegrate(5*SingularityFunction(x, 5, -2), x) 5*SingularityFunction(x, 5, -1) >>> singularityintegrate(6*SingularityFunction(x, 5, -1), x) 6*SingularityFunction(x, 5, 0) >>> singularityintegrate(x*SingularityFunction(x, 0, -1), x) 0 >>> singularityintegrate(SingularityFunction(x, 1, -1) * f(x), x) f(1)*SingularityFunction(x, 1, 0) """ if not f.has(SingularityFunction): return None if isinstance(f, SingularityFunction): x, a, n = f.args if n.is_positive or n.is_zero: return SingularityFunction(x, a, n + 1)/(n + 1) elif n in (-1, -2): return SingularityFunction(x, a, n + 1) if f.is_Mul or f.is_Pow: expr = f.rewrite(DiracDelta) expr = integrate(expr, x) return expr.rewrite(SingularityFunction) return None
e199fddb8fef1f36a0905bcc2ca1dde669fb44d73c84103b5d973723b475c4cf
""" Integral Transforms """ from functools import reduce, wraps from itertools import repeat from sympy.core import S, pi, I from sympy.core.add import Add from sympy.core.function import (AppliedUndef, count_ops, Derivative, expand, expand_complex, expand_mul, Function, Lambda, WildFunction) from sympy.core.mul import Mul from sympy.core.numbers import igcd, ilcm from sympy.core.relational import _canonical, Ge, Gt, Lt, Unequality, Eq from sympy.core.sorting import default_sort_key, ordered from sympy.core.symbol import Dummy, symbols, Wild from sympy.core.traversal import postorder_traversal from sympy.functions.combinatorial.factorials import factorial, rf from sympy.functions.elementary.complexes import (re, arg, Abs, polar_lift, periodic_argument) from sympy.functions.elementary.exponential import exp, log, exp_polar from sympy.functions.elementary.hyperbolic import cosh, coth, sinh, tanh, asinh from sympy.functions.elementary.integers import ceiling from sympy.functions.elementary.miscellaneous import Max, Min, sqrt from sympy.functions.elementary.piecewise import Piecewise, piecewise_fold from sympy.functions.elementary.trigonometric import cos, cot, sin, tan, atan from sympy.functions.special.bessel import besseli, besselj, besselk, bessely from sympy.functions.special.delta_functions import DiracDelta, Heaviside from sympy.functions.special.error_functions import erf, erfc, Ei from sympy.functions.special.gamma_functions import digamma, gamma, lowergamma from sympy.functions.special.hyper import meijerg from sympy.integrals import integrate, Integral from sympy.integrals.meijerint import _dummy from sympy.logic.boolalg import to_cnf, conjuncts, disjuncts, Or, And from sympy.matrices.matrices import MatrixBase from sympy.polys.matrices.linsolve import _lin_eq2dict, PolyNonlinearError from sympy.polys.polyroots import roots from sympy.polys.polytools import factor, Poly from sympy.polys.rationaltools import together from sympy.polys.rootoftools import CRootOf, RootSum from sympy.utilities.exceptions import (sympy_deprecation_warning, SymPyDeprecationWarning, ignore_warnings) from sympy.utilities.iterables import iterable from sympy.utilities.misc import debug ########################################################################## # Helpers / Utilities ########################################################################## class IntegralTransformError(NotImplementedError): """ Exception raised in relation to problems computing transforms. Explanation =========== This class is mostly used internally; if integrals cannot be computed objects representing unevaluated transforms are usually returned. The hint ``needeval=True`` can be used to disable returning transform objects, and instead raise this exception if an integral cannot be computed. """ def __init__(self, transform, function, msg): super().__init__( "%s Transform could not be computed: %s." % (transform, msg)) self.function = function class IntegralTransform(Function): """ Base class for integral transforms. Explanation =========== This class represents unevaluated transforms. To implement a concrete transform, derive from this class and implement the ``_compute_transform(f, x, s, **hints)`` and ``_as_integral(f, x, s)`` functions. If the transform cannot be computed, raise :obj:`IntegralTransformError`. Also set ``cls._name``. For instance, >>> from sympy import LaplaceTransform >>> LaplaceTransform._name 'Laplace' Implement ``self._collapse_extra`` if your function returns more than just a number and possibly a convergence condition. """ @property def function(self): """ The function to be transformed. """ return self.args[0] @property def function_variable(self): """ The dependent variable of the function to be transformed. """ return self.args[1] @property def transform_variable(self): """ The independent transform variable. """ return self.args[2] @property def free_symbols(self): """ This method returns the symbols that will exist when the transform is evaluated. """ return self.function.free_symbols.union({self.transform_variable}) \ - {self.function_variable} def _compute_transform(self, f, x, s, **hints): raise NotImplementedError def _as_integral(self, f, x, s): raise NotImplementedError def _collapse_extra(self, extra): cond = And(*extra) if cond == False: raise IntegralTransformError(self.__class__.name, None, '') return cond def _try_directly(self, **hints): T = None try_directly = not any(func.has(self.function_variable) for func in self.function.atoms(AppliedUndef)) if try_directly: try: T = self._compute_transform(self.function, self.function_variable, self.transform_variable, **hints) except IntegralTransformError: T = None fn = self.function if not fn.is_Add: fn = expand_mul(fn) return fn, T def doit(self, **hints): """ Try to evaluate the transform in closed form. Explanation =========== This general function handles linearity, but apart from that leaves pretty much everything to _compute_transform. Standard hints are the following: - ``simplify``: whether or not to simplify the result - ``noconds``: if True, do not return convergence conditions - ``needeval``: if True, raise IntegralTransformError instead of returning IntegralTransform objects The default values of these hints depend on the concrete transform, usually the default is ``(simplify, noconds, needeval) = (True, False, False)``. """ needeval = hints.pop('needeval', False) simplify = hints.pop('simplify', True) hints['simplify'] = simplify fn, T = self._try_directly(**hints) if T is not None: return T if fn.is_Add: hints['needeval'] = needeval res = [self.__class__(*([x] + list(self.args[1:]))).doit(**hints) for x in fn.args] extra = [] ress = [] for x in res: if not isinstance(x, tuple): x = [x] ress.append(x[0]) if len(x) == 2: # only a condition extra.append(x[1]) elif len(x) > 2: # some region parameters and a condition (Mellin, Laplace) extra += [x[1:]] if simplify==True: res = Add(*ress).simplify() else: res = Add(*ress) if not extra: return res try: extra = self._collapse_extra(extra) if iterable(extra): return tuple([res]) + tuple(extra) else: return (res, extra) except IntegralTransformError: pass if needeval: raise IntegralTransformError( self.__class__._name, self.function, 'needeval') # TODO handle derivatives etc # pull out constant coefficients coeff, rest = fn.as_coeff_mul(self.function_variable) return coeff*self.__class__(*([Mul(*rest)] + list(self.args[1:]))) @property def as_integral(self): return self._as_integral(self.function, self.function_variable, self.transform_variable) def _eval_rewrite_as_Integral(self, *args, **kwargs): return self.as_integral def _simplify(expr, doit): if doit: from sympy.simplify import simplify from sympy.simplify.powsimp import powdenest return simplify(powdenest(piecewise_fold(expr), polar=True)) return expr def _noconds_(default): """ This is a decorator generator for dropping convergence conditions. Explanation =========== Suppose you define a function ``transform(*args)`` which returns a tuple of the form ``(result, cond1, cond2, ...)``. Decorating it ``@_noconds_(default)`` will add a new keyword argument ``noconds`` to it. If ``noconds=True``, the return value will be altered to be only ``result``, whereas if ``noconds=False`` the return value will not be altered. The default value of the ``noconds`` keyword will be ``default`` (i.e. the argument of this function). """ def make_wrapper(func): @wraps(func) def wrapper(*args, noconds=default, **kwargs): res = func(*args, **kwargs) if noconds: return res[0] return res return wrapper return make_wrapper _noconds = _noconds_(False) ########################################################################## # Mellin Transform ########################################################################## def _default_integrator(f, x): return integrate(f, (x, S.Zero, S.Infinity)) @_noconds def _mellin_transform(f, x, s_, integrator=_default_integrator, simplify=True): """ Backend function to compute Mellin transforms. """ # We use a fresh dummy, because assumptions on s might drop conditions on # convergence of the integral. s = _dummy('s', 'mellin-transform', f) F = integrator(x**(s - 1) * f, x) if not F.has(Integral): return _simplify(F.subs(s, s_), simplify), (S.NegativeInfinity, S.Infinity), S.true if not F.is_Piecewise: # XXX can this work if integration gives continuous result now? raise IntegralTransformError('Mellin', f, 'could not compute integral') F, cond = F.args[0] if F.has(Integral): raise IntegralTransformError( 'Mellin', f, 'integral in unexpected form') def process_conds(cond): """ Turn ``cond`` into a strip (a, b), and auxiliary conditions. """ from sympy.solvers.inequalities import _solve_inequality a = S.NegativeInfinity b = S.Infinity aux = S.true conds = conjuncts(to_cnf(cond)) t = Dummy('t', real=True) for c in conds: a_ = S.Infinity b_ = S.NegativeInfinity aux_ = [] for d in disjuncts(c): d_ = d.replace( re, lambda x: x.as_real_imag()[0]).subs(re(s), t) if not d.is_Relational or \ d.rel_op in ('==', '!=') \ or d_.has(s) or not d_.has(t): aux_ += [d] continue soln = _solve_inequality(d_, t) if not soln.is_Relational or \ soln.rel_op in ('==', '!='): aux_ += [d] continue if soln.lts == t: b_ = Max(soln.gts, b_) else: a_ = Min(soln.lts, a_) if a_ is not S.Infinity and a_ != b: a = Max(a_, a) elif b_ is not S.NegativeInfinity and b_ != a: b = Min(b_, b) else: aux = And(aux, Or(*aux_)) return a, b, aux conds = [process_conds(c) for c in disjuncts(cond)] conds = [x for x in conds if x[2] != False] conds.sort(key=lambda x: (x[0] - x[1], count_ops(x[2]))) if not conds: raise IntegralTransformError('Mellin', f, 'no convergence found') a, b, aux = conds[0] return _simplify(F.subs(s, s_), simplify), (a, b), aux class MellinTransform(IntegralTransform): """ Class representing unevaluated Mellin transforms. For usage of this class, see the :class:`IntegralTransform` docstring. For how to compute Mellin transforms, see the :func:`mellin_transform` docstring. """ _name = 'Mellin' def _compute_transform(self, f, x, s, **hints): return _mellin_transform(f, x, s, **hints) def _as_integral(self, f, x, s): return Integral(f*x**(s - 1), (x, S.Zero, S.Infinity)) def _collapse_extra(self, extra): a = [] b = [] cond = [] for (sa, sb), c in extra: a += [sa] b += [sb] cond += [c] res = (Max(*a), Min(*b)), And(*cond) if (res[0][0] >= res[0][1]) == True or res[1] == False: raise IntegralTransformError( 'Mellin', None, 'no combined convergence.') return res def mellin_transform(f, x, s, **hints): r""" Compute the Mellin transform `F(s)` of `f(x)`, .. math :: F(s) = \int_0^\infty x^{s-1} f(x) \mathrm{d}x. For all "sensible" functions, this converges absolutely in a strip `a < \operatorname{Re}(s) < b`. Explanation =========== The Mellin transform is related via change of variables to the Fourier transform, and also to the (bilateral) Laplace transform. This function returns ``(F, (a, b), cond)`` where ``F`` is the Mellin transform of ``f``, ``(a, b)`` is the fundamental strip (as above), and ``cond`` are auxiliary convergence conditions. If the integral cannot be computed in closed form, this function returns an unevaluated :class:`MellinTransform` object. For a description of possible hints, refer to the docstring of :func:`sympy.integrals.transforms.IntegralTransform.doit`. If ``noconds=False``, then only `F` will be returned (i.e. not ``cond``, and also not the strip ``(a, b)``). Examples ======== >>> from sympy import mellin_transform, exp >>> from sympy.abc import x, s >>> mellin_transform(exp(-x), x, s) (gamma(s), (0, oo), True) See Also ======== inverse_mellin_transform, laplace_transform, fourier_transform hankel_transform, inverse_hankel_transform """ return MellinTransform(f, x, s).doit(**hints) def _rewrite_sin(m_n, s, a, b): """ Re-write the sine function ``sin(m*s + n)`` as gamma functions, compatible with the strip (a, b). Return ``(gamma1, gamma2, fac)`` so that ``f == fac/(gamma1 * gamma2)``. Examples ======== >>> from sympy.integrals.transforms import _rewrite_sin >>> from sympy import pi, S >>> from sympy.abc import s >>> _rewrite_sin((pi, 0), s, 0, 1) (gamma(s), gamma(1 - s), pi) >>> _rewrite_sin((pi, 0), s, 1, 0) (gamma(s - 1), gamma(2 - s), -pi) >>> _rewrite_sin((pi, 0), s, -1, 0) (gamma(s + 1), gamma(-s), -pi) >>> _rewrite_sin((pi, pi/2), s, S(1)/2, S(3)/2) (gamma(s - 1/2), gamma(3/2 - s), -pi) >>> _rewrite_sin((pi, pi), s, 0, 1) (gamma(s), gamma(1 - s), -pi) >>> _rewrite_sin((2*pi, 0), s, 0, S(1)/2) (gamma(2*s), gamma(1 - 2*s), pi) >>> _rewrite_sin((2*pi, 0), s, S(1)/2, 1) (gamma(2*s - 1), gamma(2 - 2*s), -pi) """ # (This is a separate function because it is moderately complicated, # and I want to doctest it.) # We want to use pi/sin(pi*x) = gamma(x)*gamma(1-x). # But there is one comlication: the gamma functions determine the # inegration contour in the definition of the G-function. Usually # it would not matter if this is slightly shifted, unless this way # we create an undefined function! # So we try to write this in such a way that the gammas are # eminently on the right side of the strip. m, n = m_n m = expand_mul(m/pi) n = expand_mul(n/pi) r = ceiling(-m*a - n.as_real_imag()[0]) # Don't use re(n), does not expand return gamma(m*s + n + r), gamma(1 - n - r - m*s), (-1)**r*pi class MellinTransformStripError(ValueError): """ Exception raised by _rewrite_gamma. Mainly for internal use. """ pass def _rewrite_gamma(f, s, a, b): """ Try to rewrite the product f(s) as a product of gamma functions, so that the inverse Mellin transform of f can be expressed as a meijer G function. Explanation =========== Return (an, ap), (bm, bq), arg, exp, fac such that G((an, ap), (bm, bq), arg/z**exp)*fac is the inverse Mellin transform of f(s). Raises IntegralTransformError or MellinTransformStripError on failure. It is asserted that f has no poles in the fundamental strip designated by (a, b). One of a and b is allowed to be None. The fundamental strip is important, because it determines the inversion contour. This function can handle exponentials, linear factors, trigonometric functions. This is a helper function for inverse_mellin_transform that will not attempt any transformations on f. Examples ======== >>> from sympy.integrals.transforms import _rewrite_gamma >>> from sympy.abc import s >>> from sympy import oo >>> _rewrite_gamma(s*(s+3)*(s-1), s, -oo, oo) (([], [-3, 0, 1]), ([-2, 1, 2], []), 1, 1, -1) >>> _rewrite_gamma((s-1)**2, s, -oo, oo) (([], [1, 1]), ([2, 2], []), 1, 1, 1) Importance of the fundamental strip: >>> _rewrite_gamma(1/s, s, 0, oo) (([1], []), ([], [0]), 1, 1, 1) >>> _rewrite_gamma(1/s, s, None, oo) (([1], []), ([], [0]), 1, 1, 1) >>> _rewrite_gamma(1/s, s, 0, None) (([1], []), ([], [0]), 1, 1, 1) >>> _rewrite_gamma(1/s, s, -oo, 0) (([], [1]), ([0], []), 1, 1, -1) >>> _rewrite_gamma(1/s, s, None, 0) (([], [1]), ([0], []), 1, 1, -1) >>> _rewrite_gamma(1/s, s, -oo, None) (([], [1]), ([0], []), 1, 1, -1) >>> _rewrite_gamma(2**(-s+3), s, -oo, oo) (([], []), ([], []), 1/2, 1, 8) """ # Our strategy will be as follows: # 1) Guess a constant c such that the inversion integral should be # performed wrt s'=c*s (instead of plain s). Write s for s'. # 2) Process all factors, rewrite them independently as gamma functions in # argument s, or exponentials of s. # 3) Try to transform all gamma functions s.t. they have argument # a+s or a-s. # 4) Check that the resulting G function parameters are valid. # 5) Combine all the exponentials. a_, b_ = S([a, b]) def left(c, is_numer): """ Decide whether pole at c lies to the left of the fundamental strip. """ # heuristically, this is the best chance for us to solve the inequalities c = expand(re(c)) if a_ is None and b_ is S.Infinity: return True if a_ is None: return c < b_ if b_ is None: return c <= a_ if (c >= b_) == True: return False if (c <= a_) == True: return True if is_numer: return None if a_.free_symbols or b_.free_symbols or c.free_symbols: return None # XXX #raise IntegralTransformError('Inverse Mellin', f, # 'Could not determine position of singularity %s' # ' relative to fundamental strip' % c) raise MellinTransformStripError('Pole inside critical strip?') # 1) s_multipliers = [] for g in f.atoms(gamma): if not g.has(s): continue arg = g.args[0] if arg.is_Add: arg = arg.as_independent(s)[1] coeff, _ = arg.as_coeff_mul(s) s_multipliers += [coeff] for g in f.atoms(sin, cos, tan, cot): if not g.has(s): continue arg = g.args[0] if arg.is_Add: arg = arg.as_independent(s)[1] coeff, _ = arg.as_coeff_mul(s) s_multipliers += [coeff/pi] s_multipliers = [Abs(x) if x.is_extended_real else x for x in s_multipliers] common_coefficient = S.One for x in s_multipliers: if not x.is_Rational: common_coefficient = x break s_multipliers = [x/common_coefficient for x in s_multipliers] if not (all(x.is_Rational for x in s_multipliers) and common_coefficient.is_extended_real): raise IntegralTransformError("Gamma", None, "Nonrational multiplier") s_multiplier = common_coefficient/reduce(ilcm, [S(x.q) for x in s_multipliers], S.One) if s_multiplier == common_coefficient: if len(s_multipliers) == 0: s_multiplier = common_coefficient else: s_multiplier = common_coefficient \ *reduce(igcd, [S(x.p) for x in s_multipliers]) f = f.subs(s, s/s_multiplier) fac = S.One/s_multiplier exponent = S.One/s_multiplier if a_ is not None: a_ *= s_multiplier if b_ is not None: b_ *= s_multiplier # 2) numer, denom = f.as_numer_denom() numer = Mul.make_args(numer) denom = Mul.make_args(denom) args = list(zip(numer, repeat(True))) + list(zip(denom, repeat(False))) facs = [] dfacs = [] # *_gammas will contain pairs (a, c) representing Gamma(a*s + c) numer_gammas = [] denom_gammas = [] # exponentials will contain bases for exponentials of s exponentials = [] def exception(fact): return IntegralTransformError("Inverse Mellin", f, "Unrecognised form '%s'." % fact) while args: fact, is_numer = args.pop() if is_numer: ugammas, lgammas = numer_gammas, denom_gammas ufacs = facs else: ugammas, lgammas = denom_gammas, numer_gammas ufacs = dfacs def linear_arg(arg): """ Test if arg is of form a*s+b, raise exception if not. """ if not arg.is_polynomial(s): raise exception(fact) p = Poly(arg, s) if p.degree() != 1: raise exception(fact) return p.all_coeffs() # constants if not fact.has(s): ufacs += [fact] # exponentials elif fact.is_Pow or isinstance(fact, exp): if fact.is_Pow: base = fact.base exp_ = fact.exp else: base = exp_polar(1) exp_ = fact.exp if exp_.is_Integer: cond = is_numer if exp_ < 0: cond = not cond args += [(base, cond)]*Abs(exp_) continue elif not base.has(s): a, b = linear_arg(exp_) if not is_numer: base = 1/base exponentials += [base**a] facs += [base**b] else: raise exception(fact) # linear factors elif fact.is_polynomial(s): p = Poly(fact, s) if p.degree() != 1: # We completely factor the poly. For this we need the roots. # Now roots() only works in some cases (low degree), and CRootOf # only works without parameters. So try both... coeff = p.LT()[1] rs = roots(p, s) if len(rs) != p.degree(): rs = CRootOf.all_roots(p) ufacs += [coeff] args += [(s - c, is_numer) for c in rs] continue a, c = p.all_coeffs() ufacs += [a] c /= -a # Now need to convert s - c if left(c, is_numer): ugammas += [(S.One, -c + 1)] lgammas += [(S.One, -c)] else: ufacs += [-1] ugammas += [(S.NegativeOne, c + 1)] lgammas += [(S.NegativeOne, c)] elif isinstance(fact, gamma): a, b = linear_arg(fact.args[0]) if is_numer: if (a > 0 and (left(-b/a, is_numer) == False)) or \ (a < 0 and (left(-b/a, is_numer) == True)): raise NotImplementedError( 'Gammas partially over the strip.') ugammas += [(a, b)] elif isinstance(fact, sin): # We try to re-write all trigs as gammas. This is not in # general the best strategy, since sometimes this is impossible, # but rewriting as exponentials would work. However trig functions # in inverse mellin transforms usually all come from simplifying # gamma terms, so this should work. a = fact.args[0] if is_numer: # No problem with the poles. gamma1, gamma2, fac_ = gamma(a/pi), gamma(1 - a/pi), pi else: gamma1, gamma2, fac_ = _rewrite_sin(linear_arg(a), s, a_, b_) args += [(gamma1, not is_numer), (gamma2, not is_numer)] ufacs += [fac_] elif isinstance(fact, tan): a = fact.args[0] args += [(sin(a, evaluate=False), is_numer), (sin(pi/2 - a, evaluate=False), not is_numer)] elif isinstance(fact, cos): a = fact.args[0] args += [(sin(pi/2 - a, evaluate=False), is_numer)] elif isinstance(fact, cot): a = fact.args[0] args += [(sin(pi/2 - a, evaluate=False), is_numer), (sin(a, evaluate=False), not is_numer)] else: raise exception(fact) fac *= Mul(*facs)/Mul(*dfacs) # 3) an, ap, bm, bq = [], [], [], [] for gammas, plus, minus, is_numer in [(numer_gammas, an, bm, True), (denom_gammas, bq, ap, False)]: while gammas: a, c = gammas.pop() if a != -1 and a != +1: # We use the gamma function multiplication theorem. p = Abs(S(a)) newa = a/p newc = c/p if not a.is_Integer: raise TypeError("a is not an integer") for k in range(p): gammas += [(newa, newc + k/p)] if is_numer: fac *= (2*pi)**((1 - p)/2) * p**(c - S.Half) exponentials += [p**a] else: fac /= (2*pi)**((1 - p)/2) * p**(c - S.Half) exponentials += [p**(-a)] continue if a == +1: plus.append(1 - c) else: minus.append(c) # 4) # TODO # 5) arg = Mul(*exponentials) # for testability, sort the arguments an.sort(key=default_sort_key) ap.sort(key=default_sort_key) bm.sort(key=default_sort_key) bq.sort(key=default_sort_key) return (an, ap), (bm, bq), arg, exponent, fac @_noconds_(True) def _inverse_mellin_transform(F, s, x_, strip, as_meijerg=False): """ A helper for the real inverse_mellin_transform function, this one here assumes x to be real and positive. """ x = _dummy('t', 'inverse-mellin-transform', F, positive=True) # Actually, we won't try integration at all. Instead we use the definition # of the Meijer G function as a fairly general inverse mellin transform. F = F.rewrite(gamma) for g in [factor(F), expand_mul(F), expand(F)]: if g.is_Add: # do all terms separately ress = [_inverse_mellin_transform(G, s, x, strip, as_meijerg, noconds=False) for G in g.args] conds = [p[1] for p in ress] ress = [p[0] for p in ress] res = Add(*ress) if not as_meijerg: res = factor(res, gens=res.atoms(Heaviside)) return res.subs(x, x_), And(*conds) try: a, b, C, e, fac = _rewrite_gamma(g, s, strip[0], strip[1]) except IntegralTransformError: continue try: G = meijerg(a, b, C/x**e) except ValueError: continue if as_meijerg: h = G else: try: from sympy.simplify import hyperexpand h = hyperexpand(G) except NotImplementedError: raise IntegralTransformError( 'Inverse Mellin', F, 'Could not calculate integral') if h.is_Piecewise and len(h.args) == 3: # XXX we break modularity here! h = Heaviside(x - Abs(C))*h.args[0].args[0] \ + Heaviside(Abs(C) - x)*h.args[1].args[0] # We must ensure that the integral along the line we want converges, # and return that value. # See [L], 5.2 cond = [Abs(arg(G.argument)) < G.delta*pi] # Note: we allow ">=" here, this corresponds to convergence if we let # limits go to oo symmetrically. ">" corresponds to absolute convergence. cond += [And(Or(len(G.ap) != len(G.bq), 0 >= re(G.nu) + 1), Abs(arg(G.argument)) == G.delta*pi)] cond = Or(*cond) if cond == False: raise IntegralTransformError( 'Inverse Mellin', F, 'does not converge') return (h*fac).subs(x, x_), cond raise IntegralTransformError('Inverse Mellin', F, '') _allowed = None class InverseMellinTransform(IntegralTransform): """ Class representing unevaluated inverse Mellin transforms. For usage of this class, see the :class:`IntegralTransform` docstring. For how to compute inverse Mellin transforms, see the :func:`inverse_mellin_transform` docstring. """ _name = 'Inverse Mellin' _none_sentinel = Dummy('None') _c = Dummy('c') def __new__(cls, F, s, x, a, b, **opts): if a is None: a = InverseMellinTransform._none_sentinel if b is None: b = InverseMellinTransform._none_sentinel return IntegralTransform.__new__(cls, F, s, x, a, b, **opts) @property def fundamental_strip(self): a, b = self.args[3], self.args[4] if a is InverseMellinTransform._none_sentinel: a = None if b is InverseMellinTransform._none_sentinel: b = None return a, b def _compute_transform(self, F, s, x, **hints): # IntegralTransform's doit will cause this hint to exist, but # InverseMellinTransform should ignore it hints.pop('simplify', True) global _allowed if _allowed is None: _allowed = { exp, gamma, sin, cos, tan, cot, cosh, sinh, tanh, coth, factorial, rf} for f in postorder_traversal(F): if f.is_Function and f.has(s) and f.func not in _allowed: raise IntegralTransformError('Inverse Mellin', F, 'Component %s not recognised.' % f) strip = self.fundamental_strip return _inverse_mellin_transform(F, s, x, strip, **hints) def _as_integral(self, F, s, x): c = self.__class__._c return Integral(F*x**(-s), (s, c - S.ImaginaryUnit*S.Infinity, c + S.ImaginaryUnit*S.Infinity))/(2*S.Pi*S.ImaginaryUnit) def inverse_mellin_transform(F, s, x, strip, **hints): r""" Compute the inverse Mellin transform of `F(s)` over the fundamental strip given by ``strip=(a, b)``. Explanation =========== This can be defined as .. math:: f(x) = \frac{1}{2\pi i} \int_{c - i\infty}^{c + i\infty} x^{-s} F(s) \mathrm{d}s, for any `c` in the fundamental strip. Under certain regularity conditions on `F` and/or `f`, this recovers `f` from its Mellin transform `F` (and vice versa), for positive real `x`. One of `a` or `b` may be passed as ``None``; a suitable `c` will be inferred. If the integral cannot be computed in closed form, this function returns an unevaluated :class:`InverseMellinTransform` object. Note that this function will assume x to be positive and real, regardless of the SymPy assumptions! For a description of possible hints, refer to the docstring of :func:`sympy.integrals.transforms.IntegralTransform.doit`. Examples ======== >>> from sympy import inverse_mellin_transform, oo, gamma >>> from sympy.abc import x, s >>> inverse_mellin_transform(gamma(s), s, x, (0, oo)) exp(-x) The fundamental strip matters: >>> f = 1/(s**2 - 1) >>> inverse_mellin_transform(f, s, x, (-oo, -1)) x*(1 - 1/x**2)*Heaviside(x - 1)/2 >>> inverse_mellin_transform(f, s, x, (-1, 1)) -x*Heaviside(1 - x)/2 - Heaviside(x - 1)/(2*x) >>> inverse_mellin_transform(f, s, x, (1, oo)) (1/2 - x**2/2)*Heaviside(1 - x)/x See Also ======== mellin_transform hankel_transform, inverse_hankel_transform """ return InverseMellinTransform(F, s, x, strip[0], strip[1]).doit(**hints) ########################################################################## # Laplace Transform ########################################################################## def _simplifyconds(expr, s, a): r""" Naively simplify some conditions occurring in ``expr``, given that `\operatorname{Re}(s) > a`. Examples ======== >>> from sympy.integrals.transforms import _simplifyconds as simp >>> from sympy.abc import x >>> from sympy import sympify as S >>> simp(abs(x**2) < 1, x, 1) False >>> simp(abs(x**2) < 1, x, 2) False >>> simp(abs(x**2) < 1, x, 0) Abs(x**2) < 1 >>> simp(abs(1/x**2) < 1, x, 1) True >>> simp(S(1) < abs(x), x, 1) True >>> simp(S(1) < abs(1/x), x, 1) False >>> from sympy import Ne >>> simp(Ne(1, x**3), x, 1) True >>> simp(Ne(1, x**3), x, 2) True >>> simp(Ne(1, x**3), x, 0) Ne(1, x**3) """ def power(ex): if ex == s: return 1 if ex.is_Pow and ex.base == s: return ex.exp return None def bigger(ex1, ex2): """ Return True only if |ex1| > |ex2|, False only if |ex1| < |ex2|. Else return None. """ if ex1.has(s) and ex2.has(s): return None if isinstance(ex1, Abs): ex1 = ex1.args[0] if isinstance(ex2, Abs): ex2 = ex2.args[0] if ex1.has(s): return bigger(1/ex2, 1/ex1) n = power(ex2) if n is None: return None try: if n > 0 and (Abs(ex1) <= Abs(a)**n) == True: return False if n < 0 and (Abs(ex1) >= Abs(a)**n) == True: return True except TypeError: pass def replie(x, y): """ simplify x < y """ if not (x.is_positive or isinstance(x, Abs)) \ or not (y.is_positive or isinstance(y, Abs)): return (x < y) r = bigger(x, y) if r is not None: return not r return (x < y) def replue(x, y): b = bigger(x, y) if b in (True, False): return True return Unequality(x, y) def repl(ex, *args): if ex in (True, False): return bool(ex) return ex.replace(*args) from sympy.simplify.radsimp import collect_abs expr = collect_abs(expr) expr = repl(expr, Lt, replie) expr = repl(expr, Gt, lambda x, y: replie(y, x)) expr = repl(expr, Unequality, replue) return S(expr) def expand_dirac_delta(expr): """ Expand an expression involving DiractDelta to get it as a linear combination of DiracDelta functions. """ return _lin_eq2dict(expr, expr.atoms(DiracDelta)) @_noconds def _laplace_transform(f, t, s_, simplify=True): """ The backend function for Laplace transforms. This backend assumes that the frontend has already split sums such that `f` is to an addition anymore. """ s = Dummy('s') a = Wild('a', exclude=[t]) deltazero = [] deltanonzero = [] try: integratable, deltadict = expand_dirac_delta(f) except PolyNonlinearError: raise IntegralTransformError( 'Laplace', f, 'could not expand DiracDelta expressions') for dirac_func, dirac_coeff in deltadict.items(): p = dirac_func.match(DiracDelta(a*t)) if p: deltazero.append(dirac_coeff.subs(t,0)/p[a]) else: if dirac_func.args[0].subs(t,0).is_zero: raise IntegralTransformError('Laplace', f,\ 'not implemented yet.') else: deltanonzero.append(dirac_func*dirac_coeff) F = Add(integrate(exp(-s*t) * Add(integratable, *deltanonzero), (t, S.Zero, S.Infinity)), Add(*deltazero)) if not F.has(Integral): return _simplify(F.subs(s, s_), simplify), S.NegativeInfinity, S.true if not F.is_Piecewise: raise IntegralTransformError( 'Laplace', f, 'could not compute integral') F, cond = F.args[0] if F.has(Integral): raise IntegralTransformError( 'Laplace', f, 'integral in unexpected form') def process_conds(conds): """ Turn ``conds`` into a strip and auxiliary conditions. """ from sympy.solvers.inequalities import _solve_inequality a = S.NegativeInfinity aux = S.true conds = conjuncts(to_cnf(conds)) p, q, w1, w2, w3, w4, w5 = symbols( 'p q w1 w2 w3 w4 w5', cls=Wild, exclude=[s]) patterns = ( p*Abs(arg((s + w3)*q)) < w2, p*Abs(arg((s + w3)*q)) <= w2, Abs(periodic_argument((s + w3)**p*q, w1)) < w2, Abs(periodic_argument((s + w3)**p*q, w1)) <= w2, Abs(periodic_argument((polar_lift(s + w3))**p*q, w1)) < w2, Abs(periodic_argument((polar_lift(s + w3))**p*q, w1)) <= w2) for c in conds: a_ = S.Infinity aux_ = [] for d in disjuncts(c): if d.is_Relational and s in d.rhs.free_symbols: d = d.reversed if d.is_Relational and isinstance(d, (Ge, Gt)): d = d.reversedsign for pat in patterns: m = d.match(pat) if m: break if m: if m[q].is_positive and m[w2]/m[p] == pi/2: d = -re(s + m[w3]) < 0 m = d.match(p - cos(w1*Abs(arg(s*w5))*w2)*Abs(s**w3)**w4 < 0) if not m: m = d.match( cos(p - Abs(periodic_argument(s**w1*w5, q))*w2)*Abs(s**w3)**w4 < 0) if not m: m = d.match( p - cos(Abs(periodic_argument(polar_lift(s)**w1*w5, q))*w2 )*Abs(s**w3)**w4 < 0) if m and all(m[wild].is_positive for wild in [w1, w2, w3, w4, w5]): d = re(s) > m[p] d_ = d.replace( re, lambda x: x.expand().as_real_imag()[0]).subs(re(s), t) if not d.is_Relational or \ d.rel_op in ('==', '!=') \ or d_.has(s) or not d_.has(t): aux_ += [d] continue soln = _solve_inequality(d_, t) if not soln.is_Relational or \ soln.rel_op in ('==', '!='): aux_ += [d] continue if soln.lts == t: raise IntegralTransformError('Laplace', f, 'convergence not in half-plane?') else: a_ = Min(soln.lts, a_) if a_ is not S.Infinity: a = Max(a_, a) else: aux = And(aux, Or(*aux_)) return a, aux.canonical if aux.is_Relational else aux conds = [process_conds(c) for c in disjuncts(cond)] conds2 = [x for x in conds if x[1] != False and x[0] is not S.NegativeInfinity] if not conds2: conds2 = [x for x in conds if x[1] != False] conds = list(ordered(conds2)) def cnt(expr): if expr in (True, False): return 0 return expr.count_ops() conds.sort(key=lambda x: (-x[0], cnt(x[1]))) if not conds: raise IntegralTransformError('Laplace', f, 'no convergence found') a, aux = conds[0] # XXX is [0] always the right one? def sbs(expr): return expr.subs(s, s_) if simplify: F = _simplifyconds(F, s, a) aux = _simplifyconds(aux, s, a) return _simplify(F.subs(s, s_), simplify), sbs(a), _canonical(sbs(aux)) def _laplace_deep_collect(f, t): """ This is an internal helper function that traverses through the epression tree of `f(t)` and collects arguments. The purpose of it is that anything like `f(w*t-1*t-c)` will be written as `f((w-1)*t-c)` such that it can match `f(a*t+b)`. """ func = f.func args = list(f.args) if len(f.args) == 0: return f else: args = [_laplace_deep_collect(arg, t) for arg in args] if func.is_Add: return func(*args).collect(t) else: return func(*args) def _laplace_build_rules(t, s): """ This is an internal helper function that returns the table of Laplace transfrom rules in terms of the time variable `t` and the frequency variable `s`. It is used by `_laplace_apply_rules`. """ a = Wild('a', exclude=[t]) b = Wild('b', exclude=[t]) n = Wild('n', exclude=[t]) tau = Wild('tau', exclude=[t]) omega = Wild('omega', exclude=[t]) dco = lambda f: _laplace_deep_collect(f,t) laplace_transform_rules = [ # ( time domain, # laplace domain, # condition, convergence plane, preparation function ) # # Catch constant (would otherwise be treated by 2.12) (a, a/s, S.true, S.Zero, dco), # DiracDelta rules (DiracDelta(a*t-b), exp(-s*b/a)/Abs(a), Or(And(a>0, b>=0), And(a<0, b<=0)), S.Zero, dco), (DiracDelta(a*t-b), S(0), Or(And(a<0, b>=0), And(a>0, b<=0)), S.Zero, dco), # Rules from http://eqworld.ipmnet.ru/en/auxiliary/inttrans/ # 2.1 (1, 1/s, S.true, S.Zero, dco), # 2.2 expressed in terms of Heaviside (Heaviside(a*t-b), exp(-s*b/a)/s, And(a>0, b>0), S.Zero, dco), (Heaviside(a*t-b), (1-exp(-s*b/a))/s, And(a<0, b<0), S.Zero, dco), (Heaviside(a*t-b), 1/s, And(a>0, b<=0), S.Zero, dco), (Heaviside(a*t-b), 0, And(a<0, b>0), S.Zero, dco), # 2.3 (t, 1/s**2, S.true, S.Zero, dco), # 2.4 (1/(a*t+b), -exp(-b/a*s)*Ei(-b/a*s)/a, a>0, S.Zero, dco), # 2.5 and 2.6 are covered by 2.11 # 2.7 (1/sqrt(a*t+b), sqrt(a*pi/s)*exp(b/a*s)*erfc(sqrt(b/a*s))/a, a>0, S.Zero, dco), # 2.8 (sqrt(t)/(t+b), sqrt(pi/s)-pi*sqrt(b)*exp(b*s)*erfc(sqrt(b*s)), S.true, S.Zero, dco), # 2.9 ((a*t+b)**(-S(3)/2), 2*b**(-S(1)/2)-2*(pi*s/a)**(S(1)/2)*exp(b/a*s)*erfc(sqrt(b/a*s))/a, a>0, S.Zero, dco), # 2.10 (t**(S(1)/2)*(t+a)**(-1), (pi/s)**(S(1)/2)-pi*a**(S(1)/2)*exp(a*s)*erfc(sqrt(a*s)), S.true, S.Zero, dco), # 2.11 (1/(a*sqrt(t) + t**(3/2)), pi*a**(S(1)/2)*exp(a*s)*erfc(sqrt(a*s)), S.true, S.Zero, dco), # 2.12 (t**n, gamma(n+1)/s**(n+1), n>-1, S.Zero, dco), # 2.13 ((a*t+b)**n, lowergamma(n+1, b/a*s)*exp(-b/a*s)/s**(n+1)/a, And(n>-1, a>0), S.Zero, dco), # 2.14 (t**n/(t+a), a**n*gamma(n+1)*lowergamma(-n,a*s), n>-1, S.Zero, dco), # 3.1 (exp(a*t-tau), exp(-tau)/(s-a), S.true, a, dco), # 3.2 (t*exp(a*t-tau), exp(-tau)/(s-a)**2, S.true, a, dco), # 3.3 (t**n*exp(a*t), gamma(n+1)/(s-a)**(n+1), n>-1, a, dco), # 3.4 and 3.5 cannot be covered here because they are # sums and only the individual sum terms will get here. # 3.6 (exp(-a*t**2), sqrt(pi/4/a)*exp(s**2/4/a)*erfc(s/sqrt(4*a)), a>0, S.Zero, dco), # 3.7 (t*exp(-a*t**2), 1/(2*a)-2/sqrt(pi)/(4*a)**(S(3)/2)*s*erfc(s/sqrt(4*a)), S.true, S.Zero, dco), # 3.8 (exp(-a/t), 2*sqrt(a/s)*besselk(1, 2*sqrt(a*s)), a>=0, S.Zero, dco), # 3.9 (sqrt(t)*exp(-a/t), S(1)/2*sqrt(pi/s**3)*(1+2*sqrt(a*s))*exp(-2*sqrt(a*s)), a>=0, S.Zero, dco), # 3.10 (exp(-a/t)/sqrt(t), sqrt(pi/s)*exp(-2*sqrt(a*s)), a>=0, S.Zero, dco), # 3.11 (exp(-a/t)/(t*sqrt(t)), sqrt(pi/a)*exp(-2*sqrt(a*s)), a>0, S.Zero, dco), # 3.12 (t**n*exp(-a/t), 2*(a/s)**((n+1)/2)*besselk(n+1, 2*sqrt(a*s)), a>0, S.Zero, dco), # 3.13 (exp(-2*sqrt(a*t)), s**(-1)-sqrt(pi*a)*s**(-S(3)/2)*exp(a/s)*erfc(sqrt(a/s)), S.true, S.Zero, dco), # 3.14 (exp(-2*sqrt(a*t))/sqrt(t), (pi/s)**(S(1)/2)*exp(a/s)*erfc(sqrt(a/s)), S.true, S.Zero, dco), # 4.1 (sinh(a*t), a/(s**2-a**2), S.true, Abs(a), dco), # 4.2 (sinh(a*t)**2, 2*a**2/(s**3-4*a**2*s**2), S.true, Abs(2*a), dco), # 4.3 (sinh(a*t)/t, log((s+a)/(s-a))/2, S.true, a, dco), # 4.4 (t**n*sinh(a*t), gamma(n+1)/2*((s-a)**(-n-1)-(s+a)**(-n-1)), n>-2, Abs(a), dco), # 4.5 (sinh(2*sqrt(a*t)), sqrt(pi*a)/s/sqrt(s)*exp(a/s), S.true, S.Zero, dco), # 4.6 (sqrt(t)*sinh(2*sqrt(a*t)), pi**(S(1)/2)*s**(-S(5)/2)*(s/2+a)*exp(a/s)*erf(sqrt(a/s))-a**(S(1)/2)*s**(-2), S.true, S.Zero, dco), # 4.7 (sinh(2*sqrt(a*t))/sqrt(t), pi**(S(1)/2)*s**(-S(1)/2)*exp(a/s)*erf(sqrt(a/s)), S.true, S.Zero, dco), # 4.8 (sinh(sqrt(a*t))**2/sqrt(t), pi**(S(1)/2)/2*s**(-S(1)/2)*(exp(a/s)-1), S.true, S.Zero, dco), # 4.9 (cosh(a*t), s/(s**2-a**2), S.true, Abs(a), dco), # 4.10 (cosh(a*t)**2, (s**2-2*a**2)/(s**3-4*a**2*s**2), S.true, Abs(2*a), dco), # 4.11 (t**n*cosh(a*t), gamma(n+1)/2*((s-a)**(-n-1)+(s+a)**(-n-1)), n>-1, Abs(a), dco), # 4.12 (cosh(2*sqrt(a*t)), 1/s+sqrt(pi*a)/s/sqrt(s)*exp(a/s)*erf(sqrt(a/s)), S.true, S.Zero, dco), # 4.13 (sqrt(t)*cosh(2*sqrt(a*t)), pi**(S(1)/2)*s**(-S(5)/2)*(s/2+a)*exp(a/s), S.true, S.Zero, dco), # 4.14 (cosh(2*sqrt(a*t))/sqrt(t), pi**(S(1)/2)*s**(-S(1)/2)*exp(a/s), S.true, S.Zero, dco), # 4.15 (cosh(sqrt(a*t))**2/sqrt(t), pi**(S(1)/2)/2*s**(-S(1)/2)*(exp(a/s)+1), S.true, S.Zero, dco), # 5.1 (log(a*t), -log(s/a+S.EulerGamma)/s, a>0, S.Zero, dco), # 5.2 (log(1+a*t), -exp(s/a)/s*Ei(-s/a), S.true, S.Zero, dco), # 5.3 (log(a*t+b), (log(b)-exp(s/b/a)/s*a*Ei(-s/b))/s*a, a>0, S.Zero, dco), # 5.4 is covered by 5.7 # 5.5 (log(t)/sqrt(t), -sqrt(pi/s)*(log(4*s)+S.EulerGamma), S.true, S.Zero, dco), # 5.6 is covered by 5.7 # 5.7 (t**n*log(t), gamma(n+1)*s**(-n-1)*(digamma(n+1)-log(s)), n>-1, S.Zero, dco), # 5.8 (log(a*t)**2, ((log(s/a)+S.EulerGamma)**2+pi**2/6)/s, a>0, S.Zero, dco), # 5.9 (exp(-a*t)*log(t), -(log(s+a)+S.EulerGamma)/(s+a), S.true, -a, dco), # 6.1 (sin(omega*t), omega/(s**2+omega**2), S.true, S.Zero, dco), # 6.2 (Abs(sin(omega*t)), omega/(s**2+omega**2)*coth(pi*s/2/omega), omega>0, S.Zero, dco), # 6.3 and 6.4 are covered by 1.8 # 6.5 is covered by 1.8 together with 2.5 # 6.6 (sin(omega*t)/t, atan(omega/s), S.true, S.Zero, dco), # 6.7 (sin(omega*t)**2/t, log(1+4*omega**2/s**2)/4, S.true, S.Zero, dco), # 6.8 (sin(omega*t)**2/t**2, omega*atan(2*omega/s)-s*log(1+4*omega**2/s**2)/4, S.true, S.Zero, dco), # 6.9 (sin(2*sqrt(a*t)), sqrt(pi*a)/s/sqrt(s)*exp(-a/s), a>0, S.Zero, dco), # 6.10 (sin(2*sqrt(a*t))/t, pi*erf(sqrt(a/s)), a>0, S.Zero, dco), # 6.11 (cos(omega*t), s/(s**2+omega**2), S.true, S.Zero, dco), # 6.12 (cos(omega*t)**2, (s**2+2*omega**2)/(s**2+4*omega**2)/s, S.true, S.Zero, dco), # 6.13 is covered by 1.9 together with 2.5 # 6.14 and 6.15 cannot be done with this method, the respective sum # parts do not converge. Solve elsewhere if really needed. # 6.16 (sqrt(t)*cos(2*sqrt(a*t)), sqrt(pi)/2*s**(-S(5)/2)*(s-2*a)*exp(-a/s), a>0, S.Zero, dco), # 6.17 (cos(2*sqrt(a*t))/sqrt(t), sqrt(pi/s)*exp(-a/s), a>0, S.Zero, dco), # 6.18 (sin(a*t)*sin(b*t), 2*a*b*s/(s**2+(a+b)**2)/(s**2+(a-b)**2), S.true, S.Zero, dco), # 6.19 (cos(a*t)*sin(b*t), b*(s**2-a**2+b**2)/(s**2+(a+b)**2)/(s**2+(a-b)**2), S.true, S.Zero, dco), # 6.20 (cos(a*t)*cos(b*t), s*(s**2+a**2+b**2)/(s**2+(a+b)**2)/(s**2+(a-b)**2), S.true, S.Zero, dco), # 6.21 (exp(b*t)*sin(a*t), a/((s-b)**2+a**2), S.true, b, dco), # 6.22 (exp(b*t)*cos(a*t), (s-b)/((s-b)**2+a**2), S.true, b, dco), # 7.1 (erf(a*t), exp(s**2/(2*a)**2)*erfc(s/(2*a))/s, a>0, S.Zero, dco), # 7.2 (erf(sqrt(a*t)), sqrt(a)/sqrt(s+a)/s, a>0, S.Zero, dco), # 7.3 (exp(a*t)*erf(sqrt(a*t)), sqrt(a)/sqrt(s)/(s-a), a>0, a, dco), # 7.4 (erf(sqrt(a/t)/2), (1-exp(-sqrt(a*s)))/s, a>0, S.Zero, dco), # 7.5 (erfc(sqrt(a*t)), (sqrt(s+a)-sqrt(a))/sqrt(s+a)/s, a>0, S.Zero, dco), # 7.6 (exp(a*t)*erfc(sqrt(a*t)), 1/(s+sqrt(a*s)), a>0, S.Zero, dco), # 7.7 (erfc(sqrt(a/t)/2), exp(-sqrt(a*s))/s, a>0, S.Zero, dco), # 8.1, 8.2 (besselj(n, a*t), a**n/(sqrt(s**2+a**2)*(s+sqrt(s**2+a**2))**n), And(a>0, n>-1), S.Zero, dco), # 8.3, 8.4 (t**b*besselj(n, a*t), 2**n/sqrt(pi)*gamma(n+S.Half)*a**n*(s**2+a**2)**(-n-S.Half), And(And(a>0, n>-S.Half), Eq(b, n)), S.Zero, dco), # 8.5 (t**b*besselj(n, a*t), 2**(n+1)/sqrt(pi)*gamma(n+S(3)/2)*a**n*s*(s**2+a**2)**(-n-S(3)/2), And(And(a>0, n>-1), Eq(b, n+1)), S.Zero, dco), # 8.6 (besselj(0, 2*sqrt(a*t)), exp(-a/s)/s, a>0, S.Zero, dco), # 8.7, 8.8 (t**(b)*besselj(n, 2*sqrt(a*t)), a**(n/2)*s**(-n-1)*exp(-a/s), And(And(a>0, n>-1), Eq(b, n*S.Half)), S.Zero, dco), # 8.9 (besselj(0, a*sqrt(t**2+b*t)), exp(b*s-b*sqrt(s**2+a**2))/sqrt(s**2+a**2), b>0, S.Zero, dco), # 8.10, 8.11 (besseli(n, a*t), a**n/(sqrt(s**2-a**2)*(s+sqrt(s**2-a**2))**n), And(a>0, n>-1), Abs(a), dco), # 8.12 (t**b*besseli(n, a*t), 2**n/sqrt(pi)*gamma(n+S.Half)*a**n*(s**2-a**2)**(-n-S.Half), And(And(a>0, n>-S.Half), Eq(b, n)), Abs(a), dco), # 8.13 (t**b*besseli(n, a*t), 2**(n+1)/sqrt(pi)*gamma(n+S(3)/2)*a**n*s*(s**2-a**2)**(-n-S(3)/2), And(And(a>0, n>-1), Eq(b, n+1)), Abs(a), dco), # 8.15, 8.16 (t**(b)*besseli(n, 2*sqrt(a*t)), a**(n/2)*s**(-n-1)*exp(a/s), And(And(a>0, n>-1), Eq(b, n*S.Half)), S.Zero, dco), # 8.17 (bessely(0, a*t), -2/pi*asinh(s/a)/sqrt(s**2+a**2), a>0, S.Zero, dco), # 8.18 (besselk(0, a*t), (log(s+sqrt(s**2-a**2)))/(sqrt(s**2-a**2)), a>0, Abs(a), dco) ] return laplace_transform_rules def _laplace_cr(f, a, c, **hints): """ Internal helper function that will return `(f, a, c)` unless `**hints` contains `noconds=True`, in which case it will only return `f`. """ conds = not hints.get('noconds', False) if conds: return f, a, c else: return f def _laplace_rule_timescale(f, t, s, doit=True, **hints): r""" This internal helper function tries to apply the time-scaling rule of the Laplace transform and returns `None` if it cannot do it. Time-scaling means the following: if $F(s)$ is the Laplace transform of, $f(t)$, then, for any $a>0$, the Laplace transform of $f(at)$ will be $\frac1a F(\frac{s}{a})$. This scaling will also affect the transform's convergence plane. """ _simplify = hints.pop('simplify', True) b = Wild('b', exclude=[t]) g = WildFunction('g', nargs=1) k, func = f.as_independent(t, as_Add=False) ma1 = func.match(g) if ma1: arg = ma1[g].args[0].collect(t) ma2 = arg.match(b*t) if ma2 and ma2[b]>0: debug('_laplace_apply_rules match:') debug(' f: %s ( %s, %s )'%(f, ma1, ma2)) debug(' rule: amplitude and time scaling (1.1, 1.2)') if ma2[b]==1: if doit==True and not any(func.has(t) for func in ma1[g].atoms(AppliedUndef)): return k*_laplace_transform(ma1[g].func(t), t, s, simplify=_simplify) else: return k*LaplaceTransform(ma1[g].func(t), t, s, **hints) else: L = _laplace_apply_rules(ma1[g].func(t), t, s/ma2[b], doit=doit, **hints) try: r, p, c = L return (k/ma2[b]*r, p, c) except TypeError: return k/ma2[b]*L return None def _laplace_rule_heaviside(f, t, s, doit=True, **hints): """ This internal helper function tries to transform a product containing the `Heaviside` function and returns `None` if it cannot do it. """ hints.pop('simplify', True) a = Wild('a', exclude=[t]) b = Wild('b', exclude=[t]) y = Wild('y') g = WildFunction('g', nargs=1) k, func = f.as_independent(t, as_Add=False) ma1 = func.match(Heaviside(y)*g) if ma1: ma2 = ma1[y].match(t-a) ma3 = ma1[g].args[0].collect(t).match(t-b) if ma2 and ma2[a]>0 and ma3 and ma2[a]==ma3[b]: debug('_laplace_apply_rules match:') debug(' f: %s ( %s, %s, %s )'%(f, ma1, ma2, ma3)) debug(' rule: time shift (1.3)') L = _laplace_apply_rules(ma1[g].func(t), t, s, doit=doit, **hints) try: r, p, c = L return (k*exp(-ma2[a]*s)*r, p, c) except TypeError: return k*exp(-ma2[a]*s)*L return None def _laplace_rule_exp(f, t, s, doit=True, **hints): """ This internal helper function tries to transform a product containing the `exp` function and returns `None` if it cannot do it. """ hints.pop('simplify', True) a = Wild('a', exclude=[t]) y = Wild('y') z = Wild('z') k, func = f.as_independent(t, as_Add=False) ma1 = func.match(exp(y)*z) if ma1: ma2 = ma1[y].collect(t).match(a*t) if ma2: debug('_laplace_apply_rules match:') debug(' f: %s ( %s, %s )'%(f, ma1, ma2)) debug(' rule: multiply with exp (1.5)') L = _laplace_apply_rules(ma1[z], t, s-ma2[a], doit=doit, **hints) try: r, p, c = L return (r, p+ma2[a], c) except TypeError: return L return None def _laplace_rule_trig(f, t, s, doit=True, **hints): """ This internal helper function tries to transform a product containing a trigonometric function (`sin`, `cos`, `sinh`, `cosh`, ) and returns `None` if it cannot do it. """ _simplify = hints.pop('simplify', True) a = Wild('a', exclude=[t]) y = Wild('y') z = Wild('z') k, func = f.as_independent(t, as_Add=False) # All of the rules have a very similar form: trig(y)*z is matched, and then # two copies of the Laplace transform of z are shifted in the s Domain # and added with a weight; see rules 1.6 to 1.9 in # http://eqworld.ipmnet.ru/en/auxiliary/inttrans/laplace1.pdf # The parameters in the tuples are (fm, nu, s1, s2, sd): # fm: Function to match # nu: Number of the rule, for debug purposes # s1: weight of the sum, 'I' for sin and '1' for all others # s2: sign of the second copy of the Laplace transform of z # sd: shift direction; shift along real or imaginary axis if `1` or `I` trigrules = [(sinh(y), '1.6', 1, -1, 1), (cosh(y), '1.7', 1, 1, 1), (sin(y), '1.8', -I, -1, I), (cos(y), '1.9', 1, 1, I)] for trigrule in trigrules: fm, nu, s1, s2, sd = trigrule ma1 = func.match(fm*z) if ma1: ma2 = ma1[y].collect(t).match(a*t) if ma2: debug('_laplace_apply_rules match:') debug(' f: %s ( %s, %s )'%(f, ma1, ma2)) debug(' rule: multiply with %s (%s)'%(fm.func, nu)) L = _laplace_apply_rules(ma1[z], t, s, doit=doit, **hints) try: r, p, c = L # The convergence plane changes only if the shift has been # done along the real axis: if sd==1: cp_shift = Abs(ma2[a]) else: cp_shift = 0 return ((s1*(r.subs(s, s-sd*ma2[a])+\ s2*r.subs(s, s+sd*ma2[a]))).simplify()/2, p+cp_shift, c) except TypeError: if doit==True and _simplify==True: return (s1*(L.subs(s, s-sd*ma2[a])+\ s2*L.subs(s, s+sd*ma2[a]))).simplify()/2 else: return (s1*(L.subs(s, s-sd*ma2[a])+\ s2*L.subs(s, s+sd*ma2[a])))/2 return None def _laplace_rule_diff(f, t, s, doit=True, **hints): """ This internal helper function tries to transform an expression containing a derivative of an undefined function and returns `None` if it cannot do it. """ hints.pop('simplify', True) a = Wild('a', exclude=[t]) y = Wild('y') n = Wild('n', exclude=[t]) g = WildFunction('g', nargs=1) ma1 = f.match(a*Derivative(g, (t, n))) if ma1 and ma1[g].args[0] == t and ma1[n].is_integer: debug('_laplace_apply_rules match:') debug(' f: %s'%(f,)) debug(' rule: time derivative (1.11, 1.12)') d = [] for k in range(ma1[n]): if k==0: y = ma1[g].func(t).subs(t, 0) else: y = Derivative(ma1[g].func(t), (t, k)).subs(t, 0) d.append(s**(ma1[n]-k-1)*y) r = s**ma1[n]*_laplace_apply_rules(ma1[g].func(t), t, s, doit=doit, **hints) return ma1[a]*(r - Add(*d)) return None def _laplace_apply_rules(f, t, s, doit=True, **hints): """ Helper function for the class LaplaceTransform. This function does a Laplace transform based on rules and, after applying the rules, hands the rest over to `_laplace_transform`, which will attempt to integrate. If it is called with `doit=False`, then it will instead return `LaplaceTransform` objects. """ k, func = f.as_independent(t, as_Add=False) simple_rules = _laplace_build_rules(t, s) for t_dom, s_dom, check, plane, prep in simple_rules: ma = prep(func).match(t_dom) if ma: debug('_laplace_apply_rules match:') debug(' f: %s'%(func,)) debug(' rule: %s o---o %s'%(t_dom, s_dom)) try: debug(' try %s'%(check,)) c = check.xreplace(ma) debug(' check %s -> %s'%(check, c)) if c==True: return _laplace_cr(k*s_dom.xreplace(ma), plane.xreplace(ma), S.true, **hints) except Exception: debug('_laplace_apply_rules did not match.') if f.has(DiracDelta): return None prog_rules = [_laplace_rule_timescale, _laplace_rule_heaviside, _laplace_rule_exp, _laplace_rule_trig, _laplace_rule_diff] for p_rule in prog_rules: LT = p_rule(f, t, s, doit=doit, **hints) if LT is not None: return LT return None class LaplaceTransform(IntegralTransform): """ Class representing unevaluated Laplace transforms. For usage of this class, see the :class:`IntegralTransform` docstring. For how to compute Laplace transforms, see the :func:`laplace_transform` docstring. """ _name = 'Laplace' def _compute_transform(self, f, t, s, **hints): LT = _laplace_apply_rules(f, t, s, **hints) if LT is None: _simplify = hints.pop('simplify', True) debug('_laplace_apply_rules could not match function %s'%(f,)) debug(' hints: %s'%(hints,)) return _laplace_transform(f, t, s, simplify=_simplify, **hints) else: return LT def _as_integral(self, f, t, s): return Integral(f*exp(-s*t), (t, S.Zero, S.Infinity)) def _collapse_extra(self, extra): conds = [] planes = [] for plane, cond in extra: conds.append(cond) planes.append(plane) cond = And(*conds) plane = Max(*planes) if cond == False: raise IntegralTransformError( 'Laplace', None, 'No combined convergence.') return plane, cond def _try_directly(self, **hints): fn = self.function debug('----> _try_directly: %s'%(fn, )) t_ = self.function_variable s_ = self.transform_variable LT = None if not fn.is_Add: fn = expand_mul(fn) try: LT = self._compute_transform(fn, t_, s_, **hints) except IntegralTransformError: LT = None return fn, LT def laplace_transform(f, t, s, legacy_matrix=True, **hints): r""" Compute the Laplace Transform `F(s)` of `f(t)`, .. math :: F(s) = \int_{0^{-}}^\infty e^{-st} f(t) \mathrm{d}t. Explanation =========== For all sensible functions, this converges absolutely in a half-plane .. math :: a < \operatorname{Re}(s) This function returns ``(F, a, cond)`` where ``F`` is the Laplace transform of ``f``, `a` is the half-plane of convergence, and `cond` are auxiliary convergence conditions. The implementation is rule-based, and if you are interested in which rules are applied, and whether integration is attemped, you can switch debug information on by setting ``sympy.SYMPY_DEBUG=True``. The lower bound is `0-`, meaning that this bound should be approached from the lower side. This is only necessary if distributions are involved. At present, it is only done if `f(t)` contains ``DiracDelta``, in which case the Laplace transform is computed implicitly as .. math :: F(s) = \lim_{\tau\to 0^{-}} \int_{\tau}^\infty e^{-st} f(t) \mathrm{d}t by applying rules. If the integral cannot be fully computed in closed form, this function returns an unevaluated :class:`LaplaceTransform` object. For a description of possible hints, refer to the docstring of :func:`sympy.integrals.transforms.IntegralTransform.doit`. If ``noconds=True``, only `F` will be returned (i.e. not ``cond``, and also not the plane ``a``). .. deprecated:: 1.9 Legacy behavior for matrices where ``laplace_transform`` with ``noconds=False`` (the default) returns a Matrix whose elements are tuples. The behavior of ``laplace_transform`` for matrices will change in a future release of SymPy to return a tuple of the transformed Matrix and the convergence conditions for the matrix as a whole. Use ``legacy_matrix=False`` to enable the new behavior. Examples ======== >>> from sympy import DiracDelta, exp, laplace_transform >>> from sympy.abc import t, s, a >>> laplace_transform(t**4, t, s) (24/s**5, 0, True) >>> laplace_transform(t**a, t, s) (gamma(a + 1)/(s*s**a), 0, re(a) > -1) >>> laplace_transform(DiracDelta(t)-a*exp(-a*t),t,s) (s/(a + s), Max(0, -a), True) See Also ======== inverse_laplace_transform, mellin_transform, fourier_transform hankel_transform, inverse_hankel_transform """ debug('\n***** laplace_transform(%s, %s, %s)'%(f, t, s)) if isinstance(f, MatrixBase) and hasattr(f, 'applyfunc'): conds = not hints.get('noconds', False) if conds and legacy_matrix: sympy_deprecation_warning( """ Calling laplace_transform() on a Matrix with noconds=False (the default) is deprecated. Either noconds=True or use legacy_matrix=False to get the new behavior. """, deprecated_since_version="1.9", active_deprecations_target="deprecated-laplace-transform-matrix", ) # Temporarily disable the deprecation warning for non-Expr objects # in Matrix with ignore_warnings(SymPyDeprecationWarning): return f.applyfunc(lambda fij: laplace_transform(fij, t, s, **hints)) else: elements_trans = [laplace_transform(fij, t, s, **hints) for fij in f] if conds: elements, avals, conditions = zip(*elements_trans) f_laplace = type(f)(*f.shape, elements) return f_laplace, Max(*avals), And(*conditions) else: return type(f)(*f.shape, elements_trans) return LaplaceTransform(f, t, s).doit(**hints) @_noconds_(True) def _inverse_laplace_transform(F, s, t_, plane, simplify=True): """ The backend function for inverse Laplace transforms. """ from sympy.integrals.meijerint import meijerint_inversion, _get_coeff_exp # There are two strategies we can try: # 1) Use inverse mellin transforms - related by a simple change of variables. # 2) Use the inversion integral. t = Dummy('t', real=True) def pw_simp(*args): """ Simplify a piecewise expression from hyperexpand. """ # XXX we break modularity here! if len(args) != 3: return Piecewise(*args) arg = args[2].args[0].argument coeff, exponent = _get_coeff_exp(arg, t) e1 = args[0].args[0] e2 = args[1].args[0] return Heaviside(1/Abs(coeff) - t**exponent)*e1 \ + Heaviside(t**exponent - 1/Abs(coeff))*e2 if F.is_rational_function(s): F = F.apart(s) if F.is_Add: f = Add(*[_inverse_laplace_transform(X, s, t, plane, simplify)\ for X in F.args]) return _simplify(f.subs(t, t_), simplify), True try: f, cond = inverse_mellin_transform(F, s, exp(-t), (None, S.Infinity), needeval=True, noconds=False) except IntegralTransformError: f = None if f is None: f = meijerint_inversion(F, s, t) if f is None: raise IntegralTransformError('Inverse Laplace', f, '') if f.is_Piecewise: f, cond = f.args[0] if f.has(Integral): raise IntegralTransformError('Inverse Laplace', f, 'inversion integral of unrecognised form.') else: cond = S.true f = f.replace(Piecewise, pw_simp) if f.is_Piecewise: # many of the functions called below can't work with piecewise # (b/c it has a bool in args) return f.subs(t, t_), cond u = Dummy('u') def simp_heaviside(arg, H0=S.Half): a = arg.subs(exp(-t), u) if a.has(t): return Heaviside(arg, H0) from sympy.solvers.inequalities import _solve_inequality rel = _solve_inequality(a > 0, u) if rel.lts == u: k = log(rel.gts) return Heaviside(t + k, H0) else: k = log(rel.lts) return Heaviside(-(t + k), H0) f = f.replace(Heaviside, simp_heaviside) def simp_exp(arg): return expand_complex(exp(arg)) f = f.replace(exp, simp_exp) # TODO it would be nice to fix cosh and sinh ... simplify messes these # exponentials up return _simplify(f.subs(t, t_), simplify), cond class InverseLaplaceTransform(IntegralTransform): """ Class representing unevaluated inverse Laplace transforms. For usage of this class, see the :class:`IntegralTransform` docstring. For how to compute inverse Laplace transforms, see the :func:`inverse_laplace_transform` docstring. """ _name = 'Inverse Laplace' _none_sentinel = Dummy('None') _c = Dummy('c') def __new__(cls, F, s, x, plane, **opts): if plane is None: plane = InverseLaplaceTransform._none_sentinel return IntegralTransform.__new__(cls, F, s, x, plane, **opts) @property def fundamental_plane(self): plane = self.args[3] if plane is InverseLaplaceTransform._none_sentinel: plane = None return plane def _compute_transform(self, F, s, t, **hints): return _inverse_laplace_transform(F, s, t, self.fundamental_plane, **hints) def _as_integral(self, F, s, t): c = self.__class__._c return Integral(exp(s*t)*F, (s, c - S.ImaginaryUnit*S.Infinity, c + S.ImaginaryUnit*S.Infinity))/(2*S.Pi*S.ImaginaryUnit) def inverse_laplace_transform(F, s, t, plane=None, **hints): r""" Compute the inverse Laplace transform of `F(s)`, defined as .. math :: f(t) = \frac{1}{2\pi i} \int_{c-i\infty}^{c+i\infty} e^{st} F(s) \mathrm{d}s, for `c` so large that `F(s)` has no singularites in the half-plane `\operatorname{Re}(s) > c-\epsilon`. Explanation =========== The plane can be specified by argument ``plane``, but will be inferred if passed as None. Under certain regularity conditions, this recovers `f(t)` from its Laplace Transform `F(s)`, for non-negative `t`, and vice versa. If the integral cannot be computed in closed form, this function returns an unevaluated :class:`InverseLaplaceTransform` object. Note that this function will always assume `t` to be real, regardless of the SymPy assumption on `t`. For a description of possible hints, refer to the docstring of :func:`sympy.integrals.transforms.IntegralTransform.doit`. Examples ======== >>> from sympy import inverse_laplace_transform, exp, Symbol >>> from sympy.abc import s, t >>> a = Symbol('a', positive=True) >>> inverse_laplace_transform(exp(-a*s)/s, s, t) Heaviside(-a + t) See Also ======== laplace_transform, _fast_inverse_laplace hankel_transform, inverse_hankel_transform """ if isinstance(F, MatrixBase) and hasattr(F, 'applyfunc'): return F.applyfunc(lambda Fij: inverse_laplace_transform(Fij, s, t, plane, **hints)) return InverseLaplaceTransform(F, s, t, plane).doit(**hints) def _fast_inverse_laplace(e, s, t): """Fast inverse Laplace transform of rational function including RootSum""" a, b, n = symbols('a, b, n', cls=Wild, exclude=[s]) def _ilt(e): if not e.has(s): return e elif e.is_Add: return _ilt_add(e) elif e.is_Mul: return _ilt_mul(e) elif e.is_Pow: return _ilt_pow(e) elif isinstance(e, RootSum): return _ilt_rootsum(e) else: raise NotImplementedError def _ilt_add(e): return e.func(*map(_ilt, e.args)) def _ilt_mul(e): coeff, expr = e.as_independent(s) if expr.is_Mul: raise NotImplementedError return coeff * _ilt(expr) def _ilt_pow(e): match = e.match((a*s + b)**n) if match is not None: nm, am, bm = match[n], match[a], match[b] if nm.is_Integer and nm < 0: return t**(-nm-1)*exp(-(bm/am)*t)/(am**-nm*gamma(-nm)) if nm == 1: return exp(-(bm/am)*t) / am raise NotImplementedError def _ilt_rootsum(e): expr = e.fun.expr [variable] = e.fun.variables return RootSum(e.poly, Lambda(variable, together(_ilt(expr)))) return _ilt(e) ########################################################################## # Fourier Transform ########################################################################## @_noconds_(True) def _fourier_transform(f, x, k, a, b, name, simplify=True): r""" Compute a general Fourier-type transform .. math:: F(k) = a \int_{-\infty}^{\infty} e^{bixk} f(x)\, dx. For suitable choice of *a* and *b*, this reduces to the standard Fourier and inverse Fourier transforms. """ F = integrate(a*f*exp(b*S.ImaginaryUnit*x*k), (x, S.NegativeInfinity, S.Infinity)) if not F.has(Integral): return _simplify(F, simplify), S.true integral_f = integrate(f, (x, S.NegativeInfinity, S.Infinity)) if integral_f in (S.NegativeInfinity, S.Infinity, S.NaN) or integral_f.has(Integral): raise IntegralTransformError(name, f, 'function not integrable on real axis') if not F.is_Piecewise: raise IntegralTransformError(name, f, 'could not compute integral') F, cond = F.args[0] if F.has(Integral): raise IntegralTransformError(name, f, 'integral in unexpected form') return _simplify(F, simplify), cond class FourierTypeTransform(IntegralTransform): """ Base class for Fourier transforms.""" def a(self): raise NotImplementedError( "Class %s must implement a(self) but does not" % self.__class__) def b(self): raise NotImplementedError( "Class %s must implement b(self) but does not" % self.__class__) def _compute_transform(self, f, x, k, **hints): return _fourier_transform(f, x, k, self.a(), self.b(), self.__class__._name, **hints) def _as_integral(self, f, x, k): a = self.a() b = self.b() return Integral(a*f*exp(b*S.ImaginaryUnit*x*k), (x, S.NegativeInfinity, S.Infinity)) class FourierTransform(FourierTypeTransform): """ Class representing unevaluated Fourier transforms. For usage of this class, see the :class:`IntegralTransform` docstring. For how to compute Fourier transforms, see the :func:`fourier_transform` docstring. """ _name = 'Fourier' def a(self): return 1 def b(self): return -2*S.Pi def fourier_transform(f, x, k, **hints): r""" Compute the unitary, ordinary-frequency Fourier transform of ``f``, defined as .. math:: F(k) = \int_{-\infty}^\infty f(x) e^{-2\pi i x k} \mathrm{d} x. Explanation =========== If the transform cannot be computed in closed form, this function returns an unevaluated :class:`FourierTransform` object. For other Fourier transform conventions, see the function :func:`sympy.integrals.transforms._fourier_transform`. For a description of possible hints, refer to the docstring of :func:`sympy.integrals.transforms.IntegralTransform.doit`. Note that for this transform, by default ``noconds=True``. Examples ======== >>> from sympy import fourier_transform, exp >>> from sympy.abc import x, k >>> fourier_transform(exp(-x**2), x, k) sqrt(pi)*exp(-pi**2*k**2) >>> fourier_transform(exp(-x**2), x, k, noconds=False) (sqrt(pi)*exp(-pi**2*k**2), True) See Also ======== inverse_fourier_transform sine_transform, inverse_sine_transform cosine_transform, inverse_cosine_transform hankel_transform, inverse_hankel_transform mellin_transform, laplace_transform """ return FourierTransform(f, x, k).doit(**hints) class InverseFourierTransform(FourierTypeTransform): """ Class representing unevaluated inverse Fourier transforms. For usage of this class, see the :class:`IntegralTransform` docstring. For how to compute inverse Fourier transforms, see the :func:`inverse_fourier_transform` docstring. """ _name = 'Inverse Fourier' def a(self): return 1 def b(self): return 2*S.Pi def inverse_fourier_transform(F, k, x, **hints): r""" Compute the unitary, ordinary-frequency inverse Fourier transform of `F`, defined as .. math:: f(x) = \int_{-\infty}^\infty F(k) e^{2\pi i x k} \mathrm{d} k. Explanation =========== If the transform cannot be computed in closed form, this function returns an unevaluated :class:`InverseFourierTransform` object. For other Fourier transform conventions, see the function :func:`sympy.integrals.transforms._fourier_transform`. For a description of possible hints, refer to the docstring of :func:`sympy.integrals.transforms.IntegralTransform.doit`. Note that for this transform, by default ``noconds=True``. Examples ======== >>> from sympy import inverse_fourier_transform, exp, sqrt, pi >>> from sympy.abc import x, k >>> inverse_fourier_transform(sqrt(pi)*exp(-(pi*k)**2), k, x) exp(-x**2) >>> inverse_fourier_transform(sqrt(pi)*exp(-(pi*k)**2), k, x, noconds=False) (exp(-x**2), True) See Also ======== fourier_transform sine_transform, inverse_sine_transform cosine_transform, inverse_cosine_transform hankel_transform, inverse_hankel_transform mellin_transform, laplace_transform """ return InverseFourierTransform(F, k, x).doit(**hints) ########################################################################## # Fourier Sine and Cosine Transform ########################################################################## @_noconds_(True) def _sine_cosine_transform(f, x, k, a, b, K, name, simplify=True): """ Compute a general sine or cosine-type transform F(k) = a int_0^oo b*sin(x*k) f(x) dx. F(k) = a int_0^oo b*cos(x*k) f(x) dx. For suitable choice of a and b, this reduces to the standard sine/cosine and inverse sine/cosine transforms. """ F = integrate(a*f*K(b*x*k), (x, S.Zero, S.Infinity)) if not F.has(Integral): return _simplify(F, simplify), S.true if not F.is_Piecewise: raise IntegralTransformError(name, f, 'could not compute integral') F, cond = F.args[0] if F.has(Integral): raise IntegralTransformError(name, f, 'integral in unexpected form') return _simplify(F, simplify), cond class SineCosineTypeTransform(IntegralTransform): """ Base class for sine and cosine transforms. Specify cls._kern. """ def a(self): raise NotImplementedError( "Class %s must implement a(self) but does not" % self.__class__) def b(self): raise NotImplementedError( "Class %s must implement b(self) but does not" % self.__class__) def _compute_transform(self, f, x, k, **hints): return _sine_cosine_transform(f, x, k, self.a(), self.b(), self.__class__._kern, self.__class__._name, **hints) def _as_integral(self, f, x, k): a = self.a() b = self.b() K = self.__class__._kern return Integral(a*f*K(b*x*k), (x, S.Zero, S.Infinity)) class SineTransform(SineCosineTypeTransform): """ Class representing unevaluated sine transforms. For usage of this class, see the :class:`IntegralTransform` docstring. For how to compute sine transforms, see the :func:`sine_transform` docstring. """ _name = 'Sine' _kern = sin def a(self): return sqrt(2)/sqrt(pi) def b(self): return S.One def sine_transform(f, x, k, **hints): r""" Compute the unitary, ordinary-frequency sine transform of `f`, defined as .. math:: F(k) = \sqrt{\frac{2}{\pi}} \int_{0}^\infty f(x) \sin(2\pi x k) \mathrm{d} x. Explanation =========== If the transform cannot be computed in closed form, this function returns an unevaluated :class:`SineTransform` object. For a description of possible hints, refer to the docstring of :func:`sympy.integrals.transforms.IntegralTransform.doit`. Note that for this transform, by default ``noconds=True``. Examples ======== >>> from sympy import sine_transform, exp >>> from sympy.abc import x, k, a >>> sine_transform(x*exp(-a*x**2), x, k) sqrt(2)*k*exp(-k**2/(4*a))/(4*a**(3/2)) >>> sine_transform(x**(-a), x, k) 2**(1/2 - a)*k**(a - 1)*gamma(1 - a/2)/gamma(a/2 + 1/2) See Also ======== fourier_transform, inverse_fourier_transform inverse_sine_transform cosine_transform, inverse_cosine_transform hankel_transform, inverse_hankel_transform mellin_transform, laplace_transform """ return SineTransform(f, x, k).doit(**hints) class InverseSineTransform(SineCosineTypeTransform): """ Class representing unevaluated inverse sine transforms. For usage of this class, see the :class:`IntegralTransform` docstring. For how to compute inverse sine transforms, see the :func:`inverse_sine_transform` docstring. """ _name = 'Inverse Sine' _kern = sin def a(self): return sqrt(2)/sqrt(pi) def b(self): return S.One def inverse_sine_transform(F, k, x, **hints): r""" Compute the unitary, ordinary-frequency inverse sine transform of `F`, defined as .. math:: f(x) = \sqrt{\frac{2}{\pi}} \int_{0}^\infty F(k) \sin(2\pi x k) \mathrm{d} k. Explanation =========== If the transform cannot be computed in closed form, this function returns an unevaluated :class:`InverseSineTransform` object. For a description of possible hints, refer to the docstring of :func:`sympy.integrals.transforms.IntegralTransform.doit`. Note that for this transform, by default ``noconds=True``. Examples ======== >>> from sympy import inverse_sine_transform, exp, sqrt, gamma >>> from sympy.abc import x, k, a >>> inverse_sine_transform(2**((1-2*a)/2)*k**(a - 1)* ... gamma(-a/2 + 1)/gamma((a+1)/2), k, x) x**(-a) >>> inverse_sine_transform(sqrt(2)*k*exp(-k**2/(4*a))/(4*sqrt(a)**3), k, x) x*exp(-a*x**2) See Also ======== fourier_transform, inverse_fourier_transform sine_transform cosine_transform, inverse_cosine_transform hankel_transform, inverse_hankel_transform mellin_transform, laplace_transform """ return InverseSineTransform(F, k, x).doit(**hints) class CosineTransform(SineCosineTypeTransform): """ Class representing unevaluated cosine transforms. For usage of this class, see the :class:`IntegralTransform` docstring. For how to compute cosine transforms, see the :func:`cosine_transform` docstring. """ _name = 'Cosine' _kern = cos def a(self): return sqrt(2)/sqrt(pi) def b(self): return S.One def cosine_transform(f, x, k, **hints): r""" Compute the unitary, ordinary-frequency cosine transform of `f`, defined as .. math:: F(k) = \sqrt{\frac{2}{\pi}} \int_{0}^\infty f(x) \cos(2\pi x k) \mathrm{d} x. Explanation =========== If the transform cannot be computed in closed form, this function returns an unevaluated :class:`CosineTransform` object. For a description of possible hints, refer to the docstring of :func:`sympy.integrals.transforms.IntegralTransform.doit`. Note that for this transform, by default ``noconds=True``. Examples ======== >>> from sympy import cosine_transform, exp, sqrt, cos >>> from sympy.abc import x, k, a >>> cosine_transform(exp(-a*x), x, k) sqrt(2)*a/(sqrt(pi)*(a**2 + k**2)) >>> cosine_transform(exp(-a*sqrt(x))*cos(a*sqrt(x)), x, k) a*exp(-a**2/(2*k))/(2*k**(3/2)) See Also ======== fourier_transform, inverse_fourier_transform, sine_transform, inverse_sine_transform inverse_cosine_transform hankel_transform, inverse_hankel_transform mellin_transform, laplace_transform """ return CosineTransform(f, x, k).doit(**hints) class InverseCosineTransform(SineCosineTypeTransform): """ Class representing unevaluated inverse cosine transforms. For usage of this class, see the :class:`IntegralTransform` docstring. For how to compute inverse cosine transforms, see the :func:`inverse_cosine_transform` docstring. """ _name = 'Inverse Cosine' _kern = cos def a(self): return sqrt(2)/sqrt(pi) def b(self): return S.One def inverse_cosine_transform(F, k, x, **hints): r""" Compute the unitary, ordinary-frequency inverse cosine transform of `F`, defined as .. math:: f(x) = \sqrt{\frac{2}{\pi}} \int_{0}^\infty F(k) \cos(2\pi x k) \mathrm{d} k. Explanation =========== If the transform cannot be computed in closed form, this function returns an unevaluated :class:`InverseCosineTransform` object. For a description of possible hints, refer to the docstring of :func:`sympy.integrals.transforms.IntegralTransform.doit`. Note that for this transform, by default ``noconds=True``. Examples ======== >>> from sympy import inverse_cosine_transform, sqrt, pi >>> from sympy.abc import x, k, a >>> inverse_cosine_transform(sqrt(2)*a/(sqrt(pi)*(a**2 + k**2)), k, x) exp(-a*x) >>> inverse_cosine_transform(1/sqrt(k), k, x) 1/sqrt(x) See Also ======== fourier_transform, inverse_fourier_transform, sine_transform, inverse_sine_transform cosine_transform hankel_transform, inverse_hankel_transform mellin_transform, laplace_transform """ return InverseCosineTransform(F, k, x).doit(**hints) ########################################################################## # Hankel Transform ########################################################################## @_noconds_(True) def _hankel_transform(f, r, k, nu, name, simplify=True): r""" Compute a general Hankel transform .. math:: F_\nu(k) = \int_{0}^\infty f(r) J_\nu(k r) r \mathrm{d} r. """ F = integrate(f*besselj(nu, k*r)*r, (r, S.Zero, S.Infinity)) if not F.has(Integral): return _simplify(F, simplify), S.true if not F.is_Piecewise: raise IntegralTransformError(name, f, 'could not compute integral') F, cond = F.args[0] if F.has(Integral): raise IntegralTransformError(name, f, 'integral in unexpected form') return _simplify(F, simplify), cond class HankelTypeTransform(IntegralTransform): """ Base class for Hankel transforms. """ def doit(self, **hints): return self._compute_transform(self.function, self.function_variable, self.transform_variable, self.args[3], **hints) def _compute_transform(self, f, r, k, nu, **hints): return _hankel_transform(f, r, k, nu, self._name, **hints) def _as_integral(self, f, r, k, nu): return Integral(f*besselj(nu, k*r)*r, (r, S.Zero, S.Infinity)) @property def as_integral(self): return self._as_integral(self.function, self.function_variable, self.transform_variable, self.args[3]) class HankelTransform(HankelTypeTransform): """ Class representing unevaluated Hankel transforms. For usage of this class, see the :class:`IntegralTransform` docstring. For how to compute Hankel transforms, see the :func:`hankel_transform` docstring. """ _name = 'Hankel' def hankel_transform(f, r, k, nu, **hints): r""" Compute the Hankel transform of `f`, defined as .. math:: F_\nu(k) = \int_{0}^\infty f(r) J_\nu(k r) r \mathrm{d} r. Explanation =========== If the transform cannot be computed in closed form, this function returns an unevaluated :class:`HankelTransform` object. For a description of possible hints, refer to the docstring of :func:`sympy.integrals.transforms.IntegralTransform.doit`. Note that for this transform, by default ``noconds=True``. Examples ======== >>> from sympy import hankel_transform, inverse_hankel_transform >>> from sympy import exp >>> from sympy.abc import r, k, m, nu, a >>> ht = hankel_transform(1/r**m, r, k, nu) >>> ht 2*k**(m - 2)*gamma(-m/2 + nu/2 + 1)/(2**m*gamma(m/2 + nu/2)) >>> inverse_hankel_transform(ht, k, r, nu) r**(-m) >>> ht = hankel_transform(exp(-a*r), r, k, 0) >>> ht a/(k**3*(a**2/k**2 + 1)**(3/2)) >>> inverse_hankel_transform(ht, k, r, 0) exp(-a*r) See Also ======== fourier_transform, inverse_fourier_transform sine_transform, inverse_sine_transform cosine_transform, inverse_cosine_transform inverse_hankel_transform mellin_transform, laplace_transform """ return HankelTransform(f, r, k, nu).doit(**hints) class InverseHankelTransform(HankelTypeTransform): """ Class representing unevaluated inverse Hankel transforms. For usage of this class, see the :class:`IntegralTransform` docstring. For how to compute inverse Hankel transforms, see the :func:`inverse_hankel_transform` docstring. """ _name = 'Inverse Hankel' def inverse_hankel_transform(F, k, r, nu, **hints): r""" Compute the inverse Hankel transform of `F` defined as .. math:: f(r) = \int_{0}^\infty F_\nu(k) J_\nu(k r) k \mathrm{d} k. Explanation =========== If the transform cannot be computed in closed form, this function returns an unevaluated :class:`InverseHankelTransform` object. For a description of possible hints, refer to the docstring of :func:`sympy.integrals.transforms.IntegralTransform.doit`. Note that for this transform, by default ``noconds=True``. Examples ======== >>> from sympy import hankel_transform, inverse_hankel_transform >>> from sympy import exp >>> from sympy.abc import r, k, m, nu, a >>> ht = hankel_transform(1/r**m, r, k, nu) >>> ht 2*k**(m - 2)*gamma(-m/2 + nu/2 + 1)/(2**m*gamma(m/2 + nu/2)) >>> inverse_hankel_transform(ht, k, r, nu) r**(-m) >>> ht = hankel_transform(exp(-a*r), r, k, 0) >>> ht a/(k**3*(a**2/k**2 + 1)**(3/2)) >>> inverse_hankel_transform(ht, k, r, 0) exp(-a*r) See Also ======== fourier_transform, inverse_fourier_transform sine_transform, inverse_sine_transform cosine_transform, inverse_cosine_transform hankel_transform mellin_transform, laplace_transform """ return InverseHankelTransform(F, k, r, nu).doit(**hints)
49a92f770de6787746b96c8bdf795c5d9a14f979e705d13e5df9151f378d5b8c
""" Module to implement integration of uni/bivariate polynomials over 2D Polytopes and uni/bi/trivariate polynomials over 3D Polytopes. Uses evaluation techniques as described in Chin et al. (2015) [1]. References =========== .. [1] Chin, Eric B., Jean B. Lasserre, and N. Sukumar. "Numerical integration of homogeneous functions on convex and nonconvex polygons and polyhedra." Computational Mechanics 56.6 (2015): 967-981 PDF link : http://dilbert.engr.ucdavis.edu/~suku/quadrature/cls-integration.pdf """ from functools import cmp_to_key from sympy.abc import x, y, z from sympy.core import S, diff, Expr, Symbol from sympy.core.sympify import _sympify from sympy.geometry import Segment2D, Polygon, Point, Point2D from sympy.polys.polytools import LC, gcd_list, degree_list, Poly from sympy.simplify.simplify import nsimplify def polytope_integrate(poly, expr=None, *, clockwise=False, max_degree=None): """Integrates polynomials over 2/3-Polytopes. Explanation =========== This function accepts the polytope in ``poly`` and the function in ``expr`` (uni/bi/trivariate polynomials are implemented) and returns the exact integral of ``expr`` over ``poly``. Parameters ========== poly : The input Polygon. expr : The input polynomial. clockwise : Binary value to sort input points of 2-Polytope clockwise.(Optional) max_degree : The maximum degree of any monomial of the input polynomial.(Optional) Examples ======== >>> from sympy.abc import x, y >>> from sympy import Point, Polygon >>> from sympy.integrals.intpoly import polytope_integrate >>> polygon = Polygon(Point(0, 0), Point(0, 1), Point(1, 1), Point(1, 0)) >>> polys = [1, x, y, x*y, x**2*y, x*y**2] >>> expr = x*y >>> polytope_integrate(polygon, expr) 1/4 >>> polytope_integrate(polygon, polys, max_degree=3) {1: 1, x: 1/2, y: 1/2, x*y: 1/4, x*y**2: 1/6, x**2*y: 1/6} """ if clockwise: if isinstance(poly, Polygon): poly = Polygon(*point_sort(poly.vertices), evaluate=False) else: raise TypeError("clockwise=True works for only 2-Polytope" "V-representation input") if isinstance(poly, Polygon): # For Vertex Representation(2D case) hp_params = hyperplane_parameters(poly) facets = poly.sides elif len(poly[0]) == 2: # For Hyperplane Representation(2D case) plen = len(poly) if len(poly[0][0]) == 2: intersections = [intersection(poly[(i - 1) % plen], poly[i], "plane2D") for i in range(0, plen)] hp_params = poly lints = len(intersections) facets = [Segment2D(intersections[i], intersections[(i + 1) % lints]) for i in range(lints)] else: raise NotImplementedError("Integration for H-representation 3D" "case not implemented yet.") else: # For Vertex Representation(3D case) vertices = poly[0] facets = poly[1:] hp_params = hyperplane_parameters(facets, vertices) if max_degree is None: if expr is None: raise TypeError('Input expression must be a valid SymPy expression') return main_integrate3d(expr, facets, vertices, hp_params) if max_degree is not None: result = {} if expr is not None: f_expr = [] for e in expr: _ = decompose(e) if len(_) == 1 and not _.popitem()[0]: f_expr.append(e) elif Poly(e).total_degree() <= max_degree: f_expr.append(e) expr = f_expr if not isinstance(expr, list) and expr is not None: raise TypeError('Input polynomials must be list of expressions') if len(hp_params[0][0]) == 3: result_dict = main_integrate3d(0, facets, vertices, hp_params, max_degree) else: result_dict = main_integrate(0, facets, hp_params, max_degree) if expr is None: return result_dict for poly in expr: poly = _sympify(poly) if poly not in result: if poly.is_zero: result[S.Zero] = S.Zero continue integral_value = S.Zero monoms = decompose(poly, separate=True) for monom in monoms: monom = nsimplify(monom) coeff, m = strip(monom) integral_value += result_dict[m] * coeff result[poly] = integral_value return result if expr is None: raise TypeError('Input expression must be a valid SymPy expression') return main_integrate(expr, facets, hp_params) def strip(monom): if monom.is_zero: return S.Zero, S.Zero elif monom.is_number: return monom, S.One else: coeff = LC(monom) return coeff, monom / coeff def _polynomial_integrate(polynomials, facets, hp_params): dims = (x, y) dim_length = len(dims) integral_value = S.Zero for deg in polynomials: poly_contribute = S.Zero facet_count = 0 for hp in hp_params: value_over_boundary = integration_reduction(facets, facet_count, hp[0], hp[1], polynomials[deg], dims, deg) poly_contribute += value_over_boundary * (hp[1] / norm(hp[0])) facet_count += 1 poly_contribute /= (dim_length + deg) integral_value += poly_contribute return integral_value def main_integrate3d(expr, facets, vertices, hp_params, max_degree=None): """Function to translate the problem of integrating uni/bi/tri-variate polynomials over a 3-Polytope to integrating over its faces. This is done using Generalized Stokes' Theorem and Euler's Theorem. Parameters ========== expr : The input polynomial. facets : Faces of the 3-Polytope(expressed as indices of `vertices`). vertices : Vertices that constitute the Polytope. hp_params : Hyperplane Parameters of the facets. max_degree : optional Max degree of constituent monomial in given list of polynomial. Examples ======== >>> from sympy.integrals.intpoly import main_integrate3d, \ hyperplane_parameters >>> cube = [[(0, 0, 0), (0, 0, 5), (0, 5, 0), (0, 5, 5), (5, 0, 0),\ (5, 0, 5), (5, 5, 0), (5, 5, 5)],\ [2, 6, 7, 3], [3, 7, 5, 1], [7, 6, 4, 5], [1, 5, 4, 0],\ [3, 1, 0, 2], [0, 4, 6, 2]] >>> vertices = cube[0] >>> faces = cube[1:] >>> hp_params = hyperplane_parameters(faces, vertices) >>> main_integrate3d(1, faces, vertices, hp_params) -125 """ result = {} dims = (x, y, z) dim_length = len(dims) if max_degree: grad_terms = gradient_terms(max_degree, 3) flat_list = [term for z_terms in grad_terms for x_term in z_terms for term in x_term] for term in flat_list: result[term[0]] = 0 for facet_count, hp in enumerate(hp_params): a, b = hp[0], hp[1] x0 = vertices[facets[facet_count][0]] for i, monom in enumerate(flat_list): # Every monomial is a tuple : # (term, x_degree, y_degree, z_degree, value over boundary) expr, x_d, y_d, z_d, z_index, y_index, x_index, _ = monom degree = x_d + y_d + z_d if b.is_zero: value_over_face = S.Zero else: value_over_face = \ integration_reduction_dynamic(facets, facet_count, a, b, expr, degree, dims, x_index, y_index, z_index, x0, grad_terms, i, vertices, hp) monom[7] = value_over_face result[expr] += value_over_face * \ (b / norm(a)) / (dim_length + x_d + y_d + z_d) return result else: integral_value = S.Zero polynomials = decompose(expr) for deg in polynomials: poly_contribute = S.Zero facet_count = 0 for i, facet in enumerate(facets): hp = hp_params[i] if hp[1].is_zero: continue pi = polygon_integrate(facet, hp, i, facets, vertices, expr, deg) poly_contribute += pi *\ (hp[1] / norm(tuple(hp[0]))) facet_count += 1 poly_contribute /= (dim_length + deg) integral_value += poly_contribute return integral_value def main_integrate(expr, facets, hp_params, max_degree=None): """Function to translate the problem of integrating univariate/bivariate polynomials over a 2-Polytope to integrating over its boundary facets. This is done using Generalized Stokes's Theorem and Euler's Theorem. Parameters ========== expr : The input polynomial. facets : Facets(Line Segments) of the 2-Polytope. hp_params : Hyperplane Parameters of the facets. max_degree : optional The maximum degree of any monomial of the input polynomial. >>> from sympy.abc import x, y >>> from sympy.integrals.intpoly import main_integrate,\ hyperplane_parameters >>> from sympy import Point, Polygon >>> triangle = Polygon(Point(0, 3), Point(5, 3), Point(1, 1)) >>> facets = triangle.sides >>> hp_params = hyperplane_parameters(triangle) >>> main_integrate(x**2 + y**2, facets, hp_params) 325/6 """ dims = (x, y) dim_length = len(dims) result = {} if max_degree: grad_terms = [[0, 0, 0, 0]] + gradient_terms(max_degree) for facet_count, hp in enumerate(hp_params): a, b = hp[0], hp[1] x0 = facets[facet_count].points[0] for i, monom in enumerate(grad_terms): # Every monomial is a tuple : # (term, x_degree, y_degree, value over boundary) m, x_d, y_d, _ = monom value = result.get(m, None) degree = S.Zero if b.is_zero: value_over_boundary = S.Zero else: degree = x_d + y_d value_over_boundary = \ integration_reduction_dynamic(facets, facet_count, a, b, m, degree, dims, x_d, y_d, max_degree, x0, grad_terms, i) monom[3] = value_over_boundary if value is not None: result[m] += value_over_boundary * \ (b / norm(a)) / (dim_length + degree) else: result[m] = value_over_boundary * \ (b / norm(a)) / (dim_length + degree) return result else: if not isinstance(expr, list): polynomials = decompose(expr) return _polynomial_integrate(polynomials, facets, hp_params) else: return {e: _polynomial_integrate(decompose(e), facets, hp_params) for e in expr} def polygon_integrate(facet, hp_param, index, facets, vertices, expr, degree): """Helper function to integrate the input uni/bi/trivariate polynomial over a certain face of the 3-Polytope. Parameters ========== facet : Particular face of the 3-Polytope over which ``expr`` is integrated. index : The index of ``facet`` in ``facets``. facets : Faces of the 3-Polytope(expressed as indices of `vertices`). vertices : Vertices that constitute the facet. expr : The input polynomial. degree : Degree of ``expr``. Examples ======== >>> from sympy.integrals.intpoly import polygon_integrate >>> cube = [[(0, 0, 0), (0, 0, 5), (0, 5, 0), (0, 5, 5), (5, 0, 0),\ (5, 0, 5), (5, 5, 0), (5, 5, 5)],\ [2, 6, 7, 3], [3, 7, 5, 1], [7, 6, 4, 5], [1, 5, 4, 0],\ [3, 1, 0, 2], [0, 4, 6, 2]] >>> facet = cube[1] >>> facets = cube[1:] >>> vertices = cube[0] >>> polygon_integrate(facet, [(0, 1, 0), 5], 0, facets, vertices, 1, 0) -25 """ expr = S(expr) if expr.is_zero: return S.Zero result = S.Zero x0 = vertices[facet[0]] facet_len = len(facet) for i, fac in enumerate(facet): side = (vertices[fac], vertices[facet[(i + 1) % facet_len]]) result += distance_to_side(x0, side, hp_param[0]) *\ lineseg_integrate(facet, i, side, expr, degree) if not expr.is_number: expr = diff(expr, x) * x0[0] + diff(expr, y) * x0[1] +\ diff(expr, z) * x0[2] result += polygon_integrate(facet, hp_param, index, facets, vertices, expr, degree - 1) result /= (degree + 2) return result def distance_to_side(point, line_seg, A): """Helper function to compute the signed distance between given 3D point and a line segment. Parameters ========== point : 3D Point line_seg : Line Segment Examples ======== >>> from sympy.integrals.intpoly import distance_to_side >>> point = (0, 0, 0) >>> distance_to_side(point, [(0, 0, 1), (0, 1, 0)], (1, 0, 0)) -sqrt(2)/2 """ x1, x2 = line_seg rev_normal = [-1 * S(i)/norm(A) for i in A] vector = [x2[i] - x1[i] for i in range(0, 3)] vector = [vector[i]/norm(vector) for i in range(0, 3)] n_side = cross_product((0, 0, 0), rev_normal, vector) vectorx0 = [line_seg[0][i] - point[i] for i in range(0, 3)] dot_product = sum([vectorx0[i] * n_side[i] for i in range(0, 3)]) return dot_product def lineseg_integrate(polygon, index, line_seg, expr, degree): """Helper function to compute the line integral of ``expr`` over ``line_seg``. Parameters =========== polygon : Face of a 3-Polytope. index : Index of line_seg in polygon. line_seg : Line Segment. Examples ======== >>> from sympy.integrals.intpoly import lineseg_integrate >>> polygon = [(0, 5, 0), (5, 5, 0), (5, 5, 5), (0, 5, 5)] >>> line_seg = [(0, 5, 0), (5, 5, 0)] >>> lineseg_integrate(polygon, 0, line_seg, 1, 0) 5 """ expr = _sympify(expr) if expr.is_zero: return S.Zero result = S.Zero x0 = line_seg[0] distance = norm(tuple([line_seg[1][i] - line_seg[0][i] for i in range(3)])) if isinstance(expr, Expr): expr_dict = {x: line_seg[1][0], y: line_seg[1][1], z: line_seg[1][2]} result += distance * expr.subs(expr_dict) else: result += distance * expr expr = diff(expr, x) * x0[0] + diff(expr, y) * x0[1] +\ diff(expr, z) * x0[2] result += lineseg_integrate(polygon, index, line_seg, expr, degree - 1) result /= (degree + 1) return result def integration_reduction(facets, index, a, b, expr, dims, degree): """Helper method for main_integrate. Returns the value of the input expression evaluated over the polytope facet referenced by a given index. Parameters =========== facets : List of facets of the polytope. index : Index referencing the facet to integrate the expression over. a : Hyperplane parameter denoting direction. b : Hyperplane parameter denoting distance. expr : The expression to integrate over the facet. dims : List of symbols denoting axes. degree : Degree of the homogeneous polynomial. Examples ======== >>> from sympy.abc import x, y >>> from sympy.integrals.intpoly import integration_reduction,\ hyperplane_parameters >>> from sympy import Point, Polygon >>> triangle = Polygon(Point(0, 3), Point(5, 3), Point(1, 1)) >>> facets = triangle.sides >>> a, b = hyperplane_parameters(triangle)[0] >>> integration_reduction(facets, 0, a, b, 1, (x, y), 0) 5 """ expr = _sympify(expr) if expr.is_zero: return expr value = S.Zero x0 = facets[index].points[0] m = len(facets) gens = (x, y) inner_product = diff(expr, gens[0]) * x0[0] + diff(expr, gens[1]) * x0[1] if inner_product != 0: value += integration_reduction(facets, index, a, b, inner_product, dims, degree - 1) value += left_integral2D(m, index, facets, x0, expr, gens) return value/(len(dims) + degree - 1) def left_integral2D(m, index, facets, x0, expr, gens): """Computes the left integral of Eq 10 in Chin et al. For the 2D case, the integral is just an evaluation of the polynomial at the intersection of two facets which is multiplied by the distance between the first point of facet and that intersection. Parameters ========== m : No. of hyperplanes. index : Index of facet to find intersections with. facets : List of facets(Line Segments in 2D case). x0 : First point on facet referenced by index. expr : Input polynomial gens : Generators which generate the polynomial Examples ======== >>> from sympy.abc import x, y >>> from sympy.integrals.intpoly import left_integral2D >>> from sympy import Point, Polygon >>> triangle = Polygon(Point(0, 3), Point(5, 3), Point(1, 1)) >>> facets = triangle.sides >>> left_integral2D(3, 0, facets, facets[0].points[0], 1, (x, y)) 5 """ value = S.Zero for j in range(m): intersect = () if j in ((index - 1) % m, (index + 1) % m): intersect = intersection(facets[index], facets[j], "segment2D") if intersect: distance_origin = norm(tuple(map(lambda x, y: x - y, intersect, x0))) if is_vertex(intersect): if isinstance(expr, Expr): if len(gens) == 3: expr_dict = {gens[0]: intersect[0], gens[1]: intersect[1], gens[2]: intersect[2]} else: expr_dict = {gens[0]: intersect[0], gens[1]: intersect[1]} value += distance_origin * expr.subs(expr_dict) else: value += distance_origin * expr return value def integration_reduction_dynamic(facets, index, a, b, expr, degree, dims, x_index, y_index, max_index, x0, monomial_values, monom_index, vertices=None, hp_param=None): """The same integration_reduction function which uses a dynamic programming approach to compute terms by using the values of the integral of previously computed terms. Parameters ========== facets : Facets of the Polytope. index : Index of facet to find intersections with.(Used in left_integral()). a, b : Hyperplane parameters. expr : Input monomial. degree : Total degree of ``expr``. dims : Tuple denoting axes variables. x_index : Exponent of 'x' in ``expr``. y_index : Exponent of 'y' in ``expr``. max_index : Maximum exponent of any monomial in ``monomial_values``. x0 : First point on ``facets[index]``. monomial_values : List of monomial values constituting the polynomial. monom_index : Index of monomial whose integration is being found. vertices : optional Coordinates of vertices constituting the 3-Polytope. hp_param : optional Hyperplane Parameter of the face of the facets[index]. Examples ======== >>> from sympy.abc import x, y >>> from sympy.integrals.intpoly import (integration_reduction_dynamic, \ hyperplane_parameters) >>> from sympy import Point, Polygon >>> triangle = Polygon(Point(0, 3), Point(5, 3), Point(1, 1)) >>> facets = triangle.sides >>> a, b = hyperplane_parameters(triangle)[0] >>> x0 = facets[0].points[0] >>> monomial_values = [[0, 0, 0, 0], [1, 0, 0, 5],\ [y, 0, 1, 15], [x, 1, 0, None]] >>> integration_reduction_dynamic(facets, 0, a, b, x, 1, (x, y), 1, 0, 1,\ x0, monomial_values, 3) 25/2 """ value = S.Zero m = len(facets) if expr == S.Zero: return expr if len(dims) == 2: if not expr.is_number: _, x_degree, y_degree, _ = monomial_values[monom_index] x_index = monom_index - max_index + \ x_index - 2 if x_degree > 0 else 0 y_index = monom_index - 1 if y_degree > 0 else 0 x_value, y_value =\ monomial_values[x_index][3], monomial_values[y_index][3] value += x_degree * x_value * x0[0] + y_degree * y_value * x0[1] value += left_integral2D(m, index, facets, x0, expr, dims) else: # For 3D use case the max_index contains the z_degree of the term z_index = max_index if not expr.is_number: x_degree, y_degree, z_degree = y_index,\ z_index - x_index - y_index, x_index x_value = monomial_values[z_index - 1][y_index - 1][x_index][7]\ if x_degree > 0 else 0 y_value = monomial_values[z_index - 1][y_index][x_index][7]\ if y_degree > 0 else 0 z_value = monomial_values[z_index - 1][y_index][x_index - 1][7]\ if z_degree > 0 else 0 value += x_degree * x_value * x0[0] + y_degree * y_value * x0[1] \ + z_degree * z_value * x0[2] value += left_integral3D(facets, index, expr, vertices, hp_param, degree) return value / (len(dims) + degree - 1) def left_integral3D(facets, index, expr, vertices, hp_param, degree): """Computes the left integral of Eq 10 in Chin et al. Explanation =========== For the 3D case, this is the sum of the integral values over constituting line segments of the face (which is accessed by facets[index]) multiplied by the distance between the first point of facet and that line segment. Parameters ========== facets : List of faces of the 3-Polytope. index : Index of face over which integral is to be calculated. expr : Input polynomial. vertices : List of vertices that constitute the 3-Polytope. hp_param : The hyperplane parameters of the face. degree : Degree of the ``expr``. Examples ======== >>> from sympy.integrals.intpoly import left_integral3D >>> cube = [[(0, 0, 0), (0, 0, 5), (0, 5, 0), (0, 5, 5), (5, 0, 0),\ (5, 0, 5), (5, 5, 0), (5, 5, 5)],\ [2, 6, 7, 3], [3, 7, 5, 1], [7, 6, 4, 5], [1, 5, 4, 0],\ [3, 1, 0, 2], [0, 4, 6, 2]] >>> facets = cube[1:] >>> vertices = cube[0] >>> left_integral3D(facets, 3, 1, vertices, ([0, -1, 0], -5), 0) -50 """ value = S.Zero facet = facets[index] x0 = vertices[facet[0]] facet_len = len(facet) for i, fac in enumerate(facet): side = (vertices[fac], vertices[facet[(i + 1) % facet_len]]) value += distance_to_side(x0, side, hp_param[0]) * \ lineseg_integrate(facet, i, side, expr, degree) return value def gradient_terms(binomial_power=0, no_of_gens=2): """Returns a list of all the possible monomials between 0 and y**binomial_power for 2D case and z**binomial_power for 3D case. Parameters ========== binomial_power : Power upto which terms are generated. no_of_gens : Denotes whether terms are being generated for 2D or 3D case. Examples ======== >>> from sympy.integrals.intpoly import gradient_terms >>> gradient_terms(2) [[1, 0, 0, 0], [y, 0, 1, 0], [y**2, 0, 2, 0], [x, 1, 0, 0], [x*y, 1, 1, 0], [x**2, 2, 0, 0]] >>> gradient_terms(2, 3) [[[[1, 0, 0, 0, 0, 0, 0, 0]]], [[[y, 0, 1, 0, 1, 0, 0, 0], [z, 0, 0, 1, 1, 0, 1, 0]], [[x, 1, 0, 0, 1, 1, 0, 0]]], [[[y**2, 0, 2, 0, 2, 0, 0, 0], [y*z, 0, 1, 1, 2, 0, 1, 0], [z**2, 0, 0, 2, 2, 0, 2, 0]], [[x*y, 1, 1, 0, 2, 1, 0, 0], [x*z, 1, 0, 1, 2, 1, 1, 0]], [[x**2, 2, 0, 0, 2, 2, 0, 0]]]] """ if no_of_gens == 2: count = 0 terms = [None] * int((binomial_power ** 2 + 3 * binomial_power + 2) / 2) for x_count in range(0, binomial_power + 1): for y_count in range(0, binomial_power - x_count + 1): terms[count] = [x**x_count*y**y_count, x_count, y_count, 0] count += 1 else: terms = [[[[x ** x_count * y ** y_count * z ** (z_count - y_count - x_count), x_count, y_count, z_count - y_count - x_count, z_count, x_count, z_count - y_count - x_count, 0] for y_count in range(z_count - x_count, -1, -1)] for x_count in range(0, z_count + 1)] for z_count in range(0, binomial_power + 1)] return terms def hyperplane_parameters(poly, vertices=None): """A helper function to return the hyperplane parameters of which the facets of the polytope are a part of. Parameters ========== poly : The input 2/3-Polytope. vertices : Vertex indices of 3-Polytope. Examples ======== >>> from sympy import Point, Polygon >>> from sympy.integrals.intpoly import hyperplane_parameters >>> hyperplane_parameters(Polygon(Point(0, 3), Point(5, 3), Point(1, 1))) [((0, 1), 3), ((1, -2), -1), ((-2, -1), -3)] >>> cube = [[(0, 0, 0), (0, 0, 5), (0, 5, 0), (0, 5, 5), (5, 0, 0),\ (5, 0, 5), (5, 5, 0), (5, 5, 5)],\ [2, 6, 7, 3], [3, 7, 5, 1], [7, 6, 4, 5], [1, 5, 4, 0],\ [3, 1, 0, 2], [0, 4, 6, 2]] >>> hyperplane_parameters(cube[1:], cube[0]) [([0, -1, 0], -5), ([0, 0, -1], -5), ([-1, 0, 0], -5), ([0, 1, 0], 0), ([1, 0, 0], 0), ([0, 0, 1], 0)] """ if isinstance(poly, Polygon): vertices = list(poly.vertices) + [poly.vertices[0]] # Close the polygon params = [None] * (len(vertices) - 1) for i in range(len(vertices) - 1): v1 = vertices[i] v2 = vertices[i + 1] a1 = v1[1] - v2[1] a2 = v2[0] - v1[0] b = v2[0] * v1[1] - v2[1] * v1[0] factor = gcd_list([a1, a2, b]) b = S(b) / factor a = (S(a1) / factor, S(a2) / factor) params[i] = (a, b) else: params = [None] * len(poly) for i, polygon in enumerate(poly): v1, v2, v3 = [vertices[vertex] for vertex in polygon[:3]] normal = cross_product(v1, v2, v3) b = sum([normal[j] * v1[j] for j in range(0, 3)]) fac = gcd_list(normal) if fac.is_zero: fac = 1 normal = [j / fac for j in normal] b = b / fac params[i] = (normal, b) return params def cross_product(v1, v2, v3): """Returns the cross-product of vectors (v2 - v1) and (v3 - v1) That is : (v2 - v1) X (v3 - v1) """ v2 = [v2[j] - v1[j] for j in range(0, 3)] v3 = [v3[j] - v1[j] for j in range(0, 3)] return [v3[2] * v2[1] - v3[1] * v2[2], v3[0] * v2[2] - v3[2] * v2[0], v3[1] * v2[0] - v3[0] * v2[1]] def best_origin(a, b, lineseg, expr): """Helper method for polytope_integrate. Currently not used in the main algorithm. Explanation =========== Returns a point on the lineseg whose vector inner product with the divergence of `expr` yields an expression with the least maximum total power. Parameters ========== a : Hyperplane parameter denoting direction. b : Hyperplane parameter denoting distance. lineseg : Line segment on which to find the origin. expr : The expression which determines the best point. Algorithm(currently works only for 2D use case) =============================================== 1 > Firstly, check for edge cases. Here that would refer to vertical or horizontal lines. 2 > If input expression is a polynomial containing more than one generator then find out the total power of each of the generators. x**2 + 3 + x*y + x**4*y**5 ---> {x: 7, y: 6} If expression is a constant value then pick the first boundary point of the line segment. 3 > First check if a point exists on the line segment where the value of the highest power generator becomes 0. If not check if the value of the next highest becomes 0. If none becomes 0 within line segment constraints then pick the first boundary point of the line segment. Actually, any point lying on the segment can be picked as best origin in the last case. Examples ======== >>> from sympy.integrals.intpoly import best_origin >>> from sympy.abc import x, y >>> from sympy import Point, Segment2D >>> l = Segment2D(Point(0, 3), Point(1, 1)) >>> expr = x**3*y**7 >>> best_origin((2, 1), 3, l, expr) (0, 3.0) """ a1, b1 = lineseg.points[0] def x_axis_cut(ls): """Returns the point where the input line segment intersects the x-axis. Parameters ========== ls : Line segment """ p, q = ls.points if p.y.is_zero: return tuple(p) elif q.y.is_zero: return tuple(q) elif p.y/q.y < S.Zero: return p.y * (p.x - q.x)/(q.y - p.y) + p.x, S.Zero else: return () def y_axis_cut(ls): """Returns the point where the input line segment intersects the y-axis. Parameters ========== ls : Line segment """ p, q = ls.points if p.x.is_zero: return tuple(p) elif q.x.is_zero: return tuple(q) elif p.x/q.x < S.Zero: return S.Zero, p.x * (p.y - q.y)/(q.x - p.x) + p.y else: return () gens = (x, y) power_gens = {} for i in gens: power_gens[i] = S.Zero if len(gens) > 1: # Special case for vertical and horizontal lines if len(gens) == 2: if a[0] == 0: if y_axis_cut(lineseg): return S.Zero, b/a[1] else: return a1, b1 elif a[1] == 0: if x_axis_cut(lineseg): return b/a[0], S.Zero else: return a1, b1 if isinstance(expr, Expr): # Find the sum total of power of each if expr.is_Add: # generator and store in a dictionary. for monomial in expr.args: if monomial.is_Pow: if monomial.args[0] in gens: power_gens[monomial.args[0]] += monomial.args[1] else: for univariate in monomial.args: term_type = len(univariate.args) if term_type == 0 and univariate in gens: power_gens[univariate] += 1 elif term_type == 2 and univariate.args[0] in gens: power_gens[univariate.args[0]] +=\ univariate.args[1] elif expr.is_Mul: for term in expr.args: term_type = len(term.args) if term_type == 0 and term in gens: power_gens[term] += 1 elif term_type == 2 and term.args[0] in gens: power_gens[term.args[0]] += term.args[1] elif expr.is_Pow: power_gens[expr.args[0]] = expr.args[1] elif expr.is_Symbol: power_gens[expr] += 1 else: # If `expr` is a constant take first vertex of the line segment. return a1, b1 # TODO : This part is quite hacky. Should be made more robust with # TODO : respect to symbol names and scalable w.r.t higher dimensions. power_gens = sorted(power_gens.items(), key=lambda k: str(k[0])) if power_gens[0][1] >= power_gens[1][1]: if y_axis_cut(lineseg): x0 = (S.Zero, b / a[1]) elif x_axis_cut(lineseg): x0 = (b / a[0], S.Zero) else: x0 = (a1, b1) else: if x_axis_cut(lineseg): x0 = (b/a[0], S.Zero) elif y_axis_cut(lineseg): x0 = (S.Zero, b/a[1]) else: x0 = (a1, b1) else: x0 = (b/a[0]) return x0 def decompose(expr, separate=False): """Decomposes an input polynomial into homogeneous ones of smaller or equal degree. Explanation =========== Returns a dictionary with keys as the degree of the smaller constituting polynomials. Values are the constituting polynomials. Parameters ========== expr : Expr Polynomial(SymPy expression). separate : bool If True then simply return a list of the constituent monomials If not then break up the polynomial into constituent homogeneous polynomials. Examples ======== >>> from sympy.abc import x, y >>> from sympy.integrals.intpoly import decompose >>> decompose(x**2 + x*y + x + y + x**3*y**2 + y**5) {1: x + y, 2: x**2 + x*y, 5: x**3*y**2 + y**5} >>> decompose(x**2 + x*y + x + y + x**3*y**2 + y**5, True) {x, x**2, y, y**5, x*y, x**3*y**2} """ poly_dict = {} if isinstance(expr, Expr) and not expr.is_number: if expr.is_Symbol: poly_dict[1] = expr elif expr.is_Add: symbols = expr.atoms(Symbol) degrees = [(sum(degree_list(monom, *symbols)), monom) for monom in expr.args] if separate: return {monom[1] for monom in degrees} else: for monom in degrees: degree, term = monom if poly_dict.get(degree): poly_dict[degree] += term else: poly_dict[degree] = term elif expr.is_Pow: _, degree = expr.args poly_dict[degree] = expr else: # Now expr can only be of `Mul` type degree = 0 for term in expr.args: term_type = len(term.args) if term_type == 0 and term.is_Symbol: degree += 1 elif term_type == 2: degree += term.args[1] poly_dict[degree] = expr else: poly_dict[0] = expr if separate: return set(poly_dict.values()) return poly_dict def point_sort(poly, normal=None, clockwise=True): """Returns the same polygon with points sorted in clockwise or anti-clockwise order. Note that it's necessary for input points to be sorted in some order (clockwise or anti-clockwise) for the integration algorithm to work. As a convention algorithm has been implemented keeping clockwise orientation in mind. Parameters ========== poly: 2D or 3D Polygon. normal : optional The normal of the plane which the 3-Polytope is a part of. clockwise : bool, optional Returns points sorted in clockwise order if True and anti-clockwise if False. Examples ======== >>> from sympy.integrals.intpoly import point_sort >>> from sympy import Point >>> point_sort([Point(0, 0), Point(1, 0), Point(1, 1)]) [Point2D(1, 1), Point2D(1, 0), Point2D(0, 0)] """ pts = poly.vertices if isinstance(poly, Polygon) else poly n = len(pts) if n < 2: return list(pts) order = S.One if clockwise else S.NegativeOne dim = len(pts[0]) if dim == 2: center = Point(sum(map(lambda vertex: vertex.x, pts)) / n, sum(map(lambda vertex: vertex.y, pts)) / n) else: center = Point(sum(map(lambda vertex: vertex.x, pts)) / n, sum(map(lambda vertex: vertex.y, pts)) / n, sum(map(lambda vertex: vertex.z, pts)) / n) def compare(a, b): if a.x - center.x >= S.Zero and b.x - center.x < S.Zero: return -order elif a.x - center.x < 0 and b.x - center.x >= 0: return order elif a.x - center.x == 0 and b.x - center.x == 0: if a.y - center.y >= 0 or b.y - center.y >= 0: return -order if a.y > b.y else order return -order if b.y > a.y else order det = (a.x - center.x) * (b.y - center.y) -\ (b.x - center.x) * (a.y - center.y) if det < 0: return -order elif det > 0: return order first = (a.x - center.x) * (a.x - center.x) +\ (a.y - center.y) * (a.y - center.y) second = (b.x - center.x) * (b.x - center.x) +\ (b.y - center.y) * (b.y - center.y) return -order if first > second else order def compare3d(a, b): det = cross_product(center, a, b) dot_product = sum([det[i] * normal[i] for i in range(0, 3)]) if dot_product < 0: return -order elif dot_product > 0: return order return sorted(pts, key=cmp_to_key(compare if dim==2 else compare3d)) def norm(point): """Returns the Euclidean norm of a point from origin. Parameters ========== point: This denotes a point in the dimension_al spac_e. Examples ======== >>> from sympy.integrals.intpoly import norm >>> from sympy import Point >>> norm(Point(2, 7)) sqrt(53) """ half = S.Half if isinstance(point, (list, tuple)): return sum([coord ** 2 for coord in point]) ** half elif isinstance(point, Point): if isinstance(point, Point2D): return (point.x ** 2 + point.y ** 2) ** half else: return (point.x ** 2 + point.y ** 2 + point.z) ** half elif isinstance(point, dict): return sum(i**2 for i in point.values()) ** half def intersection(geom_1, geom_2, intersection_type): """Returns intersection between geometric objects. Explanation =========== Note that this function is meant for use in integration_reduction and at that point in the calling function the lines denoted by the segments surely intersect within segment boundaries. Coincident lines are taken to be non-intersecting. Also, the hyperplane intersection for 2D case is also implemented. Parameters ========== geom_1, geom_2: The input line segments. Examples ======== >>> from sympy.integrals.intpoly import intersection >>> from sympy import Point, Segment2D >>> l1 = Segment2D(Point(1, 1), Point(3, 5)) >>> l2 = Segment2D(Point(2, 0), Point(2, 5)) >>> intersection(l1, l2, "segment2D") (2, 3) >>> p1 = ((-1, 0), 0) >>> p2 = ((0, 1), 1) >>> intersection(p1, p2, "plane2D") (0, 1) """ if intersection_type[:-2] == "segment": if intersection_type == "segment2D": x1, y1 = geom_1.points[0] x2, y2 = geom_1.points[1] x3, y3 = geom_2.points[0] x4, y4 = geom_2.points[1] elif intersection_type == "segment3D": x1, y1, z1 = geom_1.points[0] x2, y2, z2 = geom_1.points[1] x3, y3, z3 = geom_2.points[0] x4, y4, z4 = geom_2.points[1] denom = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4) if denom: t1 = x1 * y2 - y1 * x2 t2 = x3 * y4 - x4 * y3 return (S(t1 * (x3 - x4) - t2 * (x1 - x2)) / denom, S(t1 * (y3 - y4) - t2 * (y1 - y2)) / denom) if intersection_type[:-2] == "plane": if intersection_type == "plane2D": # Intersection of hyperplanes a1x, a1y = geom_1[0] a2x, a2y = geom_2[0] b1, b2 = geom_1[1], geom_2[1] denom = a1x * a2y - a2x * a1y if denom: return (S(b1 * a2y - b2 * a1y) / denom, S(b2 * a1x - b1 * a2x) / denom) def is_vertex(ent): """If the input entity is a vertex return True. Parameter ========= ent : Denotes a geometric entity representing a point. Examples ======== >>> from sympy import Point >>> from sympy.integrals.intpoly import is_vertex >>> is_vertex((2, 3)) True >>> is_vertex((2, 3, 6)) True >>> is_vertex(Point(2, 3)) True """ if isinstance(ent, tuple): if len(ent) in [2, 3]: return True elif isinstance(ent, Point): return True return False def plot_polytope(poly): """Plots the 2D polytope using the functions written in plotting module which in turn uses matplotlib backend. Parameter ========= poly: Denotes a 2-Polytope. """ from sympy.plotting.plot import Plot, List2DSeries xl = list(map(lambda vertex: vertex.x, poly.vertices)) yl = list(map(lambda vertex: vertex.y, poly.vertices)) xl.append(poly.vertices[0].x) # Closing the polygon yl.append(poly.vertices[0].y) l2ds = List2DSeries(xl, yl) p = Plot(l2ds, axes='label_axes=True') p.show() def plot_polynomial(expr): """Plots the polynomial using the functions written in plotting module which in turn uses matplotlib backend. Parameter ========= expr: Denotes a polynomial(SymPy expression). """ from sympy.plotting.plot import plot3d, plot gens = expr.free_symbols if len(gens) == 2: plot3d(expr) else: plot(expr)
11096cfafd85bd85ccfa969481a734e6d7741f9e6f17597f8f5e46ded5727b20
from typing import Dict as tDict, List from itertools import permutations from functools import reduce from sympy.core.add import Add from sympy.core.basic import Basic from sympy.core.mul import Mul from sympy.core.symbol import Wild, Dummy, Symbol from sympy.core.basic import sympify from sympy.core.numbers import Rational, pi, I from sympy.core.relational import Eq, Ne from sympy.core.singleton import S from sympy.core.sorting import ordered from sympy.core.traversal import iterfreeargs from sympy.functions import exp, sin, cos, tan, cot, asin, atan from sympy.functions import log, sinh, cosh, tanh, coth, asinh from sympy.functions import sqrt, erf, erfi, li, Ei from sympy.functions import besselj, bessely, besseli, besselk from sympy.functions import hankel1, hankel2, jn, yn from sympy.functions.elementary.complexes import Abs, re, im, sign, arg from sympy.functions.elementary.exponential import LambertW from sympy.functions.elementary.integers import floor, ceiling from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.special.delta_functions import Heaviside, DiracDelta from sympy.simplify.radsimp import collect from sympy.logic.boolalg import And, Or from sympy.utilities.iterables import uniq from sympy.polys import quo, gcd, lcm, factor_list, cancel, PolynomialError from sympy.polys.monomials import itermonomials from sympy.polys.polyroots import root_factors from sympy.polys.rings import PolyRing from sympy.polys.solvers import solve_lin_sys from sympy.polys.constructor import construct_domain from sympy.integrals.integrals import integrate def components(f, x): """ Returns a set of all functional components of the given expression which includes symbols, function applications and compositions and non-integer powers. Fractional powers are collected with minimal, positive exponents. Examples ======== >>> from sympy import cos, sin >>> from sympy.abc import x >>> from sympy.integrals.heurisch import components >>> components(sin(x)*cos(x)**2, x) {x, sin(x), cos(x)} See Also ======== heurisch """ result = set() if f.has_free(x): if f.is_symbol and f.is_commutative: result.add(f) elif f.is_Function or f.is_Derivative: for g in f.args: result |= components(g, x) result.add(f) elif f.is_Pow: result |= components(f.base, x) if not f.exp.is_Integer: if f.exp.is_Rational: result.add(f.base**Rational(1, f.exp.q)) else: result |= components(f.exp, x) | {f} else: for g in f.args: result |= components(g, x) return result # name -> [] of symbols _symbols_cache = {} # type: tDict[str, List[Dummy]] # NB @cacheit is not convenient here def _symbols(name, n): """get vector of symbols local to this module""" try: lsyms = _symbols_cache[name] except KeyError: lsyms = [] _symbols_cache[name] = lsyms while len(lsyms) < n: lsyms.append( Dummy('%s%i' % (name, len(lsyms))) ) return lsyms[:n] def heurisch_wrapper(f, x, rewrite=False, hints=None, mappings=None, retries=3, degree_offset=0, unnecessary_permutations=None, _try_heurisch=None): """ A wrapper around the heurisch integration algorithm. Explanation =========== This method takes the result from heurisch and checks for poles in the denominator. For each of these poles, the integral is reevaluated, and the final integration result is given in terms of a Piecewise. Examples ======== >>> from sympy import cos, symbols >>> from sympy.integrals.heurisch import heurisch, heurisch_wrapper >>> n, x = symbols('n x') >>> heurisch(cos(n*x), x) sin(n*x)/n >>> heurisch_wrapper(cos(n*x), x) Piecewise((sin(n*x)/n, Ne(n, 0)), (x, True)) See Also ======== heurisch """ from sympy.solvers.solvers import solve, denoms f = sympify(f) if not f.has_free(x): return f*x res = heurisch(f, x, rewrite, hints, mappings, retries, degree_offset, unnecessary_permutations, _try_heurisch) if not isinstance(res, Basic): return res # We consider each denominator in the expression, and try to find # cases where one or more symbolic denominator might be zero. The # conditions for these cases are stored in the list slns. # # Since denoms returns a set we use ordered. This is important because the # ordering of slns determines the order of the resulting Piecewise so we # need a deterministic order here to make the output deterministic. slns = [] for d in ordered(denoms(res)): try: slns += solve([d], dict=True, exclude=(x,)) except NotImplementedError: pass if not slns: return res slns = list(uniq(slns)) # Remove the solutions corresponding to poles in the original expression. slns0 = [] for d in denoms(f): try: slns0 += solve([d], dict=True, exclude=(x,)) except NotImplementedError: pass slns = [s for s in slns if s not in slns0] if not slns: return res if len(slns) > 1: eqs = [] for sub_dict in slns: eqs.extend([Eq(key, value) for key, value in sub_dict.items()]) slns = solve(eqs, dict=True, exclude=(x,)) + slns # For each case listed in the list slns, we reevaluate the integral. pairs = [] for sub_dict in slns: expr = heurisch(f.subs(sub_dict), x, rewrite, hints, mappings, retries, degree_offset, unnecessary_permutations, _try_heurisch) cond = And(*[Eq(key, value) for key, value in sub_dict.items()]) generic = Or(*[Ne(key, value) for key, value in sub_dict.items()]) if expr is None: expr = integrate(f.subs(sub_dict),x) pairs.append((expr, cond)) # If there is one condition, put the generic case first. Otherwise, # doing so may lead to longer Piecewise formulas if len(pairs) == 1: pairs = [(heurisch(f, x, rewrite, hints, mappings, retries, degree_offset, unnecessary_permutations, _try_heurisch), generic), (pairs[0][0], True)] else: pairs.append((heurisch(f, x, rewrite, hints, mappings, retries, degree_offset, unnecessary_permutations, _try_heurisch), True)) return Piecewise(*pairs) class BesselTable: """ Derivatives of Bessel functions of orders n and n-1 in terms of each other. See the docstring of DiffCache. """ def __init__(self): self.table = {} self.n = Dummy('n') self.z = Dummy('z') self._create_table() def _create_table(t): table, n, z = t.table, t.n, t.z for f in (besselj, bessely, hankel1, hankel2): table[f] = (f(n-1, z) - n*f(n, z)/z, (n-1)*f(n-1, z)/z - f(n, z)) f = besseli table[f] = (f(n-1, z) - n*f(n, z)/z, (n-1)*f(n-1, z)/z + f(n, z)) f = besselk table[f] = (-f(n-1, z) - n*f(n, z)/z, (n-1)*f(n-1, z)/z - f(n, z)) for f in (jn, yn): table[f] = (f(n-1, z) - (n+1)*f(n, z)/z, (n-1)*f(n-1, z)/z - f(n, z)) def diffs(t, f, n, z): if f in t.table: diff0, diff1 = t.table[f] repl = [(t.n, n), (t.z, z)] return (diff0.subs(repl), diff1.subs(repl)) def has(t, f): return f in t.table _bessel_table = None class DiffCache: """ Store for derivatives of expressions. Explanation =========== The standard form of the derivative of a Bessel function of order n contains two Bessel functions of orders n-1 and n+1, respectively. Such forms cannot be used in parallel Risch algorithm, because there is a linear recurrence relation between the three functions while the algorithm expects that functions and derivatives are represented in terms of algebraically independent transcendentals. The solution is to take two of the functions, e.g., those of orders n and n-1, and to express the derivatives in terms of the pair. To guarantee that the proper form is used the two derivatives are cached as soon as one is encountered. Derivatives of other functions are also cached at no extra cost. All derivatives are with respect to the same variable `x`. """ def __init__(self, x): self.cache = {} self.x = x global _bessel_table if not _bessel_table: _bessel_table = BesselTable() def get_diff(self, f): cache = self.cache if f in cache: pass elif (not hasattr(f, 'func') or not _bessel_table.has(f.func)): cache[f] = cancel(f.diff(self.x)) else: n, z = f.args d0, d1 = _bessel_table.diffs(f.func, n, z) dz = self.get_diff(z) cache[f] = d0*dz cache[f.func(n-1, z)] = d1*dz return cache[f] def heurisch(f, x, rewrite=False, hints=None, mappings=None, retries=3, degree_offset=0, unnecessary_permutations=None, _try_heurisch=None): """ Compute indefinite integral using heuristic Risch algorithm. Explanation =========== This is a heuristic approach to indefinite integration in finite terms using the extended heuristic (parallel) Risch algorithm, based on Manuel Bronstein's "Poor Man's Integrator". The algorithm supports various classes of functions including transcendental elementary or special functions like Airy, Bessel, Whittaker and Lambert. Note that this algorithm is not a decision procedure. If it isn't able to compute the antiderivative for a given function, then this is not a proof that such a functions does not exist. One should use recursive Risch algorithm in such case. It's an open question if this algorithm can be made a full decision procedure. This is an internal integrator procedure. You should use top level 'integrate' function in most cases, as this procedure needs some preprocessing steps and otherwise may fail. Specification ============= heurisch(f, x, rewrite=False, hints=None) where f : expression x : symbol rewrite -> force rewrite 'f' in terms of 'tan' and 'tanh' hints -> a list of functions that may appear in anti-derivate - hints = None --> no suggestions at all - hints = [ ] --> try to figure out - hints = [f1, ..., fn] --> we know better Examples ======== >>> from sympy import tan >>> from sympy.integrals.heurisch import heurisch >>> from sympy.abc import x, y >>> heurisch(y*tan(x), x) y*log(tan(x)**2 + 1)/2 See Manuel Bronstein's "Poor Man's Integrator": References ========== .. [1] http://www-sop.inria.fr/cafe/Manuel.Bronstein/pmint/index.html For more information on the implemented algorithm refer to: .. [2] K. Geddes, L. Stefanus, On the Risch-Norman Integration Method and its Implementation in Maple, Proceedings of ISSAC'89, ACM Press, 212-217. .. [3] J. H. Davenport, On the Parallel Risch Algorithm (I), Proceedings of EUROCAM'82, LNCS 144, Springer, 144-157. .. [4] J. H. Davenport, On the Parallel Risch Algorithm (III): Use of Tangents, SIGSAM Bulletin 16 (1982), 3-6. .. [5] J. H. Davenport, B. M. Trager, On the Parallel Risch Algorithm (II), ACM Transactions on Mathematical Software 11 (1985), 356-362. See Also ======== sympy.integrals.integrals.Integral.doit sympy.integrals.integrals.Integral sympy.integrals.heurisch.components """ f = sympify(f) # There are some functions that Heurisch cannot currently handle, # so do not even try. # Set _try_heurisch=True to skip this check if _try_heurisch is not True: if f.has(Abs, re, im, sign, Heaviside, DiracDelta, floor, ceiling, arg): return if not f.has_free(x): return f*x if not f.is_Add: indep, f = f.as_independent(x) else: indep = S.One rewritables = { (sin, cos, cot): tan, (sinh, cosh, coth): tanh, } if rewrite: for candidates, rule in rewritables.items(): f = f.rewrite(candidates, rule) else: for candidates in rewritables.keys(): if f.has(*candidates): break else: rewrite = True terms = components(f, x) dcache = DiffCache(x) if hints is not None: if not hints: a = Wild('a', exclude=[x]) b = Wild('b', exclude=[x]) c = Wild('c', exclude=[x]) for g in set(terms): # using copy of terms if g.is_Function: if isinstance(g, li): M = g.args[0].match(a*x**b) if M is not None: terms.add( x*(li(M[a]*x**M[b]) - (M[a]*x**M[b])**(-1/M[b])*Ei((M[b]+1)*log(M[a]*x**M[b])/M[b])) ) #terms.add( x*(li(M[a]*x**M[b]) - (x**M[b])**(-1/M[b])*Ei((M[b]+1)*log(M[a]*x**M[b])/M[b])) ) #terms.add( x*(li(M[a]*x**M[b]) - x*Ei((M[b]+1)*log(M[a]*x**M[b])/M[b])) ) #terms.add( li(M[a]*x**M[b]) - Ei((M[b]+1)*log(M[a]*x**M[b])/M[b]) ) elif isinstance(g, exp): M = g.args[0].match(a*x**2) if M is not None: if M[a].is_positive: terms.add(erfi(sqrt(M[a])*x)) else: # M[a].is_negative or unknown terms.add(erf(sqrt(-M[a])*x)) M = g.args[0].match(a*x**2 + b*x + c) if M is not None: if M[a].is_positive: terms.add(sqrt(pi/4*(-M[a]))*exp(M[c] - M[b]**2/(4*M[a]))* erfi(sqrt(M[a])*x + M[b]/(2*sqrt(M[a])))) elif M[a].is_negative: terms.add(sqrt(pi/4*(-M[a]))*exp(M[c] - M[b]**2/(4*M[a]))* erf(sqrt(-M[a])*x - M[b]/(2*sqrt(-M[a])))) M = g.args[0].match(a*log(x)**2) if M is not None: if M[a].is_positive: terms.add(erfi(sqrt(M[a])*log(x) + 1/(2*sqrt(M[a])))) if M[a].is_negative: terms.add(erf(sqrt(-M[a])*log(x) - 1/(2*sqrt(-M[a])))) elif g.is_Pow: if g.exp.is_Rational and g.exp.q == 2: M = g.base.match(a*x**2 + b) if M is not None and M[b].is_positive: if M[a].is_positive: terms.add(asinh(sqrt(M[a]/M[b])*x)) elif M[a].is_negative: terms.add(asin(sqrt(-M[a]/M[b])*x)) M = g.base.match(a*x**2 - b) if M is not None and M[b].is_positive: if M[a].is_positive: dF = 1/sqrt(M[a]*x**2 - M[b]) F = log(2*sqrt(M[a])*sqrt(M[a]*x**2 - M[b]) + 2*M[a]*x)/sqrt(M[a]) dcache.cache[F] = dF # hack: F.diff(x) doesn't automatically simplify to f terms.add(F) elif M[a].is_negative: terms.add(-M[b]/2*sqrt(-M[a])* atan(sqrt(-M[a])*x/sqrt(M[a]*x**2 - M[b]))) else: terms |= set(hints) for g in set(terms): # using copy of terms terms |= components(dcache.get_diff(g), x) # XXX: The commented line below makes heurisch more deterministic wrt # PYTHONHASHSEED and the iteration order of sets. There are other places # where sets are iterated over but this one is possibly the most important. # Theoretically the order here should not matter but different orderings # can expose potential bugs in the different code paths so potentially it # is better to keep the non-determinism. # # terms = list(ordered(terms)) # TODO: caching is significant factor for why permutations work at all. Change this. V = _symbols('x', len(terms)) # sort mapping expressions from largest to smallest (last is always x). mapping = list(reversed(list(zip(*ordered( # [(a[0].as_independent(x)[1], a) for a in zip(terms, V)])))[1])) # rev_mapping = {v: k for k, v in mapping} # if mappings is None: # # optimizing the number of permutations of mapping # assert mapping[-1][0] == x # if not, find it and correct this comment unnecessary_permutations = [mapping.pop(-1)] mappings = permutations(mapping) else: unnecessary_permutations = unnecessary_permutations or [] def _substitute(expr): return expr.subs(mapping) for mapping in mappings: mapping = list(mapping) mapping = mapping + unnecessary_permutations diffs = [ _substitute(dcache.get_diff(g)) for g in terms ] denoms = [ g.as_numer_denom()[1] for g in diffs ] if all(h.is_polynomial(*V) for h in denoms) and _substitute(f).is_rational_function(*V): denom = reduce(lambda p, q: lcm(p, q, *V), denoms) break else: if not rewrite: result = heurisch(f, x, rewrite=True, hints=hints, unnecessary_permutations=unnecessary_permutations) if result is not None: return indep*result return None numers = [ cancel(denom*g) for g in diffs ] def _derivation(h): return Add(*[ d * h.diff(v) for d, v in zip(numers, V) ]) def _deflation(p): for y in V: if not p.has(y): continue if _derivation(p) is not S.Zero: c, q = p.as_poly(y).primitive() return _deflation(c)*gcd(q, q.diff(y)).as_expr() return p def _splitter(p): for y in V: if not p.has(y): continue if _derivation(y) is not S.Zero: c, q = p.as_poly(y).primitive() q = q.as_expr() h = gcd(q, _derivation(q), y) s = quo(h, gcd(q, q.diff(y), y), y) c_split = _splitter(c) if s.as_poly(y).degree() == 0: return (c_split[0], q * c_split[1]) q_split = _splitter(cancel(q / s)) return (c_split[0]*q_split[0]*s, c_split[1]*q_split[1]) return (S.One, p) special = {} for term in terms: if term.is_Function: if isinstance(term, tan): special[1 + _substitute(term)**2] = False elif isinstance(term, tanh): special[1 + _substitute(term)] = False special[1 - _substitute(term)] = False elif isinstance(term, LambertW): special[_substitute(term)] = True F = _substitute(f) P, Q = F.as_numer_denom() u_split = _splitter(denom) v_split = _splitter(Q) polys = set(list(v_split) + [ u_split[0] ] + list(special.keys())) s = u_split[0] * Mul(*[ k for k, v in special.items() if v ]) polified = [ p.as_poly(*V) for p in [s, P, Q] ] if None in polified: return None #--- definitions for _integrate a, b, c = [ p.total_degree() for p in polified ] poly_denom = (s * v_split[0] * _deflation(v_split[1])).as_expr() def _exponent(g): if g.is_Pow: if g.exp.is_Rational and g.exp.q != 1: if g.exp.p > 0: return g.exp.p + g.exp.q - 1 else: return abs(g.exp.p + g.exp.q) else: return 1 elif not g.is_Atom and g.args: return max([ _exponent(h) for h in g.args ]) else: return 1 A, B = _exponent(f), a + max(b, c) if A > 1 and B > 1: monoms = tuple(ordered(itermonomials(V, A + B - 1 + degree_offset))) else: monoms = tuple(ordered(itermonomials(V, A + B + degree_offset))) poly_coeffs = _symbols('A', len(monoms)) poly_part = Add(*[ poly_coeffs[i]*monomial for i, monomial in enumerate(monoms) ]) reducibles = set() for poly in ordered(polys): coeff, factors = factor_list(poly, *V) reducibles.add(coeff) for fact, mul in factors: reducibles.add(fact) def _integrate(field=None): atans = set() pairs = set() if field == 'Q': irreducibles = set(reducibles) else: setV = set(V) irreducibles = set() for poly in ordered(reducibles): zV = setV & set(iterfreeargs(poly)) for z in ordered(zV): s = set(root_factors(poly, z, filter=field)) irreducibles |= s break log_part, atan_part = [], [] for poly in ordered(irreducibles): m = collect(poly, I, evaluate=False) y = m.get(I, S.Zero) if y: x = m.get(S.One, S.Zero) if x.has(I) or y.has(I): continue # nontrivial x + I*y pairs.add((x, y)) irreducibles.remove(poly) while pairs: x, y = pairs.pop() if (x, -y) in pairs: pairs.remove((x, -y)) # Choosing b with no minus sign if y.could_extract_minus_sign(): y = -y irreducibles.add(x*x + y*y) atans.add(atan(x/y)) else: irreducibles.add(x + I*y) B = _symbols('B', len(irreducibles)) C = _symbols('C', len(atans)) # Note: the ordering matters here for poly, b in reversed(list(zip(ordered(irreducibles), B))): if poly.has(*V): poly_coeffs.append(b) log_part.append(b * log(poly)) for poly, c in reversed(list(zip(ordered(atans), C))): if poly.has(*V): poly_coeffs.append(c) atan_part.append(c * poly) # TODO: Currently it's better to use symbolic expressions here instead # of rational functions, because it's simpler and FracElement doesn't # give big speed improvement yet. This is because cancellation is slow # due to slow polynomial GCD algorithms. If this gets improved then # revise this code. candidate = poly_part/poly_denom + Add(*log_part) + Add(*atan_part) h = F - _derivation(candidate) / denom raw_numer = h.as_numer_denom()[0] # Rewrite raw_numer as a polynomial in K[coeffs][V] where K is a field # that we have to determine. We can't use simply atoms() because log(3), # sqrt(y) and similar expressions can appear, leading to non-trivial # domains. syms = set(poly_coeffs) | set(V) non_syms = set() def find_non_syms(expr): if expr.is_Integer or expr.is_Rational: pass # ignore trivial numbers elif expr in syms: pass # ignore variables elif not expr.has_free(*syms): non_syms.add(expr) elif expr.is_Add or expr.is_Mul or expr.is_Pow: list(map(find_non_syms, expr.args)) else: # TODO: Non-polynomial expression. This should have been # filtered out at an earlier stage. raise PolynomialError try: find_non_syms(raw_numer) except PolynomialError: return None else: ground, _ = construct_domain(non_syms, field=True) coeff_ring = PolyRing(poly_coeffs, ground) ring = PolyRing(V, coeff_ring) try: numer = ring.from_expr(raw_numer) except ValueError: raise PolynomialError solution = solve_lin_sys(numer.coeffs(), coeff_ring, _raw=False) if solution is None: return None else: return candidate.xreplace(solution).xreplace( dict(zip(poly_coeffs, [S.Zero]*len(poly_coeffs)))) if all(isinstance(_, Symbol) for _ in V): more_free = F.free_symbols - set(V) else: Fd = F.as_dummy() more_free = Fd.xreplace(dict(zip(V, (Dummy() for _ in V))) ).free_symbols & Fd.free_symbols if not more_free: # all free generators are identified in V solution = _integrate('Q') if solution is None: solution = _integrate() else: solution = _integrate() if solution is not None: antideriv = solution.subs(rev_mapping) antideriv = cancel(antideriv).expand() if antideriv.is_Add: antideriv = antideriv.as_independent(x)[1] return indep*antideriv else: if retries >= 0: result = heurisch(f, x, mappings=mappings, rewrite=rewrite, hints=hints, retries=retries - 1, unnecessary_permutations=unnecessary_permutations) if result is not None: return indep*result return None
96b4b5d004deba766679f3843c334260f49b0e01087d8145ade1d1f043360331
""" The Risch Algorithm for transcendental function integration. The core algorithms for the Risch algorithm are here. The subproblem algorithms are in the rde.py and prde.py files for the Risch Differential Equation solver and the parametric problems solvers, respectively. All important information concerning the differential extension for an integrand is stored in a DifferentialExtension object, which in the code is usually called DE. Throughout the code and Inside the DifferentialExtension object, the conventions/attribute names are that the base domain is QQ and each differential extension is x, t0, t1, ..., tn-1 = DE.t. DE.x is the variable of integration (Dx == 1), DE.D is a list of the derivatives of x, t1, t2, ..., tn-1 = t, DE.T is the list [x, t1, t2, ..., tn-1], DE.t is the outer-most variable of the differential extension at the given level (the level can be adjusted using DE.increment_level() and DE.decrement_level()), k is the field C(x, t0, ..., tn-2), where C is the constant field. The numerator of a fraction is denoted by a and the denominator by d. If the fraction is named f, fa == numer(f) and fd == denom(f). Fractions are returned as tuples (fa, fd). DE.d and DE.t are used to represent the topmost derivation and extension variable, respectively. The docstring of a function signifies whether an argument is in k[t], in which case it will just return a Poly in t, or in k(t), in which case it will return the fraction (fa, fd). Other variable names probably come from the names used in Bronstein's book. """ from types import GeneratorType from functools import reduce from sympy.core.function import Lambda from sympy.core.mul import Mul from sympy.core.numbers import ilcm, I, oo from sympy.core.power import Pow from sympy.core.relational import Ne from sympy.core.singleton import S from sympy.core.sorting import ordered, default_sort_key from sympy.core.symbol import Dummy, Symbol from sympy.functions.elementary.exponential import log, exp from sympy.functions.elementary.hyperbolic import (cosh, coth, sinh, tanh) from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import (atan, sin, cos, tan, acot, cot, asin, acos) from .integrals import integrate, Integral from .heurisch import _symbols from sympy.polys.polyerrors import DomainError, PolynomialError from sympy.polys.polytools import (real_roots, cancel, Poly, gcd, reduced) from sympy.polys.rootoftools import RootSum from sympy.utilities.iterables import numbered_symbols def integer_powers(exprs): """ Rewrites a list of expressions as integer multiples of each other. Explanation =========== For example, if you have [x, x/2, x**2 + 1, 2*x/3], then you can rewrite this as [(x/6) * 6, (x/6) * 3, (x**2 + 1) * 1, (x/6) * 4]. This is useful in the Risch integration algorithm, where we must write exp(x) + exp(x/2) as (exp(x/2))**2 + exp(x/2), but not as exp(x) + sqrt(exp(x)) (this is because only the transcendental case is implemented and we therefore cannot integrate algebraic extensions). The integer multiples returned by this function for each term are the smallest possible (their content equals 1). Returns a list of tuples where the first element is the base term and the second element is a list of `(item, factor)` terms, where `factor` is the integer multiplicative factor that must multiply the base term to obtain the original item. The easiest way to understand this is to look at an example: >>> from sympy.abc import x >>> from sympy.integrals.risch import integer_powers >>> integer_powers([x, x/2, x**2 + 1, 2*x/3]) [(x/6, [(x, 6), (x/2, 3), (2*x/3, 4)]), (x**2 + 1, [(x**2 + 1, 1)])] We can see how this relates to the example at the beginning of the docstring. It chose x/6 as the first base term. Then, x can be written as (x/2) * 2, so we get (0, 2), and so on. Now only element (x**2 + 1) remains, and there are no other terms that can be written as a rational multiple of that, so we get that it can be written as (x**2 + 1) * 1. """ # Here is the strategy: # First, go through each term and determine if it can be rewritten as a # rational multiple of any of the terms gathered so far. # cancel(a/b).is_Rational is sufficient for this. If it is a multiple, we # add its multiple to the dictionary. terms = {} for term in exprs: for trm, trm_list in terms.items(): a = cancel(term/trm) if a.is_Rational: trm_list.append((term, a)) break else: terms[term] = [(term, S.One)] # After we have done this, we have all the like terms together, so we just # need to find a common denominator so that we can get the base term and # integer multiples such that each term can be written as an integer # multiple of the base term, and the content of the integers is 1. newterms = {} for term, term_list in terms.items(): common_denom = reduce(ilcm, [i.as_numer_denom()[1] for _, i in term_list]) newterm = term/common_denom newmults = [(i, j*common_denom) for i, j in term_list] newterms[newterm] = newmults return sorted(iter(newterms.items()), key=lambda item: item[0].sort_key()) class DifferentialExtension: """ A container for all the information relating to a differential extension. Explanation =========== The attributes of this object are (see also the docstring of __init__): - f: The original (Expr) integrand. - x: The variable of integration. - T: List of variables in the extension. - D: List of derivations in the extension; corresponds to the elements of T. - fa: Poly of the numerator of the integrand. - fd: Poly of the denominator of the integrand. - Tfuncs: Lambda() representations of each element of T (except for x). For back-substitution after integration. - backsubs: A (possibly empty) list of further substitutions to be made on the final integral to make it look more like the integrand. - exts: - extargs: - cases: List of string representations of the cases of T. - t: The top level extension variable, as defined by the current level (see level below). - d: The top level extension derivation, as defined by the current derivation (see level below). - case: The string representation of the case of self.d. (Note that self.T and self.D will always contain the complete extension, regardless of the level. Therefore, you should ALWAYS use DE.t and DE.d instead of DE.T[-1] and DE.D[-1]. If you want to have a list of the derivations or variables only up to the current level, use DE.D[:len(DE.D) + DE.level + 1] and DE.T[:len(DE.T) + DE.level + 1]. Note that, in particular, the derivation() function does this.) The following are also attributes, but will probably not be useful other than in internal use: - newf: Expr form of fa/fd. - level: The number (between -1 and -len(self.T)) such that self.T[self.level] == self.t and self.D[self.level] == self.d. Use the methods self.increment_level() and self.decrement_level() to change the current level. """ # __slots__ is defined mainly so we can iterate over all the attributes # of the class easily (the memory use doesn't matter too much, since we # only create one DifferentialExtension per integration). Also, it's nice # to have a safeguard when debugging. __slots__ = ('f', 'x', 'T', 'D', 'fa', 'fd', 'Tfuncs', 'backsubs', 'exts', 'extargs', 'cases', 'case', 't', 'd', 'newf', 'level', 'ts', 'dummy') def __init__(self, f=None, x=None, handle_first='log', dummy=False, extension=None, rewrite_complex=None): """ Tries to build a transcendental extension tower from ``f`` with respect to ``x``. Explanation =========== If it is successful, creates a DifferentialExtension object with, among others, the attributes fa, fd, D, T, Tfuncs, and backsubs such that fa and fd are Polys in T[-1] with rational coefficients in T[:-1], fa/fd == f, and D[i] is a Poly in T[i] with rational coefficients in T[:i] representing the derivative of T[i] for each i from 1 to len(T). Tfuncs is a list of Lambda objects for back replacing the functions after integrating. Lambda() is only used (instead of lambda) to make them easier to test and debug. Note that Tfuncs corresponds to the elements of T, except for T[0] == x, but they should be back-substituted in reverse order. backsubs is a (possibly empty) back-substitution list that should be applied on the completed integral to make it look more like the original integrand. If it is unsuccessful, it raises NotImplementedError. You can also create an object by manually setting the attributes as a dictionary to the extension keyword argument. You must include at least D. Warning, any attribute that is not given will be set to None. The attributes T, t, d, cases, case, x, and level are set automatically and do not need to be given. The functions in the Risch Algorithm will NOT check to see if an attribute is None before using it. This also does not check to see if the extension is valid (non-algebraic) or even if it is self-consistent. Therefore, this should only be used for testing/debugging purposes. """ # XXX: If you need to debug this function, set the break point here if extension: if 'D' not in extension: raise ValueError("At least the key D must be included with " "the extension flag to DifferentialExtension.") for attr in extension: setattr(self, attr, extension[attr]) self._auto_attrs() return elif f is None or x is None: raise ValueError("Either both f and x or a manual extension must " "be given.") if handle_first not in ('log', 'exp'): raise ValueError("handle_first must be 'log' or 'exp', not %s." % str(handle_first)) # f will be the original function, self.f might change if we reset # (e.g., we pull out a constant from an exponential) self.f = f self.x = x # setting the default value 'dummy' self.dummy = dummy self.reset() exp_new_extension, log_new_extension = True, True # case of 'automatic' choosing if rewrite_complex is None: rewrite_complex = I in self.f.atoms() if rewrite_complex: rewritables = { (sin, cos, cot, tan, sinh, cosh, coth, tanh): exp, (asin, acos, acot, atan): log, } # rewrite the trigonometric components for candidates, rule in rewritables.items(): self.newf = self.newf.rewrite(candidates, rule) self.newf = cancel(self.newf) else: if any(i.has(x) for i in self.f.atoms(sin, cos, tan, atan, asin, acos)): raise NotImplementedError("Trigonometric extensions are not " "supported (yet!)") exps = set() pows = set() numpows = set() sympows = set() logs = set() symlogs = set() while True: if self.newf.is_rational_function(*self.T): break if not exp_new_extension and not log_new_extension: # We couldn't find a new extension on the last pass, so I guess # we can't do it. raise NotImplementedError("Couldn't find an elementary " "transcendental extension for %s. Try using a " % str(f) + "manual extension with the extension flag.") exps, pows, numpows, sympows, log_new_extension = \ self._rewrite_exps_pows(exps, pows, numpows, sympows, log_new_extension) logs, symlogs = self._rewrite_logs(logs, symlogs) if handle_first == 'exp' or not log_new_extension: exp_new_extension = self._exp_part(exps) if exp_new_extension is None: # reset and restart self.f = self.newf self.reset() exp_new_extension = True continue if handle_first == 'log' or not exp_new_extension: log_new_extension = self._log_part(logs) self.fa, self.fd = frac_in(self.newf, self.t) self._auto_attrs() return def __getattr__(self, attr): # Avoid AttributeErrors when debugging if attr not in self.__slots__: raise AttributeError("%s has no attribute %s" % (repr(self), repr(attr))) return None def _rewrite_exps_pows(self, exps, pows, numpows, sympows, log_new_extension): """ Rewrite exps/pows for better processing. """ from .prde import is_deriv_k # Pre-preparsing. ################# # Get all exp arguments, so we can avoid ahead of time doing # something like t1 = exp(x), t2 = exp(x/2) == sqrt(t1). # Things like sqrt(exp(x)) do not automatically simplify to # exp(x/2), so they will be viewed as algebraic. The easiest way # to handle this is to convert all instances of exp(a)**Rational # to exp(Rational*a) before doing anything else. Note that the # _exp_part code can generate terms of this form, so we do need to # do this at each pass (or else modify it to not do that). ratpows = [i for i in self.newf.atoms(Pow) if (isinstance(i.base, exp) and i.exp.is_Rational)] ratpows_repl = [ (i, i.base.base**(i.exp*i.base.exp)) for i in ratpows] self.backsubs += [(j, i) for i, j in ratpows_repl] self.newf = self.newf.xreplace(dict(ratpows_repl)) # To make the process deterministic, the args are sorted # so that functions with smaller op-counts are processed first. # Ties are broken with the default_sort_key. # XXX Although the method is deterministic no additional work # has been done to guarantee that the simplest solution is # returned and that it would be affected be using different # variables. Though it is possible that this is the case # one should know that it has not been done intentionally, so # further improvements may be possible. # TODO: This probably doesn't need to be completely recomputed at # each pass. exps = update_sets(exps, self.newf.atoms(exp), lambda i: i.exp.is_rational_function(*self.T) and i.exp.has(*self.T)) pows = update_sets(pows, self.newf.atoms(Pow), lambda i: i.exp.is_rational_function(*self.T) and i.exp.has(*self.T)) numpows = update_sets(numpows, set(pows), lambda i: not i.base.has(*self.T)) sympows = update_sets(sympows, set(pows) - set(numpows), lambda i: i.base.is_rational_function(*self.T) and not i.exp.is_Integer) # The easiest way to deal with non-base E powers is to convert them # into base E, integrate, and then convert back. for i in ordered(pows): old = i new = exp(i.exp*log(i.base)) # If exp is ever changed to automatically reduce exp(x*log(2)) # to 2**x, then this will break. The solution is to not change # exp to do that :) if i in sympows: if i.exp.is_Rational: raise NotImplementedError("Algebraic extensions are " "not supported (%s)." % str(i)) # We can add a**b only if log(a) in the extension, because # a**b == exp(b*log(a)). basea, based = frac_in(i.base, self.t) A = is_deriv_k(basea, based, self) if A is None: # Nonelementary monomial (so far) # TODO: Would there ever be any benefit from just # adding log(base) as a new monomial? # ANSWER: Yes, otherwise we can't integrate x**x (or # rather prove that it has no elementary integral) # without first manually rewriting it as exp(x*log(x)) self.newf = self.newf.xreplace({old: new}) self.backsubs += [(new, old)] log_new_extension = self._log_part([log(i.base)]) exps = update_sets(exps, self.newf.atoms(exp), lambda i: i.exp.is_rational_function(*self.T) and i.exp.has(*self.T)) continue ans, u, const = A newterm = exp(i.exp*(log(const) + u)) # Under the current implementation, exp kills terms # only if they are of the form a*log(x), where a is a # Number. This case should have already been killed by the # above tests. Again, if this changes to kill more than # that, this will break, which maybe is a sign that you # shouldn't be changing that. Actually, if anything, this # auto-simplification should be removed. See # http://groups.google.com/group/sympy/browse_thread/thread/a61d48235f16867f self.newf = self.newf.xreplace({i: newterm}) elif i not in numpows: continue else: # i in numpows newterm = new # TODO: Just put it in self.Tfuncs self.backsubs.append((new, old)) self.newf = self.newf.xreplace({old: newterm}) exps.append(newterm) return exps, pows, numpows, sympows, log_new_extension def _rewrite_logs(self, logs, symlogs): """ Rewrite logs for better processing. """ atoms = self.newf.atoms(log) logs = update_sets(logs, atoms, lambda i: i.args[0].is_rational_function(*self.T) and i.args[0].has(*self.T)) symlogs = update_sets(symlogs, atoms, lambda i: i.has(*self.T) and i.args[0].is_Pow and i.args[0].base.is_rational_function(*self.T) and not i.args[0].exp.is_Integer) # We can handle things like log(x**y) by converting it to y*log(x) # This will fix not only symbolic exponents of the argument, but any # non-Integer exponent, like log(sqrt(x)). The exponent can also # depend on x, like log(x**x). for i in ordered(symlogs): # Unlike in the exponential case above, we do not ever # potentially add new monomials (above we had to add log(a)). # Therefore, there is no need to run any is_deriv functions # here. Just convert log(a**b) to b*log(a) and let # log_new_extension() handle it from there. lbase = log(i.args[0].base) logs.append(lbase) new = i.args[0].exp*lbase self.newf = self.newf.xreplace({i: new}) self.backsubs.append((new, i)) # remove any duplicates logs = sorted(set(logs), key=default_sort_key) return logs, symlogs def _auto_attrs(self): """ Set attributes that are generated automatically. """ if not self.T: # i.e., when using the extension flag and T isn't given self.T = [i.gen for i in self.D] if not self.x: self.x = self.T[0] self.cases = [get_case(d, t) for d, t in zip(self.D, self.T)] self.level = -1 self.t = self.T[self.level] self.d = self.D[self.level] self.case = self.cases[self.level] def _exp_part(self, exps): """ Try to build an exponential extension. Returns ======= Returns True if there was a new extension, False if there was no new extension but it was able to rewrite the given exponentials in terms of the existing extension, and None if the entire extension building process should be restarted. If the process fails because there is no way around an algebraic extension (e.g., exp(log(x)/2)), it will raise NotImplementedError. """ from .prde import is_log_deriv_k_t_radical new_extension = False restart = False expargs = [i.exp for i in exps] ip = integer_powers(expargs) for arg, others in ip: # Minimize potential problems with algebraic substitution others.sort(key=lambda i: i[1]) arga, argd = frac_in(arg, self.t) A = is_log_deriv_k_t_radical(arga, argd, self) if A is not None: ans, u, n, const = A # if n is 1 or -1, it's algebraic, but we can handle it if n == -1: # This probably will never happen, because # Rational.as_numer_denom() returns the negative term in # the numerator. But in case that changes, reduce it to # n == 1. n = 1 u **= -1 const *= -1 ans = [(i, -j) for i, j in ans] if n == 1: # Example: exp(x + x**2) over QQ(x, exp(x), exp(x**2)) self.newf = self.newf.xreplace({exp(arg): exp(const)*Mul(*[ u**power for u, power in ans])}) self.newf = self.newf.xreplace({exp(p*exparg): exp(const*p) * Mul(*[u**power for u, power in ans]) for exparg, p in others}) # TODO: Add something to backsubs to put exp(const*p) # back together. continue else: # Bad news: we have an algebraic radical. But maybe we # could still avoid it by choosing a different extension. # For example, integer_powers() won't handle exp(x/2 + 1) # over QQ(x, exp(x)), but if we pull out the exp(1), it # will. Or maybe we have exp(x + x**2/2), over # QQ(x, exp(x), exp(x**2)), which is exp(x)*sqrt(exp(x**2)), # but if we use QQ(x, exp(x), exp(x**2/2)), then they will # all work. # # So here is what we do: If there is a non-zero const, pull # it out and retry. Also, if len(ans) > 1, then rewrite # exp(arg) as the product of exponentials from ans, and # retry that. If const == 0 and len(ans) == 1, then we # assume that it would have been handled by either # integer_powers() or n == 1 above if it could be handled, # so we give up at that point. For example, you can never # handle exp(log(x)/2) because it equals sqrt(x). if const or len(ans) > 1: rad = Mul(*[term**(power/n) for term, power in ans]) self.newf = self.newf.xreplace({exp(p*exparg): exp(const*p)*rad for exparg, p in others}) self.newf = self.newf.xreplace(dict(list(zip(reversed(self.T), reversed([f(self.x) for f in self.Tfuncs]))))) restart = True break else: # TODO: give algebraic dependence in error string raise NotImplementedError("Cannot integrate over " "algebraic extensions.") else: arga, argd = frac_in(arg, self.t) darga = (argd*derivation(Poly(arga, self.t), self) - arga*derivation(Poly(argd, self.t), self)) dargd = argd**2 darga, dargd = darga.cancel(dargd, include=True) darg = darga.as_expr()/dargd.as_expr() self.t = next(self.ts) self.T.append(self.t) self.extargs.append(arg) self.exts.append('exp') self.D.append(darg.as_poly(self.t, expand=False)*Poly(self.t, self.t, expand=False)) if self.dummy: i = Dummy("i") else: i = Symbol('i') self.Tfuncs += [Lambda(i, exp(arg.subs(self.x, i)))] self.newf = self.newf.xreplace( {exp(exparg): self.t**p for exparg, p in others}) new_extension = True if restart: return None return new_extension def _log_part(self, logs): """ Try to build a logarithmic extension. Returns ======= Returns True if there was a new extension and False if there was no new extension but it was able to rewrite the given logarithms in terms of the existing extension. Unlike with exponential extensions, there is no way that a logarithm is not transcendental over and cannot be rewritten in terms of an already existing extension in a non-algebraic way, so this function does not ever return None or raise NotImplementedError. """ from .prde import is_deriv_k new_extension = False logargs = [i.args[0] for i in logs] for arg in ordered(logargs): # The log case is easier, because whenever a logarithm is algebraic # over the base field, it is of the form a1*t1 + ... an*tn + c, # which is a polynomial, so we can just replace it with that. # In other words, we don't have to worry about radicals. arga, argd = frac_in(arg, self.t) A = is_deriv_k(arga, argd, self) if A is not None: ans, u, const = A newterm = log(const) + u self.newf = self.newf.xreplace({log(arg): newterm}) continue else: arga, argd = frac_in(arg, self.t) darga = (argd*derivation(Poly(arga, self.t), self) - arga*derivation(Poly(argd, self.t), self)) dargd = argd**2 darg = darga.as_expr()/dargd.as_expr() self.t = next(self.ts) self.T.append(self.t) self.extargs.append(arg) self.exts.append('log') self.D.append(cancel(darg.as_expr()/arg).as_poly(self.t, expand=False)) if self.dummy: i = Dummy("i") else: i = Symbol('i') self.Tfuncs += [Lambda(i, log(arg.subs(self.x, i)))] self.newf = self.newf.xreplace({log(arg): self.t}) new_extension = True return new_extension @property def _important_attrs(self): """ Returns some of the more important attributes of self. Explanation =========== Used for testing and debugging purposes. The attributes are (fa, fd, D, T, Tfuncs, backsubs, exts, extargs). """ return (self.fa, self.fd, self.D, self.T, self.Tfuncs, self.backsubs, self.exts, self.extargs) # NOTE: this printing doesn't follow the Python's standard # eval(repr(DE)) == DE, where DE is the DifferentialExtension object, # also this printing is supposed to contain all the important # attributes of a DifferentialExtension object def __repr__(self): # no need to have GeneratorType object printed in it r = [(attr, getattr(self, attr)) for attr in self.__slots__ if not isinstance(getattr(self, attr), GeneratorType)] return self.__class__.__name__ + '(dict(%r))' % (r) # fancy printing of DifferentialExtension object def __str__(self): return (self.__class__.__name__ + '({fa=%s, fd=%s, D=%s})' % (self.fa, self.fd, self.D)) # should only be used for debugging purposes, internally # f1 = f2 = log(x) at different places in code execution # may return D1 != D2 as True, since 'level' or other attribute # may differ def __eq__(self, other): for attr in self.__class__.__slots__: d1, d2 = getattr(self, attr), getattr(other, attr) if not (isinstance(d1, GeneratorType) or d1 == d2): return False return True def reset(self): """ Reset self to an initial state. Used by __init__. """ self.t = self.x self.T = [self.x] self.D = [Poly(1, self.x)] self.level = -1 self.exts = [None] self.extargs = [None] if self.dummy: self.ts = numbered_symbols('t', cls=Dummy) else: # For testing self.ts = numbered_symbols('t') # For various things that we change to make things work that we need to # change back when we are done. self.backsubs = [] self.Tfuncs = [] self.newf = self.f def indices(self, extension): """ Parameters ========== extension : str Represents a valid extension type. Returns ======= list: A list of indices of 'exts' where extension of type 'extension' is present. Examples ======== >>> from sympy.integrals.risch import DifferentialExtension >>> from sympy import log, exp >>> from sympy.abc import x >>> DE = DifferentialExtension(log(x) + exp(x), x, handle_first='exp') >>> DE.indices('log') [2] >>> DE.indices('exp') [1] """ return [i for i, ext in enumerate(self.exts) if ext == extension] def increment_level(self): """ Increment the level of self. Explanation =========== This makes the working differential extension larger. self.level is given relative to the end of the list (-1, -2, etc.), so we do not need do worry about it when building the extension. """ if self.level >= -1: raise ValueError("The level of the differential extension cannot " "be incremented any further.") self.level += 1 self.t = self.T[self.level] self.d = self.D[self.level] self.case = self.cases[self.level] return None def decrement_level(self): """ Decrease the level of self. Explanation =========== This makes the working differential extension smaller. self.level is given relative to the end of the list (-1, -2, etc.), so we do not need do worry about it when building the extension. """ if self.level <= -len(self.T): raise ValueError("The level of the differential extension cannot " "be decremented any further.") self.level -= 1 self.t = self.T[self.level] self.d = self.D[self.level] self.case = self.cases[self.level] return None def update_sets(seq, atoms, func): s = set(seq) s = atoms.intersection(s) new = atoms - s s.update(list(filter(func, new))) return list(s) class DecrementLevel: """ A context manager for decrementing the level of a DifferentialExtension. """ __slots__ = ('DE',) def __init__(self, DE): self.DE = DE return def __enter__(self): self.DE.decrement_level() def __exit__(self, exc_type, exc_value, traceback): self.DE.increment_level() class NonElementaryIntegralException(Exception): """ Exception used by subroutines within the Risch algorithm to indicate to one another that the function being integrated does not have an elementary integral in the given differential field. """ # TODO: Rewrite algorithms below to use this (?) # TODO: Pass through information about why the integral was nonelementary, # and store that in the resulting NonElementaryIntegral somehow. pass def gcdex_diophantine(a, b, c): """ Extended Euclidean Algorithm, Diophantine version. Explanation =========== Given ``a``, ``b`` in K[x] and ``c`` in (a, b), the ideal generated by ``a`` and ``b``, return (s, t) such that s*a + t*b == c and either s == 0 or s.degree() < b.degree(). """ # Extended Euclidean Algorithm (Diophantine Version) pg. 13 # TODO: This should go in densetools.py. # XXX: Bettter name? s, g = a.half_gcdex(b) s *= c.exquo(g) # Inexact division means c is not in (a, b) if s and s.degree() >= b.degree(): _, s = s.div(b) t = (c - s*a).exquo(b) return (s, t) def frac_in(f, t, *, cancel=False, **kwargs): """ Returns the tuple (fa, fd), where fa and fd are Polys in t. Explanation =========== This is a common idiom in the Risch Algorithm functions, so we abstract it out here. ``f`` should be a basic expression, a Poly, or a tuple (fa, fd), where fa and fd are either basic expressions or Polys, and f == fa/fd. **kwargs are applied to Poly. """ if isinstance(f, tuple): fa, fd = f f = fa.as_expr()/fd.as_expr() fa, fd = f.as_expr().as_numer_denom() fa, fd = fa.as_poly(t, **kwargs), fd.as_poly(t, **kwargs) if cancel: fa, fd = fa.cancel(fd, include=True) if fa is None or fd is None: raise ValueError("Could not turn %s into a fraction in %s." % (f, t)) return (fa, fd) def as_poly_1t(p, t, z): """ (Hackish) way to convert an element ``p`` of K[t, 1/t] to K[t, z]. In other words, ``z == 1/t`` will be a dummy variable that Poly can handle better. See issue 5131. Examples ======== >>> from sympy import random_poly >>> from sympy.integrals.risch import as_poly_1t >>> from sympy.abc import x, z >>> p1 = random_poly(x, 10, -10, 10) >>> p2 = random_poly(x, 10, -10, 10) >>> p = p1 + p2.subs(x, 1/x) >>> as_poly_1t(p, x, z).as_expr().subs(z, 1/x) == p True """ # TODO: Use this on the final result. That way, we can avoid answers like # (...)*exp(-x). pa, pd = frac_in(p, t, cancel=True) if not pd.is_monomial: # XXX: Is there a better Poly exception that we could raise here? # Either way, if you see this (from the Risch Algorithm) it indicates # a bug. raise PolynomialError("%s is not an element of K[%s, 1/%s]." % (p, t, t)) d = pd.degree(t) one_t_part = pa.slice(0, d + 1) r = pd.degree() - pa.degree() t_part = pa - one_t_part try: t_part = t_part.to_field().exquo(pd) except DomainError as e: # issue 4950 raise NotImplementedError(e) # Compute the negative degree parts. one_t_part = Poly.from_list(reversed(one_t_part.rep.rep), *one_t_part.gens, domain=one_t_part.domain) if 0 < r < oo: one_t_part *= Poly(t**r, t) one_t_part = one_t_part.replace(t, z) # z will be 1/t if pd.nth(d): one_t_part *= Poly(1/pd.nth(d), z, expand=False) ans = t_part.as_poly(t, z, expand=False) + one_t_part.as_poly(t, z, expand=False) return ans def derivation(p, DE, coefficientD=False, basic=False): """ Computes Dp. Explanation =========== Given the derivation D with D = d/dx and p is a polynomial in t over K(x), return Dp. If coefficientD is True, it computes the derivation kD (kappaD), which is defined as kD(sum(ai*Xi**i, (i, 0, n))) == sum(Dai*Xi**i, (i, 1, n)) (Definition 3.2.2, page 80). X in this case is T[-1], so coefficientD computes the derivative just with respect to T[:-1], with T[-1] treated as a constant. If ``basic=True``, the returns a Basic expression. Elements of D can still be instances of Poly. """ if basic: r = 0 else: r = Poly(0, DE.t) t = DE.t if coefficientD: if DE.level <= -len(DE.T): # 'base' case, the answer is 0. return r DE.decrement_level() D = DE.D[:len(DE.D) + DE.level + 1] T = DE.T[:len(DE.T) + DE.level + 1] for d, v in zip(D, T): pv = p.as_poly(v) if pv is None or basic: pv = p.as_expr() if basic: r += d.as_expr()*pv.diff(v) else: r += (d.as_expr()*pv.diff(v).as_expr()).as_poly(t) if basic: r = cancel(r) if coefficientD: DE.increment_level() return r def get_case(d, t): """ Returns the type of the derivation d. Returns one of {'exp', 'tan', 'base', 'primitive', 'other_linear', 'other_nonlinear'}. """ if not d.expr.has(t): if d.is_one: return 'base' return 'primitive' if d.rem(Poly(t, t)).is_zero: return 'exp' if d.rem(Poly(1 + t**2, t)).is_zero: return 'tan' if d.degree(t) > 1: return 'other_nonlinear' return 'other_linear' def splitfactor(p, DE, coefficientD=False, z=None): """ Splitting factorization. Explanation =========== Given a derivation D on k[t] and ``p`` in k[t], return (p_n, p_s) in k[t] x k[t] such that p = p_n*p_s, p_s is special, and each square factor of p_n is normal. Page. 100 """ kinv = [1/x for x in DE.T[:DE.level]] if z: kinv.append(z) One = Poly(1, DE.t, domain=p.get_domain()) Dp = derivation(p, DE, coefficientD=coefficientD) # XXX: Is this right? if p.is_zero: return (p, One) if not p.expr.has(DE.t): s = p.as_poly(*kinv).gcd(Dp.as_poly(*kinv)).as_poly(DE.t) n = p.exquo(s) return (n, s) if not Dp.is_zero: h = p.gcd(Dp).to_field() g = p.gcd(p.diff(DE.t)).to_field() s = h.exquo(g) if s.degree(DE.t) == 0: return (p, One) q_split = splitfactor(p.exquo(s), DE, coefficientD=coefficientD) return (q_split[0], q_split[1]*s) else: return (p, One) def splitfactor_sqf(p, DE, coefficientD=False, z=None, basic=False): """ Splitting Square-free Factorization. Explanation =========== Given a derivation D on k[t] and ``p`` in k[t], returns (N1, ..., Nm) and (S1, ..., Sm) in k[t]^m such that p = (N1*N2**2*...*Nm**m)*(S1*S2**2*...*Sm**m) is a splitting factorization of ``p`` and the Ni and Si are square-free and coprime. """ # TODO: This algorithm appears to be faster in every case # TODO: Verify this and splitfactor() for multiple extensions kkinv = [1/x for x in DE.T[:DE.level]] + DE.T[:DE.level] if z: kkinv = [z] S = [] N = [] p_sqf = p.sqf_list_include() if p.is_zero: return (((p, 1),), ()) for pi, i in p_sqf: Si = pi.as_poly(*kkinv).gcd(derivation(pi, DE, coefficientD=coefficientD,basic=basic).as_poly(*kkinv)).as_poly(DE.t) pi = Poly(pi, DE.t) Si = Poly(Si, DE.t) Ni = pi.exquo(Si) if not Si.is_one: S.append((Si, i)) if not Ni.is_one: N.append((Ni, i)) return (tuple(N), tuple(S)) def canonical_representation(a, d, DE): """ Canonical Representation. Explanation =========== Given a derivation D on k[t] and f = a/d in k(t), return (f_p, f_s, f_n) in k[t] x k(t) x k(t) such that f = f_p + f_s + f_n is the canonical representation of f (f_p is a polynomial, f_s is reduced (has a special denominator), and f_n is simple (has a normal denominator). """ # Make d monic l = Poly(1/d.LC(), DE.t) a, d = a.mul(l), d.mul(l) q, r = a.div(d) dn, ds = splitfactor(d, DE) b, c = gcdex_diophantine(dn.as_poly(DE.t), ds.as_poly(DE.t), r.as_poly(DE.t)) b, c = b.as_poly(DE.t), c.as_poly(DE.t) return (q, (b, ds), (c, dn)) def hermite_reduce(a, d, DE): """ Hermite Reduction - Mack's Linear Version. Given a derivation D on k(t) and f = a/d in k(t), returns g, h, r in k(t) such that f = Dg + h + r, h is simple, and r is reduced. """ # Make d monic l = Poly(1/d.LC(), DE.t) a, d = a.mul(l), d.mul(l) fp, fs, fn = canonical_representation(a, d, DE) a, d = fn l = Poly(1/d.LC(), DE.t) a, d = a.mul(l), d.mul(l) ga = Poly(0, DE.t) gd = Poly(1, DE.t) dd = derivation(d, DE) dm = gcd(d.to_field(), dd.to_field()).as_poly(DE.t) ds, _ = d.div(dm) while dm.degree(DE.t) > 0: ddm = derivation(dm, DE) dm2 = gcd(dm.to_field(), ddm.to_field()) dms, _ = dm.div(dm2) ds_ddm = ds.mul(ddm) ds_ddm_dm, _ = ds_ddm.div(dm) b, c = gcdex_diophantine(-ds_ddm_dm.as_poly(DE.t), dms.as_poly(DE.t), a.as_poly(DE.t)) b, c = b.as_poly(DE.t), c.as_poly(DE.t) db = derivation(b, DE).as_poly(DE.t) ds_dms, _ = ds.div(dms) a = c.as_poly(DE.t) - db.mul(ds_dms).as_poly(DE.t) ga = ga*dm + b*gd gd = gd*dm ga, gd = ga.cancel(gd, include=True) dm = dm2 q, r = a.div(ds) ga, gd = ga.cancel(gd, include=True) r, d = r.cancel(ds, include=True) rra = q*fs[1] + fp*fs[1] + fs[0] rrd = fs[1] rra, rrd = rra.cancel(rrd, include=True) return ((ga, gd), (r, d), (rra, rrd)) def polynomial_reduce(p, DE): """ Polynomial Reduction. Explanation =========== Given a derivation D on k(t) and p in k[t] where t is a nonlinear monomial over k, return q, r in k[t] such that p = Dq + r, and deg(r) < deg_t(Dt). """ q = Poly(0, DE.t) while p.degree(DE.t) >= DE.d.degree(DE.t): m = p.degree(DE.t) - DE.d.degree(DE.t) + 1 q0 = Poly(DE.t**m, DE.t).mul(Poly(p.as_poly(DE.t).LC()/ (m*DE.d.LC()), DE.t)) q += q0 p = p - derivation(q0, DE) return (q, p) def laurent_series(a, d, F, n, DE): """ Contribution of ``F`` to the full partial fraction decomposition of A/D. Explanation =========== Given a field K of characteristic 0 and ``A``,``D``,``F`` in K[x] with D monic, nonzero, coprime with A, and ``F`` the factor of multiplicity n in the square- free factorization of D, return the principal parts of the Laurent series of A/D at all the zeros of ``F``. """ if F.degree()==0: return 0 Z = _symbols('z', n) z = Symbol('z') Z.insert(0, z) delta_a = Poly(0, DE.t) delta_d = Poly(1, DE.t) E = d.quo(F**n) ha, hd = (a, E*Poly(z**n, DE.t)) dF = derivation(F,DE) B, _ = gcdex_diophantine(E, F, Poly(1,DE.t)) C, _ = gcdex_diophantine(dF, F, Poly(1,DE.t)) # initialization F_store = F V, DE_D_list, H_list= [], [], [] for j in range(0, n): # jth derivative of z would be substituted with dfnth/(j+1) where dfnth =(d^n)f/(dx)^n F_store = derivation(F_store, DE) v = (F_store.as_expr())/(j + 1) V.append(v) DE_D_list.append(Poly(Z[j + 1],Z[j])) DE_new = DifferentialExtension(extension = {'D': DE_D_list}) #a differential indeterminate for j in range(0, n): zEha = Poly(z**(n + j), DE.t)*E**(j + 1)*ha zEhd = hd Pa, Pd = cancel((zEha, zEhd))[1], cancel((zEha, zEhd))[2] Q = Pa.quo(Pd) for i in range(0, j + 1): Q = Q.subs(Z[i], V[i]) Dha = (hd*derivation(ha, DE, basic=True).as_poly(DE.t) + ha*derivation(hd, DE, basic=True).as_poly(DE.t) + hd*derivation(ha, DE_new, basic=True).as_poly(DE.t) + ha*derivation(hd, DE_new, basic=True).as_poly(DE.t)) Dhd = Poly(j + 1, DE.t)*hd**2 ha, hd = Dha, Dhd Ff, _ = F.div(gcd(F, Q)) F_stara, F_stard = frac_in(Ff, DE.t) if F_stara.degree(DE.t) - F_stard.degree(DE.t) > 0: QBC = Poly(Q, DE.t)*B**(1 + j)*C**(n + j) H = QBC H_list.append(H) H = (QBC*F_stard).rem(F_stara) alphas = real_roots(F_stara) for alpha in list(alphas): delta_a = delta_a*Poly((DE.t - alpha)**(n - j), DE.t) + Poly(H.eval(alpha), DE.t) delta_d = delta_d*Poly((DE.t - alpha)**(n - j), DE.t) return (delta_a, delta_d, H_list) def recognize_derivative(a, d, DE, z=None): """ Compute the squarefree factorization of the denominator of f and for each Di the polynomial H in K[x] (see Theorem 2.7.1), using the LaurentSeries algorithm. Write Di = GiEi where Gj = gcd(Hn, Di) and gcd(Ei,Hn) = 1. Since the residues of f at the roots of Gj are all 0, and the residue of f at a root alpha of Ei is Hi(a) != 0, f is the derivative of a rational function if and only if Ei = 1 for each i, which is equivalent to Di | H[-1] for each i. """ flag =True a, d = a.cancel(d, include=True) _, r = a.div(d) Np, Sp = splitfactor_sqf(d, DE, coefficientD=True, z=z) j = 1 for s, _ in Sp: delta_a, delta_d, H = laurent_series(r, d, s, j, DE) g = gcd(d, H[-1]).as_poly() if g is not d: flag = False break j = j + 1 return flag def recognize_log_derivative(a, d, DE, z=None): """ There exists a v in K(x)* such that f = dv/v where f a rational function if and only if f can be written as f = A/D where D is squarefree,deg(A) < deg(D), gcd(A, D) = 1, and all the roots of the Rothstein-Trager resultant are integers. In that case, any of the Rothstein-Trager, Lazard-Rioboo-Trager or Czichowski algorithm produces u in K(x) such that du/dx = uf. """ z = z or Dummy('z') a, d = a.cancel(d, include=True) _, a = a.div(d) pz = Poly(z, DE.t) Dd = derivation(d, DE) q = a - pz*Dd r, _ = d.resultant(q, includePRS=True) r = Poly(r, z) Np, Sp = splitfactor_sqf(r, DE, coefficientD=True, z=z) for s, _ in Sp: # TODO also consider the complex roots which should # turn the flag false a = real_roots(s.as_poly(z)) if not all(j.is_Integer for j in a): return False return True def residue_reduce(a, d, DE, z=None, invert=True): """ Lazard-Rioboo-Rothstein-Trager resultant reduction. Explanation =========== Given a derivation ``D`` on k(t) and f in k(t) simple, return g elementary over k(t) and a Boolean b in {True, False} such that f - Dg in k[t] if b == True or f + h and f + h - Dg do not have an elementary integral over k(t) for any h in k<t> (reduced) if b == False. Returns (G, b), where G is a tuple of tuples of the form (s_i, S_i), such that g = Add(*[RootSum(s_i, lambda z: z*log(S_i(z, t))) for S_i, s_i in G]). f - Dg is the remaining integral, which is elementary only if b == True, and hence the integral of f is elementary only if b == True. f - Dg is not calculated in this function because that would require explicitly calculating the RootSum. Use residue_reduce_derivation(). """ # TODO: Use log_to_atan() from rationaltools.py # If r = residue_reduce(...), then the logarithmic part is given by: # sum([RootSum(a[0].as_poly(z), lambda i: i*log(a[1].as_expr()).subs(z, # i)).subs(t, log(x)) for a in r[0]]) z = z or Dummy('z') a, d = a.cancel(d, include=True) a, d = a.to_field().mul_ground(1/d.LC()), d.to_field().mul_ground(1/d.LC()) kkinv = [1/x for x in DE.T[:DE.level]] + DE.T[:DE.level] if a.is_zero: return ([], True) _, a = a.div(d) pz = Poly(z, DE.t) Dd = derivation(d, DE) q = a - pz*Dd if Dd.degree(DE.t) <= d.degree(DE.t): r, R = d.resultant(q, includePRS=True) else: r, R = q.resultant(d, includePRS=True) R_map, H = {}, [] for i in R: R_map[i.degree()] = i r = Poly(r, z) Np, Sp = splitfactor_sqf(r, DE, coefficientD=True, z=z) for s, i in Sp: if i == d.degree(DE.t): s = Poly(s, z).monic() H.append((s, d)) else: h = R_map.get(i) if h is None: continue h_lc = Poly(h.as_poly(DE.t).LC(), DE.t, field=True) h_lc_sqf = h_lc.sqf_list_include(all=True) for a, j in h_lc_sqf: h = Poly(h, DE.t, field=True).exquo(Poly(gcd(a, s**j, *kkinv), DE.t)) s = Poly(s, z).monic() if invert: h_lc = Poly(h.as_poly(DE.t).LC(), DE.t, field=True, expand=False) inv, coeffs = h_lc.as_poly(z, field=True).invert(s), [S.One] for coeff in h.coeffs()[1:]: L = reduced(inv*coeff.as_poly(inv.gens), [s])[1] coeffs.append(L.as_expr()) h = Poly(dict(list(zip(h.monoms(), coeffs))), DE.t) H.append((s, h)) b = not any(cancel(i.as_expr()).has(DE.t, z) for i, _ in Np) return (H, b) def residue_reduce_to_basic(H, DE, z): """ Converts the tuple returned by residue_reduce() into a Basic expression. """ # TODO: check what Lambda does with RootOf i = Dummy('i') s = list(zip(reversed(DE.T), reversed([f(DE.x) for f in DE.Tfuncs]))) return sum(RootSum(a[0].as_poly(z), Lambda(i, i*log(a[1].as_expr()).subs( {z: i}).subs(s))) for a in H) def residue_reduce_derivation(H, DE, z): """ Computes the derivation of an expression returned by residue_reduce(). In general, this is a rational function in t, so this returns an as_expr() result. """ # TODO: verify that this is correct for multiple extensions i = Dummy('i') return S(sum(RootSum(a[0].as_poly(z), Lambda(i, i*derivation(a[1], DE).as_expr().subs(z, i)/a[1].as_expr().subs(z, i))) for a in H)) def integrate_primitive_polynomial(p, DE): """ Integration of primitive polynomials. Explanation =========== Given a primitive monomial t over k, and ``p`` in k[t], return q in k[t], r in k, and a bool b in {True, False} such that r = p - Dq is in k if b is True, or r = p - Dq does not have an elementary integral over k(t) if b is False. """ Zero = Poly(0, DE.t) q = Poly(0, DE.t) if not p.expr.has(DE.t): return (Zero, p, True) from .prde import limited_integrate while True: if not p.expr.has(DE.t): return (q, p, True) Dta, Dtb = frac_in(DE.d, DE.T[DE.level - 1]) with DecrementLevel(DE): # We had better be integrating the lowest extension (x) # with ratint(). a = p.LC() aa, ad = frac_in(a, DE.t) try: rv = limited_integrate(aa, ad, [(Dta, Dtb)], DE) if rv is None: raise NonElementaryIntegralException (ba, bd), c = rv except NonElementaryIntegralException: return (q, p, False) m = p.degree(DE.t) q0 = c[0].as_poly(DE.t)*Poly(DE.t**(m + 1)/(m + 1), DE.t) + \ (ba.as_expr()/bd.as_expr()).as_poly(DE.t)*Poly(DE.t**m, DE.t) p = p - derivation(q0, DE) q = q + q0 def integrate_primitive(a, d, DE, z=None): """ Integration of primitive functions. Explanation =========== Given a primitive monomial t over k and f in k(t), return g elementary over k(t), i in k(t), and b in {True, False} such that i = f - Dg is in k if b is True or i = f - Dg does not have an elementary integral over k(t) if b is False. This function returns a Basic expression for the first argument. If b is True, the second argument is Basic expression in k to recursively integrate. If b is False, the second argument is an unevaluated Integral, which has been proven to be nonelementary. """ # XXX: a and d must be canceled, or this might return incorrect results z = z or Dummy("z") s = list(zip(reversed(DE.T), reversed([f(DE.x) for f in DE.Tfuncs]))) g1, h, r = hermite_reduce(a, d, DE) g2, b = residue_reduce(h[0], h[1], DE, z=z) if not b: i = cancel(a.as_expr()/d.as_expr() - (g1[1]*derivation(g1[0], DE) - g1[0]*derivation(g1[1], DE)).as_expr()/(g1[1]**2).as_expr() - residue_reduce_derivation(g2, DE, z)) i = NonElementaryIntegral(cancel(i).subs(s), DE.x) return ((g1[0].as_expr()/g1[1].as_expr()).subs(s) + residue_reduce_to_basic(g2, DE, z), i, b) # h - Dg2 + r p = cancel(h[0].as_expr()/h[1].as_expr() - residue_reduce_derivation(g2, DE, z) + r[0].as_expr()/r[1].as_expr()) p = p.as_poly(DE.t) q, i, b = integrate_primitive_polynomial(p, DE) ret = ((g1[0].as_expr()/g1[1].as_expr() + q.as_expr()).subs(s) + residue_reduce_to_basic(g2, DE, z)) if not b: # TODO: This does not do the right thing when b is False i = NonElementaryIntegral(cancel(i.as_expr()).subs(s), DE.x) else: i = cancel(i.as_expr()) return (ret, i, b) def integrate_hyperexponential_polynomial(p, DE, z): """ Integration of hyperexponential polynomials. Explanation =========== Given a hyperexponential monomial t over k and ``p`` in k[t, 1/t], return q in k[t, 1/t] and a bool b in {True, False} such that p - Dq in k if b is True, or p - Dq does not have an elementary integral over k(t) if b is False. """ t1 = DE.t dtt = DE.d.exquo(Poly(DE.t, DE.t)) qa = Poly(0, DE.t) qd = Poly(1, DE.t) b = True if p.is_zero: return(qa, qd, b) from sympy.integrals.rde import rischDE with DecrementLevel(DE): for i in range(-p.degree(z), p.degree(t1) + 1): if not i: continue elif i < 0: # If you get AttributeError: 'NoneType' object has no attribute 'nth' # then this should really not have expand=False # But it shouldn't happen because p is already a Poly in t and z a = p.as_poly(z, expand=False).nth(-i) else: # If you get AttributeError: 'NoneType' object has no attribute 'nth' # then this should really not have expand=False a = p.as_poly(t1, expand=False).nth(i) aa, ad = frac_in(a, DE.t, field=True) aa, ad = aa.cancel(ad, include=True) iDt = Poly(i, t1)*dtt iDta, iDtd = frac_in(iDt, DE.t, field=True) try: va, vd = rischDE(iDta, iDtd, Poly(aa, DE.t), Poly(ad, DE.t), DE) va, vd = frac_in((va, vd), t1, cancel=True) except NonElementaryIntegralException: b = False else: qa = qa*vd + va*Poly(t1**i)*qd qd *= vd return (qa, qd, b) def integrate_hyperexponential(a, d, DE, z=None, conds='piecewise'): """ Integration of hyperexponential functions. Explanation =========== Given a hyperexponential monomial t over k and f in k(t), return g elementary over k(t), i in k(t), and a bool b in {True, False} such that i = f - Dg is in k if b is True or i = f - Dg does not have an elementary integral over k(t) if b is False. This function returns a Basic expression for the first argument. If b is True, the second argument is Basic expression in k to recursively integrate. If b is False, the second argument is an unevaluated Integral, which has been proven to be nonelementary. """ # XXX: a and d must be canceled, or this might return incorrect results z = z or Dummy("z") s = list(zip(reversed(DE.T), reversed([f(DE.x) for f in DE.Tfuncs]))) g1, h, r = hermite_reduce(a, d, DE) g2, b = residue_reduce(h[0], h[1], DE, z=z) if not b: i = cancel(a.as_expr()/d.as_expr() - (g1[1]*derivation(g1[0], DE) - g1[0]*derivation(g1[1], DE)).as_expr()/(g1[1]**2).as_expr() - residue_reduce_derivation(g2, DE, z)) i = NonElementaryIntegral(cancel(i.subs(s)), DE.x) return ((g1[0].as_expr()/g1[1].as_expr()).subs(s) + residue_reduce_to_basic(g2, DE, z), i, b) # p should be a polynomial in t and 1/t, because Sirr == k[t, 1/t] # h - Dg2 + r p = cancel(h[0].as_expr()/h[1].as_expr() - residue_reduce_derivation(g2, DE, z) + r[0].as_expr()/r[1].as_expr()) pp = as_poly_1t(p, DE.t, z) qa, qd, b = integrate_hyperexponential_polynomial(pp, DE, z) i = pp.nth(0, 0) ret = ((g1[0].as_expr()/g1[1].as_expr()).subs(s) \ + residue_reduce_to_basic(g2, DE, z)) qas = qa.as_expr().subs(s) qds = qd.as_expr().subs(s) if conds == 'piecewise' and DE.x not in qds.free_symbols: # We have to be careful if the exponent is S.Zero! # XXX: Does qd = 0 always necessarily correspond to the exponential # equaling 1? ret += Piecewise( (qas/qds, Ne(qds, 0)), (integrate((p - i).subs(DE.t, 1).subs(s), DE.x), True) ) else: ret += qas/qds if not b: i = p - (qd*derivation(qa, DE) - qa*derivation(qd, DE)).as_expr()/\ (qd**2).as_expr() i = NonElementaryIntegral(cancel(i).subs(s), DE.x) return (ret, i, b) def integrate_hypertangent_polynomial(p, DE): """ Integration of hypertangent polynomials. Explanation =========== Given a differential field k such that sqrt(-1) is not in k, a hypertangent monomial t over k, and p in k[t], return q in k[t] and c in k such that p - Dq - c*D(t**2 + 1)/(t**1 + 1) is in k and p - Dq does not have an elementary integral over k(t) if Dc != 0. """ # XXX: Make sure that sqrt(-1) is not in k. q, r = polynomial_reduce(p, DE) a = DE.d.exquo(Poly(DE.t**2 + 1, DE.t)) c = Poly(r.nth(1)/(2*a.as_expr()), DE.t) return (q, c) def integrate_nonlinear_no_specials(a, d, DE, z=None): """ Integration of nonlinear monomials with no specials. Explanation =========== Given a nonlinear monomial t over k such that Sirr ({p in k[t] | p is special, monic, and irreducible}) is empty, and f in k(t), returns g elementary over k(t) and a Boolean b in {True, False} such that f - Dg is in k if b == True, or f - Dg does not have an elementary integral over k(t) if b == False. This function is applicable to all nonlinear extensions, but in the case where it returns b == False, it will only have proven that the integral of f - Dg is nonelementary if Sirr is empty. This function returns a Basic expression. """ # TODO: Integral from k? # TODO: split out nonelementary integral # XXX: a and d must be canceled, or this might not return correct results z = z or Dummy("z") s = list(zip(reversed(DE.T), reversed([f(DE.x) for f in DE.Tfuncs]))) g1, h, r = hermite_reduce(a, d, DE) g2, b = residue_reduce(h[0], h[1], DE, z=z) if not b: return ((g1[0].as_expr()/g1[1].as_expr()).subs(s) + residue_reduce_to_basic(g2, DE, z), b) # Because f has no specials, this should be a polynomial in t, or else # there is a bug. p = cancel(h[0].as_expr()/h[1].as_expr() - residue_reduce_derivation(g2, DE, z).as_expr() + r[0].as_expr()/r[1].as_expr()).as_poly(DE.t) q1, q2 = polynomial_reduce(p, DE) if q2.expr.has(DE.t): b = False else: b = True ret = (cancel(g1[0].as_expr()/g1[1].as_expr() + q1.as_expr()).subs(s) + residue_reduce_to_basic(g2, DE, z)) return (ret, b) class NonElementaryIntegral(Integral): """ Represents a nonelementary Integral. Explanation =========== If the result of integrate() is an instance of this class, it is guaranteed to be nonelementary. Note that integrate() by default will try to find any closed-form solution, even in terms of special functions which may themselves not be elementary. To make integrate() only give elementary solutions, or, in the cases where it can prove the integral to be nonelementary, instances of this class, use integrate(risch=True). In this case, integrate() may raise NotImplementedError if it cannot make such a determination. integrate() uses the deterministic Risch algorithm to integrate elementary functions or prove that they have no elementary integral. In some cases, this algorithm can split an integral into an elementary and nonelementary part, so that the result of integrate will be the sum of an elementary expression and a NonElementaryIntegral. Examples ======== >>> from sympy import integrate, exp, log, Integral >>> from sympy.abc import x >>> a = integrate(exp(-x**2), x, risch=True) >>> print(a) Integral(exp(-x**2), x) >>> type(a) <class 'sympy.integrals.risch.NonElementaryIntegral'> >>> expr = (2*log(x)**2 - log(x) - x**2)/(log(x)**3 - x**2*log(x)) >>> b = integrate(expr, x, risch=True) >>> print(b) -log(-x + log(x))/2 + log(x + log(x))/2 + Integral(1/log(x), x) >>> type(b.atoms(Integral).pop()) <class 'sympy.integrals.risch.NonElementaryIntegral'> """ # TODO: This is useful in and of itself, because isinstance(result, # NonElementaryIntegral) will tell if the integral has been proven to be # elementary. But should we do more? Perhaps a no-op .doit() if # elementary=True? Or maybe some information on why the integral is # nonelementary. pass def risch_integrate(f, x, extension=None, handle_first='log', separate_integral=False, rewrite_complex=None, conds='piecewise'): r""" The Risch Integration Algorithm. Explanation =========== Only transcendental functions are supported. Currently, only exponentials and logarithms are supported, but support for trigonometric functions is forthcoming. If this function returns an unevaluated Integral in the result, it means that it has proven that integral to be nonelementary. Any errors will result in raising NotImplementedError. The unevaluated Integral will be an instance of NonElementaryIntegral, a subclass of Integral. handle_first may be either 'exp' or 'log'. This changes the order in which the extension is built, and may result in a different (but equivalent) solution (for an example of this, see issue 5109). It is also possible that the integral may be computed with one but not the other, because not all cases have been implemented yet. It defaults to 'log' so that the outer extension is exponential when possible, because more of the exponential case has been implemented. If ``separate_integral`` is ``True``, the result is returned as a tuple (ans, i), where the integral is ans + i, ans is elementary, and i is either a NonElementaryIntegral or 0. This useful if you want to try further integrating the NonElementaryIntegral part using other algorithms to possibly get a solution in terms of special functions. It is False by default. Examples ======== >>> from sympy.integrals.risch import risch_integrate >>> from sympy import exp, log, pprint >>> from sympy.abc import x First, we try integrating exp(-x**2). Except for a constant factor of 2/sqrt(pi), this is the famous error function. >>> pprint(risch_integrate(exp(-x**2), x)) / | | 2 | -x | e dx | / The unevaluated Integral in the result means that risch_integrate() has proven that exp(-x**2) does not have an elementary anti-derivative. In many cases, risch_integrate() can split out the elementary anti-derivative part from the nonelementary anti-derivative part. For example, >>> pprint(risch_integrate((2*log(x)**2 - log(x) - x**2)/(log(x)**3 - ... x**2*log(x)), x)) / | log(-x + log(x)) log(x + log(x)) | 1 - ---------------- + --------------- + | ------ dx 2 2 | log(x) | / This means that it has proven that the integral of 1/log(x) is nonelementary. This function is also known as the logarithmic integral, and is often denoted as Li(x). risch_integrate() currently only accepts purely transcendental functions with exponentials and logarithms, though note that this can include nested exponentials and logarithms, as well as exponentials with bases other than E. >>> pprint(risch_integrate(exp(x)*exp(exp(x)), x)) / x\ \e / e >>> pprint(risch_integrate(exp(exp(x)), x)) / | | / x\ | \e / | e dx | / >>> pprint(risch_integrate(x*x**x*log(x) + x**x + x*x**x, x)) x x*x >>> pprint(risch_integrate(x**x, x)) / | | x | x dx | / >>> pprint(risch_integrate(-1/(x*log(x)*log(log(x))**2), x)) 1 ----------- log(log(x)) """ f = S(f) DE = extension or DifferentialExtension(f, x, handle_first=handle_first, dummy=True, rewrite_complex=rewrite_complex) fa, fd = DE.fa, DE.fd result = S.Zero for case in reversed(DE.cases): if not fa.expr.has(DE.t) and not fd.expr.has(DE.t) and not case == 'base': DE.decrement_level() fa, fd = frac_in((fa, fd), DE.t) continue fa, fd = fa.cancel(fd, include=True) if case == 'exp': ans, i, b = integrate_hyperexponential(fa, fd, DE, conds=conds) elif case == 'primitive': ans, i, b = integrate_primitive(fa, fd, DE) elif case == 'base': # XXX: We can't call ratint() directly here because it doesn't # handle polynomials correctly. ans = integrate(fa.as_expr()/fd.as_expr(), DE.x, risch=False) b = False i = S.Zero else: raise NotImplementedError("Only exponential and logarithmic " "extensions are currently supported.") result += ans if b: DE.decrement_level() fa, fd = frac_in(i, DE.t) else: result = result.subs(DE.backsubs) if not i.is_zero: i = NonElementaryIntegral(i.function.subs(DE.backsubs),i.limits) if not separate_integral: result += i return result else: if isinstance(i, NonElementaryIntegral): return (result, i) else: return (result, 0)
ca3321e84065fe9f5c507251bfea9b897074e94c30030cacff8e092ad86da4a1
""" Algorithms for solving Parametric Risch Differential Equations. The methods used for solving Parametric Risch Differential Equations parallel those for solving Risch Differential Equations. See the outline in the docstring of rde.py for more information. The Parametric Risch Differential Equation problem is, given f, g1, ..., gm in K(t), to determine if there exist y in K(t) and c1, ..., cm in Const(K) such that Dy + f*y == Sum(ci*gi, (i, 1, m)), and to find such y and ci if they exist. For the algorithms here G is a list of tuples of factions of the terms on the right hand side of the equation (i.e., gi in k(t)), and Q is a list of terms on the right hand side of the equation (i.e., qi in k[t]). See the docstring of each function for more information. """ import itertools from functools import reduce from sympy.core import Dummy, ilcm, Add, Mul, Pow, S from sympy.integrals.rde import (order_at, order_at_oo, weak_normalizer, bound_degree) from sympy.integrals.risch import (gcdex_diophantine, frac_in, derivation, residue_reduce, splitfactor, residue_reduce_derivation, DecrementLevel, recognize_log_derivative) from sympy.polys import Poly, lcm, cancel, sqf_list from sympy.polys.polymatrix import PolyMatrix as Matrix from sympy.solvers import solve zeros = Matrix.zeros eye = Matrix.eye def prde_normal_denom(fa, fd, G, DE): """ Parametric Risch Differential Equation - Normal part of the denominator. Explanation =========== Given a derivation D on k[t] and f, g1, ..., gm in k(t) with f weakly normalized with respect to t, return the tuple (a, b, G, h) such that a, h in k[t], b in k<t>, G = [g1, ..., gm] in k(t)^m, and for any solution c1, ..., cm in Const(k) and y in k(t) of Dy + f*y == Sum(ci*gi, (i, 1, m)), q == y*h in k<t> satisfies a*Dq + b*q == Sum(ci*Gi, (i, 1, m)). """ dn, ds = splitfactor(fd, DE) Gas, Gds = list(zip(*G)) gd = reduce(lambda i, j: i.lcm(j), Gds, Poly(1, DE.t)) en, es = splitfactor(gd, DE) p = dn.gcd(en) h = en.gcd(en.diff(DE.t)).quo(p.gcd(p.diff(DE.t))) a = dn*h c = a*h ba = a*fa - dn*derivation(h, DE)*fd ba, bd = ba.cancel(fd, include=True) G = [(c*A).cancel(D, include=True) for A, D in G] return (a, (ba, bd), G, h) def real_imag(ba, bd, gen): """ Helper function, to get the real and imaginary part of a rational function evaluated at sqrt(-1) without actually evaluating it at sqrt(-1). Explanation =========== Separates the even and odd power terms by checking the degree of terms wrt mod 4. Returns a tuple (ba[0], ba[1], bd) where ba[0] is real part of the numerator ba[1] is the imaginary part and bd is the denominator of the rational function. """ bd = bd.as_poly(gen).as_dict() ba = ba.as_poly(gen).as_dict() denom_real = [value if key[0] % 4 == 0 else -value if key[0] % 4 == 2 else 0 for key, value in bd.items()] denom_imag = [value if key[0] % 4 == 1 else -value if key[0] % 4 == 3 else 0 for key, value in bd.items()] bd_real = sum(r for r in denom_real) bd_imag = sum(r for r in denom_imag) num_real = [value if key[0] % 4 == 0 else -value if key[0] % 4 == 2 else 0 for key, value in ba.items()] num_imag = [value if key[0] % 4 == 1 else -value if key[0] % 4 == 3 else 0 for key, value in ba.items()] ba_real = sum(r for r in num_real) ba_imag = sum(r for r in num_imag) ba = ((ba_real*bd_real + ba_imag*bd_imag).as_poly(gen), (ba_imag*bd_real - ba_real*bd_imag).as_poly(gen)) bd = (bd_real*bd_real + bd_imag*bd_imag).as_poly(gen) return (ba[0], ba[1], bd) def prde_special_denom(a, ba, bd, G, DE, case='auto'): """ Parametric Risch Differential Equation - Special part of the denominator. Explanation =========== Case is one of {'exp', 'tan', 'primitive'} for the hyperexponential, hypertangent, and primitive cases, respectively. For the hyperexponential (resp. hypertangent) case, given a derivation D on k[t] and a in k[t], b in k<t>, and g1, ..., gm in k(t) with Dt/t in k (resp. Dt/(t**2 + 1) in k, sqrt(-1) not in k), a != 0, and gcd(a, t) == 1 (resp. gcd(a, t**2 + 1) == 1), return the tuple (A, B, GG, h) such that A, B, h in k[t], GG = [gg1, ..., ggm] in k(t)^m, and for any solution c1, ..., cm in Const(k) and q in k<t> of a*Dq + b*q == Sum(ci*gi, (i, 1, m)), r == q*h in k[t] satisfies A*Dr + B*r == Sum(ci*ggi, (i, 1, m)). For case == 'primitive', k<t> == k[t], so it returns (a, b, G, 1) in this case. """ # TODO: Merge this with the very similar special_denom() in rde.py if case == 'auto': case = DE.case if case == 'exp': p = Poly(DE.t, DE.t) elif case == 'tan': p = Poly(DE.t**2 + 1, DE.t) elif case in ('primitive', 'base'): B = ba.quo(bd) return (a, B, G, Poly(1, DE.t)) else: raise ValueError("case must be one of {'exp', 'tan', 'primitive', " "'base'}, not %s." % case) nb = order_at(ba, p, DE.t) - order_at(bd, p, DE.t) nc = min([order_at(Ga, p, DE.t) - order_at(Gd, p, DE.t) for Ga, Gd in G]) n = min(0, nc - min(0, nb)) if not nb: # Possible cancellation. if case == 'exp': dcoeff = DE.d.quo(Poly(DE.t, DE.t)) with DecrementLevel(DE): # We are guaranteed to not have problems, # because case != 'base'. alphaa, alphad = frac_in(-ba.eval(0)/bd.eval(0)/a.eval(0), DE.t) etaa, etad = frac_in(dcoeff, DE.t) A = parametric_log_deriv(alphaa, alphad, etaa, etad, DE) if A is not None: Q, m, z = A if Q == 1: n = min(n, m) elif case == 'tan': dcoeff = DE.d.quo(Poly(DE.t**2 + 1, DE.t)) with DecrementLevel(DE): # We are guaranteed to not have problems, # because case != 'base'. betaa, alphaa, alphad = real_imag(ba, bd*a, DE.t) betad = alphad etaa, etad = frac_in(dcoeff, DE.t) if recognize_log_derivative(Poly(2, DE.t)*betaa, betad, DE): A = parametric_log_deriv(alphaa, alphad, etaa, etad, DE) B = parametric_log_deriv(betaa, betad, etaa, etad, DE) if A is not None and B is not None: Q, s, z = A # TODO: Add test if Q == 1: n = min(n, s/2) N = max(0, -nb) pN = p**N pn = p**-n # This is 1/h A = a*pN B = ba*pN.quo(bd) + Poly(n, DE.t)*a*derivation(p, DE).quo(p)*pN G = [(Ga*pN*pn).cancel(Gd, include=True) for Ga, Gd in G] h = pn # (a*p**N, (b + n*a*Dp/p)*p**N, g1*p**(N - n), ..., gm*p**(N - n), p**-n) return (A, B, G, h) def prde_linear_constraints(a, b, G, DE): """ Parametric Risch Differential Equation - Generate linear constraints on the constants. Explanation =========== Given a derivation D on k[t], a, b, in k[t] with gcd(a, b) == 1, and G = [g1, ..., gm] in k(t)^m, return Q = [q1, ..., qm] in k[t]^m and a matrix M with entries in k(t) such that for any solution c1, ..., cm in Const(k) and p in k[t] of a*Dp + b*p == Sum(ci*gi, (i, 1, m)), (c1, ..., cm) is a solution of Mx == 0, and p and the ci satisfy a*Dp + b*p == Sum(ci*qi, (i, 1, m)). Because M has entries in k(t), and because Matrix does not play well with Poly, M will be a Matrix of Basic expressions. """ m = len(G) Gns, Gds = list(zip(*G)) d = reduce(lambda i, j: i.lcm(j), Gds) d = Poly(d, field=True) Q = [(ga*(d).quo(gd)).div(d) for ga, gd in G] if not all(ri.is_zero for _, ri in Q): N = max(ri.degree(DE.t) for _, ri in Q) M = Matrix(N + 1, m, lambda i, j: Q[j][1].nth(i), DE.t) else: M = Matrix(0, m, [], DE.t) # No constraints, return the empty matrix. qs, _ = list(zip(*Q)) return (qs, M) def poly_linear_constraints(p, d): """ Given p = [p1, ..., pm] in k[t]^m and d in k[t], return q = [q1, ..., qm] in k[t]^m and a matrix M with entries in k such that Sum(ci*pi, (i, 1, m)), for c1, ..., cm in k, is divisible by d if and only if (c1, ..., cm) is a solution of Mx = 0, in which case the quotient is Sum(ci*qi, (i, 1, m)). """ m = len(p) q, r = zip(*[pi.div(d) for pi in p]) if not all(ri.is_zero for ri in r): n = max(ri.degree() for ri in r) M = Matrix(n + 1, m, lambda i, j: r[j].nth(i), d.gens) else: M = Matrix(0, m, [], d.gens) # No constraints. return q, M def constant_system(A, u, DE): """ Generate a system for the constant solutions. Explanation =========== Given a differential field (K, D) with constant field C = Const(K), a Matrix A, and a vector (Matrix) u with coefficients in K, returns the tuple (B, v, s), where B is a Matrix with coefficients in C and v is a vector (Matrix) such that either v has coefficients in C, in which case s is True and the solutions in C of Ax == u are exactly all the solutions of Bx == v, or v has a non-constant coefficient, in which case s is False Ax == u has no constant solution. This algorithm is used both in solving parametric problems and in determining if an element a of K is a derivative of an element of K or the logarithmic derivative of a K-radical using the structure theorem approach. Because Poly does not play well with Matrix yet, this algorithm assumes that all matrix entries are Basic expressions. """ if not A: return A, u Au = A.row_join(u) Au, _ = Au.rref() # Warning: This will NOT return correct results if cancel() cannot reduce # an identically zero expression to 0. The danger is that we might # incorrectly prove that an integral is nonelementary (such as # risch_integrate(exp((sin(x)**2 + cos(x)**2 - 1)*x**2), x). # But this is a limitation in computer algebra in general, and implicit # in the correctness of the Risch Algorithm is the computability of the # constant field (actually, this same correctness problem exists in any # algorithm that uses rref()). # # We therefore limit ourselves to constant fields that are computable # via the cancel() function, in order to prevent a speed bottleneck from # calling some more complex simplification function (rational function # coefficients will fall into this class). Furthermore, (I believe) this # problem will only crop up if the integral explicitly contains an # expression in the constant field that is identically zero, but cannot # be reduced to such by cancel(). Therefore, a careful user can avoid this # problem entirely by being careful with the sorts of expressions that # appear in his integrand in the variables other than the integration # variable (the structure theorems should be able to completely decide these # problems in the integration variable). A, u = Au[:, :-1], Au[:, -1] D = lambda x: derivation(x, DE, basic=True) for j, i in itertools.product(range(A.cols), range(A.rows)): if A[i, j].expr.has(*DE.T): # This assumes that const(F(t0, ..., tn) == const(K) == F Ri = A[i, :] # Rm+1; m = A.rows DAij = D(A[i, j]) Rm1 = Ri.applyfunc(lambda x: D(x) / DAij) um1 = D(u[i]) / DAij Aj = A[:, j] A = A - Aj * Rm1 u = u - Aj * um1 A = A.col_join(Rm1) u = u.col_join(Matrix([um1], u.gens)) return (A, u) def prde_spde(a, b, Q, n, DE): """ Special Polynomial Differential Equation algorithm: Parametric Version. Explanation =========== Given a derivation D on k[t], an integer n, and a, b, q1, ..., qm in k[t] with deg(a) > 0 and gcd(a, b) == 1, return (A, B, Q, R, n1), with Qq = [q1, ..., qm] and R = [r1, ..., rm], such that for any solution c1, ..., cm in Const(k) and q in k[t] of degree at most n of a*Dq + b*q == Sum(ci*gi, (i, 1, m)), p = (q - Sum(ci*ri, (i, 1, m)))/a has degree at most n1 and satisfies A*Dp + B*p == Sum(ci*qi, (i, 1, m)) """ R, Z = list(zip(*[gcdex_diophantine(b, a, qi) for qi in Q])) A = a B = b + derivation(a, DE) Qq = [zi - derivation(ri, DE) for ri, zi in zip(R, Z)] R = list(R) n1 = n - a.degree(DE.t) return (A, B, Qq, R, n1) def prde_no_cancel_b_large(b, Q, n, DE): """ Parametric Poly Risch Differential Equation - No cancellation: deg(b) large enough. Explanation =========== Given a derivation D on k[t], n in ZZ, and b, q1, ..., qm in k[t] with b != 0 and either D == d/dt or deg(b) > max(0, deg(D) - 1), returns h1, ..., hr in k[t] and a matrix A with coefficients in Const(k) such that if c1, ..., cm in Const(k) and q in k[t] satisfy deg(q) <= n and Dq + b*q == Sum(ci*qi, (i, 1, m)), then q = Sum(dj*hj, (j, 1, r)), where d1, ..., dr in Const(k) and A*Matrix([[c1, ..., cm, d1, ..., dr]]).T == 0. """ db = b.degree(DE.t) m = len(Q) H = [Poly(0, DE.t)]*m for N, i in itertools.product(range(n, -1, -1), range(m)): # [n, ..., 0] si = Q[i].nth(N + db)/b.LC() sitn = Poly(si*DE.t**N, DE.t) H[i] = H[i] + sitn Q[i] = Q[i] - derivation(sitn, DE) - b*sitn if all(qi.is_zero for qi in Q): dc = -1 M = zeros(0, 2, DE.t) else: dc = max([qi.degree(DE.t) for qi in Q]) M = Matrix(dc + 1, m, lambda i, j: Q[j].nth(i), DE.t) A, u = constant_system(M, zeros(dc + 1, 1, DE.t), DE) c = eye(m, DE.t) A = A.row_join(zeros(A.rows, m, DE.t)).col_join(c.row_join(-c)) return (H, A) def prde_no_cancel_b_small(b, Q, n, DE): """ Parametric Poly Risch Differential Equation - No cancellation: deg(b) small enough. Explanation =========== Given a derivation D on k[t], n in ZZ, and b, q1, ..., qm in k[t] with deg(b) < deg(D) - 1 and either D == d/dt or deg(D) >= 2, returns h1, ..., hr in k[t] and a matrix A with coefficients in Const(k) such that if c1, ..., cm in Const(k) and q in k[t] satisfy deg(q) <= n and Dq + b*q == Sum(ci*qi, (i, 1, m)) then q = Sum(dj*hj, (j, 1, r)) where d1, ..., dr in Const(k) and A*Matrix([[c1, ..., cm, d1, ..., dr]]).T == 0. """ m = len(Q) H = [Poly(0, DE.t)]*m for N, i in itertools.product(range(n, 0, -1), range(m)): # [n, ..., 1] si = Q[i].nth(N + DE.d.degree(DE.t) - 1)/(N*DE.d.LC()) sitn = Poly(si*DE.t**N, DE.t) H[i] = H[i] + sitn Q[i] = Q[i] - derivation(sitn, DE) - b*sitn if b.degree(DE.t) > 0: for i in range(m): si = Poly(Q[i].nth(b.degree(DE.t))/b.LC(), DE.t) H[i] = H[i] + si Q[i] = Q[i] - derivation(si, DE) - b*si if all(qi.is_zero for qi in Q): dc = -1 M = Matrix() else: dc = max([qi.degree(DE.t) for qi in Q]) M = Matrix(dc + 1, m, lambda i, j: Q[j].nth(i), DE.t) A, u = constant_system(M, zeros(dc + 1, 1, DE.t), DE) c = eye(m, DE.t) A = A.row_join(zeros(A.rows, m, DE.t)).col_join(c.row_join(-c)) return (H, A) # else: b is in k, deg(qi) < deg(Dt) t = DE.t if DE.case != 'base': with DecrementLevel(DE): t0 = DE.t # k = k0(t0) ba, bd = frac_in(b, t0, field=True) Q0 = [frac_in(qi.TC(), t0, field=True) for qi in Q] f, B = param_rischDE(ba, bd, Q0, DE) # f = [f1, ..., fr] in k^r and B is a matrix with # m + r columns and entries in Const(k) = Const(k0) # such that Dy0 + b*y0 = Sum(ci*qi, (i, 1, m)) has # a solution y0 in k with c1, ..., cm in Const(k) # if and only y0 = Sum(dj*fj, (j, 1, r)) where # d1, ..., dr ar in Const(k) and # B*Matrix([c1, ..., cm, d1, ..., dr]) == 0. # Transform fractions (fa, fd) in f into constant # polynomials fa/fd in k[t]. # (Is there a better way?) f = [Poly(fa.as_expr()/fd.as_expr(), t, field=True) for fa, fd in f] B = Matrix.from_Matrix(B.to_Matrix(), t) else: # Base case. Dy == 0 for all y in k and b == 0. # Dy + b*y = Sum(ci*qi) is solvable if and only if # Sum(ci*qi) == 0 in which case the solutions are # y = d1*f1 for f1 = 1 and any d1 in Const(k) = k. f = [Poly(1, t, field=True)] # r = 1 B = Matrix([[qi.TC() for qi in Q] + [S.Zero]], DE.t) # The condition for solvability is # B*Matrix([c1, ..., cm, d1]) == 0 # There are no constraints on d1. # Coefficients of t^j (j > 0) in Sum(ci*qi) must be zero. d = max([qi.degree(DE.t) for qi in Q]) if d > 0: M = Matrix(d, m, lambda i, j: Q[j].nth(i + 1), DE.t) A, _ = constant_system(M, zeros(d, 1, DE.t), DE) else: # No constraints on the hj. A = Matrix(0, m, [], DE.t) # Solutions of the original equation are # y = Sum(dj*fj, (j, 1, r) + Sum(ei*hi, (i, 1, m)), # where ei == ci (i = 1, ..., m), when # A*Matrix([c1, ..., cm]) == 0 and # B*Matrix([c1, ..., cm, d1, ..., dr]) == 0 # Build combined constraint matrix with m + r + m columns. r = len(f) I = eye(m, DE.t) A = A.row_join(zeros(A.rows, r + m, DE.t)) B = B.row_join(zeros(B.rows, m, DE.t)) C = I.row_join(zeros(m, r, DE.t)).row_join(-I) return f + H, A.col_join(B).col_join(C) def prde_cancel_liouvillian(b, Q, n, DE): """ Pg, 237. """ H = [] # Why use DecrementLevel? Below line answers that: # Assuming that we can solve such problems over 'k' (not k[t]) if DE.case == 'primitive': with DecrementLevel(DE): ba, bd = frac_in(b, DE.t, field=True) for i in range(n, -1, -1): if DE.case == 'exp': # this re-checking can be avoided with DecrementLevel(DE): ba, bd = frac_in(b + (i*(derivation(DE.t, DE)/DE.t)).as_poly(b.gens), DE.t, field=True) with DecrementLevel(DE): Qy = [frac_in(q.nth(i), DE.t, field=True) for q in Q] fi, Ai = param_rischDE(ba, bd, Qy, DE) fi = [Poly(fa.as_expr()/fd.as_expr(), DE.t, field=True) for fa, fd in fi] Ai = Ai.set_gens(DE.t) ri = len(fi) if i == n: M = Ai else: M = Ai.col_join(M.row_join(zeros(M.rows, ri, DE.t))) Fi, hi = [None]*ri, [None]*ri # from eq. on top of p.238 (unnumbered) for j in range(ri): hji = fi[j] * (DE.t**i).as_poly(fi[j].gens) hi[j] = hji # building up Sum(djn*(D(fjn*t^n) - b*fjnt^n)) Fi[j] = -(derivation(hji, DE) - b*hji) H += hi # in the next loop instead of Q it has # to be Q + Fi taking its place Q = Q + Fi return (H, M) def param_poly_rischDE(a, b, q, n, DE): """Polynomial solutions of a parametric Risch differential equation. Explanation =========== Given a derivation D in k[t], a, b in k[t] relatively prime, and q = [q1, ..., qm] in k[t]^m, return h = [h1, ..., hr] in k[t]^r and a matrix A with m + r columns and entries in Const(k) such that a*Dp + b*p = Sum(ci*qi, (i, 1, m)) has a solution p of degree <= n in k[t] with c1, ..., cm in Const(k) if and only if p = Sum(dj*hj, (j, 1, r)) where d1, ..., dr are in Const(k) and (c1, ..., cm, d1, ..., dr) is a solution of Ax == 0. """ m = len(q) if n < 0: # Only the trivial zero solution is possible. # Find relations between the qi. if all(qi.is_zero for qi in q): return [], zeros(1, m, DE.t) # No constraints. N = max([qi.degree(DE.t) for qi in q]) M = Matrix(N + 1, m, lambda i, j: q[j].nth(i), DE.t) A, _ = constant_system(M, zeros(M.rows, 1, DE.t), DE) return [], A if a.is_ground: # Normalization: a = 1. a = a.LC() b, q = b.quo_ground(a), [qi.quo_ground(a) for qi in q] if not b.is_zero and (DE.case == 'base' or b.degree() > max(0, DE.d.degree() - 1)): return prde_no_cancel_b_large(b, q, n, DE) elif ((b.is_zero or b.degree() < DE.d.degree() - 1) and (DE.case == 'base' or DE.d.degree() >= 2)): return prde_no_cancel_b_small(b, q, n, DE) elif (DE.d.degree() >= 2 and b.degree() == DE.d.degree() - 1 and n > -b.as_poly().LC()/DE.d.as_poly().LC()): raise NotImplementedError("prde_no_cancel_b_equal() is " "not yet implemented.") else: # Liouvillian cases if DE.case in ('primitive', 'exp'): return prde_cancel_liouvillian(b, q, n, DE) else: raise NotImplementedError("non-linear and hypertangent " "cases have not yet been implemented") # else: deg(a) > 0 # Iterate SPDE as long as possible cumulating coefficient # and terms for the recovery of original solutions. alpha, beta = a.one, [a.zero]*m while n >= 0: # and a, b relatively prime a, b, q, r, n = prde_spde(a, b, q, n, DE) beta = [betai + alpha*ri for betai, ri in zip(beta, r)] alpha *= a # Solutions p of a*Dp + b*p = Sum(ci*qi) correspond to # solutions alpha*p + Sum(ci*betai) of the initial equation. d = a.gcd(b) if not d.is_ground: break # a*Dp + b*p = Sum(ci*qi) may have a polynomial solution # only if the sum is divisible by d. qq, M = poly_linear_constraints(q, d) # qq = [qq1, ..., qqm] where qqi = qi.quo(d). # M is a matrix with m columns an entries in k. # Sum(fi*qi, (i, 1, m)), where f1, ..., fm are elements of k, is # divisible by d if and only if M*Matrix([f1, ..., fm]) == 0, # in which case the quotient is Sum(fi*qqi). A, _ = constant_system(M, zeros(M.rows, 1, DE.t), DE) # A is a matrix with m columns and entries in Const(k). # Sum(ci*qqi) is Sum(ci*qi).quo(d), and the remainder is zero # for c1, ..., cm in Const(k) if and only if # A*Matrix([c1, ...,cm]) == 0. V = A.nullspace() # V = [v1, ..., vu] where each vj is a column matrix with # entries aj1, ..., ajm in Const(k). # Sum(aji*qi) is divisible by d with exact quotient Sum(aji*qqi). # Sum(ci*qi) is divisible by d if and only if ci = Sum(dj*aji) # (i = 1, ..., m) for some d1, ..., du in Const(k). # In that case, solutions of # a*Dp + b*p = Sum(ci*qi) = Sum(dj*Sum(aji*qi)) # are the same as those of # (a/d)*Dp + (b/d)*p = Sum(dj*rj) # where rj = Sum(aji*qqi). if not V: # No non-trivial solution. return [], eye(m, DE.t) # Could return A, but this has # the minimum number of rows. Mqq = Matrix([qq]) # A single row. r = [(Mqq*vj)[0] for vj in V] # [r1, ..., ru] # Solutions of (a/d)*Dp + (b/d)*p = Sum(dj*rj) correspond to # solutions alpha*p + Sum(Sum(dj*aji)*betai) of the initial # equation. These are equal to alpha*p + Sum(dj*fj) where # fj = Sum(aji*betai). Mbeta = Matrix([beta]) f = [(Mbeta*vj)[0] for vj in V] # [f1, ..., fu] # # Solve the reduced equation recursively. # g, B = param_poly_rischDE(a.quo(d), b.quo(d), r, n, DE) # g = [g1, ..., gv] in k[t]^v and and B is a matrix with u + v # columns and entries in Const(k) such that # (a/d)*Dp + (b/d)*p = Sum(dj*rj) has a solution p of degree <= n # in k[t] if and only if p = Sum(ek*gk) where e1, ..., ev are in # Const(k) and B*Matrix([d1, ..., du, e1, ..., ev]) == 0. # The solutions of the original equation are then # Sum(dj*fj, (j, 1, u)) + alpha*Sum(ek*gk, (k, 1, v)). # Collect solution components. h = f + [alpha*gk for gk in g] # Build combined relation matrix. A = -eye(m, DE.t) for vj in V: A = A.row_join(vj) A = A.row_join(zeros(m, len(g), DE.t)) A = A.col_join(zeros(B.rows, m, DE.t).row_join(B)) return h, A def param_rischDE(fa, fd, G, DE): """ Solve a Parametric Risch Differential Equation: Dy + f*y == Sum(ci*Gi, (i, 1, m)). Explanation =========== Given a derivation D in k(t), f in k(t), and G = [G1, ..., Gm] in k(t)^m, return h = [h1, ..., hr] in k(t)^r and a matrix A with m + r columns and entries in Const(k) such that Dy + f*y = Sum(ci*Gi, (i, 1, m)) has a solution y in k(t) with c1, ..., cm in Const(k) if and only if y = Sum(dj*hj, (j, 1, r)) where d1, ..., dr are in Const(k) and (c1, ..., cm, d1, ..., dr) is a solution of Ax == 0. Elements of k(t) are tuples (a, d) with a and d in k[t]. """ m = len(G) q, (fa, fd) = weak_normalizer(fa, fd, DE) # Solutions of the weakly normalized equation Dz + f*z = q*Sum(ci*Gi) # correspond to solutions y = z/q of the original equation. gamma = q G = [(q*ga).cancel(gd, include=True) for ga, gd in G] a, (ba, bd), G, hn = prde_normal_denom(fa, fd, G, DE) # Solutions q in k<t> of a*Dq + b*q = Sum(ci*Gi) correspond # to solutions z = q/hn of the weakly normalized equation. gamma *= hn A, B, G, hs = prde_special_denom(a, ba, bd, G, DE) # Solutions p in k[t] of A*Dp + B*p = Sum(ci*Gi) correspond # to solutions q = p/hs of the previous equation. gamma *= hs g = A.gcd(B) a, b, g = A.quo(g), B.quo(g), [gia.cancel(gid*g, include=True) for gia, gid in G] # a*Dp + b*p = Sum(ci*gi) may have a polynomial solution # only if the sum is in k[t]. q, M = prde_linear_constraints(a, b, g, DE) # q = [q1, ..., qm] where qi in k[t] is the polynomial component # of the partial fraction expansion of gi. # M is a matrix with m columns and entries in k. # Sum(fi*gi, (i, 1, m)), where f1, ..., fm are elements of k, # is a polynomial if and only if M*Matrix([f1, ..., fm]) == 0, # in which case the sum is equal to Sum(fi*qi). M, _ = constant_system(M, zeros(M.rows, 1, DE.t), DE) # M is a matrix with m columns and entries in Const(k). # Sum(ci*gi) is in k[t] for c1, ..., cm in Const(k) # if and only if M*Matrix([c1, ..., cm]) == 0, # in which case the sum is Sum(ci*qi). ## Reduce number of constants at this point V = M.nullspace() # V = [v1, ..., vu] where each vj is a column matrix with # entries aj1, ..., ajm in Const(k). # Sum(aji*gi) is in k[t] and equal to Sum(aji*qi) (j = 1, ..., u). # Sum(ci*gi) is in k[t] if and only is ci = Sum(dj*aji) # (i = 1, ..., m) for some d1, ..., du in Const(k). # In that case, # Sum(ci*gi) = Sum(ci*qi) = Sum(dj*Sum(aji*qi)) = Sum(dj*rj) # where rj = Sum(aji*qi) (j = 1, ..., u) in k[t]. if not V: # No non-trivial solution return [], eye(m, DE.t) Mq = Matrix([q]) # A single row. r = [(Mq*vj)[0] for vj in V] # [r1, ..., ru] # Solutions of a*Dp + b*p = Sum(dj*rj) correspond to solutions # y = p/gamma of the initial equation with ci = Sum(dj*aji). try: # We try n=5. At least for prde_spde, it will always # terminate no matter what n is. n = bound_degree(a, b, r, DE, parametric=True) except NotImplementedError: # A temporary bound is set. Eventually, it will be removed. # the currently added test case takes large time # even with n=5, and much longer with large n's. n = 5 h, B = param_poly_rischDE(a, b, r, n, DE) # h = [h1, ..., hv] in k[t]^v and and B is a matrix with u + v # columns and entries in Const(k) such that # a*Dp + b*p = Sum(dj*rj) has a solution p of degree <= n # in k[t] if and only if p = Sum(ek*hk) where e1, ..., ev are in # Const(k) and B*Matrix([d1, ..., du, e1, ..., ev]) == 0. # The solutions of the original equation for ci = Sum(dj*aji) # (i = 1, ..., m) are then y = Sum(ek*hk, (k, 1, v))/gamma. ## Build combined relation matrix with m + u + v columns. A = -eye(m, DE.t) for vj in V: A = A.row_join(vj) A = A.row_join(zeros(m, len(h), DE.t)) A = A.col_join(zeros(B.rows, m, DE.t).row_join(B)) ## Eliminate d1, ..., du. W = A.nullspace() # W = [w1, ..., wt] where each wl is a column matrix with # entries blk (k = 1, ..., m + u + v) in Const(k). # The vectors (bl1, ..., blm) generate the space of those # constant families (c1, ..., cm) for which a solution of # the equation Dy + f*y == Sum(ci*Gi) exists. They generate # the space and form a basis except possibly when Dy + f*y == 0 # is solvable in k(t}. The corresponding solutions are # y = Sum(blk'*hk, (k, 1, v))/gamma, where k' = k + m + u. v = len(h) shape = (len(W), m+v) elements = [wl[:m] + wl[-v:] for wl in W] # excise dj's. items = [e for row in elements for e in row] # Need to set the shape in case W is empty M = Matrix(*shape, items, DE.t) N = M.nullspace() # N = [n1, ..., ns] where the ni in Const(k)^(m + v) are column # vectors generating the space of linear relations between # c1, ..., cm, e1, ..., ev. C = Matrix([ni[:] for ni in N], DE.t) # rows n1, ..., ns. return [hk.cancel(gamma, include=True) for hk in h], C def limited_integrate_reduce(fa, fd, G, DE): """ Simpler version of step 1 & 2 for the limited integration problem. Explanation =========== Given a derivation D on k(t) and f, g1, ..., gn in k(t), return (a, b, h, N, g, V) such that a, b, h in k[t], N is a non-negative integer, g in k(t), V == [v1, ..., vm] in k(t)^m, and for any solution v in k(t), c1, ..., cm in C of f == Dv + Sum(ci*wi, (i, 1, m)), p = v*h is in k<t>, and p and the ci satisfy a*Dp + b*p == g + Sum(ci*vi, (i, 1, m)). Furthermore, if S1irr == Sirr, then p is in k[t], and if t is nonlinear or Liouvillian over k, then deg(p) <= N. So that the special part is always computed, this function calls the more general prde_special_denom() automatically if it cannot determine that S1irr == Sirr. Furthermore, it will automatically call bound_degree() when t is linear and non-Liouvillian, which for the transcendental case, implies that Dt == a*t + b with for some a, b in k*. """ dn, ds = splitfactor(fd, DE) E = [splitfactor(gd, DE) for _, gd in G] En, Es = list(zip(*E)) c = reduce(lambda i, j: i.lcm(j), (dn,) + En) # lcm(dn, en1, ..., enm) hn = c.gcd(c.diff(DE.t)) a = hn b = -derivation(hn, DE) N = 0 # These are the cases where we know that S1irr = Sirr, but there could be # others, and this algorithm will need to be extended to handle them. if DE.case in ('base', 'primitive', 'exp', 'tan'): hs = reduce(lambda i, j: i.lcm(j), (ds,) + Es) # lcm(ds, es1, ..., esm) a = hn*hs b -= (hn*derivation(hs, DE)).quo(hs) mu = min(order_at_oo(fa, fd, DE.t), min([order_at_oo(ga, gd, DE.t) for ga, gd in G])) # So far, all the above are also nonlinear or Liouvillian, but if this # changes, then this will need to be updated to call bound_degree() # as per the docstring of this function (DE.case == 'other_linear'). N = hn.degree(DE.t) + hs.degree(DE.t) + max(0, 1 - DE.d.degree(DE.t) - mu) else: # TODO: implement this raise NotImplementedError V = [(-a*hn*ga).cancel(gd, include=True) for ga, gd in G] return (a, b, a, N, (a*hn*fa).cancel(fd, include=True), V) def limited_integrate(fa, fd, G, DE): """ Solves the limited integration problem: f = Dv + Sum(ci*wi, (i, 1, n)) """ fa, fd = fa*Poly(1/fd.LC(), DE.t), fd.monic() # interpreting limited integration problem as a # parametric Risch DE problem Fa = Poly(0, DE.t) Fd = Poly(1, DE.t) G = [(fa, fd)] + G h, A = param_rischDE(Fa, Fd, G, DE) V = A.nullspace() V = [v for v in V if v[0] != 0] if not V: return None else: # we can take any vector from V, we take V[0] c0 = V[0][0] # v = [-1, c1, ..., cm, d1, ..., dr] v = V[0]/(-c0) r = len(h) m = len(v) - r - 1 C = list(v[1: m + 1]) y = -sum([v[m + 1 + i]*h[i][0].as_expr()/h[i][1].as_expr() \ for i in range(r)]) y_num, y_den = y.as_numer_denom() Ya, Yd = Poly(y_num, DE.t), Poly(y_den, DE.t) Y = Ya*Poly(1/Yd.LC(), DE.t), Yd.monic() return Y, C def parametric_log_deriv_heu(fa, fd, wa, wd, DE, c1=None): """ Parametric logarithmic derivative heuristic. Explanation =========== Given a derivation D on k[t], f in k(t), and a hyperexponential monomial theta over k(t), raises either NotImplementedError, in which case the heuristic failed, or returns None, in which case it has proven that no solution exists, or returns a solution (n, m, v) of the equation n*f == Dv/v + m*Dtheta/theta, with v in k(t)* and n, m in ZZ with n != 0. If this heuristic fails, the structure theorem approach will need to be used. The argument w == Dtheta/theta """ # TODO: finish writing this and write tests c1 = c1 or Dummy('c1') p, a = fa.div(fd) q, b = wa.div(wd) B = max(0, derivation(DE.t, DE).degree(DE.t) - 1) C = max(p.degree(DE.t), q.degree(DE.t)) if q.degree(DE.t) > B: eqs = [p.nth(i) - c1*q.nth(i) for i in range(B + 1, C + 1)] s = solve(eqs, c1) if not s or not s[c1].is_Rational: # deg(q) > B, no solution for c. return None M, N = s[c1].as_numer_denom() M_poly = M.as_poly(q.gens) N_poly = N.as_poly(q.gens) nfmwa = N_poly*fa*wd - M_poly*wa*fd nfmwd = fd*wd Qv = is_log_deriv_k_t_radical_in_field(nfmwa, nfmwd, DE, 'auto') if Qv is None: # (N*f - M*w) is not the logarithmic derivative of a k(t)-radical. return None Q, v = Qv if Q.is_zero or v.is_zero: return None return (Q*N, Q*M, v) if p.degree(DE.t) > B: return None c = lcm(fd.as_poly(DE.t).LC(), wd.as_poly(DE.t).LC()) l = fd.monic().lcm(wd.monic())*Poly(c, DE.t) ln, ls = splitfactor(l, DE) z = ls*ln.gcd(ln.diff(DE.t)) if not z.has(DE.t): # TODO: We treat this as 'no solution', until the structure # theorem version of parametric_log_deriv is implemented. return None u1, r1 = (fa*l.quo(fd)).div(z) # (l*f).div(z) u2, r2 = (wa*l.quo(wd)).div(z) # (l*w).div(z) eqs = [r1.nth(i) - c1*r2.nth(i) for i in range(z.degree(DE.t))] s = solve(eqs, c1) if not s or not s[c1].is_Rational: # deg(q) <= B, no solution for c. return None M, N = s[c1].as_numer_denom() nfmwa = N.as_poly(DE.t)*fa*wd - M.as_poly(DE.t)*wa*fd nfmwd = fd*wd Qv = is_log_deriv_k_t_radical_in_field(nfmwa, nfmwd, DE) if Qv is None: # (N*f - M*w) is not the logarithmic derivative of a k(t)-radical. return None Q, v = Qv if Q.is_zero or v.is_zero: return None return (Q*N, Q*M, v) def parametric_log_deriv(fa, fd, wa, wd, DE): # TODO: Write the full algorithm using the structure theorems. # try: A = parametric_log_deriv_heu(fa, fd, wa, wd, DE) # except NotImplementedError: # Heuristic failed, we have to use the full method. # TODO: This could be implemented more efficiently. # It isn't too worrisome, because the heuristic handles most difficult # cases. return A def is_deriv_k(fa, fd, DE): r""" Checks if Df/f is the derivative of an element of k(t). Explanation =========== a in k(t) is the derivative of an element of k(t) if there exists b in k(t) such that a = Db. Either returns (ans, u), such that Df/f == Du, or None, which means that Df/f is not the derivative of an element of k(t). ans is a list of tuples such that Add(*[i*j for i, j in ans]) == u. This is useful for seeing exactly which elements of k(t) produce u. This function uses the structure theorem approach, which says that for any f in K, Df/f is the derivative of a element of K if and only if there are ri in QQ such that:: --- --- Dt \ r * Dt + \ r * i Df / i i / i --- = --. --- --- t f i in L i in E i K/C(x) K/C(x) Where C = Const(K), L_K/C(x) = { i in {1, ..., n} such that t_i is transcendental over C(x)(t_1, ..., t_i-1) and Dt_i = Da_i/a_i, for some a_i in C(x)(t_1, ..., t_i-1)* } (i.e., the set of all indices of logarithmic monomials of K over C(x)), and E_K/C(x) = { i in {1, ..., n} such that t_i is transcendental over C(x)(t_1, ..., t_i-1) and Dt_i/t_i = Da_i, for some a_i in C(x)(t_1, ..., t_i-1) } (i.e., the set of all indices of hyperexponential monomials of K over C(x)). If K is an elementary extension over C(x), then the cardinality of L_K/C(x) U E_K/C(x) is exactly the transcendence degree of K over C(x). Furthermore, because Const_D(K) == Const_D(C(x)) == C, deg(Dt_i) == 1 when t_i is in E_K/C(x) and deg(Dt_i) == 0 when t_i is in L_K/C(x), implying in particular that E_K/C(x) and L_K/C(x) are disjoint. The sets L_K/C(x) and E_K/C(x) must, by their nature, be computed recursively using this same function. Therefore, it is required to pass them as indices to D (or T). E_args are the arguments of the hyperexponentials indexed by E_K (i.e., if i is in E_K, then T[i] == exp(E_args[i])). This is needed to compute the final answer u such that Df/f == Du. log(f) will be the same as u up to a additive constant. This is because they will both behave the same as monomials. For example, both log(x) and log(2*x) == log(x) + log(2) satisfy Dt == 1/x, because log(2) is constant. Therefore, the term const is returned. const is such that log(const) + f == u. This is calculated by dividing the arguments of one logarithm from the other. Therefore, it is necessary to pass the arguments of the logarithmic terms in L_args. To handle the case where we are given Df/f, not f, use is_deriv_k_in_field(). See also ======== is_log_deriv_k_t_radical_in_field, is_log_deriv_k_t_radical """ # Compute Df/f dfa, dfd = (fd*derivation(fa, DE) - fa*derivation(fd, DE)), fd*fa dfa, dfd = dfa.cancel(dfd, include=True) # Our assumption here is that each monomial is recursively transcendental if len(DE.exts) != len(DE.D): if [i for i in DE.cases if i == 'tan'] or \ ({i for i in DE.cases if i == 'primitive'} - set(DE.indices('log'))): raise NotImplementedError("Real version of the structure " "theorems with hypertangent support is not yet implemented.") # TODO: What should really be done in this case? raise NotImplementedError("Nonelementary extensions not supported " "in the structure theorems.") E_part = [DE.D[i].quo(Poly(DE.T[i], DE.T[i])).as_expr() for i in DE.indices('exp')] L_part = [DE.D[i].as_expr() for i in DE.indices('log')] # The expression dfa/dfd might not be polynomial in any of its symbols so we # use a Dummy as the generator for PolyMatrix. dum = Dummy() lhs = Matrix([E_part + L_part], dum) rhs = Matrix([dfa.as_expr()/dfd.as_expr()], dum) A, u = constant_system(lhs, rhs, DE) u = u.to_Matrix() # Poly to Expr if not A or not all(derivation(i, DE, basic=True).is_zero for i in u): # If the elements of u are not all constant # Note: See comment in constant_system # Also note: derivation(basic=True) calls cancel() return None else: if not all(i.is_Rational for i in u): raise NotImplementedError("Cannot work with non-rational " "coefficients in this case.") else: terms = ([DE.extargs[i] for i in DE.indices('exp')] + [DE.T[i] for i in DE.indices('log')]) ans = list(zip(terms, u)) result = Add(*[Mul(i, j) for i, j in ans]) argterms = ([DE.T[i] for i in DE.indices('exp')] + [DE.extargs[i] for i in DE.indices('log')]) l = [] ld = [] for i, j in zip(argterms, u): # We need to get around things like sqrt(x**2) != x # and also sqrt(x**2 + 2*x + 1) != x + 1 # Issue 10798: i need not be a polynomial i, d = i.as_numer_denom() icoeff, iterms = sqf_list(i) l.append(Mul(*([Pow(icoeff, j)] + [Pow(b, e*j) for b, e in iterms]))) dcoeff, dterms = sqf_list(d) ld.append(Mul(*([Pow(dcoeff, j)] + [Pow(b, e*j) for b, e in dterms]))) const = cancel(fa.as_expr()/fd.as_expr()/Mul(*l)*Mul(*ld)) return (ans, result, const) def is_log_deriv_k_t_radical(fa, fd, DE, Df=True): r""" Checks if Df is the logarithmic derivative of a k(t)-radical. Explanation =========== b in k(t) can be written as the logarithmic derivative of a k(t) radical if there exist n in ZZ and u in k(t) with n, u != 0 such that n*b == Du/u. Either returns (ans, u, n, const) or None, which means that Df cannot be written as the logarithmic derivative of a k(t)-radical. ans is a list of tuples such that Mul(*[i**j for i, j in ans]) == u. This is useful for seeing exactly what elements of k(t) produce u. This function uses the structure theorem approach, which says that for any f in K, Df is the logarithmic derivative of a K-radical if and only if there are ri in QQ such that:: --- --- Dt \ r * Dt + \ r * i / i i / i --- = Df. --- --- t i in L i in E i K/C(x) K/C(x) Where C = Const(K), L_K/C(x) = { i in {1, ..., n} such that t_i is transcendental over C(x)(t_1, ..., t_i-1) and Dt_i = Da_i/a_i, for some a_i in C(x)(t_1, ..., t_i-1)* } (i.e., the set of all indices of logarithmic monomials of K over C(x)), and E_K/C(x) = { i in {1, ..., n} such that t_i is transcendental over C(x)(t_1, ..., t_i-1) and Dt_i/t_i = Da_i, for some a_i in C(x)(t_1, ..., t_i-1) } (i.e., the set of all indices of hyperexponential monomials of K over C(x)). If K is an elementary extension over C(x), then the cardinality of L_K/C(x) U E_K/C(x) is exactly the transcendence degree of K over C(x). Furthermore, because Const_D(K) == Const_D(C(x)) == C, deg(Dt_i) == 1 when t_i is in E_K/C(x) and deg(Dt_i) == 0 when t_i is in L_K/C(x), implying in particular that E_K/C(x) and L_K/C(x) are disjoint. The sets L_K/C(x) and E_K/C(x) must, by their nature, be computed recursively using this same function. Therefore, it is required to pass them as indices to D (or T). L_args are the arguments of the logarithms indexed by L_K (i.e., if i is in L_K, then T[i] == log(L_args[i])). This is needed to compute the final answer u such that n*f == Du/u. exp(f) will be the same as u up to a multiplicative constant. This is because they will both behave the same as monomials. For example, both exp(x) and exp(x + 1) == E*exp(x) satisfy Dt == t. Therefore, the term const is returned. const is such that exp(const)*f == u. This is calculated by subtracting the arguments of one exponential from the other. Therefore, it is necessary to pass the arguments of the exponential terms in E_args. To handle the case where we are given Df, not f, use is_log_deriv_k_t_radical_in_field(). See also ======== is_log_deriv_k_t_radical_in_field, is_deriv_k """ if Df: dfa, dfd = (fd*derivation(fa, DE) - fa*derivation(fd, DE)).cancel(fd**2, include=True) else: dfa, dfd = fa, fd # Our assumption here is that each monomial is recursively transcendental if len(DE.exts) != len(DE.D): if [i for i in DE.cases if i == 'tan'] or \ ({i for i in DE.cases if i == 'primitive'} - set(DE.indices('log'))): raise NotImplementedError("Real version of the structure " "theorems with hypertangent support is not yet implemented.") # TODO: What should really be done in this case? raise NotImplementedError("Nonelementary extensions not supported " "in the structure theorems.") E_part = [DE.D[i].quo(Poly(DE.T[i], DE.T[i])).as_expr() for i in DE.indices('exp')] L_part = [DE.D[i].as_expr() for i in DE.indices('log')] # The expression dfa/dfd might not be polynomial in any of its symbols so we # use a Dummy as the generator for PolyMatrix. dum = Dummy() lhs = Matrix([E_part + L_part], dum) rhs = Matrix([dfa.as_expr()/dfd.as_expr()], dum) A, u = constant_system(lhs, rhs, DE) u = u.to_Matrix() # Poly to Expr if not A or not all(derivation(i, DE, basic=True).is_zero for i in u): # If the elements of u are not all constant # Note: See comment in constant_system # Also note: derivation(basic=True) calls cancel() return None else: if not all(i.is_Rational for i in u): # TODO: But maybe we can tell if they're not rational, like # log(2)/log(3). Also, there should be an option to continue # anyway, even if the result might potentially be wrong. raise NotImplementedError("Cannot work with non-rational " "coefficients in this case.") else: n = reduce(ilcm, [i.as_numer_denom()[1] for i in u]) u *= n terms = ([DE.T[i] for i in DE.indices('exp')] + [DE.extargs[i] for i in DE.indices('log')]) ans = list(zip(terms, u)) result = Mul(*[Pow(i, j) for i, j in ans]) # exp(f) will be the same as result up to a multiplicative # constant. We now find the log of that constant. argterms = ([DE.extargs[i] for i in DE.indices('exp')] + [DE.T[i] for i in DE.indices('log')]) const = cancel(fa.as_expr()/fd.as_expr() - Add(*[Mul(i, j/n) for i, j in zip(argterms, u)])) return (ans, result, n, const) def is_log_deriv_k_t_radical_in_field(fa, fd, DE, case='auto', z=None): """ Checks if f can be written as the logarithmic derivative of a k(t)-radical. Explanation =========== It differs from is_log_deriv_k_t_radical(fa, fd, DE, Df=False) for any given fa, fd, DE in that it finds the solution in the given field not in some (possibly unspecified extension) and "in_field" with the function name is used to indicate that. f in k(t) can be written as the logarithmic derivative of a k(t) radical if there exist n in ZZ and u in k(t) with n, u != 0 such that n*f == Du/u. Either returns (n, u) or None, which means that f cannot be written as the logarithmic derivative of a k(t)-radical. case is one of {'primitive', 'exp', 'tan', 'auto'} for the primitive, hyperexponential, and hypertangent cases, respectively. If case is 'auto', it will attempt to determine the type of the derivation automatically. See also ======== is_log_deriv_k_t_radical, is_deriv_k """ fa, fd = fa.cancel(fd, include=True) # f must be simple n, s = splitfactor(fd, DE) if not s.is_one: pass z = z or Dummy('z') H, b = residue_reduce(fa, fd, DE, z=z) if not b: # I will have to verify, but I believe that the answer should be # None in this case. This should never happen for the # functions given when solving the parametric logarithmic # derivative problem when integration elementary functions (see # Bronstein's book, page 255), so most likely this indicates a bug. return None roots = [(i, i.real_roots()) for i, _ in H] if not all(len(j) == i.degree() and all(k.is_Rational for k in j) for i, j in roots): # If f is the logarithmic derivative of a k(t)-radical, then all the # roots of the resultant must be rational numbers. return None # [(a, i), ...], where i*log(a) is a term in the log-part of the integral # of f respolys, residues = list(zip(*roots)) or [[], []] # Note: this might be empty, but everything below should work find in that # case (it should be the same as if it were [[1, 1]]) residueterms = [(H[j][1].subs(z, i), i) for j in range(len(H)) for i in residues[j]] # TODO: finish writing this and write tests p = cancel(fa.as_expr()/fd.as_expr() - residue_reduce_derivation(H, DE, z)) p = p.as_poly(DE.t) if p is None: # f - Dg will be in k[t] if f is the logarithmic derivative of a k(t)-radical return None if p.degree(DE.t) >= max(1, DE.d.degree(DE.t)): return None if case == 'auto': case = DE.case if case == 'exp': wa, wd = derivation(DE.t, DE).cancel(Poly(DE.t, DE.t), include=True) with DecrementLevel(DE): pa, pd = frac_in(p, DE.t, cancel=True) wa, wd = frac_in((wa, wd), DE.t) A = parametric_log_deriv(pa, pd, wa, wd, DE) if A is None: return None n, e, u = A u *= DE.t**e elif case == 'primitive': with DecrementLevel(DE): pa, pd = frac_in(p, DE.t) A = is_log_deriv_k_t_radical_in_field(pa, pd, DE, case='auto') if A is None: return None n, u = A elif case == 'base': # TODO: we can use more efficient residue reduction from ratint() if not fd.is_sqf or fa.degree() >= fd.degree(): # f is the logarithmic derivative in the base case if and only if # f = fa/fd, fd is square-free, deg(fa) < deg(fd), and # gcd(fa, fd) == 1. The last condition is handled by cancel() above. return None # Note: if residueterms = [], returns (1, 1) # f had better be 0 in that case. n = reduce(ilcm, [i.as_numer_denom()[1] for _, i in residueterms], S.One) u = Mul(*[Pow(i, j*n) for i, j in residueterms]) return (n, u) elif case == 'tan': raise NotImplementedError("The hypertangent case is " "not yet implemented for is_log_deriv_k_t_radical_in_field()") elif case in ('other_linear', 'other_nonlinear'): # XXX: If these are supported by the structure theorems, change to NotImplementedError. raise ValueError("The %s case is not supported in this function." % case) else: raise ValueError("case must be one of {'primitive', 'exp', 'tan', " "'base', 'auto'}, not %s" % case) common_denom = reduce(ilcm, [i.as_numer_denom()[1] for i in [j for _, j in residueterms]] + [n], S.One) residueterms = [(i, j*common_denom) for i, j in residueterms] m = common_denom//n if common_denom != n*m: # Verify exact division raise ValueError("Inexact division") u = cancel(u**m*Mul(*[Pow(i, j) for i, j in residueterms])) return (common_denom, u)
590e8057412e57da2abaf499ce2b33db37a4c3b4fb1127156e139701d6f89ed3
from sympy.core import cacheit, Dummy, Ne, Integer, Rational, S, Wild from sympy.functions import binomial, sin, cos, Piecewise, Abs from .integrals import integrate # TODO sin(a*x)*cos(b*x) -> sin((a+b)x) + sin((a-b)x) ? # creating, each time, Wild's and sin/cos/Mul is expensive. Also, our match & # subs are very slow when not cached, and if we create Wild each time, we # effectively block caching. # # so we cache the pattern # need to use a function instead of lamda since hash of lambda changes on # each call to _pat_sincos def _integer_instance(n): return isinstance(n, Integer) @cacheit def _pat_sincos(x): a = Wild('a', exclude=[x]) n, m = [Wild(s, exclude=[x], properties=[_integer_instance]) for s in 'nm'] pat = sin(a*x)**n * cos(a*x)**m return pat, a, n, m _u = Dummy('u') def trigintegrate(f, x, conds='piecewise'): """ Integrate f = Mul(trig) over x. Examples ======== >>> from sympy import sin, cos, tan, sec >>> from sympy.integrals.trigonometry import trigintegrate >>> from sympy.abc import x >>> trigintegrate(sin(x)*cos(x), x) sin(x)**2/2 >>> trigintegrate(sin(x)**2, x) x/2 - sin(x)*cos(x)/2 >>> trigintegrate(tan(x)*sec(x), x) 1/cos(x) >>> trigintegrate(sin(x)*tan(x), x) -log(sin(x) - 1)/2 + log(sin(x) + 1)/2 - sin(x) References ========== .. [1] http://en.wikibooks.org/wiki/Calculus/Integration_techniques See Also ======== sympy.integrals.integrals.Integral.doit sympy.integrals.integrals.Integral """ pat, a, n, m = _pat_sincos(x) f = f.rewrite('sincos') M = f.match(pat) if M is None: return n, m = M[n], M[m] if n.is_zero and m.is_zero: return x zz = x if n.is_zero else S.Zero a = M[a] if n.is_odd or m.is_odd: u = _u n_, m_ = n.is_odd, m.is_odd # take smallest n or m -- to choose simplest substitution if n_ and m_: # Make sure to choose the positive one # otherwise an incorrect integral can occur. if n < 0 and m > 0: m_ = True n_ = False elif m < 0 and n > 0: n_ = True m_ = False # Both are negative so choose the smallest n or m # in absolute value for simplest substitution. elif (n < 0 and m < 0): n_ = n > m m_ = not (n > m) # Both n and m are odd and positive else: n_ = (n < m) # NB: careful here, one of the m_ = not (n < m) # conditions *must* be true # n m u=C (n-1)/2 m # S(x) * C(x) dx --> -(1-u^2) * u du if n_: ff = -(1 - u**2)**((n - 1)/2) * u**m uu = cos(a*x) # n m u=S n (m-1)/2 # S(x) * C(x) dx --> u * (1-u^2) du elif m_: ff = u**n * (1 - u**2)**((m - 1)/2) uu = sin(a*x) fi = integrate(ff, u) # XXX cyclic deps fx = fi.subs(u, uu) if conds == 'piecewise': return Piecewise((fx / a, Ne(a, 0)), (zz, True)) return fx / a # n & m are both even # # 2k 2m 2l 2l # we transform S (x) * C (x) into terms with only S (x) or C (x) # # example: # 100 4 100 2 2 100 4 2 # S (x) * C (x) = S (x) * (1-S (x)) = S (x) * (1 + S (x) - 2*S (x)) # # 104 102 100 # = S (x) - 2*S (x) + S (x) # 2k # then S is integrated with recursive formula # take largest n or m -- to choose simplest substitution n_ = (Abs(n) > Abs(m)) m_ = (Abs(m) > Abs(n)) res = S.Zero if n_: # 2k 2 k i 2i # C = (1 - S ) = sum(i, (-) * B(k, i) * S ) if m > 0: for i in range(0, m//2 + 1): res += (S.NegativeOne**i * binomial(m//2, i) * _sin_pow_integrate(n + 2*i, x)) elif m == 0: res = _sin_pow_integrate(n, x) else: # m < 0 , |n| > |m| # / # | # | m n # | cos (x) sin (x) dx = # | # | #/ # / # | # -1 m+1 n-1 n - 1 | m+2 n-2 # ________ cos (x) sin (x) + _______ | cos (x) sin (x) dx # | # m + 1 m + 1 | # / res = (Rational(-1, m + 1) * cos(x)**(m + 1) * sin(x)**(n - 1) + Rational(n - 1, m + 1) * trigintegrate(cos(x)**(m + 2)*sin(x)**(n - 2), x)) elif m_: # 2k 2 k i 2i # S = (1 - C ) = sum(i, (-) * B(k, i) * C ) if n > 0: # / / # | | # | m n | -m n # | cos (x)*sin (x) dx or | cos (x) * sin (x) dx # | | # / / # # |m| > |n| ; m, n >0 ; m, n belong to Z - {0} # n 2 # sin (x) term is expanded here in terms of cos (x), # and then integrated. # for i in range(0, n//2 + 1): res += (S.NegativeOne**i * binomial(n//2, i) * _cos_pow_integrate(m + 2*i, x)) elif n == 0: # / # | # | 1 # | _ _ _ # | m # | cos (x) # / # res = _cos_pow_integrate(m, x) else: # n < 0 , |m| > |n| # / # | # | m n # | cos (x) sin (x) dx = # | # | #/ # / # | # 1 m-1 n+1 m - 1 | m-2 n+2 # _______ cos (x) sin (x) + _______ | cos (x) sin (x) dx # | # n + 1 n + 1 | # / res = (Rational(1, n + 1) * cos(x)**(m - 1)*sin(x)**(n + 1) + Rational(m - 1, n + 1) * trigintegrate(cos(x)**(m - 2)*sin(x)**(n + 2), x)) else: if m == n: ##Substitute sin(2x)/2 for sin(x)cos(x) and then Integrate. res = integrate((sin(2*x)*S.Half)**m, x) elif (m == -n): if n < 0: # Same as the scheme described above. # the function argument to integrate in the end will # be 1, this cannot be integrated by trigintegrate. # Hence use sympy.integrals.integrate. res = (Rational(1, n + 1) * cos(x)**(m - 1) * sin(x)**(n + 1) + Rational(m - 1, n + 1) * integrate(cos(x)**(m - 2) * sin(x)**(n + 2), x)) else: res = (Rational(-1, m + 1) * cos(x)**(m + 1) * sin(x)**(n - 1) + Rational(n - 1, m + 1) * integrate(cos(x)**(m + 2)*sin(x)**(n - 2), x)) if conds == 'piecewise': return Piecewise((res.subs(x, a*x) / a, Ne(a, 0)), (zz, True)) return res.subs(x, a*x) / a def _sin_pow_integrate(n, x): if n > 0: if n == 1: #Recursion break return -cos(x) # n > 0 # / / # | | # | n -1 n-1 n - 1 | n-2 # | sin (x) dx = ______ cos (x) sin (x) + _______ | sin (x) dx # | | # | n n | #/ / # # return (Rational(-1, n) * cos(x) * sin(x)**(n - 1) + Rational(n - 1, n) * _sin_pow_integrate(n - 2, x)) if n < 0: if n == -1: ##Make sure this does not come back here again. ##Recursion breaks here or at n==0. return trigintegrate(1/sin(x), x) # n < 0 # / / # | | # | n 1 n+1 n + 2 | n+2 # | sin (x) dx = _______ cos (x) sin (x) + _______ | sin (x) dx # | | # | n + 1 n + 1 | #/ / # return (Rational(1, n + 1) * cos(x) * sin(x)**(n + 1) + Rational(n + 2, n + 1) * _sin_pow_integrate(n + 2, x)) else: #n == 0 #Recursion break. return x def _cos_pow_integrate(n, x): if n > 0: if n == 1: #Recursion break. return sin(x) # n > 0 # / / # | | # | n 1 n-1 n - 1 | n-2 # | sin (x) dx = ______ sin (x) cos (x) + _______ | cos (x) dx # | | # | n n | #/ / # return (Rational(1, n) * sin(x) * cos(x)**(n - 1) + Rational(n - 1, n) * _cos_pow_integrate(n - 2, x)) if n < 0: if n == -1: ##Recursion break return trigintegrate(1/cos(x), x) # n < 0 # / / # | | # | n -1 n+1 n + 2 | n+2 # | cos (x) dx = _______ sin (x) cos (x) + _______ | cos (x) dx # | | # | n + 1 n + 1 | #/ / # return (Rational(-1, n + 1) * sin(x) * cos(x)**(n + 1) + Rational(n + 2, n + 1) * _cos_pow_integrate(n + 2, x)) else: # n == 0 #Recursion Break. return x
2d84caadbc4593a4f43f315d891659fbb73159b7bcd533c5e9a3274e50d22b11
""" Integrate functions by rewriting them as Meijer G-functions. There are three user-visible functions that can be used by other parts of the sympy library to solve various integration problems: - meijerint_indefinite - meijerint_definite - meijerint_inversion They can be used to compute, respectively, indefinite integrals, definite integrals over intervals of the real line, and inverse laplace-type integrals (from c-I*oo to c+I*oo). See the respective docstrings for details. The main references for this are: [L] Luke, Y. L. (1969), The Special Functions and Their Approximations, Volume 1 [R] Kelly B. Roach. Meijer G Function Representations. In: Proceedings of the 1997 International Symposium on Symbolic and Algebraic Computation, pages 205-211, New York, 1997. ACM. [P] A. P. Prudnikov, Yu. A. Brychkov and O. I. Marichev (1990). Integrals and Series: More Special Functions, Vol. 3,. Gordon and Breach Science Publisher """ import itertools from typing import Dict as tDict, Tuple as tTuple from sympy import SYMPY_DEBUG from sympy.core import S, Expr from sympy.core.add import Add from sympy.core.cache import cacheit from sympy.core.containers import Tuple from sympy.core.exprtools import factor_terms from sympy.core.function import (expand, expand_mul, expand_power_base, expand_trig, Function) from sympy.core.mul import Mul from sympy.core.numbers import ilcm, Rational, pi from sympy.core.relational import Eq, Ne, _canonical_coeff from sympy.core.sorting import default_sort_key, ordered from sympy.core.symbol import Dummy, symbols, Wild from sympy.core.sympify import sympify from sympy.functions.combinatorial.factorials import factorial from sympy.functions.elementary.complexes import (re, im, arg, Abs, sign, unpolarify, polarify, polar_lift, principal_branch, unbranched_argument, periodic_argument) from sympy.functions.elementary.exponential import exp, exp_polar, log from sympy.functions.elementary.integers import ceiling from sympy.functions.elementary.hyperbolic import (cosh, sinh, _rewrite_hyperbolics_as_exp, HyperbolicFunction) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.piecewise import Piecewise, piecewise_fold from sympy.functions.elementary.trigonometric import (cos, sin, sinc, TrigonometricFunction) from sympy.functions.special.bessel import besselj, bessely, besseli, besselk from sympy.functions.special.delta_functions import DiracDelta, Heaviside from sympy.functions.special.elliptic_integrals import elliptic_k, elliptic_e from sympy.functions.special.error_functions import (erf, erfc, erfi, Ei, expint, Si, Ci, Shi, Chi, fresnels, fresnelc) from sympy.functions.special.gamma_functions import gamma from sympy.functions.special.hyper import hyper, meijerg from sympy.functions.special.singularity_functions import SingularityFunction from .integrals import Integral from sympy.logic.boolalg import And, Or, BooleanAtom, Not, BooleanFunction from sympy.polys import cancel, factor from sympy.utilities.iterables import multiset_partitions from sympy.utilities.misc import debug as _debug # keep this at top for easy reference z = Dummy('z') def _has(res, *f): # return True if res has f; in the case of Piecewise # only return True if *all* pieces have f res = piecewise_fold(res) if getattr(res, 'is_Piecewise', False): return all(_has(i, *f) for i in res.args) return res.has(*f) def _create_lookup_table(table): """ Add formulae for the function -> meijerg lookup table. """ def wild(n): return Wild(n, exclude=[z]) p, q, a, b, c = list(map(wild, 'pqabc')) n = Wild('n', properties=[lambda x: x.is_Integer and x > 0]) t = p*z**q def add(formula, an, ap, bm, bq, arg=t, fac=S.One, cond=True, hint=True): table.setdefault(_mytype(formula, z), []).append((formula, [(fac, meijerg(an, ap, bm, bq, arg))], cond, hint)) def addi(formula, inst, cond, hint=True): table.setdefault( _mytype(formula, z), []).append((formula, inst, cond, hint)) def constant(a): return [(a, meijerg([1], [], [], [0], z)), (a, meijerg([], [1], [0], [], z))] table[()] = [(a, constant(a), True, True)] # [P], Section 8. class IsNonPositiveInteger(Function): @classmethod def eval(cls, arg): arg = unpolarify(arg) if arg.is_Integer is True: return arg <= 0 # Section 8.4.2 # TODO this needs more polar_lift (c/f entry for exp) add(Heaviside(t - b)*(t - b)**(a - 1), [a], [], [], [0], t/b, gamma(a)*b**(a - 1), And(b > 0)) add(Heaviside(b - t)*(b - t)**(a - 1), [], [a], [0], [], t/b, gamma(a)*b**(a - 1), And(b > 0)) add(Heaviside(z - (b/p)**(1/q))*(t - b)**(a - 1), [a], [], [], [0], t/b, gamma(a)*b**(a - 1), And(b > 0)) add(Heaviside((b/p)**(1/q) - z)*(b - t)**(a - 1), [], [a], [0], [], t/b, gamma(a)*b**(a - 1), And(b > 0)) add((b + t)**(-a), [1 - a], [], [0], [], t/b, b**(-a)/gamma(a), hint=Not(IsNonPositiveInteger(a))) add(Abs(b - t)**(-a), [1 - a], [(1 - a)/2], [0], [(1 - a)/2], t/b, 2*sin(pi*a/2)*gamma(1 - a)*Abs(b)**(-a), re(a) < 1) add((t**a - b**a)/(t - b), [0, a], [], [0, a], [], t/b, b**(a - 1)*sin(a*pi)/pi) # 12 def A1(r, sign, nu): return pi**Rational(-1, 2)*(-sign*nu/2)**(1 - 2*r) def tmpadd(r, sgn): # XXX the a**2 is bad for matching add((sqrt(a**2 + t) + sgn*a)**b/(a**2 + t)**r, [(1 + b)/2, 1 - 2*r + b/2], [], [(b - sgn*b)/2], [(b + sgn*b)/2], t/a**2, a**(b - 2*r)*A1(r, sgn, b)) tmpadd(0, 1) tmpadd(0, -1) tmpadd(S.Half, 1) tmpadd(S.Half, -1) # 13 def tmpadd(r, sgn): add((sqrt(a + p*z**q) + sgn*sqrt(p)*z**(q/2))**b/(a + p*z**q)**r, [1 - r + sgn*b/2], [1 - r - sgn*b/2], [0, S.Half], [], p*z**q/a, a**(b/2 - r)*A1(r, sgn, b)) tmpadd(0, 1) tmpadd(0, -1) tmpadd(S.Half, 1) tmpadd(S.Half, -1) # (those after look obscure) # Section 8.4.3 add(exp(polar_lift(-1)*t), [], [], [0], []) # TODO can do sin^n, sinh^n by expansion ... where? # 8.4.4 (hyperbolic functions) add(sinh(t), [], [1], [S.Half], [1, 0], t**2/4, pi**Rational(3, 2)) add(cosh(t), [], [S.Half], [0], [S.Half, S.Half], t**2/4, pi**Rational(3, 2)) # Section 8.4.5 # TODO can do t + a. but can also do by expansion... (XXX not really) add(sin(t), [], [], [S.Half], [0], t**2/4, sqrt(pi)) add(cos(t), [], [], [0], [S.Half], t**2/4, sqrt(pi)) # Section 8.4.6 (sinc function) add(sinc(t), [], [], [0], [Rational(-1, 2)], t**2/4, sqrt(pi)/2) # Section 8.5.5 def make_log1(subs): N = subs[n] return [(S.NegativeOne**N*factorial(N), meijerg([], [1]*(N + 1), [0]*(N + 1), [], t))] def make_log2(subs): N = subs[n] return [(factorial(N), meijerg([1]*(N + 1), [], [], [0]*(N + 1), t))] # TODO these only hold for positive p, and can be made more general # but who uses log(x)*Heaviside(a-x) anyway ... # TODO also it would be nice to derive them recursively ... addi(log(t)**n*Heaviside(1 - t), make_log1, True) addi(log(t)**n*Heaviside(t - 1), make_log2, True) def make_log3(subs): return make_log1(subs) + make_log2(subs) addi(log(t)**n, make_log3, True) addi(log(t + a), constant(log(a)) + [(S.One, meijerg([1, 1], [], [1], [0], t/a))], True) addi(log(Abs(t - a)), constant(log(Abs(a))) + [(pi, meijerg([1, 1], [S.Half], [1], [0, S.Half], t/a))], True) # TODO log(x)/(x+a) and log(x)/(x-1) can also be done. should they # be derivable? # TODO further formulae in this section seem obscure # Sections 8.4.9-10 # TODO # Section 8.4.11 addi(Ei(t), constant(-S.ImaginaryUnit*pi) + [(S.NegativeOne, meijerg([], [1], [0, 0], [], t*polar_lift(-1)))], True) # Section 8.4.12 add(Si(t), [1], [], [S.Half], [0, 0], t**2/4, sqrt(pi)/2) add(Ci(t), [], [1], [0, 0], [S.Half], t**2/4, -sqrt(pi)/2) # Section 8.4.13 add(Shi(t), [S.Half], [], [0], [Rational(-1, 2), Rational(-1, 2)], polar_lift(-1)*t**2/4, t*sqrt(pi)/4) add(Chi(t), [], [S.Half, 1], [0, 0], [S.Half, S.Half], t**2/4, - pi**S('3/2')/2) # generalized exponential integral add(expint(a, t), [], [a], [a - 1, 0], [], t) # Section 8.4.14 add(erf(t), [1], [], [S.Half], [0], t**2, 1/sqrt(pi)) # TODO exp(-x)*erf(I*x) does not work add(erfc(t), [], [1], [0, S.Half], [], t**2, 1/sqrt(pi)) # This formula for erfi(z) yields a wrong(?) minus sign #add(erfi(t), [1], [], [S.Half], [0], -t**2, I/sqrt(pi)) add(erfi(t), [S.Half], [], [0], [Rational(-1, 2)], -t**2, t/sqrt(pi)) # Fresnel Integrals add(fresnels(t), [1], [], [Rational(3, 4)], [0, Rational(1, 4)], pi**2*t**4/16, S.Half) add(fresnelc(t), [1], [], [Rational(1, 4)], [0, Rational(3, 4)], pi**2*t**4/16, S.Half) ##### bessel-type functions ##### # Section 8.4.19 add(besselj(a, t), [], [], [a/2], [-a/2], t**2/4) # all of the following are derivable #add(sin(t)*besselj(a, t), [Rational(1, 4), Rational(3, 4)], [], [(1+a)/2], # [-a/2, a/2, (1-a)/2], t**2, 1/sqrt(2)) #add(cos(t)*besselj(a, t), [Rational(1, 4), Rational(3, 4)], [], [a/2], # [-a/2, (1+a)/2, (1-a)/2], t**2, 1/sqrt(2)) #add(besselj(a, t)**2, [S.Half], [], [a], [-a, 0], t**2, 1/sqrt(pi)) #add(besselj(a, t)*besselj(b, t), [0, S.Half], [], [(a + b)/2], # [-(a+b)/2, (a - b)/2, (b - a)/2], t**2, 1/sqrt(pi)) # Section 8.4.20 add(bessely(a, t), [], [-(a + 1)/2], [a/2, -a/2], [-(a + 1)/2], t**2/4) # TODO all of the following should be derivable #add(sin(t)*bessely(a, t), [Rational(1, 4), Rational(3, 4)], [(1 - a - 1)/2], # [(1 + a)/2, (1 - a)/2], [(1 - a - 1)/2, (1 - 1 - a)/2, (1 - 1 + a)/2], # t**2, 1/sqrt(2)) #add(cos(t)*bessely(a, t), [Rational(1, 4), Rational(3, 4)], [(0 - a - 1)/2], # [(0 + a)/2, (0 - a)/2], [(0 - a - 1)/2, (1 - 0 - a)/2, (1 - 0 + a)/2], # t**2, 1/sqrt(2)) #add(besselj(a, t)*bessely(b, t), [0, S.Half], [(a - b - 1)/2], # [(a + b)/2, (a - b)/2], [(a - b - 1)/2, -(a + b)/2, (b - a)/2], # t**2, 1/sqrt(pi)) #addi(bessely(a, t)**2, # [(2/sqrt(pi), meijerg([], [S.Half, S.Half - a], [0, a, -a], # [S.Half - a], t**2)), # (1/sqrt(pi), meijerg([S.Half], [], [a], [-a, 0], t**2))], # True) #addi(bessely(a, t)*bessely(b, t), # [(2/sqrt(pi), meijerg([], [0, S.Half, (1 - a - b)/2], # [(a + b)/2, (a - b)/2, (b - a)/2, -(a + b)/2], # [(1 - a - b)/2], t**2)), # (1/sqrt(pi), meijerg([0, S.Half], [], [(a + b)/2], # [-(a + b)/2, (a - b)/2, (b - a)/2], t**2))], # True) # Section 8.4.21 ? # Section 8.4.22 add(besseli(a, t), [], [(1 + a)/2], [a/2], [-a/2, (1 + a)/2], t**2/4, pi) # TODO many more formulas. should all be derivable # Section 8.4.23 add(besselk(a, t), [], [], [a/2, -a/2], [], t**2/4, S.Half) # TODO many more formulas. should all be derivable # Complete elliptic integrals K(z) and E(z) add(elliptic_k(t), [S.Half, S.Half], [], [0], [0], -t, S.Half) add(elliptic_e(t), [S.Half, 3*S.Half], [], [0], [0], -t, Rational(-1, 2)/2) #################################################################### # First some helper functions. #################################################################### from sympy.utilities.timeutils import timethis timeit = timethis('meijerg') def _mytype(f, x): """ Create a hashable entity describing the type of f. """ if x not in f.free_symbols: return () elif f.is_Function: return (type(f),) else: types = [_mytype(a, x) for a in f.args] res = [] for t in types: res += list(t) res.sort() return tuple(res) class _CoeffExpValueError(ValueError): """ Exception raised by _get_coeff_exp, for internal use only. """ pass def _get_coeff_exp(expr, x): """ When expr is known to be of the form c*x**b, with c and/or b possibly 1, return c, b. Examples ======== >>> from sympy.abc import x, a, b >>> from sympy.integrals.meijerint import _get_coeff_exp >>> _get_coeff_exp(a*x**b, x) (a, b) >>> _get_coeff_exp(x, x) (1, 1) >>> _get_coeff_exp(2*x, x) (2, 1) >>> _get_coeff_exp(x**3, x) (1, 3) """ from sympy.simplify import powsimp (c, m) = expand_power_base(powsimp(expr)).as_coeff_mul(x) if not m: return c, S.Zero [m] = m if m.is_Pow: if m.base != x: raise _CoeffExpValueError('expr not of form a*x**b') return c, m.exp elif m == x: return c, S.One else: raise _CoeffExpValueError('expr not of form a*x**b: %s' % expr) def _exponents(expr, x): """ Find the exponents of ``x`` (not including zero) in ``expr``. Examples ======== >>> from sympy.integrals.meijerint import _exponents >>> from sympy.abc import x, y >>> from sympy import sin >>> _exponents(x, x) {1} >>> _exponents(x**2, x) {2} >>> _exponents(x**2 + x, x) {1, 2} >>> _exponents(x**3*sin(x + x**y) + 1/x, x) {-1, 1, 3, y} """ def _exponents_(expr, x, res): if expr == x: res.update([1]) return if expr.is_Pow and expr.base == x: res.update([expr.exp]) return for argument in expr.args: _exponents_(argument, x, res) res = set() _exponents_(expr, x, res) return res def _functions(expr, x): """ Find the types of functions in expr, to estimate the complexity. """ return {e.func for e in expr.atoms(Function) if x in e.free_symbols} def _find_splitting_points(expr, x): """ Find numbers a such that a linear substitution x -> x + a would (hopefully) simplify expr. Examples ======== >>> from sympy.integrals.meijerint import _find_splitting_points as fsp >>> from sympy import sin >>> from sympy.abc import x >>> fsp(x, x) {0} >>> fsp((x-1)**3, x) {1} >>> fsp(sin(x+3)*x, x) {-3, 0} """ p, q = [Wild(n, exclude=[x]) for n in 'pq'] def compute_innermost(expr, res): if not isinstance(expr, Expr): return m = expr.match(p*x + q) if m and m[p] != 0: res.add(-m[q]/m[p]) return if expr.is_Atom: return for argument in expr.args: compute_innermost(argument, res) innermost = set() compute_innermost(expr, innermost) return innermost def _split_mul(f, x): """ Split expression ``f`` into fac, po, g, where fac is a constant factor, po = x**s for some s independent of s, and g is "the rest". Examples ======== >>> from sympy.integrals.meijerint import _split_mul >>> from sympy import sin >>> from sympy.abc import s, x >>> _split_mul((3*x)**s*sin(x**2)*x, x) (3**s, x*x**s, sin(x**2)) """ fac = S.One po = S.One g = S.One f = expand_power_base(f) args = Mul.make_args(f) for a in args: if a == x: po *= x elif x not in a.free_symbols: fac *= a else: if a.is_Pow and x not in a.exp.free_symbols: c, t = a.base.as_coeff_mul(x) if t != (x,): c, t = expand_mul(a.base).as_coeff_mul(x) if t == (x,): po *= x**a.exp fac *= unpolarify(polarify(c**a.exp, subs=False)) continue g *= a return fac, po, g def _mul_args(f): """ Return a list ``L`` such that ``Mul(*L) == f``. If ``f`` is not a ``Mul`` or ``Pow``, ``L=[f]``. If ``f=g**n`` for an integer ``n``, ``L=[g]*n``. If ``f`` is a ``Mul``, ``L`` comes from applying ``_mul_args`` to all factors of ``f``. """ args = Mul.make_args(f) gs = [] for g in args: if g.is_Pow and g.exp.is_Integer: n = g.exp base = g.base if n < 0: n = -n base = 1/base gs += [base]*n else: gs.append(g) return gs def _mul_as_two_parts(f): """ Find all the ways to split ``f`` into a product of two terms. Return None on failure. Explanation =========== Although the order is canonical from multiset_partitions, this is not necessarily the best order to process the terms. For example, if the case of len(gs) == 2 is removed and multiset is allowed to sort the terms, some tests fail. Examples ======== >>> from sympy.integrals.meijerint import _mul_as_two_parts >>> from sympy import sin, exp, ordered >>> from sympy.abc import x >>> list(ordered(_mul_as_two_parts(x*sin(x)*exp(x)))) [(x, exp(x)*sin(x)), (x*exp(x), sin(x)), (x*sin(x), exp(x))] """ gs = _mul_args(f) if len(gs) < 2: return None if len(gs) == 2: return [tuple(gs)] return [(Mul(*x), Mul(*y)) for (x, y) in multiset_partitions(gs, 2)] def _inflate_g(g, n): """ Return C, h such that h is a G function of argument z**n and g = C*h. """ # TODO should this be a method of meijerg? # See: [L, page 150, equation (5)] def inflate(params, n): """ (a1, .., ak) -> (a1/n, (a1+1)/n, ..., (ak + n-1)/n) """ return [(a + i)/n for a, i in itertools.product(params, range(n))] v = S(len(g.ap) - len(g.bq)) C = n**(1 + g.nu + v/2) C /= (2*pi)**((n - 1)*g.delta) return C, meijerg(inflate(g.an, n), inflate(g.aother, n), inflate(g.bm, n), inflate(g.bother, n), g.argument**n * n**(n*v)) def _flip_g(g): """ Turn the G function into one of inverse argument (i.e. G(1/x) -> G'(x)) """ # See [L], section 5.2 def tr(l): return [1 - a for a in l] return meijerg(tr(g.bm), tr(g.bother), tr(g.an), tr(g.aother), 1/g.argument) def _inflate_fox_h(g, a): r""" Let d denote the integrand in the definition of the G function ``g``. Consider the function H which is defined in the same way, but with integrand d/Gamma(a*s) (contour conventions as usual). If ``a`` is rational, the function H can be written as C*G, for a constant C and a G-function G. This function returns C, G. """ if a < 0: return _inflate_fox_h(_flip_g(g), -a) p = S(a.p) q = S(a.q) # We use the substitution s->qs, i.e. inflate g by q. We are left with an # extra factor of Gamma(p*s), for which we use Gauss' multiplication # theorem. D, g = _inflate_g(g, q) z = g.argument D /= (2*pi)**((1 - p)/2)*p**Rational(-1, 2) z /= p**p bs = [(n + 1)/p for n in range(p)] return D, meijerg(g.an, g.aother, g.bm, list(g.bother) + bs, z) _dummies = {} # type: tDict[tTuple[str, str], Dummy] def _dummy(name, token, expr, **kwargs): """ Return a dummy. This will return the same dummy if the same token+name is requested more than once, and it is not already in expr. This is for being cache-friendly. """ d = _dummy_(name, token, **kwargs) if d in expr.free_symbols: return Dummy(name, **kwargs) return d def _dummy_(name, token, **kwargs): """ Return a dummy associated to name and token. Same effect as declaring it globally. """ global _dummies if not (name, token) in _dummies: _dummies[(name, token)] = Dummy(name, **kwargs) return _dummies[(name, token)] def _is_analytic(f, x): """ Check if f(x), when expressed using G functions on the positive reals, will in fact agree with the G functions almost everywhere """ return not any(x in expr.free_symbols for expr in f.atoms(Heaviside, Abs)) def _condsimp(cond, first=True): """ Do naive simplifications on ``cond``. Explanation =========== Note that this routine is completely ad-hoc, simplification rules being added as need arises rather than following any logical pattern. Examples ======== >>> from sympy.integrals.meijerint import _condsimp as simp >>> from sympy import Or, Eq >>> from sympy.abc import x, y >>> simp(Or(x < y, Eq(x, y))) x <= y """ if first: cond = cond.replace(lambda _: _.is_Relational, _canonical_coeff) first = False if not isinstance(cond, BooleanFunction): return cond p, q, r = symbols('p q r', cls=Wild) # transforms tests use 0, 4, 5 and 11-14 # meijer tests use 0, 2, 11, 14 # joint_rv uses 6, 7 rules = [ (Or(p < q, Eq(p, q)), p <= q), # 0 # The next two obviously are instances of a general pattern, but it is # easier to spell out the few cases we care about. (And(Abs(arg(p)) <= pi, Abs(arg(p) - 2*pi) <= pi), Eq(arg(p) - pi, 0)), # 1 (And(Abs(2*arg(p) + pi) <= pi, Abs(2*arg(p) - pi) <= pi), Eq(arg(p), 0)), # 2 (And(Abs(2*arg(p) + pi) < pi, Abs(2*arg(p) - pi) <= pi), S.false), # 3 (And(Abs(arg(p) - pi/2) <= pi/2, Abs(arg(p) + pi/2) <= pi/2), Eq(arg(p), 0)), # 4 (And(Abs(arg(p) - pi/2) <= pi/2, Abs(arg(p) + pi/2) < pi/2), S.false), # 5 (And(Abs(arg(p**2/2 + 1)) < pi, Ne(Abs(arg(p**2/2 + 1)), pi)), S.true), # 6 (Or(Abs(arg(p**2/2 + 1)) < pi, Ne(1/(p**2/2 + 1), 0)), S.true), # 7 (And(Abs(unbranched_argument(p)) <= pi, Abs(unbranched_argument(exp_polar(-2*pi*S.ImaginaryUnit)*p)) <= pi), Eq(unbranched_argument(exp_polar(-S.ImaginaryUnit*pi)*p), 0)), # 8 (And(Abs(unbranched_argument(p)) <= pi/2, Abs(unbranched_argument(exp_polar(-pi*S.ImaginaryUnit)*p)) <= pi/2), Eq(unbranched_argument(exp_polar(-S.ImaginaryUnit*pi/2)*p), 0)), # 9 (Or(p <= q, And(p < q, r)), p <= q), # 10 (Ne(p**2, 1) & (p**2 > 1), p**2 > 1), # 11 (Ne(1/p, 1) & (cos(Abs(arg(p)))*Abs(p) > 1), Abs(p) > 1), # 12 (Ne(p, 2) & (cos(Abs(arg(p)))*Abs(p) > 2), Abs(p) > 2), # 13 ((Abs(arg(p)) < pi/2) & (cos(Abs(arg(p)))*sqrt(Abs(p**2)) > 1), p**2 > 1), # 14 ] cond = cond.func(*list(map(lambda _: _condsimp(_, first), cond.args))) change = True while change: change = False for irule, (fro, to) in enumerate(rules): if fro.func != cond.func: continue for n, arg1 in enumerate(cond.args): if r in fro.args[0].free_symbols: m = arg1.match(fro.args[1]) num = 1 else: num = 0 m = arg1.match(fro.args[0]) if not m: continue otherargs = [x.subs(m) for x in fro.args[:num] + fro.args[num + 1:]] otherlist = [n] for arg2 in otherargs: for k, arg3 in enumerate(cond.args): if k in otherlist: continue if arg2 == arg3: otherlist += [k] break if isinstance(arg3, And) and arg2.args[1] == r and \ isinstance(arg2, And) and arg2.args[0] in arg3.args: otherlist += [k] break if isinstance(arg3, And) and arg2.args[0] == r and \ isinstance(arg2, And) and arg2.args[1] in arg3.args: otherlist += [k] break if len(otherlist) != len(otherargs) + 1: continue newargs = [arg_ for (k, arg_) in enumerate(cond.args) if k not in otherlist] + [to.subs(m)] if SYMPY_DEBUG: if irule not in (0, 2, 4, 5, 6, 7, 11, 12, 13, 14): print('used new rule:', irule) cond = cond.func(*newargs) change = True break # final tweak def rel_touchup(rel): if rel.rel_op != '==' or rel.rhs != 0: return rel # handle Eq(*, 0) LHS = rel.lhs m = LHS.match(arg(p)**q) if not m: m = LHS.match(unbranched_argument(polar_lift(p)**q)) if not m: if isinstance(LHS, periodic_argument) and not LHS.args[0].is_polar \ and LHS.args[1] is S.Infinity: return (LHS.args[0] > 0) return rel return (m[p] > 0) cond = cond.replace(lambda _: _.is_Relational, rel_touchup) if SYMPY_DEBUG: print('_condsimp: ', cond) return cond def _eval_cond(cond): """ Re-evaluate the conditions. """ if isinstance(cond, bool): return cond return _condsimp(cond.doit()) #################################################################### # Now the "backbone" functions to do actual integration. #################################################################### def _my_principal_branch(expr, period, full_pb=False): """ Bring expr nearer to its principal branch by removing superfluous factors. This function does *not* guarantee to yield the principal branch, to avoid introducing opaque principal_branch() objects, unless full_pb=True. """ res = principal_branch(expr, period) if not full_pb: res = res.replace(principal_branch, lambda x, y: x) return res def _rewrite_saxena_1(fac, po, g, x): """ Rewrite the integral fac*po*g dx, from zero to infinity, as integral fac*G, where G has argument a*x. Note po=x**s. Return fac, G. """ _, s = _get_coeff_exp(po, x) a, b = _get_coeff_exp(g.argument, x) period = g.get_period() a = _my_principal_branch(a, period) # We substitute t = x**b. C = fac/(Abs(b)*a**((s + 1)/b - 1)) # Absorb a factor of (at)**((1 + s)/b - 1). def tr(l): return [a + (1 + s)/b - 1 for a in l] return C, meijerg(tr(g.an), tr(g.aother), tr(g.bm), tr(g.bother), a*x) def _check_antecedents_1(g, x, helper=False): r""" Return a condition under which the mellin transform of g exists. Any power of x has already been absorbed into the G function, so this is just $\int_0^\infty g\, dx$. See [L, section 5.6.1]. (Note that s=1.) If ``helper`` is True, only check if the MT exists at infinity, i.e. if $\int_1^\infty g\, dx$ exists. """ # NOTE if you update these conditions, please update the documentation as well delta = g.delta eta, _ = _get_coeff_exp(g.argument, x) m, n, p, q = S([len(g.bm), len(g.an), len(g.ap), len(g.bq)]) if p > q: def tr(l): return [1 - x for x in l] return _check_antecedents_1(meijerg(tr(g.bm), tr(g.bother), tr(g.an), tr(g.aother), x/eta), x) tmp = [-re(b) < 1 for b in g.bm] + [1 < 1 - re(a) for a in g.an] cond_3 = And(*tmp) tmp += [-re(b) < 1 for b in g.bother] tmp += [1 < 1 - re(a) for a in g.aother] cond_3_star = And(*tmp) cond_4 = (-re(g.nu) + (q + 1 - p)/2 > q - p) def debug(*msg): _debug(*msg) debug('Checking antecedents for 1 function:') debug(' delta=%s, eta=%s, m=%s, n=%s, p=%s, q=%s' % (delta, eta, m, n, p, q)) debug(' ap = %s, %s' % (list(g.an), list(g.aother))) debug(' bq = %s, %s' % (list(g.bm), list(g.bother))) debug(' cond_3=%s, cond_3*=%s, cond_4=%s' % (cond_3, cond_3_star, cond_4)) conds = [] # case 1 case1 = [] tmp1 = [1 <= n, p < q, 1 <= m] tmp2 = [1 <= p, 1 <= m, Eq(q, p + 1), Not(And(Eq(n, 0), Eq(m, p + 1)))] tmp3 = [1 <= p, Eq(q, p)] for k in range(ceiling(delta/2) + 1): tmp3 += [Ne(Abs(unbranched_argument(eta)), (delta - 2*k)*pi)] tmp = [delta > 0, Abs(unbranched_argument(eta)) < delta*pi] extra = [Ne(eta, 0), cond_3] if helper: extra = [] for t in [tmp1, tmp2, tmp3]: case1 += [And(*(t + tmp + extra))] conds += case1 debug(' case 1:', case1) # case 2 extra = [cond_3] if helper: extra = [] case2 = [And(Eq(n, 0), p + 1 <= m, m <= q, Abs(unbranched_argument(eta)) < delta*pi, *extra)] conds += case2 debug(' case 2:', case2) # case 3 extra = [cond_3, cond_4] if helper: extra = [] case3 = [And(p < q, 1 <= m, delta > 0, Eq(Abs(unbranched_argument(eta)), delta*pi), *extra)] case3 += [And(p <= q - 2, Eq(delta, 0), Eq(Abs(unbranched_argument(eta)), 0), *extra)] conds += case3 debug(' case 3:', case3) # TODO altered cases 4-7 # extra case from wofram functions site: # (reproduced verbatim from Prudnikov, section 2.24.2) # http://functions.wolfram.com/HypergeometricFunctions/MeijerG/21/02/01/ case_extra = [] case_extra += [Eq(p, q), Eq(delta, 0), Eq(unbranched_argument(eta), 0), Ne(eta, 0)] if not helper: case_extra += [cond_3] s = [] for a, b in zip(g.ap, g.bq): s += [b - a] case_extra += [re(Add(*s)) < 0] case_extra = And(*case_extra) conds += [case_extra] debug(' extra case:', [case_extra]) case_extra_2 = [And(delta > 0, Abs(unbranched_argument(eta)) < delta*pi)] if not helper: case_extra_2 += [cond_3] case_extra_2 = And(*case_extra_2) conds += [case_extra_2] debug(' second extra case:', [case_extra_2]) # TODO This leaves only one case from the three listed by Prudnikov. # Investigate if these indeed cover everything; if so, remove the rest. return Or(*conds) def _int0oo_1(g, x): r""" Evaluate $\int_0^\infty g\, dx$ using G functions, assuming the necessary conditions are fulfilled. Examples ======== >>> from sympy.abc import a, b, c, d, x, y >>> from sympy import meijerg >>> from sympy.integrals.meijerint import _int0oo_1 >>> _int0oo_1(meijerg([a], [b], [c], [d], x*y), x) gamma(-a)*gamma(c + 1)/(y*gamma(-d)*gamma(b + 1)) """ from sympy.simplify import gammasimp # See [L, section 5.6.1]. Note that s=1. eta, _ = _get_coeff_exp(g.argument, x) res = 1/eta # XXX TODO we should reduce order first for b in g.bm: res *= gamma(b + 1) for a in g.an: res *= gamma(1 - a - 1) for b in g.bother: res /= gamma(1 - b - 1) for a in g.aother: res /= gamma(a + 1) return gammasimp(unpolarify(res)) def _rewrite_saxena(fac, po, g1, g2, x, full_pb=False): """ Rewrite the integral ``fac*po*g1*g2`` from 0 to oo in terms of G functions with argument ``c*x``. Explanation =========== Return C, f1, f2 such that integral C f1 f2 from 0 to infinity equals integral fac ``po``, ``g1``, ``g2`` from 0 to infinity. Examples ======== >>> from sympy.integrals.meijerint import _rewrite_saxena >>> from sympy.abc import s, t, m >>> from sympy import meijerg >>> g1 = meijerg([], [], [0], [], s*t) >>> g2 = meijerg([], [], [m/2], [-m/2], t**2/4) >>> r = _rewrite_saxena(1, t**0, g1, g2, t) >>> r[0] s/(4*sqrt(pi)) >>> r[1] meijerg(((), ()), ((-1/2, 0), ()), s**2*t/4) >>> r[2] meijerg(((), ()), ((m/2,), (-m/2,)), t/4) """ def pb(g): a, b = _get_coeff_exp(g.argument, x) per = g.get_period() return meijerg(g.an, g.aother, g.bm, g.bother, _my_principal_branch(a, per, full_pb)*x**b) _, s = _get_coeff_exp(po, x) _, b1 = _get_coeff_exp(g1.argument, x) _, b2 = _get_coeff_exp(g2.argument, x) if (b1 < 0) == True: b1 = -b1 g1 = _flip_g(g1) if (b2 < 0) == True: b2 = -b2 g2 = _flip_g(g2) if not b1.is_Rational or not b2.is_Rational: return m1, n1 = b1.p, b1.q m2, n2 = b2.p, b2.q tau = ilcm(m1*n2, m2*n1) r1 = tau//(m1*n2) r2 = tau//(m2*n1) C1, g1 = _inflate_g(g1, r1) C2, g2 = _inflate_g(g2, r2) g1 = pb(g1) g2 = pb(g2) fac *= C1*C2 a1, b = _get_coeff_exp(g1.argument, x) a2, _ = _get_coeff_exp(g2.argument, x) # arbitrarily tack on the x**s part to g1 # TODO should we try both? exp = (s + 1)/b - 1 fac = fac/(Abs(b) * a1**exp) def tr(l): return [a + exp for a in l] g1 = meijerg(tr(g1.an), tr(g1.aother), tr(g1.bm), tr(g1.bother), a1*x) g2 = meijerg(g2.an, g2.aother, g2.bm, g2.bother, a2*x) from sympy.simplify import powdenest return powdenest(fac, polar=True), g1, g2 def _check_antecedents(g1, g2, x): """ Return a condition under which the integral theorem applies. """ # Yes, this is madness. # XXX TODO this is a testing *nightmare* # NOTE if you update these conditions, please update the documentation as well # The following conditions are found in # [P], Section 2.24.1 # # They are also reproduced (verbatim!) at # http://functions.wolfram.com/HypergeometricFunctions/MeijerG/21/02/03/ # # Note: k=l=r=alpha=1 sigma, _ = _get_coeff_exp(g1.argument, x) omega, _ = _get_coeff_exp(g2.argument, x) s, t, u, v = S([len(g1.bm), len(g1.an), len(g1.ap), len(g1.bq)]) m, n, p, q = S([len(g2.bm), len(g2.an), len(g2.ap), len(g2.bq)]) bstar = s + t - (u + v)/2 cstar = m + n - (p + q)/2 rho = g1.nu + (u - v)/2 + 1 mu = g2.nu + (p - q)/2 + 1 phi = q - p - (v - u) eta = 1 - (v - u) - mu - rho psi = (pi*(q - m - n) + Abs(unbranched_argument(omega)))/(q - p) theta = (pi*(v - s - t) + Abs(unbranched_argument(sigma)))/(v - u) _debug('Checking antecedents:') _debug(' sigma=%s, s=%s, t=%s, u=%s, v=%s, b*=%s, rho=%s' % (sigma, s, t, u, v, bstar, rho)) _debug(' omega=%s, m=%s, n=%s, p=%s, q=%s, c*=%s, mu=%s,' % (omega, m, n, p, q, cstar, mu)) _debug(' phi=%s, eta=%s, psi=%s, theta=%s' % (phi, eta, psi, theta)) def _c1(): for g in [g1, g2]: for i, j in itertools.product(g.an, g.bm): diff = i - j if diff.is_integer and diff.is_positive: return False return True c1 = _c1() c2 = And(*[re(1 + i + j) > 0 for i in g1.bm for j in g2.bm]) c3 = And(*[re(1 + i + j) < 1 + 1 for i in g1.an for j in g2.an]) c4 = And(*[(p - q)*re(1 + i - 1) - re(mu) > Rational(-3, 2) for i in g1.an]) c5 = And(*[(p - q)*re(1 + i) - re(mu) > Rational(-3, 2) for i in g1.bm]) c6 = And(*[(u - v)*re(1 + i - 1) - re(rho) > Rational(-3, 2) for i in g2.an]) c7 = And(*[(u - v)*re(1 + i) - re(rho) > Rational(-3, 2) for i in g2.bm]) c8 = (Abs(phi) + 2*re((rho - 1)*(q - p) + (v - u)*(q - p) + (mu - 1)*(v - u)) > 0) c9 = (Abs(phi) - 2*re((rho - 1)*(q - p) + (v - u)*(q - p) + (mu - 1)*(v - u)) > 0) c10 = (Abs(unbranched_argument(sigma)) < bstar*pi) c11 = Eq(Abs(unbranched_argument(sigma)), bstar*pi) c12 = (Abs(unbranched_argument(omega)) < cstar*pi) c13 = Eq(Abs(unbranched_argument(omega)), cstar*pi) # The following condition is *not* implemented as stated on the wolfram # function site. In the book of Prudnikov there is an additional part # (the And involving re()). However, I only have this book in russian, and # I don't read any russian. The following condition is what other people # have told me it means. # Worryingly, it is different from the condition implemented in REDUCE. # The REDUCE implementation: # https://reduce-algebra.svn.sourceforge.net/svnroot/reduce-algebra/trunk/packages/defint/definta.red # (search for tst14) # The Wolfram alpha version: # http://functions.wolfram.com/HypergeometricFunctions/MeijerG/21/02/03/03/0014/ z0 = exp(-(bstar + cstar)*pi*S.ImaginaryUnit) zos = unpolarify(z0*omega/sigma) zso = unpolarify(z0*sigma/omega) if zos == 1/zso: c14 = And(Eq(phi, 0), bstar + cstar <= 1, Or(Ne(zos, 1), re(mu + rho + v - u) < 1, re(mu + rho + q - p) < 1)) else: def _cond(z): '''Returns True if abs(arg(1-z)) < pi, avoiding arg(0). Explanation =========== If ``z`` is 1 then arg is NaN. This raises a TypeError on `NaN < pi`. Previously this gave `False` so this behavior has been hardcoded here but someone should check if this NaN is more serious! This NaN is triggered by test_meijerint() in test_meijerint.py: `meijerint_definite(exp(x), x, 0, I)` ''' return z != 1 and Abs(arg(1 - z)) < pi c14 = And(Eq(phi, 0), bstar - 1 + cstar <= 0, Or(And(Ne(zos, 1), _cond(zos)), And(re(mu + rho + v - u) < 1, Eq(zos, 1)))) c14_alt = And(Eq(phi, 0), cstar - 1 + bstar <= 0, Or(And(Ne(zso, 1), _cond(zso)), And(re(mu + rho + q - p) < 1, Eq(zso, 1)))) # Since r=k=l=1, in our case there is c14_alt which is the same as calling # us with (g1, g2) = (g2, g1). The conditions below enumerate all cases # (i.e. we don't have to try arguments reversed by hand), and indeed try # all symmetric cases. (i.e. whenever there is a condition involving c14, # there is also a dual condition which is exactly what we would get when g1, # g2 were interchanged, *but c14 was unaltered*). # Hence the following seems correct: c14 = Or(c14, c14_alt) ''' When `c15` is NaN (e.g. from `psi` being NaN as happens during 'test_issue_4992' and/or `theta` is NaN as in 'test_issue_6253', both in `test_integrals.py`) the comparison to 0 formerly gave False whereas now an error is raised. To keep the old behavior, the value of NaN is replaced with False but perhaps a closer look at this condition should be made: XXX how should conditions leading to c15=NaN be handled? ''' try: lambda_c = (q - p)*Abs(omega)**(1/(q - p))*cos(psi) \ + (v - u)*Abs(sigma)**(1/(v - u))*cos(theta) # the TypeError might be raised here, e.g. if lambda_c is NaN if _eval_cond(lambda_c > 0) != False: c15 = (lambda_c > 0) else: def lambda_s0(c1, c2): return c1*(q - p)*Abs(omega)**(1/(q - p))*sin(psi) \ + c2*(v - u)*Abs(sigma)**(1/(v - u))*sin(theta) lambda_s = Piecewise( ((lambda_s0(+1, +1)*lambda_s0(-1, -1)), And(Eq(unbranched_argument(sigma), 0), Eq(unbranched_argument(omega), 0))), (lambda_s0(sign(unbranched_argument(omega)), +1)*lambda_s0(sign(unbranched_argument(omega)), -1), And(Eq(unbranched_argument(sigma), 0), Ne(unbranched_argument(omega), 0))), (lambda_s0(+1, sign(unbranched_argument(sigma)))*lambda_s0(-1, sign(unbranched_argument(sigma))), And(Ne(unbranched_argument(sigma), 0), Eq(unbranched_argument(omega), 0))), (lambda_s0(sign(unbranched_argument(omega)), sign(unbranched_argument(sigma))), True)) tmp = [lambda_c > 0, And(Eq(lambda_c, 0), Ne(lambda_s, 0), re(eta) > -1), And(Eq(lambda_c, 0), Eq(lambda_s, 0), re(eta) > 0)] c15 = Or(*tmp) except TypeError: c15 = False for cond, i in [(c1, 1), (c2, 2), (c3, 3), (c4, 4), (c5, 5), (c6, 6), (c7, 7), (c8, 8), (c9, 9), (c10, 10), (c11, 11), (c12, 12), (c13, 13), (c14, 14), (c15, 15)]: _debug(' c%s:' % i, cond) # We will return Or(*conds) conds = [] def pr(count): _debug(' case %s:' % count, conds[-1]) conds += [And(m*n*s*t != 0, bstar.is_positive is True, cstar.is_positive is True, c1, c2, c3, c10, c12)] # 1 pr(1) conds += [And(Eq(u, v), Eq(bstar, 0), cstar.is_positive is True, sigma.is_positive is True, re(rho) < 1, c1, c2, c3, c12)] # 2 pr(2) conds += [And(Eq(p, q), Eq(cstar, 0), bstar.is_positive is True, omega.is_positive is True, re(mu) < 1, c1, c2, c3, c10)] # 3 pr(3) conds += [And(Eq(p, q), Eq(u, v), Eq(bstar, 0), Eq(cstar, 0), sigma.is_positive is True, omega.is_positive is True, re(mu) < 1, re(rho) < 1, Ne(sigma, omega), c1, c2, c3)] # 4 pr(4) conds += [And(Eq(p, q), Eq(u, v), Eq(bstar, 0), Eq(cstar, 0), sigma.is_positive is True, omega.is_positive is True, re(mu + rho) < 1, Ne(omega, sigma), c1, c2, c3)] # 5 pr(5) conds += [And(p > q, s.is_positive is True, bstar.is_positive is True, cstar >= 0, c1, c2, c3, c5, c10, c13)] # 6 pr(6) conds += [And(p < q, t.is_positive is True, bstar.is_positive is True, cstar >= 0, c1, c2, c3, c4, c10, c13)] # 7 pr(7) conds += [And(u > v, m.is_positive is True, cstar.is_positive is True, bstar >= 0, c1, c2, c3, c7, c11, c12)] # 8 pr(8) conds += [And(u < v, n.is_positive is True, cstar.is_positive is True, bstar >= 0, c1, c2, c3, c6, c11, c12)] # 9 pr(9) conds += [And(p > q, Eq(u, v), Eq(bstar, 0), cstar >= 0, sigma.is_positive is True, re(rho) < 1, c1, c2, c3, c5, c13)] # 10 pr(10) conds += [And(p < q, Eq(u, v), Eq(bstar, 0), cstar >= 0, sigma.is_positive is True, re(rho) < 1, c1, c2, c3, c4, c13)] # 11 pr(11) conds += [And(Eq(p, q), u > v, bstar >= 0, Eq(cstar, 0), omega.is_positive is True, re(mu) < 1, c1, c2, c3, c7, c11)] # 12 pr(12) conds += [And(Eq(p, q), u < v, bstar >= 0, Eq(cstar, 0), omega.is_positive is True, re(mu) < 1, c1, c2, c3, c6, c11)] # 13 pr(13) conds += [And(p < q, u > v, bstar >= 0, cstar >= 0, c1, c2, c3, c4, c7, c11, c13)] # 14 pr(14) conds += [And(p > q, u < v, bstar >= 0, cstar >= 0, c1, c2, c3, c5, c6, c11, c13)] # 15 pr(15) conds += [And(p > q, u > v, bstar >= 0, cstar >= 0, c1, c2, c3, c5, c7, c8, c11, c13, c14)] # 16 pr(16) conds += [And(p < q, u < v, bstar >= 0, cstar >= 0, c1, c2, c3, c4, c6, c9, c11, c13, c14)] # 17 pr(17) conds += [And(Eq(t, 0), s.is_positive is True, bstar.is_positive is True, phi.is_positive is True, c1, c2, c10)] # 18 pr(18) conds += [And(Eq(s, 0), t.is_positive is True, bstar.is_positive is True, phi.is_negative is True, c1, c3, c10)] # 19 pr(19) conds += [And(Eq(n, 0), m.is_positive is True, cstar.is_positive is True, phi.is_negative is True, c1, c2, c12)] # 20 pr(20) conds += [And(Eq(m, 0), n.is_positive is True, cstar.is_positive is True, phi.is_positive is True, c1, c3, c12)] # 21 pr(21) conds += [And(Eq(s*t, 0), bstar.is_positive is True, cstar.is_positive is True, c1, c2, c3, c10, c12)] # 22 pr(22) conds += [And(Eq(m*n, 0), bstar.is_positive is True, cstar.is_positive is True, c1, c2, c3, c10, c12)] # 23 pr(23) # The following case is from [Luke1969]. As far as I can tell, it is *not* # covered by Prudnikov's. # Let G1 and G2 be the two G-functions. Suppose the integral exists from # 0 to a > 0 (this is easy the easy part), that G1 is exponential decay at # infinity, and that the mellin transform of G2 exists. # Then the integral exists. mt1_exists = _check_antecedents_1(g1, x, helper=True) mt2_exists = _check_antecedents_1(g2, x, helper=True) conds += [And(mt2_exists, Eq(t, 0), u < s, bstar.is_positive is True, c10, c1, c2, c3)] pr('E1') conds += [And(mt2_exists, Eq(s, 0), v < t, bstar.is_positive is True, c10, c1, c2, c3)] pr('E2') conds += [And(mt1_exists, Eq(n, 0), p < m, cstar.is_positive is True, c12, c1, c2, c3)] pr('E3') conds += [And(mt1_exists, Eq(m, 0), q < n, cstar.is_positive is True, c12, c1, c2, c3)] pr('E4') # Let's short-circuit if this worked ... # the rest is corner-cases and terrible to read. r = Or(*conds) if _eval_cond(r) != False: return r conds += [And(m + n > p, Eq(t, 0), Eq(phi, 0), s.is_positive is True, bstar.is_positive is True, cstar.is_negative is True, Abs(unbranched_argument(omega)) < (m + n - p + 1)*pi, c1, c2, c10, c14, c15)] # 24 pr(24) conds += [And(m + n > q, Eq(s, 0), Eq(phi, 0), t.is_positive is True, bstar.is_positive is True, cstar.is_negative is True, Abs(unbranched_argument(omega)) < (m + n - q + 1)*pi, c1, c3, c10, c14, c15)] # 25 pr(25) conds += [And(Eq(p, q - 1), Eq(t, 0), Eq(phi, 0), s.is_positive is True, bstar.is_positive is True, cstar >= 0, cstar*pi < Abs(unbranched_argument(omega)), c1, c2, c10, c14, c15)] # 26 pr(26) conds += [And(Eq(p, q + 1), Eq(s, 0), Eq(phi, 0), t.is_positive is True, bstar.is_positive is True, cstar >= 0, cstar*pi < Abs(unbranched_argument(omega)), c1, c3, c10, c14, c15)] # 27 pr(27) conds += [And(p < q - 1, Eq(t, 0), Eq(phi, 0), s.is_positive is True, bstar.is_positive is True, cstar >= 0, cstar*pi < Abs(unbranched_argument(omega)), Abs(unbranched_argument(omega)) < (m + n - p + 1)*pi, c1, c2, c10, c14, c15)] # 28 pr(28) conds += [And( p > q + 1, Eq(s, 0), Eq(phi, 0), t.is_positive is True, bstar.is_positive is True, cstar >= 0, cstar*pi < Abs(unbranched_argument(omega)), Abs(unbranched_argument(omega)) < (m + n - q + 1)*pi, c1, c3, c10, c14, c15)] # 29 pr(29) conds += [And(Eq(n, 0), Eq(phi, 0), s + t > 0, m.is_positive is True, cstar.is_positive is True, bstar.is_negative is True, Abs(unbranched_argument(sigma)) < (s + t - u + 1)*pi, c1, c2, c12, c14, c15)] # 30 pr(30) conds += [And(Eq(m, 0), Eq(phi, 0), s + t > v, n.is_positive is True, cstar.is_positive is True, bstar.is_negative is True, Abs(unbranched_argument(sigma)) < (s + t - v + 1)*pi, c1, c3, c12, c14, c15)] # 31 pr(31) conds += [And(Eq(n, 0), Eq(phi, 0), Eq(u, v - 1), m.is_positive is True, cstar.is_positive is True, bstar >= 0, bstar*pi < Abs(unbranched_argument(sigma)), Abs(unbranched_argument(sigma)) < (bstar + 1)*pi, c1, c2, c12, c14, c15)] # 32 pr(32) conds += [And(Eq(m, 0), Eq(phi, 0), Eq(u, v + 1), n.is_positive is True, cstar.is_positive is True, bstar >= 0, bstar*pi < Abs(unbranched_argument(sigma)), Abs(unbranched_argument(sigma)) < (bstar + 1)*pi, c1, c3, c12, c14, c15)] # 33 pr(33) conds += [And( Eq(n, 0), Eq(phi, 0), u < v - 1, m.is_positive is True, cstar.is_positive is True, bstar >= 0, bstar*pi < Abs(unbranched_argument(sigma)), Abs(unbranched_argument(sigma)) < (s + t - u + 1)*pi, c1, c2, c12, c14, c15)] # 34 pr(34) conds += [And( Eq(m, 0), Eq(phi, 0), u > v + 1, n.is_positive is True, cstar.is_positive is True, bstar >= 0, bstar*pi < Abs(unbranched_argument(sigma)), Abs(unbranched_argument(sigma)) < (s + t - v + 1)*pi, c1, c3, c12, c14, c15)] # 35 pr(35) return Or(*conds) # NOTE An alternative, but as far as I can tell weaker, set of conditions # can be found in [L, section 5.6.2]. def _int0oo(g1, g2, x): """ Express integral from zero to infinity g1*g2 using a G function, assuming the necessary conditions are fulfilled. Examples ======== >>> from sympy.integrals.meijerint import _int0oo >>> from sympy.abc import s, t, m >>> from sympy import meijerg, S >>> g1 = meijerg([], [], [-S(1)/2, 0], [], s**2*t/4) >>> g2 = meijerg([], [], [m/2], [-m/2], t/4) >>> _int0oo(g1, g2, t) 4*meijerg(((1/2, 0), ()), ((m/2,), (-m/2,)), s**(-2))/s**2 """ # See: [L, section 5.6.2, equation (1)] eta, _ = _get_coeff_exp(g1.argument, x) omega, _ = _get_coeff_exp(g2.argument, x) def neg(l): return [-x for x in l] a1 = neg(g1.bm) + list(g2.an) a2 = list(g2.aother) + neg(g1.bother) b1 = neg(g1.an) + list(g2.bm) b2 = list(g2.bother) + neg(g1.aother) return meijerg(a1, a2, b1, b2, omega/eta)/eta def _rewrite_inversion(fac, po, g, x): """ Absorb ``po`` == x**s into g. """ _, s = _get_coeff_exp(po, x) a, b = _get_coeff_exp(g.argument, x) def tr(l): return [t + s/b for t in l] from sympy.simplify import powdenest return (powdenest(fac/a**(s/b), polar=True), meijerg(tr(g.an), tr(g.aother), tr(g.bm), tr(g.bother), g.argument)) def _check_antecedents_inversion(g, x): """ Check antecedents for the laplace inversion integral. """ _debug('Checking antecedents for inversion:') z = g.argument _, e = _get_coeff_exp(z, x) if e < 0: _debug(' Flipping G.') # We want to assume that argument gets large as |x| -> oo return _check_antecedents_inversion(_flip_g(g), x) def statement_half(a, b, c, z, plus): coeff, exponent = _get_coeff_exp(z, x) a *= exponent b *= coeff**c c *= exponent conds = [] wp = b*exp(S.ImaginaryUnit*re(c)*pi/2) wm = b*exp(-S.ImaginaryUnit*re(c)*pi/2) if plus: w = wp else: w = wm conds += [And(Or(Eq(b, 0), re(c) <= 0), re(a) <= -1)] conds += [And(Ne(b, 0), Eq(im(c), 0), re(c) > 0, re(w) < 0)] conds += [And(Ne(b, 0), Eq(im(c), 0), re(c) > 0, re(w) <= 0, re(a) <= -1)] return Or(*conds) def statement(a, b, c, z): """ Provide a convergence statement for z**a * exp(b*z**c), c/f sphinx docs. """ return And(statement_half(a, b, c, z, True), statement_half(a, b, c, z, False)) # Notations from [L], section 5.7-10 m, n, p, q = S([len(g.bm), len(g.an), len(g.ap), len(g.bq)]) tau = m + n - p nu = q - m - n rho = (tau - nu)/2 sigma = q - p if sigma == 1: epsilon = S.Half elif sigma > 1: epsilon = 1 else: epsilon = S.NaN theta = ((1 - sigma)/2 + Add(*g.bq) - Add(*g.ap))/sigma delta = g.delta _debug(' m=%s, n=%s, p=%s, q=%s, tau=%s, nu=%s, rho=%s, sigma=%s' % ( m, n, p, q, tau, nu, rho, sigma)) _debug(' epsilon=%s, theta=%s, delta=%s' % (epsilon, theta, delta)) # First check if the computation is valid. if not (g.delta >= e/2 or (p >= 1 and p >= q)): _debug(' Computation not valid for these parameters.') return False # Now check if the inversion integral exists. # Test "condition A" for a, b in itertools.product(g.an, g.bm): if (a - b).is_integer and a > b: _debug(' Not a valid G function.') return False # There are two cases. If p >= q, we can directly use a slater expansion # like [L], 5.2 (11). Note in particular that the asymptotics of such an # expansion even hold when some of the parameters differ by integers, i.e. # the formula itself would not be valid! (b/c G functions are cts. in their # parameters) # When p < q, we need to use the theorems of [L], 5.10. if p >= q: _debug(' Using asymptotic Slater expansion.') return And(*[statement(a - 1, 0, 0, z) for a in g.an]) def E(z): return And(*[statement(a - 1, 0, 0, z) for a in g.an]) def H(z): return statement(theta, -sigma, 1/sigma, z) def Hp(z): return statement_half(theta, -sigma, 1/sigma, z, True) def Hm(z): return statement_half(theta, -sigma, 1/sigma, z, False) # [L], section 5.10 conds = [] # Theorem 1 -- p < q from test above conds += [And(1 <= n, 1 <= m, rho*pi - delta >= pi/2, delta > 0, E(z*exp(S.ImaginaryUnit*pi*(nu + 1))))] # Theorem 2, statements (2) and (3) conds += [And(p + 1 <= m, m + 1 <= q, delta > 0, delta < pi/2, n == 0, (m - p + 1)*pi - delta >= pi/2, Hp(z*exp(S.ImaginaryUnit*pi*(q - m))), Hm(z*exp(-S.ImaginaryUnit*pi*(q - m))))] # Theorem 2, statement (5) -- p < q from test above conds += [And(m == q, n == 0, delta > 0, (sigma + epsilon)*pi - delta >= pi/2, H(z))] # Theorem 3, statements (6) and (7) conds += [And(Or(And(p <= q - 2, 1 <= tau, tau <= sigma/2), And(p + 1 <= m + n, m + n <= (p + q)/2)), delta > 0, delta < pi/2, (tau + 1)*pi - delta >= pi/2, Hp(z*exp(S.ImaginaryUnit*pi*nu)), Hm(z*exp(-S.ImaginaryUnit*pi*nu)))] # Theorem 4, statements (10) and (11) -- p < q from test above conds += [And(1 <= m, rho > 0, delta > 0, delta + rho*pi < pi/2, (tau + epsilon)*pi - delta >= pi/2, Hp(z*exp(S.ImaginaryUnit*pi*nu)), Hm(z*exp(-S.ImaginaryUnit*pi*nu)))] # Trivial case conds += [m == 0] # TODO # Theorem 5 is quite general # Theorem 6 contains special cases for q=p+1 return Or(*conds) def _int_inversion(g, x, t): """ Compute the laplace inversion integral, assuming the formula applies. """ b, a = _get_coeff_exp(g.argument, x) C, g = _inflate_fox_h(meijerg(g.an, g.aother, g.bm, g.bother, b/t**a), -a) return C/t*g #################################################################### # Finally, the real meat. #################################################################### _lookup_table = None @cacheit @timeit def _rewrite_single(f, x, recursive=True): """ Try to rewrite f as a sum of single G functions of the form C*x**s*G(a*x**b), where b is a rational number and C is independent of x. We guarantee that result.argument.as_coeff_mul(x) returns (a, (x**b,)) or (a, ()). Returns a list of tuples (C, s, G) and a condition cond. Returns None on failure. """ from .transforms import (mellin_transform, inverse_mellin_transform, IntegralTransformError, MellinTransformStripError) global _lookup_table if not _lookup_table: _lookup_table = {} _create_lookup_table(_lookup_table) if isinstance(f, meijerg): coeff, m = factor(f.argument, x).as_coeff_mul(x) if len(m) > 1: return None m = m[0] if m.is_Pow: if m.base != x or not m.exp.is_Rational: return None elif m != x: return None return [(1, 0, meijerg(f.an, f.aother, f.bm, f.bother, coeff*m))], True f_ = f f = f.subs(x, z) t = _mytype(f, z) if t in _lookup_table: l = _lookup_table[t] for formula, terms, cond, hint in l: subs = f.match(formula, old=True) if subs: subs_ = {} for fro, to in subs.items(): subs_[fro] = unpolarify(polarify(to, lift=True), exponents_only=True) subs = subs_ if not isinstance(hint, bool): hint = hint.subs(subs) if hint == False: continue if not isinstance(cond, (bool, BooleanAtom)): cond = unpolarify(cond.subs(subs)) if _eval_cond(cond) == False: continue if not isinstance(terms, list): terms = terms(subs) res = [] for fac, g in terms: r1 = _get_coeff_exp(unpolarify(fac.subs(subs).subs(z, x), exponents_only=True), x) try: g = g.subs(subs).subs(z, x) except ValueError: continue # NOTE these substitutions can in principle introduce oo, # zoo and other absurdities. It shouldn't matter, # but better be safe. if Tuple(*(r1 + (g,))).has(S.Infinity, S.ComplexInfinity, S.NegativeInfinity): continue g = meijerg(g.an, g.aother, g.bm, g.bother, unpolarify(g.argument, exponents_only=True)) res.append(r1 + (g,)) if res: return res, cond # try recursive mellin transform if not recursive: return None _debug('Trying recursive Mellin transform method.') def my_imt(F, s, x, strip): """ Calling simplify() all the time is slow and not helpful, since most of the time it only factors things in a way that has to be un-done anyway. But sometimes it can remove apparent poles. """ # XXX should this be in inverse_mellin_transform? try: return inverse_mellin_transform(F, s, x, strip, as_meijerg=True, needeval=True) except MellinTransformStripError: from sympy.simplify import simplify return inverse_mellin_transform( simplify(cancel(expand(F))), s, x, strip, as_meijerg=True, needeval=True) f = f_ s = _dummy('s', 'rewrite-single', f) # to avoid infinite recursion, we have to force the two g functions case def my_integrator(f, x): r = _meijerint_definite_4(f, x, only_double=True) if r is not None: from sympy.simplify import hyperexpand res, cond = r res = _my_unpolarify(hyperexpand(res, rewrite='nonrepsmall')) return Piecewise((res, cond), (Integral(f, (x, S.Zero, S.Infinity)), True)) return Integral(f, (x, S.Zero, S.Infinity)) try: F, strip, _ = mellin_transform(f, x, s, integrator=my_integrator, simplify=False, needeval=True) g = my_imt(F, s, x, strip) except IntegralTransformError: g = None if g is None: # We try to find an expression by analytic continuation. # (also if the dummy is already in the expression, there is no point in # putting in another one) a = _dummy_('a', 'rewrite-single') if a not in f.free_symbols and _is_analytic(f, x): try: F, strip, _ = mellin_transform(f.subs(x, a*x), x, s, integrator=my_integrator, needeval=True, simplify=False) g = my_imt(F, s, x, strip).subs(a, 1) except IntegralTransformError: g = None if g is None or g.has(S.Infinity, S.NaN, S.ComplexInfinity): _debug('Recursive Mellin transform failed.') return None args = Add.make_args(g) res = [] for f in args: c, m = f.as_coeff_mul(x) if len(m) > 1: raise NotImplementedError('Unexpected form...') g = m[0] a, b = _get_coeff_exp(g.argument, x) res += [(c, 0, meijerg(g.an, g.aother, g.bm, g.bother, unpolarify(polarify( a, lift=True), exponents_only=True) *x**b))] _debug('Recursive Mellin transform worked:', g) return res, True def _rewrite1(f, x, recursive=True): """ Try to rewrite ``f`` using a (sum of) single G functions with argument a*x**b. Return fac, po, g such that f = fac*po*g, fac is independent of ``x``. and po = x**s. Here g is a result from _rewrite_single. Return None on failure. """ fac, po, g = _split_mul(f, x) g = _rewrite_single(g, x, recursive) if g: return fac, po, g[0], g[1] def _rewrite2(f, x): """ Try to rewrite ``f`` as a product of two G functions of arguments a*x**b. Return fac, po, g1, g2 such that f = fac*po*g1*g2, where fac is independent of x and po is x**s. Here g1 and g2 are results of _rewrite_single. Returns None on failure. """ fac, po, g = _split_mul(f, x) if any(_rewrite_single(expr, x, False) is None for expr in _mul_args(g)): return None l = _mul_as_two_parts(g) if not l: return None l = list(ordered(l, [ lambda p: max(len(_exponents(p[0], x)), len(_exponents(p[1], x))), lambda p: max(len(_functions(p[0], x)), len(_functions(p[1], x))), lambda p: max(len(_find_splitting_points(p[0], x)), len(_find_splitting_points(p[1], x)))])) for recursive, (fac1, fac2) in itertools.product((False, True), l): g1 = _rewrite_single(fac1, x, recursive) g2 = _rewrite_single(fac2, x, recursive) if g1 and g2: cond = And(g1[1], g2[1]) if cond != False: return fac, po, g1[0], g2[0], cond def meijerint_indefinite(f, x): """ Compute an indefinite integral of ``f`` by rewriting it as a G function. Examples ======== >>> from sympy.integrals.meijerint import meijerint_indefinite >>> from sympy import sin >>> from sympy.abc import x >>> meijerint_indefinite(sin(x), x) -cos(x) """ f = sympify(f) results = [] for a in sorted(_find_splitting_points(f, x) | {S.Zero}, key=default_sort_key): res = _meijerint_indefinite_1(f.subs(x, x + a), x) if not res: continue res = res.subs(x, x - a) if _has(res, hyper, meijerg): results.append(res) else: return res if f.has(HyperbolicFunction): _debug('Try rewriting hyperbolics in terms of exp.') rv = meijerint_indefinite( _rewrite_hyperbolics_as_exp(f), x) if rv: if not isinstance(rv, list): from sympy.simplify.radsimp import collect return collect(factor_terms(rv), rv.atoms(exp)) results.extend(rv) if results: return next(ordered(results)) def _meijerint_indefinite_1(f, x): """ Helper that does not attempt any substitution. """ _debug('Trying to compute the indefinite integral of', f, 'wrt', x) from sympy.simplify import hyperexpand, powdenest gs = _rewrite1(f, x) if gs is None: # Note: the code that calls us will do expand() and try again return None fac, po, gl, cond = gs _debug(' could rewrite:', gs) res = S.Zero for C, s, g in gl: a, b = _get_coeff_exp(g.argument, x) _, c = _get_coeff_exp(po, x) c += s # we do a substitution t=a*x**b, get integrand fac*t**rho*g fac_ = fac * C / (b*a**((1 + c)/b)) rho = (c + 1)/b - 1 # we now use t**rho*G(params, t) = G(params + rho, t) # [L, page 150, equation (4)] # and integral G(params, t) dt = G(1, params+1, 0, t) # (or a similar expression with 1 and 0 exchanged ... pick the one # which yields a well-defined function) # [R, section 5] # (Note that this dummy will immediately go away again, so we # can safely pass S.One for ``expr``.) t = _dummy('t', 'meijerint-indefinite', S.One) def tr(p): return [a + rho + 1 for a in p] if any(b.is_integer and (b <= 0) == True for b in tr(g.bm)): r = -meijerg( tr(g.an), tr(g.aother) + [1], tr(g.bm) + [0], tr(g.bother), t) else: r = meijerg( tr(g.an) + [1], tr(g.aother), tr(g.bm), tr(g.bother) + [0], t) # The antiderivative is most often expected to be defined # in the neighborhood of x = 0. if b.is_extended_nonnegative and not f.subs(x, 0).has(S.NaN, S.ComplexInfinity): place = 0 # Assume we can expand at zero else: place = None r = hyperexpand(r.subs(t, a*x**b), place=place) # now substitute back # Note: we really do want the powers of x to combine. res += powdenest(fac_*r, polar=True) def _clean(res): """This multiplies out superfluous powers of x we created, and chops off constants: >> _clean(x*(exp(x)/x - 1/x) + 3) exp(x) cancel is used before mul_expand since it is possible for an expression to have an additive constant that does not become isolated with simple expansion. Such a situation was identified in issue 6369: Examples ======== >>> from sympy import sqrt, cancel >>> from sympy.abc import x >>> a = sqrt(2*x + 1) >>> bad = (3*x*a**5 + 2*x - a**5 + 1)/a**2 >>> bad.expand().as_independent(x)[0] 0 >>> cancel(bad).expand().as_independent(x)[0] 1 """ res = expand_mul(cancel(res), deep=False) return Add._from_args(res.as_coeff_add(x)[1]) res = piecewise_fold(res, evaluate=None) if res.is_Piecewise: newargs = [] for e, c in res.args: e = _my_unpolarify(_clean(e)) newargs += [(e, c)] res = Piecewise(*newargs, evaluate=False) else: res = _my_unpolarify(_clean(res)) return Piecewise((res, _my_unpolarify(cond)), (Integral(f, x), True)) @timeit def meijerint_definite(f, x, a, b): """ Integrate ``f`` over the interval [``a``, ``b``], by rewriting it as a product of two G functions, or as a single G function. Return res, cond, where cond are convergence conditions. Examples ======== >>> from sympy.integrals.meijerint import meijerint_definite >>> from sympy import exp, oo >>> from sympy.abc import x >>> meijerint_definite(exp(-x**2), x, -oo, oo) (sqrt(pi), True) This function is implemented as a succession of functions meijerint_definite, _meijerint_definite_2, _meijerint_definite_3, _meijerint_definite_4. Each function in the list calls the next one (presumably) several times. This means that calling meijerint_definite can be very costly. """ # This consists of three steps: # 1) Change the integration limits to 0, oo # 2) Rewrite in terms of G functions # 3) Evaluate the integral # # There are usually several ways of doing this, and we want to try all. # This function does (1), calls _meijerint_definite_2 for step (2). _debug('Integrating', f, 'wrt %s from %s to %s.' % (x, a, b)) f = sympify(f) if f.has(DiracDelta): _debug('Integrand has DiracDelta terms - giving up.') return None if f.has(SingularityFunction): _debug('Integrand has Singularity Function terms - giving up.') return None f_, x_, a_, b_ = f, x, a, b # Let's use a dummy in case any of the boundaries has x. d = Dummy('x') f = f.subs(x, d) x = d if a == b: return (S.Zero, True) results = [] if a is S.NegativeInfinity and b is not S.Infinity: return meijerint_definite(f.subs(x, -x), x, -b, -a) elif a is S.NegativeInfinity: # Integrating -oo to oo. We need to find a place to split the integral. _debug(' Integrating -oo to +oo.') innermost = _find_splitting_points(f, x) _debug(' Sensible splitting points:', innermost) for c in sorted(innermost, key=default_sort_key, reverse=True) + [S.Zero]: _debug(' Trying to split at', c) if not c.is_extended_real: _debug(' Non-real splitting point.') continue res1 = _meijerint_definite_2(f.subs(x, x + c), x) if res1 is None: _debug(' But could not compute first integral.') continue res2 = _meijerint_definite_2(f.subs(x, c - x), x) if res2 is None: _debug(' But could not compute second integral.') continue res1, cond1 = res1 res2, cond2 = res2 cond = _condsimp(And(cond1, cond2)) if cond == False: _debug(' But combined condition is always false.') continue res = res1 + res2 return res, cond elif a is S.Infinity: res = meijerint_definite(f, x, b, S.Infinity) return -res[0], res[1] elif (a, b) == (S.Zero, S.Infinity): # This is a common case - try it directly first. res = _meijerint_definite_2(f, x) if res: if _has(res[0], meijerg): results.append(res) else: return res else: if b is S.Infinity: for split in _find_splitting_points(f, x): if (a - split >= 0) == True: _debug('Trying x -> x + %s' % split) res = _meijerint_definite_2(f.subs(x, x + split) *Heaviside(x + split - a), x) if res: if _has(res[0], meijerg): results.append(res) else: return res f = f.subs(x, x + a) b = b - a a = 0 if b is not S.Infinity: phi = exp(S.ImaginaryUnit*arg(b)) b = Abs(b) f = f.subs(x, phi*x) f *= Heaviside(b - x)*phi b = S.Infinity _debug('Changed limits to', a, b) _debug('Changed function to', f) res = _meijerint_definite_2(f, x) if res: if _has(res[0], meijerg): results.append(res) else: return res if f_.has(HyperbolicFunction): _debug('Try rewriting hyperbolics in terms of exp.') rv = meijerint_definite( _rewrite_hyperbolics_as_exp(f_), x_, a_, b_) if rv: if not isinstance(rv, list): from sympy.simplify.radsimp import collect rv = (collect(factor_terms(rv[0]), rv[0].atoms(exp)),) + rv[1:] return rv results.extend(rv) if results: return next(ordered(results)) def _guess_expansion(f, x): """ Try to guess sensible rewritings for integrand f(x). """ res = [(f, 'original integrand')] orig = res[-1][0] saw = {orig} expanded = expand_mul(orig) if expanded not in saw: res += [(expanded, 'expand_mul')] saw.add(expanded) expanded = expand(orig) if expanded not in saw: res += [(expanded, 'expand')] saw.add(expanded) if orig.has(TrigonometricFunction, HyperbolicFunction): expanded = expand_mul(expand_trig(orig)) if expanded not in saw: res += [(expanded, 'expand_trig, expand_mul')] saw.add(expanded) if orig.has(cos, sin): from sympy.simplify.fu import sincos_to_sum reduced = sincos_to_sum(orig) if reduced not in saw: res += [(reduced, 'trig power reduction')] saw.add(reduced) return res def _meijerint_definite_2(f, x): """ Try to integrate f dx from zero to infinity. The body of this function computes various 'simplifications' f1, f2, ... of f (e.g. by calling expand_mul(), trigexpand() - see _guess_expansion) and calls _meijerint_definite_3 with each of these in succession. If _meijerint_definite_3 succeeds with any of the simplified functions, returns this result. """ # This function does preparation for (2), calls # _meijerint_definite_3 for (2) and (3) combined. # use a positive dummy - we integrate from 0 to oo # XXX if a nonnegative symbol is used there will be test failures dummy = _dummy('x', 'meijerint-definite2', f, positive=True) f = f.subs(x, dummy) x = dummy if f == 0: return S.Zero, True for g, explanation in _guess_expansion(f, x): _debug('Trying', explanation) res = _meijerint_definite_3(g, x) if res: return res def _meijerint_definite_3(f, x): """ Try to integrate f dx from zero to infinity. This function calls _meijerint_definite_4 to try to compute the integral. If this fails, it tries using linearity. """ res = _meijerint_definite_4(f, x) if res and res[1] != False: return res if f.is_Add: _debug('Expanding and evaluating all terms.') ress = [_meijerint_definite_4(g, x) for g in f.args] if all(r is not None for r in ress): conds = [] res = S.Zero for r, c in ress: res += r conds += [c] c = And(*conds) if c != False: return res, c def _my_unpolarify(f): return _eval_cond(unpolarify(f)) @timeit def _meijerint_definite_4(f, x, only_double=False): """ Try to integrate f dx from zero to infinity. Explanation =========== This function tries to apply the integration theorems found in literature, i.e. it tries to rewrite f as either one or a product of two G-functions. The parameter ``only_double`` is used internally in the recursive algorithm to disable trying to rewrite f as a single G-function. """ from sympy.simplify import hyperexpand # This function does (2) and (3) _debug('Integrating', f) # Try single G function. if not only_double: gs = _rewrite1(f, x, recursive=False) if gs is not None: fac, po, g, cond = gs _debug('Could rewrite as single G function:', fac, po, g) res = S.Zero for C, s, f in g: if C == 0: continue C, f = _rewrite_saxena_1(fac*C, po*x**s, f, x) res += C*_int0oo_1(f, x) cond = And(cond, _check_antecedents_1(f, x)) if cond == False: break cond = _my_unpolarify(cond) if cond == False: _debug('But cond is always False.') else: _debug('Result before branch substitutions is:', res) return _my_unpolarify(hyperexpand(res)), cond # Try two G functions. gs = _rewrite2(f, x) if gs is not None: for full_pb in [False, True]: fac, po, g1, g2, cond = gs _debug('Could rewrite as two G functions:', fac, po, g1, g2) res = S.Zero for C1, s1, f1 in g1: for C2, s2, f2 in g2: r = _rewrite_saxena(fac*C1*C2, po*x**(s1 + s2), f1, f2, x, full_pb) if r is None: _debug('Non-rational exponents.') return C, f1_, f2_ = r _debug('Saxena subst for yielded:', C, f1_, f2_) cond = And(cond, _check_antecedents(f1_, f2_, x)) if cond == False: break res += C*_int0oo(f1_, f2_, x) else: continue break cond = _my_unpolarify(cond) if cond == False: _debug('But cond is always False (full_pb=%s).' % full_pb) else: _debug('Result before branch substitutions is:', res) if only_double: return res, cond return _my_unpolarify(hyperexpand(res)), cond def meijerint_inversion(f, x, t): r""" Compute the inverse laplace transform $\int_{c+i\infty}^{c-i\infty} f(x) e^{tx}\, dx$, for real c larger than the real part of all singularities of ``f``. Note that ``t`` is always assumed real and positive. Return None if the integral does not exist or could not be evaluated. Examples ======== >>> from sympy.abc import x, t >>> from sympy.integrals.meijerint import meijerint_inversion >>> meijerint_inversion(1/x, x, t) Heaviside(t) """ f_ = f t_ = t t = Dummy('t', polar=True) # We don't want sqrt(t**2) = abs(t) etc f = f.subs(t_, t) _debug('Laplace-inverting', f) if not _is_analytic(f, x): _debug('But expression is not analytic.') return None # Exponentials correspond to shifts; we filter them out and then # shift the result later. If we are given an Add this will not # work, but the calling code will take care of that. shift = S.Zero if f.is_Mul: args = list(f.args) elif isinstance(f, exp): args = [f] else: args = None if args: newargs = [] exponentials = [] while args: arg = args.pop() if isinstance(arg, exp): arg2 = expand(arg) if arg2.is_Mul: args += arg2.args continue try: a, b = _get_coeff_exp(arg.args[0], x) except _CoeffExpValueError: b = 0 if b == 1: exponentials.append(a) else: newargs.append(arg) elif arg.is_Pow: arg2 = expand(arg) if arg2.is_Mul: args += arg2.args continue if x not in arg.base.free_symbols: try: a, b = _get_coeff_exp(arg.exp, x) except _CoeffExpValueError: b = 0 if b == 1: exponentials.append(a*log(arg.base)) newargs.append(arg) else: newargs.append(arg) shift = Add(*exponentials) f = Mul(*newargs) if x not in f.free_symbols: _debug('Expression consists of constant and exp shift:', f, shift) cond = Eq(im(shift), 0) if cond == False: _debug('but shift is nonreal, cannot be a Laplace transform') return None res = f*DiracDelta(t + shift) _debug('Result is a delta function, possibly conditional:', res, cond) # cond is True or Eq return Piecewise((res.subs(t, t_), cond)) gs = _rewrite1(f, x) if gs is not None: fac, po, g, cond = gs _debug('Could rewrite as single G function:', fac, po, g) res = S.Zero for C, s, f in g: C, f = _rewrite_inversion(fac*C, po*x**s, f, x) res += C*_int_inversion(f, x, t) cond = And(cond, _check_antecedents_inversion(f, x)) if cond == False: break cond = _my_unpolarify(cond) if cond == False: _debug('But cond is always False.') else: _debug('Result before branch substitution:', res) from sympy.simplify import hyperexpand res = _my_unpolarify(hyperexpand(res)) if not res.has(Heaviside): res *= Heaviside(t) res = res.subs(t, t + shift) if not isinstance(cond, bool): cond = cond.subs(t, t + shift) from .transforms import InverseLaplaceTransform return Piecewise((res.subs(t, t_), cond), (InverseLaplaceTransform(f_.subs(t, t_), x, t_, None), True))
237ee98e5f03220e75e0bf496caf6e8bee0dc8f35d989a3c288174da5c4656d7
"""Base class for all the objects in SymPy""" from __future__ import annotations from collections import defaultdict from collections.abc import Mapping from itertools import chain, zip_longest from .assumptions import ManagedProperties from .cache import cacheit from .core import BasicMeta from .sympify import _sympify, sympify, SympifyError, _external_converter from .sorting import ordered from .kind import Kind, UndefinedKind from ._print_helpers import Printable from sympy.utilities.decorator import deprecated from sympy.utilities.exceptions import sympy_deprecation_warning from sympy.utilities.iterables import iterable, numbered_symbols from sympy.utilities.misc import filldedent, func_name from inspect import getmro def as_Basic(expr): """Return expr as a Basic instance using strict sympify or raise a TypeError; this is just a wrapper to _sympify, raising a TypeError instead of a SympifyError.""" try: return _sympify(expr) except SympifyError: raise TypeError( 'Argument must be a Basic object, not `%s`' % func_name( expr)) class Basic(Printable, metaclass=ManagedProperties): """ Base class for all SymPy objects. Notes and conventions ===================== 1) Always use ``.args``, when accessing parameters of some instance: >>> from sympy import cot >>> from sympy.abc import x, y >>> cot(x).args (x,) >>> cot(x).args[0] x >>> (x*y).args (x, y) >>> (x*y).args[1] y 2) Never use internal methods or variables (the ones prefixed with ``_``): >>> cot(x)._args # do not use this, use cot(x).args instead (x,) 3) By "SymPy object" we mean something that can be returned by ``sympify``. But not all objects one encounters using SymPy are subclasses of Basic. For example, mutable objects are not: >>> from sympy import Basic, Matrix, sympify >>> A = Matrix([[1, 2], [3, 4]]).as_mutable() >>> isinstance(A, Basic) False >>> B = sympify(A) >>> isinstance(B, Basic) True """ __slots__ = ('_mhash', # hash value '_args', # arguments '_assumptions' ) _args: tuple[Basic, ...] _mhash: int | None # To be overridden with True in the appropriate subclasses is_number = False is_Atom = False is_Symbol = False is_symbol = False is_Indexed = False is_Dummy = False is_Wild = False is_Function = False is_Add = False is_Mul = False is_Pow = False is_Number = False is_Float = False is_Rational = False is_Integer = False is_NumberSymbol = False is_Order = False is_Derivative = False is_Piecewise = False is_Poly = False is_AlgebraicNumber = False is_Relational = False is_Equality = False is_Boolean = False is_Not = False is_Matrix = False is_Vector = False is_Point = False is_MatAdd = False is_MatMul = False is_real: bool | None is_zero: bool | None is_negative: bool | None is_commutative: bool | None kind: Kind = UndefinedKind def __new__(cls, *args): obj = object.__new__(cls) obj._assumptions = cls.default_assumptions obj._mhash = None # will be set by __hash__ method. obj._args = args # all items in args must be Basic objects return obj def copy(self): return self.func(*self.args) def __getnewargs__(self): return self.args def __getstate__(self): return None def __setstate__(self, state): for name, value in state.items(): setattr(self, name, value) def __reduce_ex__(self, protocol): if protocol < 2: msg = "Only pickle protocol 2 or higher is supported by SymPy" raise NotImplementedError(msg) return super().__reduce_ex__(protocol) def __hash__(self) -> int: # hash cannot be cached using cache_it because infinite recurrence # occurs as hash is needed for setting cache dictionary keys h = self._mhash if h is None: h = hash((type(self).__name__,) + self._hashable_content()) self._mhash = h return h def _hashable_content(self): """Return a tuple of information about self that can be used to compute the hash. If a class defines additional attributes, like ``name`` in Symbol, then this method should be updated accordingly to return such relevant attributes. Defining more than _hashable_content is necessary if __eq__ has been defined by a class. See note about this in Basic.__eq__.""" return self._args @property def assumptions0(self): """ Return object `type` assumptions. For example: Symbol('x', real=True) Symbol('x', integer=True) are different objects. In other words, besides Python type (Symbol in this case), the initial assumptions are also forming their typeinfo. Examples ======== >>> from sympy import Symbol >>> from sympy.abc import x >>> x.assumptions0 {'commutative': True} >>> x = Symbol("x", positive=True) >>> x.assumptions0 {'commutative': True, 'complex': True, 'extended_negative': False, 'extended_nonnegative': True, 'extended_nonpositive': False, 'extended_nonzero': True, 'extended_positive': True, 'extended_real': True, 'finite': True, 'hermitian': True, 'imaginary': False, 'infinite': False, 'negative': False, 'nonnegative': True, 'nonpositive': False, 'nonzero': True, 'positive': True, 'real': True, 'zero': False} """ return {} def compare(self, other): """ Return -1, 0, 1 if the object is smaller, equal, or greater than other. Not in the mathematical sense. If the object is of a different type from the "other" then their classes are ordered according to the sorted_classes list. Examples ======== >>> from sympy.abc import x, y >>> x.compare(y) -1 >>> x.compare(x) 0 >>> y.compare(x) 1 """ # all redefinitions of __cmp__ method should start with the # following lines: if self is other: return 0 n1 = self.__class__ n2 = other.__class__ c = (n1 > n2) - (n1 < n2) if c: return c # st = self._hashable_content() ot = other._hashable_content() c = (len(st) > len(ot)) - (len(st) < len(ot)) if c: return c for l, r in zip(st, ot): l = Basic(*l) if isinstance(l, frozenset) else l r = Basic(*r) if isinstance(r, frozenset) else r if isinstance(l, Basic): c = l.compare(r) else: c = (l > r) - (l < r) if c: return c return 0 @staticmethod def _compare_pretty(a, b): from sympy.series.order import Order if isinstance(a, Order) and not isinstance(b, Order): return 1 if not isinstance(a, Order) and isinstance(b, Order): return -1 if a.is_Rational and b.is_Rational: l = a.p * b.q r = b.p * a.q return (l > r) - (l < r) else: from .symbol import Wild p1, p2, p3 = Wild("p1"), Wild("p2"), Wild("p3") r_a = a.match(p1 * p2**p3) if r_a and p3 in r_a: a3 = r_a[p3] r_b = b.match(p1 * p2**p3) if r_b and p3 in r_b: b3 = r_b[p3] c = Basic.compare(a3, b3) if c != 0: return c return Basic.compare(a, b) @classmethod def fromiter(cls, args, **assumptions): """ Create a new object from an iterable. This is a convenience function that allows one to create objects from any iterable, without having to convert to a list or tuple first. Examples ======== >>> from sympy import Tuple >>> Tuple.fromiter(i for i in range(5)) (0, 1, 2, 3, 4) """ return cls(*tuple(args), **assumptions) @classmethod def class_key(cls): """Nice order of classes. """ return 5, 0, cls.__name__ @cacheit def sort_key(self, order=None): """ Return a sort key. Examples ======== >>> from sympy import S, I >>> sorted([S(1)/2, I, -I], key=lambda x: x.sort_key()) [1/2, -I, I] >>> S("[x, 1/x, 1/x**2, x**2, x**(1/2), x**(1/4), x**(3/2)]") [x, 1/x, x**(-2), x**2, sqrt(x), x**(1/4), x**(3/2)] >>> sorted(_, key=lambda x: x.sort_key()) [x**(-2), 1/x, x**(1/4), sqrt(x), x, x**(3/2), x**2] """ # XXX: remove this when issue 5169 is fixed def inner_key(arg): if isinstance(arg, Basic): return arg.sort_key(order) else: return arg args = self._sorted_args args = len(args), tuple([inner_key(arg) for arg in args]) return self.class_key(), args, S.One.sort_key(), S.One def _do_eq_sympify(self, other): """Returns a boolean indicating whether a == b when either a or b is not a Basic. This is only done for types that were either added to `converter` by a 3rd party or when the object has `_sympy_` defined. This essentially reuses the code in `_sympify` that is specific for this use case. Non-user defined types that are meant to work with SymPy should be handled directly in the __eq__ methods of the `Basic` classes it could equate to and not be converted. Note that after conversion, `==` is used again since it is not neccesarily clear whether `self` or `other`'s __eq__ method needs to be used.""" for superclass in type(other).__mro__: conv = _external_converter.get(superclass) if conv is not None: return self == conv(other) if hasattr(other, '_sympy_'): return self == other._sympy_() return NotImplemented def __eq__(self, other): """Return a boolean indicating whether a == b on the basis of their symbolic trees. This is the same as a.compare(b) == 0 but faster. Notes ===== If a class that overrides __eq__() needs to retain the implementation of __hash__() from a parent class, the interpreter must be told this explicitly by setting __hash__ : Callable[[object], int] = <ParentClass>.__hash__. Otherwise the inheritance of __hash__() will be blocked, just as if __hash__ had been explicitly set to None. References ========== from http://docs.python.org/dev/reference/datamodel.html#object.__hash__ """ if self is other: return True if not isinstance(other, Basic): return self._do_eq_sympify(other) # check for pure number expr if not (self.is_Number and other.is_Number) and ( type(self) != type(other)): return False a, b = self._hashable_content(), other._hashable_content() if a != b: return False # check number *in* an expression for a, b in zip(a, b): if not isinstance(a, Basic): continue if a.is_Number and type(a) != type(b): return False return True def __ne__(self, other): """``a != b`` -> Compare two symbolic trees and see whether they are different this is the same as: ``a.compare(b) != 0`` but faster """ return not self == other def dummy_eq(self, other, symbol=None): """ Compare two expressions and handle dummy symbols. Examples ======== >>> from sympy import Dummy >>> from sympy.abc import x, y >>> u = Dummy('u') >>> (u**2 + 1).dummy_eq(x**2 + 1) True >>> (u**2 + 1) == (x**2 + 1) False >>> (u**2 + y).dummy_eq(x**2 + y, x) True >>> (u**2 + y).dummy_eq(x**2 + y, y) False """ s = self.as_dummy() o = _sympify(other) o = o.as_dummy() dummy_symbols = [i for i in s.free_symbols if i.is_Dummy] if len(dummy_symbols) == 1: dummy = dummy_symbols.pop() else: return s == o if symbol is None: symbols = o.free_symbols if len(symbols) == 1: symbol = symbols.pop() else: return s == o tmp = dummy.__class__() return s.xreplace({dummy: tmp}) == o.xreplace({symbol: tmp}) def atoms(self, *types): """Returns the atoms that form the current object. By default, only objects that are truly atomic and cannot be divided into smaller pieces are returned: symbols, numbers, and number symbols like I and pi. It is possible to request atoms of any type, however, as demonstrated below. Examples ======== >>> from sympy import I, pi, sin >>> from sympy.abc import x, y >>> (1 + x + 2*sin(y + I*pi)).atoms() {1, 2, I, pi, x, y} If one or more types are given, the results will contain only those types of atoms. >>> from sympy import Number, NumberSymbol, Symbol >>> (1 + x + 2*sin(y + I*pi)).atoms(Symbol) {x, y} >>> (1 + x + 2*sin(y + I*pi)).atoms(Number) {1, 2} >>> (1 + x + 2*sin(y + I*pi)).atoms(Number, NumberSymbol) {1, 2, pi} >>> (1 + x + 2*sin(y + I*pi)).atoms(Number, NumberSymbol, I) {1, 2, I, pi} Note that I (imaginary unit) and zoo (complex infinity) are special types of number symbols and are not part of the NumberSymbol class. The type can be given implicitly, too: >>> (1 + x + 2*sin(y + I*pi)).atoms(x) # x is a Symbol {x, y} Be careful to check your assumptions when using the implicit option since ``S(1).is_Integer = True`` but ``type(S(1))`` is ``One``, a special type of SymPy atom, while ``type(S(2))`` is type ``Integer`` and will find all integers in an expression: >>> from sympy import S >>> (1 + x + 2*sin(y + I*pi)).atoms(S(1)) {1} >>> (1 + x + 2*sin(y + I*pi)).atoms(S(2)) {1, 2} Finally, arguments to atoms() can select more than atomic atoms: any SymPy type (loaded in core/__init__.py) can be listed as an argument and those types of "atoms" as found in scanning the arguments of the expression recursively: >>> from sympy import Function, Mul >>> from sympy.core.function import AppliedUndef >>> f = Function('f') >>> (1 + f(x) + 2*sin(y + I*pi)).atoms(Function) {f(x), sin(y + I*pi)} >>> (1 + f(x) + 2*sin(y + I*pi)).atoms(AppliedUndef) {f(x)} >>> (1 + x + 2*sin(y + I*pi)).atoms(Mul) {I*pi, 2*sin(y + I*pi)} """ if types: types = tuple( [t if isinstance(t, type) else type(t) for t in types]) nodes = _preorder_traversal(self) if types: result = {node for node in nodes if isinstance(node, types)} else: result = {node for node in nodes if not node.args} return result @property def free_symbols(self) -> set[Basic]: """Return from the atoms of self those which are free symbols. Not all free symbols are ``Symbol``. Eg: IndexedBase('I')[0].free_symbols For most expressions, all symbols are free symbols. For some classes this is not true. e.g. Integrals use Symbols for the dummy variables which are bound variables, so Integral has a method to return all symbols except those. Derivative keeps track of symbols with respect to which it will perform a derivative; those are bound variables, too, so it has its own free_symbols method. Any other method that uses bound variables should implement a free_symbols method.""" empty: set[Basic] = set() return empty.union(*(a.free_symbols for a in self.args)) @property def expr_free_symbols(self): sympy_deprecation_warning(""" The expr_free_symbols property is deprecated. Use free_symbols to get the free symbols of an expression. """, deprecated_since_version="1.9", active_deprecations_target="deprecated-expr-free-symbols") return set() def as_dummy(self): """Return the expression with any objects having structurally bound symbols replaced with unique, canonical symbols within the object in which they appear and having only the default assumption for commutativity being True. When applied to a symbol a new symbol having only the same commutativity will be returned. Examples ======== >>> from sympy import Integral, Symbol >>> from sympy.abc import x >>> r = Symbol('r', real=True) >>> Integral(r, (r, x)).as_dummy() Integral(_0, (_0, x)) >>> _.variables[0].is_real is None True >>> r.as_dummy() _r Notes ===== Any object that has structurally bound variables should have a property, `bound_symbols` that returns those symbols appearing in the object. """ from .symbol import Dummy, Symbol def can(x): # mask free that shadow bound free = x.free_symbols bound = set(x.bound_symbols) d = {i: Dummy() for i in bound & free} x = x.subs(d) # replace bound with canonical names x = x.xreplace(x.canonical_variables) # return after undoing masking return x.xreplace({v: k for k, v in d.items()}) if not self.has(Symbol): return self return self.replace( lambda x: hasattr(x, 'bound_symbols'), can, simultaneous=False) @property def canonical_variables(self): """Return a dictionary mapping any variable defined in ``self.bound_symbols`` to Symbols that do not clash with any free symbols in the expression. Examples ======== >>> from sympy import Lambda >>> from sympy.abc import x >>> Lambda(x, 2*x).canonical_variables {x: _0} """ if not hasattr(self, 'bound_symbols'): return {} dums = numbered_symbols('_') reps = {} # watch out for free symbol that are not in bound symbols; # those that are in bound symbols are about to get changed bound = self.bound_symbols names = {i.name for i in self.free_symbols - set(bound)} for b in bound: d = next(dums) if b.is_Symbol: while d.name in names: d = next(dums) reps[b] = d return reps def rcall(self, *args): """Apply on the argument recursively through the expression tree. This method is used to simulate a common abuse of notation for operators. For instance, in SymPy the following will not work: ``(x+Lambda(y, 2*y))(z) == x+2*z``, however, you can use: >>> from sympy import Lambda >>> from sympy.abc import x, y, z >>> (x + Lambda(y, 2*y)).rcall(z) x + 2*z """ return Basic._recursive_call(self, args) @staticmethod def _recursive_call(expr_to_call, on_args): """Helper for rcall method.""" from .symbol import Symbol def the_call_method_is_overridden(expr): for cls in getmro(type(expr)): if '__call__' in cls.__dict__: return cls != Basic if callable(expr_to_call) and the_call_method_is_overridden(expr_to_call): if isinstance(expr_to_call, Symbol): # XXX When you call a Symbol it is return expr_to_call # transformed into an UndefFunction else: return expr_to_call(*on_args) elif expr_to_call.args: args = [Basic._recursive_call( sub, on_args) for sub in expr_to_call.args] return type(expr_to_call)(*args) else: return expr_to_call def is_hypergeometric(self, k): from sympy.simplify.simplify import hypersimp from sympy.functions.elementary.piecewise import Piecewise if self.has(Piecewise): return None return hypersimp(self, k) is not None @property def is_comparable(self): """Return True if self can be computed to a real number (or already is a real number) with precision, else False. Examples ======== >>> from sympy import exp_polar, pi, I >>> (I*exp_polar(I*pi/2)).is_comparable True >>> (I*exp_polar(I*pi*2)).is_comparable False A False result does not mean that `self` cannot be rewritten into a form that would be comparable. For example, the difference computed below is zero but without simplification it does not evaluate to a zero with precision: >>> e = 2**pi*(1 + 2**pi) >>> dif = e - e.expand() >>> dif.is_comparable False >>> dif.n(2)._prec 1 """ is_extended_real = self.is_extended_real if is_extended_real is False: return False if not self.is_number: return False # don't re-eval numbers that are already evaluated since # this will create spurious precision n, i = [p.evalf(2) if not p.is_Number else p for p in self.as_real_imag()] if not (i.is_Number and n.is_Number): return False if i: # if _prec = 1 we can't decide and if not, # the answer is False because numbers with # imaginary parts can't be compared # so return False return False else: return n._prec != 1 @property def func(self): """ The top-level function in an expression. The following should hold for all objects:: >> x == x.func(*x.args) Examples ======== >>> from sympy.abc import x >>> a = 2*x >>> a.func <class 'sympy.core.mul.Mul'> >>> a.args (2, x) >>> a.func(*a.args) 2*x >>> a == a.func(*a.args) True """ return self.__class__ @property def args(self) -> tuple[Basic, ...]: """Returns a tuple of arguments of 'self'. Examples ======== >>> from sympy import cot >>> from sympy.abc import x, y >>> cot(x).args (x,) >>> cot(x).args[0] x >>> (x*y).args (x, y) >>> (x*y).args[1] y Notes ===== Never use self._args, always use self.args. Only use _args in __new__ when creating a new function. Do not override .args() from Basic (so that it is easy to change the interface in the future if needed). """ return self._args @property def _sorted_args(self): """ The same as ``args``. Derived classes which do not fix an order on their arguments should override this method to produce the sorted representation. """ return self.args def as_content_primitive(self, radical=False, clear=True): """A stub to allow Basic args (like Tuple) to be skipped when computing the content and primitive components of an expression. See Also ======== sympy.core.expr.Expr.as_content_primitive """ return S.One, self def subs(self, *args, **kwargs): """ Substitutes old for new in an expression after sympifying args. `args` is either: - two arguments, e.g. foo.subs(old, new) - one iterable argument, e.g. foo.subs(iterable). The iterable may be o an iterable container with (old, new) pairs. In this case the replacements are processed in the order given with successive patterns possibly affecting replacements already made. o a dict or set whose key/value items correspond to old/new pairs. In this case the old/new pairs will be sorted by op count and in case of a tie, by number of args and the default_sort_key. The resulting sorted list is then processed as an iterable container (see previous). If the keyword ``simultaneous`` is True, the subexpressions will not be evaluated until all the substitutions have been made. Examples ======== >>> from sympy import pi, exp, limit, oo >>> from sympy.abc import x, y >>> (1 + x*y).subs(x, pi) pi*y + 1 >>> (1 + x*y).subs({x:pi, y:2}) 1 + 2*pi >>> (1 + x*y).subs([(x, pi), (y, 2)]) 1 + 2*pi >>> reps = [(y, x**2), (x, 2)] >>> (x + y).subs(reps) 6 >>> (x + y).subs(reversed(reps)) x**2 + 2 >>> (x**2 + x**4).subs(x**2, y) y**2 + y To replace only the x**2 but not the x**4, use xreplace: >>> (x**2 + x**4).xreplace({x**2: y}) x**4 + y To delay evaluation until all substitutions have been made, set the keyword ``simultaneous`` to True: >>> (x/y).subs([(x, 0), (y, 0)]) 0 >>> (x/y).subs([(x, 0), (y, 0)], simultaneous=True) nan This has the added feature of not allowing subsequent substitutions to affect those already made: >>> ((x + y)/y).subs({x + y: y, y: x + y}) 1 >>> ((x + y)/y).subs({x + y: y, y: x + y}, simultaneous=True) y/(x + y) In order to obtain a canonical result, unordered iterables are sorted by count_op length, number of arguments and by the default_sort_key to break any ties. All other iterables are left unsorted. >>> from sympy import sqrt, sin, cos >>> from sympy.abc import a, b, c, d, e >>> A = (sqrt(sin(2*x)), a) >>> B = (sin(2*x), b) >>> C = (cos(2*x), c) >>> D = (x, d) >>> E = (exp(x), e) >>> expr = sqrt(sin(2*x))*sin(exp(x)*x)*cos(2*x) + sin(2*x) >>> expr.subs(dict([A, B, C, D, E])) a*c*sin(d*e) + b The resulting expression represents a literal replacement of the old arguments with the new arguments. This may not reflect the limiting behavior of the expression: >>> (x**3 - 3*x).subs({x: oo}) nan >>> limit(x**3 - 3*x, x, oo) oo If the substitution will be followed by numerical evaluation, it is better to pass the substitution to evalf as >>> (1/x).evalf(subs={x: 3.0}, n=21) 0.333333333333333333333 rather than >>> (1/x).subs({x: 3.0}).evalf(21) 0.333333333333333314830 as the former will ensure that the desired level of precision is obtained. See Also ======== replace: replacement capable of doing wildcard-like matching, parsing of match, and conditional replacements xreplace: exact node replacement in expr tree; also capable of using matching rules sympy.core.evalf.EvalfMixin.evalf: calculates the given formula to a desired level of precision """ from .containers import Dict from .symbol import Dummy, Symbol from .numbers import _illegal unordered = False if len(args) == 1: sequence = args[0] if isinstance(sequence, set): unordered = True elif isinstance(sequence, (Dict, Mapping)): unordered = True sequence = sequence.items() elif not iterable(sequence): raise ValueError(filldedent(""" When a single argument is passed to subs it should be a dictionary of old: new pairs or an iterable of (old, new) tuples.""")) elif len(args) == 2: sequence = [args] else: raise ValueError("subs accepts either 1 or 2 arguments") sequence = list(sequence) for i, s in enumerate(sequence): if isinstance(s[0], str): # when old is a string we prefer Symbol s = Symbol(s[0]), s[1] try: s = [sympify(_, strict=not isinstance(_, (str, type))) for _ in s] except SympifyError: # if it can't be sympified, skip it sequence[i] = None continue # skip if there is no change sequence[i] = None if _aresame(*s) else tuple(s) sequence = list(filter(None, sequence)) simultaneous = kwargs.pop('simultaneous', False) if unordered: from .sorting import _nodes, default_sort_key sequence = dict(sequence) # order so more complex items are first and items # of identical complexity are ordered so # f(x) < f(y) < x < y # \___ 2 __/ \_1_/ <- number of nodes # # For more complex ordering use an unordered sequence. k = list(ordered(sequence, default=False, keys=( lambda x: -_nodes(x), default_sort_key, ))) sequence = [(k, sequence[k]) for k in k] # do infinities first if not simultaneous: redo = [i for i, seq in enumerate(sequence) if seq[1] in _illegal] for i in reversed(redo): sequence.insert(0, sequence.pop(i)) if simultaneous: # XXX should this be the default for dict subs? reps = {} rv = self kwargs['hack2'] = True m = Dummy('subs_m') for old, new in sequence: com = new.is_commutative if com is None: com = True d = Dummy('subs_d', commutative=com) # using d*m so Subs will be used on dummy variables # in things like Derivative(f(x, y), x) in which x # is both free and bound rv = rv._subs(old, d*m, **kwargs) if not isinstance(rv, Basic): break reps[d] = new reps[m] = S.One # get rid of m return rv.xreplace(reps) else: rv = self for old, new in sequence: rv = rv._subs(old, new, **kwargs) if not isinstance(rv, Basic): break return rv @cacheit def _subs(self, old, new, **hints): """Substitutes an expression old -> new. If self is not equal to old then _eval_subs is called. If _eval_subs does not want to make any special replacement then a None is received which indicates that the fallback should be applied wherein a search for replacements is made amongst the arguments of self. >>> from sympy import Add >>> from sympy.abc import x, y, z Examples ======== Add's _eval_subs knows how to target x + y in the following so it makes the change: >>> (x + y + z).subs(x + y, 1) z + 1 Add's _eval_subs does not need to know how to find x + y in the following: >>> Add._eval_subs(z*(x + y) + 3, x + y, 1) is None True The returned None will cause the fallback routine to traverse the args and pass the z*(x + y) arg to Mul where the change will take place and the substitution will succeed: >>> (z*(x + y) + 3).subs(x + y, 1) z + 3 ** Developers Notes ** An _eval_subs routine for a class should be written if: 1) any arguments are not instances of Basic (e.g. bool, tuple); 2) some arguments should not be targeted (as in integration variables); 3) if there is something other than a literal replacement that should be attempted (as in Piecewise where the condition may be updated without doing a replacement). If it is overridden, here are some special cases that might arise: 1) If it turns out that no special change was made and all the original sub-arguments should be checked for replacements then None should be returned. 2) If it is necessary to do substitutions on a portion of the expression then _subs should be called. _subs will handle the case of any sub-expression being equal to old (which usually would not be the case) while its fallback will handle the recursion into the sub-arguments. For example, after Add's _eval_subs removes some matching terms it must process the remaining terms so it calls _subs on each of the un-matched terms and then adds them onto the terms previously obtained. 3) If the initial expression should remain unchanged then the original expression should be returned. (Whenever an expression is returned, modified or not, no further substitution of old -> new is attempted.) Sum's _eval_subs routine uses this strategy when a substitution is attempted on any of its summation variables. """ def fallback(self, old, new): """ Try to replace old with new in any of self's arguments. """ hit = False args = list(self.args) for i, arg in enumerate(args): if not hasattr(arg, '_eval_subs'): continue arg = arg._subs(old, new, **hints) if not _aresame(arg, args[i]): hit = True args[i] = arg if hit: rv = self.func(*args) hack2 = hints.get('hack2', False) if hack2 and self.is_Mul and not rv.is_Mul: # 2-arg hack coeff = S.One nonnumber = [] for i in args: if i.is_Number: coeff *= i else: nonnumber.append(i) nonnumber = self.func(*nonnumber) if coeff is S.One: return nonnumber else: return self.func(coeff, nonnumber, evaluate=False) return rv return self if _aresame(self, old): return new rv = self._eval_subs(old, new) if rv is None: rv = fallback(self, old, new) return rv def _eval_subs(self, old, new): """Override this stub if you want to do anything more than attempt a replacement of old with new in the arguments of self. See also ======== _subs """ return None def xreplace(self, rule): """ Replace occurrences of objects within the expression. Parameters ========== rule : dict-like Expresses a replacement rule Returns ======= xreplace : the result of the replacement Examples ======== >>> from sympy import symbols, pi, exp >>> x, y, z = symbols('x y z') >>> (1 + x*y).xreplace({x: pi}) pi*y + 1 >>> (1 + x*y).xreplace({x: pi, y: 2}) 1 + 2*pi Replacements occur only if an entire node in the expression tree is matched: >>> (x*y + z).xreplace({x*y: pi}) z + pi >>> (x*y*z).xreplace({x*y: pi}) x*y*z >>> (2*x).xreplace({2*x: y, x: z}) y >>> (2*2*x).xreplace({2*x: y, x: z}) 4*z >>> (x + y + 2).xreplace({x + y: 2}) x + y + 2 >>> (x + 2 + exp(x + 2)).xreplace({x + 2: y}) x + exp(y) + 2 xreplace does not differentiate between free and bound symbols. In the following, subs(x, y) would not change x since it is a bound symbol, but xreplace does: >>> from sympy import Integral >>> Integral(x, (x, 1, 2*x)).xreplace({x: y}) Integral(y, (y, 1, 2*y)) Trying to replace x with an expression raises an error: >>> Integral(x, (x, 1, 2*x)).xreplace({x: 2*y}) # doctest: +SKIP ValueError: Invalid limits given: ((2*y, 1, 4*y),) See Also ======== replace: replacement capable of doing wildcard-like matching, parsing of match, and conditional replacements subs: substitution of subexpressions as defined by the objects themselves. """ value, _ = self._xreplace(rule) return value def _xreplace(self, rule): """ Helper for xreplace. Tracks whether a replacement actually occurred. """ if self in rule: return rule[self], True elif rule: args = [] changed = False for a in self.args: _xreplace = getattr(a, '_xreplace', None) if _xreplace is not None: a_xr = _xreplace(rule) args.append(a_xr[0]) changed |= a_xr[1] else: args.append(a) args = tuple(args) if changed: return self.func(*args), True return self, False @cacheit def has(self, *patterns): """ Test whether any subexpression matches any of the patterns. Examples ======== >>> from sympy import sin >>> from sympy.abc import x, y, z >>> (x**2 + sin(x*y)).has(z) False >>> (x**2 + sin(x*y)).has(x, y, z) True >>> x.has(x) True Note ``has`` is a structural algorithm with no knowledge of mathematics. Consider the following half-open interval: >>> from sympy import Interval >>> i = Interval.Lopen(0, 5); i Interval.Lopen(0, 5) >>> i.args (0, 5, True, False) >>> i.has(4) # there is no "4" in the arguments False >>> i.has(0) # there *is* a "0" in the arguments True Instead, use ``contains`` to determine whether a number is in the interval or not: >>> i.contains(4) True >>> i.contains(0) False Note that ``expr.has(*patterns)`` is exactly equivalent to ``any(expr.has(p) for p in patterns)``. In particular, ``False`` is returned when the list of patterns is empty. >>> x.has() False """ return self._has(iterargs, *patterns) @cacheit def has_free(self, *patterns): """return True if self has object(s) ``x`` as a free expression else False. Examples ======== >>> from sympy import Integral, Function >>> from sympy.abc import x, y >>> f = Function('f') >>> g = Function('g') >>> expr = Integral(f(x), (f(x), 1, g(y))) >>> expr.free_symbols {y} >>> expr.has_free(g(y)) True >>> expr.has_free(*(x, f(x))) False This works for subexpressions and types, too: >>> expr.has_free(g) True >>> (x + y + 1).has_free(y + 1) True """ return self._has(iterfreeargs, *patterns) def _has(self, iterargs, *patterns): # separate out types and unhashable objects type_set = set() # only types p_set = set() # hashable non-types for p in patterns: if isinstance(p, BasicMeta): type_set.add(p) continue if not isinstance(p, Basic): try: p = _sympify(p) except SympifyError: continue # Basic won't have this in it p_set.add(p) # fails if object defines __eq__ but # doesn't define __hash__ types = tuple(type_set) # for i in iterargs(self): # if i in p_set: # <--- here, too return True if isinstance(i, types): return True # use matcher if defined, e.g. operations defines # matcher that checks for exact subset containment, # (x + y + 1).has(x + 1) -> True for i in p_set - type_set: # types don't have matchers if not hasattr(i, '_has_matcher'): continue match = i._has_matcher() if any(match(arg) for arg in iterargs(self)): return True # no success return False def replace(self, query, value, map=False, simultaneous=True, exact=None): """ Replace matching subexpressions of ``self`` with ``value``. If ``map = True`` then also return the mapping {old: new} where ``old`` was a sub-expression found with query and ``new`` is the replacement value for it. If the expression itself does not match the query, then the returned value will be ``self.xreplace(map)`` otherwise it should be ``self.subs(ordered(map.items()))``. Traverses an expression tree and performs replacement of matching subexpressions from the bottom to the top of the tree. The default approach is to do the replacement in a simultaneous fashion so changes made are targeted only once. If this is not desired or causes problems, ``simultaneous`` can be set to False. In addition, if an expression containing more than one Wild symbol is being used to match subexpressions and the ``exact`` flag is None it will be set to True so the match will only succeed if all non-zero values are received for each Wild that appears in the match pattern. Setting this to False accepts a match of 0; while setting it True accepts all matches that have a 0 in them. See example below for cautions. The list of possible combinations of queries and replacement values is listed below: Examples ======== Initial setup >>> from sympy import log, sin, cos, tan, Wild, Mul, Add >>> from sympy.abc import x, y >>> f = log(sin(x)) + tan(sin(x**2)) 1.1. type -> type obj.replace(type, newtype) When object of type ``type`` is found, replace it with the result of passing its argument(s) to ``newtype``. >>> f.replace(sin, cos) log(cos(x)) + tan(cos(x**2)) >>> sin(x).replace(sin, cos, map=True) (cos(x), {sin(x): cos(x)}) >>> (x*y).replace(Mul, Add) x + y 1.2. type -> func obj.replace(type, func) When object of type ``type`` is found, apply ``func`` to its argument(s). ``func`` must be written to handle the number of arguments of ``type``. >>> f.replace(sin, lambda arg: sin(2*arg)) log(sin(2*x)) + tan(sin(2*x**2)) >>> (x*y).replace(Mul, lambda *args: sin(2*Mul(*args))) sin(2*x*y) 2.1. pattern -> expr obj.replace(pattern(wild), expr(wild)) Replace subexpressions matching ``pattern`` with the expression written in terms of the Wild symbols in ``pattern``. >>> a, b = map(Wild, 'ab') >>> f.replace(sin(a), tan(a)) log(tan(x)) + tan(tan(x**2)) >>> f.replace(sin(a), tan(a/2)) log(tan(x/2)) + tan(tan(x**2/2)) >>> f.replace(sin(a), a) log(x) + tan(x**2) >>> (x*y).replace(a*x, a) y Matching is exact by default when more than one Wild symbol is used: matching fails unless the match gives non-zero values for all Wild symbols: >>> (2*x + y).replace(a*x + b, b - a) y - 2 >>> (2*x).replace(a*x + b, b - a) 2*x When set to False, the results may be non-intuitive: >>> (2*x).replace(a*x + b, b - a, exact=False) 2/x 2.2. pattern -> func obj.replace(pattern(wild), lambda wild: expr(wild)) All behavior is the same as in 2.1 but now a function in terms of pattern variables is used rather than an expression: >>> f.replace(sin(a), lambda a: sin(2*a)) log(sin(2*x)) + tan(sin(2*x**2)) 3.1. func -> func obj.replace(filter, func) Replace subexpression ``e`` with ``func(e)`` if ``filter(e)`` is True. >>> g = 2*sin(x**3) >>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2) 4*sin(x**9) The expression itself is also targeted by the query but is done in such a fashion that changes are not made twice. >>> e = x*(x*y + 1) >>> e.replace(lambda x: x.is_Mul, lambda x: 2*x) 2*x*(2*x*y + 1) When matching a single symbol, `exact` will default to True, but this may or may not be the behavior that is desired: Here, we want `exact=False`: >>> from sympy import Function >>> f = Function('f') >>> e = f(1) + f(0) >>> q = f(a), lambda a: f(a + 1) >>> e.replace(*q, exact=False) f(1) + f(2) >>> e.replace(*q, exact=True) f(0) + f(2) But here, the nature of matching makes selecting the right setting tricky: >>> e = x**(1 + y) >>> (x**(1 + y)).replace(x**(1 + a), lambda a: x**-a, exact=False) x >>> (x**(1 + y)).replace(x**(1 + a), lambda a: x**-a, exact=True) x**(-x - y + 1) >>> (x**y).replace(x**(1 + a), lambda a: x**-a, exact=False) x >>> (x**y).replace(x**(1 + a), lambda a: x**-a, exact=True) x**(1 - y) It is probably better to use a different form of the query that describes the target expression more precisely: >>> (1 + x**(1 + y)).replace( ... lambda x: x.is_Pow and x.exp.is_Add and x.exp.args[0] == 1, ... lambda x: x.base**(1 - (x.exp - 1))) ... x**(1 - y) + 1 See Also ======== subs: substitution of subexpressions as defined by the objects themselves. xreplace: exact node replacement in expr tree; also capable of using matching rules """ try: query = _sympify(query) except SympifyError: pass try: value = _sympify(value) except SympifyError: pass if isinstance(query, type): _query = lambda expr: isinstance(expr, query) if isinstance(value, type): _value = lambda expr, result: value(*expr.args) elif callable(value): _value = lambda expr, result: value(*expr.args) else: raise TypeError( "given a type, replace() expects another " "type or a callable") elif isinstance(query, Basic): _query = lambda expr: expr.match(query) if exact is None: from .symbol import Wild exact = (len(query.atoms(Wild)) > 1) if isinstance(value, Basic): if exact: _value = lambda expr, result: (value.subs(result) if all(result.values()) else expr) else: _value = lambda expr, result: value.subs(result) elif callable(value): # match dictionary keys get the trailing underscore stripped # from them and are then passed as keywords to the callable; # if ``exact`` is True, only accept match if there are no null # values amongst those matched. if exact: _value = lambda expr, result: (value(** {str(k)[:-1]: v for k, v in result.items()}) if all(val for val in result.values()) else expr) else: _value = lambda expr, result: value(** {str(k)[:-1]: v for k, v in result.items()}) else: raise TypeError( "given an expression, replace() expects " "another expression or a callable") elif callable(query): _query = query if callable(value): _value = lambda expr, result: value(expr) else: raise TypeError( "given a callable, replace() expects " "another callable") else: raise TypeError( "first argument to replace() must be a " "type, an expression or a callable") def walk(rv, F): """Apply ``F`` to args and then to result. """ args = getattr(rv, 'args', None) if args is not None: if args: newargs = tuple([walk(a, F) for a in args]) if args != newargs: rv = rv.func(*newargs) if simultaneous: # if rv is something that was already # matched (that was changed) then skip # applying F again for i, e in enumerate(args): if rv == e and e != newargs[i]: return rv rv = F(rv) return rv mapping = {} # changes that took place def rec_replace(expr): result = _query(expr) if result or result == {}: v = _value(expr, result) if v is not None and v != expr: if map: mapping[expr] = v expr = v return expr rv = walk(self, rec_replace) return (rv, mapping) if map else rv def find(self, query, group=False): """Find all subexpressions matching a query. """ query = _make_find_query(query) results = list(filter(query, _preorder_traversal(self))) if not group: return set(results) else: groups = {} for result in results: if result in groups: groups[result] += 1 else: groups[result] = 1 return groups def count(self, query): """Count the number of matching subexpressions. """ query = _make_find_query(query) return sum(bool(query(sub)) for sub in _preorder_traversal(self)) def matches(self, expr, repl_dict=None, old=False): """ Helper method for match() that looks for a match between Wild symbols in self and expressions in expr. Examples ======== >>> from sympy import symbols, Wild, Basic >>> a, b, c = symbols('a b c') >>> x = Wild('x') >>> Basic(a + x, x).matches(Basic(a + b, c)) is None True >>> Basic(a + x, x).matches(Basic(a + b + c, b + c)) {x_: b + c} """ expr = sympify(expr) if not isinstance(expr, self.__class__): return None if repl_dict is None: repl_dict = {} else: repl_dict = repl_dict.copy() if self == expr: return repl_dict if len(self.args) != len(expr.args): return None d = repl_dict # already a copy for arg, other_arg in zip(self.args, expr.args): if arg == other_arg: continue if arg.is_Relational: try: d = arg.xreplace(d).matches(other_arg, d, old=old) except TypeError: # Should be InvalidComparisonError when introduced d = None else: d = arg.xreplace(d).matches(other_arg, d, old=old) if d is None: return None return d def match(self, pattern, old=False): """ Pattern matching. Wild symbols match all. Return ``None`` when expression (self) does not match with pattern. Otherwise return a dictionary such that:: pattern.xreplace(self.match(pattern)) == self Examples ======== >>> from sympy import Wild, Sum >>> from sympy.abc import x, y >>> p = Wild("p") >>> q = Wild("q") >>> r = Wild("r") >>> e = (x+y)**(x+y) >>> e.match(p**p) {p_: x + y} >>> e.match(p**q) {p_: x + y, q_: x + y} >>> e = (2*x)**2 >>> e.match(p*q**r) {p_: 4, q_: x, r_: 2} >>> (p*q**r).xreplace(e.match(p*q**r)) 4*x**2 Structurally bound symbols are ignored during matching: >>> Sum(x, (x, 1, 2)).match(Sum(y, (y, 1, p))) {p_: 2} But they can be identified if desired: >>> Sum(x, (x, 1, 2)).match(Sum(q, (q, 1, p))) {p_: 2, q_: x} The ``old`` flag will give the old-style pattern matching where expressions and patterns are essentially solved to give the match. Both of the following give None unless ``old=True``: >>> (x - 2).match(p - x, old=True) {p_: 2*x - 2} >>> (2/x).match(p*x, old=True) {p_: 2/x**2} """ pattern = sympify(pattern) # match non-bound symbols canonical = lambda x: x if x.is_Symbol else x.as_dummy() m = canonical(pattern).matches(canonical(self), old=old) if m is None: return m from .symbol import Wild from .function import WildFunction wild = pattern.atoms(Wild, WildFunction) # sanity check if set(m) - wild: raise ValueError(filldedent(''' Some `matches` routine did not use a copy of repl_dict and injected unexpected symbols. Report this as an error at https://github.com/sympy/sympy/issues''')) # now see if bound symbols were requested bwild = wild - set(m) if not bwild: return m # replace free-Wild symbols in pattern with match result # so they will match but not be in the next match wpat = pattern.xreplace(m) # identify remaining bound wild w = wpat.matches(self, old=old) # add them to m if w: m.update(w) # done return m def count_ops(self, visual=None): """wrapper for count_ops that returns the operation count.""" from .function import count_ops return count_ops(self, visual) def doit(self, **hints): """Evaluate objects that are not evaluated by default like limits, integrals, sums and products. All objects of this kind will be evaluated recursively, unless some species were excluded via 'hints' or unless the 'deep' hint was set to 'False'. >>> from sympy import Integral >>> from sympy.abc import x >>> 2*Integral(x, x) 2*Integral(x, x) >>> (2*Integral(x, x)).doit() x**2 >>> (2*Integral(x, x)).doit(deep=False) 2*Integral(x, x) """ if hints.get('deep', True): terms = [term.doit(**hints) if isinstance(term, Basic) else term for term in self.args] return self.func(*terms) else: return self def simplify(self, **kwargs): """See the simplify function in sympy.simplify""" from sympy.simplify.simplify import simplify return simplify(self, **kwargs) def refine(self, assumption=True): """See the refine function in sympy.assumptions""" from sympy.assumptions.refine import refine return refine(self, assumption) def _eval_derivative_n_times(self, s, n): # This is the default evaluator for derivatives (as called by `diff` # and `Derivative`), it will attempt a loop to derive the expression # `n` times by calling the corresponding `_eval_derivative` method, # while leaving the derivative unevaluated if `n` is symbolic. This # method should be overridden if the object has a closed form for its # symbolic n-th derivative. from .numbers import Integer if isinstance(n, (int, Integer)): obj = self for i in range(n): obj2 = obj._eval_derivative(s) if obj == obj2 or obj2 is None: break obj = obj2 return obj2 else: return None def rewrite(self, *args, deep=True, **hints): """ Rewrite *self* using a defined rule. Rewriting transforms an expression to another, which is mathematically equivalent but structurally different. For example you can rewrite trigonometric functions as complex exponentials or combinatorial functions as gamma function. This method takes a *pattern* and a *rule* as positional arguments. *pattern* is optional parameter which defines the types of expressions that will be transformed. If it is not passed, all possible expressions will be rewritten. *rule* defines how the expression will be rewritten. Parameters ========== args : *rule*, or *pattern* and *rule*. - *pattern* is a type or an iterable of types. - *rule* can be any object. deep : bool, optional. If ``True``, subexpressions are recursively transformed. Default is ``True``. Examples ======== If *pattern* is unspecified, all possible expressions are transformed. >>> from sympy import cos, sin, exp, I >>> from sympy.abc import x >>> expr = cos(x) + I*sin(x) >>> expr.rewrite(exp) exp(I*x) Pattern can be a type or an iterable of types. >>> expr.rewrite(sin, exp) exp(I*x)/2 + cos(x) - exp(-I*x)/2 >>> expr.rewrite([cos,], exp) exp(I*x)/2 + I*sin(x) + exp(-I*x)/2 >>> expr.rewrite([cos, sin], exp) exp(I*x) Rewriting behavior can be implemented by defining ``_eval_rewrite()`` method. >>> from sympy import Expr, sqrt, pi >>> class MySin(Expr): ... def _eval_rewrite(self, rule, args, **hints): ... x, = args ... if rule == cos: ... return cos(pi/2 - x, evaluate=False) ... if rule == sqrt: ... return sqrt(1 - cos(x)**2) >>> MySin(MySin(x)).rewrite(cos) cos(-cos(-x + pi/2) + pi/2) >>> MySin(x).rewrite(sqrt) sqrt(1 - cos(x)**2) Defining ``_eval_rewrite_as_[...]()`` method is supported for backwards compatibility reason. This may be removed in the future and using it is discouraged. >>> class MySin(Expr): ... def _eval_rewrite_as_cos(self, *args, **hints): ... x, = args ... return cos(pi/2 - x, evaluate=False) >>> MySin(x).rewrite(cos) cos(-x + pi/2) """ if not args: return self hints.update(deep=deep) pattern = args[:-1] rule = args[-1] # support old design by _eval_rewrite_as_[...] method if isinstance(rule, str): method = "_eval_rewrite_as_%s" % rule elif hasattr(rule, "__name__"): # rule is class or function clsname = rule.__name__ method = "_eval_rewrite_as_%s" % clsname else: # rule is instance clsname = rule.__class__.__name__ method = "_eval_rewrite_as_%s" % clsname if pattern: if iterable(pattern[0]): pattern = pattern[0] pattern = tuple(p for p in pattern if self.has(p)) if not pattern: return self # hereafter, empty pattern is interpreted as all pattern. return self._rewrite(pattern, rule, method, **hints) def _rewrite(self, pattern, rule, method, **hints): deep = hints.pop('deep', True) if deep: args = [a._rewrite(pattern, rule, method, **hints) for a in self.args] else: args = self.args if not pattern or any(isinstance(self, p) for p in pattern): meth = getattr(self, method, None) if meth is not None: rewritten = meth(*args, **hints) else: rewritten = self._eval_rewrite(rule, args, **hints) if rewritten is not None: return rewritten if not args: return self return self.func(*args) def _eval_rewrite(self, rule, args, **hints): return None _constructor_postprocessor_mapping = {} # type: ignore @classmethod def _exec_constructor_postprocessors(cls, obj): # WARNING: This API is experimental. # This is an experimental API that introduces constructor # postprosessors for SymPy Core elements. If an argument of a SymPy # expression has a `_constructor_postprocessor_mapping` attribute, it will # be interpreted as a dictionary containing lists of postprocessing # functions for matching expression node names. clsname = obj.__class__.__name__ postprocessors = defaultdict(list) for i in obj.args: try: postprocessor_mappings = ( Basic._constructor_postprocessor_mapping[cls].items() for cls in type(i).mro() if cls in Basic._constructor_postprocessor_mapping ) for k, v in chain.from_iterable(postprocessor_mappings): postprocessors[k].extend([j for j in v if j not in postprocessors[k]]) except TypeError: pass for f in postprocessors.get(clsname, []): obj = f(obj) return obj def _sage_(self): """ Convert *self* to a symbolic expression of SageMath. This version of the method is merely a placeholder. """ old_method = self._sage_ from sage.interfaces.sympy import sympy_init sympy_init() # may monkey-patch _sage_ method into self's class or superclasses if old_method == self._sage_: raise NotImplementedError('conversion to SageMath is not implemented') else: # call the freshly monkey-patched method return self._sage_() def could_extract_minus_sign(self): return False # see Expr.could_extract_minus_sign class Atom(Basic): """ A parent class for atomic things. An atom is an expression with no subexpressions. Examples ======== Symbol, Number, Rational, Integer, ... But not: Add, Mul, Pow, ... """ is_Atom = True __slots__ = () def matches(self, expr, repl_dict=None, old=False): if self == expr: if repl_dict is None: return {} return repl_dict.copy() def xreplace(self, rule, hack2=False): return rule.get(self, self) def doit(self, **hints): return self @classmethod def class_key(cls): return 2, 0, cls.__name__ @cacheit def sort_key(self, order=None): return self.class_key(), (1, (str(self),)), S.One.sort_key(), S.One def _eval_simplify(self, **kwargs): return self @property def _sorted_args(self): # this is here as a safeguard against accidentally using _sorted_args # on Atoms -- they cannot be rebuilt as atom.func(*atom._sorted_args) # since there are no args. So the calling routine should be checking # to see that this property is not called for Atoms. raise AttributeError('Atoms have no args. It might be necessary' ' to make a check for Atoms in the calling code.') def _aresame(a, b): """Return True if a and b are structurally the same, else False. Examples ======== In SymPy (as in Python) two numbers compare the same if they have the same underlying base-2 representation even though they may not be the same type: >>> from sympy import S >>> 2.0 == S(2) True >>> 0.5 == S.Half True This routine was written to provide a query for such cases that would give false when the types do not match: >>> from sympy.core.basic import _aresame >>> _aresame(S(2.0), S(2)) False """ from .numbers import Number from .function import AppliedUndef, UndefinedFunction as UndefFunc if isinstance(a, Number) and isinstance(b, Number): return a == b and a.__class__ == b.__class__ for i, j in zip_longest(_preorder_traversal(a), _preorder_traversal(b)): if i != j or type(i) != type(j): if ((isinstance(i, UndefFunc) and isinstance(j, UndefFunc)) or (isinstance(i, AppliedUndef) and isinstance(j, AppliedUndef))): if i.class_key() != j.class_key(): return False else: return False return True def _ne(a, b): # use this as a second test after `a != b` if you want to make # sure that things are truly equal, e.g. # a, b = 0.5, S.Half # a !=b or _ne(a, b) -> True from .numbers import Number # 0.5 == S.Half if isinstance(a, Number) and isinstance(b, Number): return a.__class__ != b.__class__ def _atomic(e, recursive=False): """Return atom-like quantities as far as substitution is concerned: Derivatives, Functions and Symbols. Do not return any 'atoms' that are inside such quantities unless they also appear outside, too, unless `recursive` is True. Examples ======== >>> from sympy import Derivative, Function, cos >>> from sympy.abc import x, y >>> from sympy.core.basic import _atomic >>> f = Function('f') >>> _atomic(x + y) {x, y} >>> _atomic(x + f(y)) {x, f(y)} >>> _atomic(Derivative(f(x), x) + cos(x) + y) {y, cos(x), Derivative(f(x), x)} """ pot = _preorder_traversal(e) seen = set() if isinstance(e, Basic): free = getattr(e, "free_symbols", None) if free is None: return {e} else: return set() from .symbol import Symbol from .function import Derivative, Function atoms = set() for p in pot: if p in seen: pot.skip() continue seen.add(p) if isinstance(p, Symbol) and p in free: atoms.add(p) elif isinstance(p, (Derivative, Function)): if not recursive: pot.skip() atoms.add(p) return atoms def _make_find_query(query): """Convert the argument of Basic.find() into a callable""" try: query = _sympify(query) except SympifyError: pass if isinstance(query, type): return lambda expr: isinstance(expr, query) elif isinstance(query, Basic): return lambda expr: expr.match(query) is not None return query # Delayed to avoid cyclic import from .singleton import S from .traversal import (preorder_traversal as _preorder_traversal, iterargs, iterfreeargs) preorder_traversal = deprecated( """ Using preorder_traversal from the sympy.core.basic submodule is deprecated. Instead, use preorder_traversal from the top-level sympy namespace, like sympy.preorder_traversal """, deprecated_since_version="1.10", active_deprecations_target="deprecated-traversal-functions-moved", )(_preorder_traversal)
62824d966b2846f3ade3e399608977bd20331f3286cae7e81568761b7b9b474a
from __future__ import annotations from typing import Callable from math import log as _log, sqrt as _sqrt from itertools import product from .sympify import _sympify from .cache import cacheit from .singleton import S from .expr import Expr from .evalf import PrecisionExhausted from .function import (expand_complex, expand_multinomial, expand_mul, _mexpand, PoleError) from .logic import fuzzy_bool, fuzzy_not, fuzzy_and, fuzzy_or from .parameters import global_parameters from .relational import is_gt, is_lt from .kind import NumberKind, UndefinedKind from sympy.external.gmpy import HAS_GMPY, gmpy from sympy.utilities.iterables import sift from sympy.utilities.exceptions import sympy_deprecation_warning from sympy.utilities.misc import as_int from sympy.multipledispatch import Dispatcher from mpmath.libmp import sqrtrem as mpmath_sqrtrem def isqrt(n): """Return the largest integer less than or equal to sqrt(n).""" if n < 0: raise ValueError("n must be nonnegative") n = int(n) # Fast path: with IEEE 754 binary64 floats and a correctly-rounded # math.sqrt, int(math.sqrt(n)) works for any integer n satisfying 0 <= n < # 4503599761588224 = 2**52 + 2**27. But Python doesn't guarantee either # IEEE 754 format floats *or* correct rounding of math.sqrt, so check the # answer and fall back to the slow method if necessary. if n < 4503599761588224: s = int(_sqrt(n)) if 0 <= n - s*s <= 2*s: return s return integer_nthroot(n, 2)[0] def integer_nthroot(y, n): """ Return a tuple containing x = floor(y**(1/n)) and a boolean indicating whether the result is exact (that is, whether x**n == y). Examples ======== >>> from sympy import integer_nthroot >>> integer_nthroot(16, 2) (4, True) >>> integer_nthroot(26, 2) (5, False) To simply determine if a number is a perfect square, the is_square function should be used: >>> from sympy.ntheory.primetest import is_square >>> is_square(26) False See Also ======== sympy.ntheory.primetest.is_square integer_log """ y, n = as_int(y), as_int(n) if y < 0: raise ValueError("y must be nonnegative") if n < 1: raise ValueError("n must be positive") if HAS_GMPY and n < 2**63: # Currently it works only for n < 2**63, else it produces TypeError # sympy issue: https://github.com/sympy/sympy/issues/18374 # gmpy2 issue: https://github.com/aleaxit/gmpy/issues/257 if HAS_GMPY >= 2: x, t = gmpy.iroot(y, n) else: x, t = gmpy.root(y, n) return as_int(x), bool(t) return _integer_nthroot_python(y, n) def _integer_nthroot_python(y, n): if y in (0, 1): return y, True if n == 1: return y, True if n == 2: x, rem = mpmath_sqrtrem(y) return int(x), not rem if n >= y.bit_length(): return 1, False # Get initial estimate for Newton's method. Care must be taken to # avoid overflow try: guess = int(y**(1./n) + 0.5) except OverflowError: exp = _log(y, 2)/n if exp > 53: shift = int(exp - 53) guess = int(2.0**(exp - shift) + 1) << shift else: guess = int(2.0**exp) if guess > 2**50: # Newton iteration xprev, x = -1, guess while 1: t = x**(n - 1) xprev, x = x, ((n - 1)*x + y//t)//n if abs(x - xprev) < 2: break else: x = guess # Compensate t = x**n while t < y: x += 1 t = x**n while t > y: x -= 1 t = x**n return int(x), t == y # int converts long to int if possible def integer_log(y, x): r""" Returns ``(e, bool)`` where e is the largest nonnegative integer such that :math:`|y| \geq |x^e|` and ``bool`` is True if $y = x^e$. Examples ======== >>> from sympy import integer_log >>> integer_log(125, 5) (3, True) >>> integer_log(17, 9) (1, False) >>> integer_log(4, -2) (2, True) >>> integer_log(-125,-5) (3, True) See Also ======== integer_nthroot sympy.ntheory.primetest.is_square sympy.ntheory.factor_.multiplicity sympy.ntheory.factor_.perfect_power """ if x == 1: raise ValueError('x cannot take value as 1') if y == 0: raise ValueError('y cannot take value as 0') if x in (-2, 2): x = int(x) y = as_int(y) e = y.bit_length() - 1 return e, x**e == y if x < 0: n, b = integer_log(y if y > 0 else -y, -x) return n, b and bool(n % 2 if y < 0 else not n % 2) x = as_int(x) y = as_int(y) r = e = 0 while y >= x: d = x m = 1 while y >= d: y, rem = divmod(y, d) r = r or rem e += m if y > d: d *= d m *= 2 return e, r == 0 and y == 1 class Pow(Expr): """ Defines the expression x**y as "x raised to a power y" .. deprecated:: 1.7 Using arguments that aren't subclasses of :class:`~.Expr` in core operators (:class:`~.Mul`, :class:`~.Add`, and :class:`~.Pow`) is deprecated. See :ref:`non-expr-args-deprecated` for details. Singleton definitions involving (0, 1, -1, oo, -oo, I, -I): +--------------+---------+-----------------------------------------------+ | expr | value | reason | +==============+=========+===============================================+ | z**0 | 1 | Although arguments over 0**0 exist, see [2]. | +--------------+---------+-----------------------------------------------+ | z**1 | z | | +--------------+---------+-----------------------------------------------+ | (-oo)**(-1) | 0 | | +--------------+---------+-----------------------------------------------+ | (-1)**-1 | -1 | | +--------------+---------+-----------------------------------------------+ | S.Zero**-1 | zoo | This is not strictly true, as 0**-1 may be | | | | undefined, but is convenient in some contexts | | | | where the base is assumed to be positive. | +--------------+---------+-----------------------------------------------+ | 1**-1 | 1 | | +--------------+---------+-----------------------------------------------+ | oo**-1 | 0 | | +--------------+---------+-----------------------------------------------+ | 0**oo | 0 | Because for all complex numbers z near | | | | 0, z**oo -> 0. | +--------------+---------+-----------------------------------------------+ | 0**-oo | zoo | This is not strictly true, as 0**oo may be | | | | oscillating between positive and negative | | | | values or rotating in the complex plane. | | | | It is convenient, however, when the base | | | | is positive. | +--------------+---------+-----------------------------------------------+ | 1**oo | nan | Because there are various cases where | | 1**-oo | | lim(x(t),t)=1, lim(y(t),t)=oo (or -oo), | | | | but lim( x(t)**y(t), t) != 1. See [3]. | +--------------+---------+-----------------------------------------------+ | b**zoo | nan | Because b**z has no limit as z -> zoo | +--------------+---------+-----------------------------------------------+ | (-1)**oo | nan | Because of oscillations in the limit. | | (-1)**(-oo) | | | +--------------+---------+-----------------------------------------------+ | oo**oo | oo | | +--------------+---------+-----------------------------------------------+ | oo**-oo | 0 | | +--------------+---------+-----------------------------------------------+ | (-oo)**oo | nan | | | (-oo)**-oo | | | +--------------+---------+-----------------------------------------------+ | oo**I | nan | oo**e could probably be best thought of as | | (-oo)**I | | the limit of x**e for real x as x tends to | | | | oo. If e is I, then the limit does not exist | | | | and nan is used to indicate that. | +--------------+---------+-----------------------------------------------+ | oo**(1+I) | zoo | If the real part of e is positive, then the | | (-oo)**(1+I) | | limit of abs(x**e) is oo. So the limit value | | | | is zoo. | +--------------+---------+-----------------------------------------------+ | oo**(-1+I) | 0 | If the real part of e is negative, then the | | -oo**(-1+I) | | limit is 0. | +--------------+---------+-----------------------------------------------+ Because symbolic computations are more flexible than floating point calculations and we prefer to never return an incorrect answer, we choose not to conform to all IEEE 754 conventions. This helps us avoid extra test-case code in the calculation of limits. See Also ======== sympy.core.numbers.Infinity sympy.core.numbers.NegativeInfinity sympy.core.numbers.NaN References ========== .. [1] https://en.wikipedia.org/wiki/Exponentiation .. [2] https://en.wikipedia.org/wiki/Exponentiation#Zero_to_the_power_of_zero .. [3] https://en.wikipedia.org/wiki/Indeterminate_forms """ is_Pow = True __slots__ = ('is_commutative',) args: tuple[Expr, Expr] _args: tuple[Expr, Expr] @cacheit def __new__(cls, b, e, evaluate=None): if evaluate is None: evaluate = global_parameters.evaluate b = _sympify(b) e = _sympify(e) # XXX: This can be removed when non-Expr args are disallowed rather # than deprecated. from .relational import Relational if isinstance(b, Relational) or isinstance(e, Relational): raise TypeError('Relational cannot be used in Pow') # XXX: This should raise TypeError once deprecation period is over: for arg in [b, e]: if not isinstance(arg, Expr): sympy_deprecation_warning( f""" Using non-Expr arguments in Pow is deprecated (in this case, one of the arguments is of type {type(arg).__name__!r}). If you really did intend to construct a power with this base, use the ** operator instead.""", deprecated_since_version="1.7", active_deprecations_target="non-expr-args-deprecated", stacklevel=4, ) if evaluate: if e is S.ComplexInfinity: return S.NaN if e is S.Infinity: if is_gt(b, S.One): return S.Infinity if is_gt(b, S.NegativeOne) and is_lt(b, S.One): return S.Zero if is_lt(b, S.NegativeOne): if b.is_finite: return S.ComplexInfinity if b.is_finite is False: return S.NaN if e is S.Zero: return S.One elif e is S.One: return b elif e == -1 and not b: return S.ComplexInfinity elif e.__class__.__name__ == "AccumulationBounds": if b == S.Exp1: from sympy.calculus.accumulationbounds import AccumBounds return AccumBounds(Pow(b, e.min), Pow(b, e.max)) # autosimplification if base is a number and exp odd/even # if base is Number then the base will end up positive; we # do not do this with arbitrary expressions since symbolic # cancellation might occur as in (x - 1)/(1 - x) -> -1. If # we returned Piecewise((-1, Ne(x, 1))) for such cases then # we could do this...but we don't elif (e.is_Symbol and e.is_integer or e.is_Integer ) and (b.is_number and b.is_Mul or b.is_Number ) and b.could_extract_minus_sign(): if e.is_even: b = -b elif e.is_odd: return -Pow(-b, e) if S.NaN in (b, e): # XXX S.NaN**x -> S.NaN under assumption that x != 0 return S.NaN elif b is S.One: if abs(e).is_infinite: return S.NaN return S.One else: # recognize base as E from sympy.functions.elementary.exponential import exp_polar if not e.is_Atom and b is not S.Exp1 and not isinstance(b, exp_polar): from .exprtools import factor_terms from sympy.functions.elementary.exponential import log from sympy.simplify.radsimp import fraction c, ex = factor_terms(e, sign=False).as_coeff_Mul() num, den = fraction(ex) if isinstance(den, log) and den.args[0] == b: return S.Exp1**(c*num) elif den.is_Add: from sympy.functions.elementary.complexes import sign, im s = sign(im(b)) if s.is_Number and s and den == \ log(-factor_terms(b, sign=False)) + s*S.ImaginaryUnit*S.Pi: return S.Exp1**(c*num) obj = b._eval_power(e) if obj is not None: return obj obj = Expr.__new__(cls, b, e) obj = cls._exec_constructor_postprocessors(obj) if not isinstance(obj, Pow): return obj obj.is_commutative = (b.is_commutative and e.is_commutative) return obj def inverse(self, argindex=1): if self.base == S.Exp1: from sympy.functions.elementary.exponential import log return log return None @property def base(self) -> Expr: return self._args[0] @property def exp(self) -> Expr: return self._args[1] @property def kind(self): if self.exp.kind is NumberKind: return self.base.kind else: return UndefinedKind @classmethod def class_key(cls): return 3, 2, cls.__name__ def _eval_refine(self, assumptions): from sympy.assumptions.ask import ask, Q b, e = self.as_base_exp() if ask(Q.integer(e), assumptions) and b.could_extract_minus_sign(): if ask(Q.even(e), assumptions): return Pow(-b, e) elif ask(Q.odd(e), assumptions): return -Pow(-b, e) def _eval_power(self, other): b, e = self.as_base_exp() if b is S.NaN: return (b**e)**other # let __new__ handle it s = None if other.is_integer: s = 1 elif b.is_polar: # e.g. exp_polar, besselj, var('p', polar=True)... s = 1 elif e.is_extended_real is not None: from sympy.functions.elementary.complexes import arg, im, re, sign from sympy.functions.elementary.exponential import exp, log from sympy.functions.elementary.integers import floor # helper functions =========================== def _half(e): """Return True if the exponent has a literal 2 as the denominator, else None.""" if getattr(e, 'q', None) == 2: return True n, d = e.as_numer_denom() if n.is_integer and d == 2: return True def _n2(e): """Return ``e`` evaluated to a Number with 2 significant digits, else None.""" try: rv = e.evalf(2, strict=True) if rv.is_Number: return rv except PrecisionExhausted: pass # =================================================== if e.is_extended_real: # we need _half(other) with constant floor or # floor(S.Half - e*arg(b)/2/pi) == 0 # handle -1 as special case if e == -1: # floor arg. is 1/2 + arg(b)/2/pi if _half(other): if b.is_negative is True: return S.NegativeOne**other*Pow(-b, e*other) elif b.is_negative is False: # XXX ok if im(b) != 0? return Pow(b, -other) elif e.is_even: if b.is_extended_real: b = abs(b) if b.is_imaginary: b = abs(im(b))*S.ImaginaryUnit if (abs(e) < 1) == True or e == 1: s = 1 # floor = 0 elif b.is_extended_nonnegative: s = 1 # floor = 0 elif re(b).is_extended_nonnegative and (abs(e) < 2) == True: s = 1 # floor = 0 elif _half(other): s = exp(2*S.Pi*S.ImaginaryUnit*other*floor( S.Half - e*arg(b)/(2*S.Pi))) if s.is_extended_real and _n2(sign(s) - s) == 0: s = sign(s) else: s = None else: # e.is_extended_real is False requires: # _half(other) with constant floor or # floor(S.Half - im(e*log(b))/2/pi) == 0 try: s = exp(2*S.ImaginaryUnit*S.Pi*other* floor(S.Half - im(e*log(b))/2/S.Pi)) # be careful to test that s is -1 or 1 b/c sign(I) == I: # so check that s is real if s.is_extended_real and _n2(sign(s) - s) == 0: s = sign(s) else: s = None except PrecisionExhausted: s = None if s is not None: return s*Pow(b, e*other) def _eval_Mod(self, q): r"""A dispatched function to compute `b^e \bmod q`, dispatched by ``Mod``. Notes ===== Algorithms: 1. For unevaluated integer power, use built-in ``pow`` function with 3 arguments, if powers are not too large wrt base. 2. For very large powers, use totient reduction if $e \ge \log(m)$. Bound on m, is for safe factorization memory wise i.e. $m^{1/4}$. For pollard-rho to be faster than built-in pow $\log(e) > m^{1/4}$ check is added. 3. For any unevaluated power found in `b` or `e`, the step 2 will be recursed down to the base and the exponent such that the $b \bmod q$ becomes the new base and $\phi(q) + e \bmod \phi(q)$ becomes the new exponent, and then the computation for the reduced expression can be done. """ base, exp = self.base, self.exp if exp.is_integer and exp.is_positive: if q.is_integer and base % q == 0: return S.Zero from sympy.ntheory.factor_ import totient if base.is_Integer and exp.is_Integer and q.is_Integer: b, e, m = int(base), int(exp), int(q) mb = m.bit_length() if mb <= 80 and e >= mb and e.bit_length()**4 >= m: phi = int(totient(m)) return Integer(pow(b, phi + e%phi, m)) return Integer(pow(b, e, m)) from .mod import Mod if isinstance(base, Pow) and base.is_integer and base.is_number: base = Mod(base, q) return Mod(Pow(base, exp, evaluate=False), q) if isinstance(exp, Pow) and exp.is_integer and exp.is_number: bit_length = int(q).bit_length() # XXX Mod-Pow actually attempts to do a hanging evaluation # if this dispatched function returns None. # May need some fixes in the dispatcher itself. if bit_length <= 80: phi = totient(q) exp = phi + Mod(exp, phi) return Mod(Pow(base, exp, evaluate=False), q) def _eval_is_even(self): if self.exp.is_integer and self.exp.is_positive: return self.base.is_even def _eval_is_negative(self): ext_neg = Pow._eval_is_extended_negative(self) if ext_neg is True: return self.is_finite return ext_neg def _eval_is_extended_positive(self): if self.base == self.exp: if self.base.is_extended_nonnegative: return True elif self.base.is_positive: if self.exp.is_real: return True elif self.base.is_extended_negative: if self.exp.is_even: return True if self.exp.is_odd: return False elif self.base.is_zero: if self.exp.is_extended_real: return self.exp.is_zero elif self.base.is_extended_nonpositive: if self.exp.is_odd: return False elif self.base.is_imaginary: if self.exp.is_integer: m = self.exp % 4 if m.is_zero: return True if m.is_integer and m.is_zero is False: return False if self.exp.is_imaginary: from sympy.functions.elementary.exponential import log return log(self.base).is_imaginary def _eval_is_extended_negative(self): if self.exp is S.Half: if self.base.is_complex or self.base.is_extended_real: return False if self.base.is_extended_negative: if self.exp.is_odd and self.base.is_finite: return True if self.exp.is_even: return False elif self.base.is_extended_positive: if self.exp.is_extended_real: return False elif self.base.is_zero: if self.exp.is_extended_real: return False elif self.base.is_extended_nonnegative: if self.exp.is_extended_nonnegative: return False elif self.base.is_extended_nonpositive: if self.exp.is_even: return False elif self.base.is_extended_real: if self.exp.is_even: return False def _eval_is_zero(self): if self.base.is_zero: if self.exp.is_extended_positive: return True elif self.exp.is_extended_nonpositive: return False elif self.base == S.Exp1: return self.exp is S.NegativeInfinity elif self.base.is_zero is False: if self.base.is_finite and self.exp.is_finite: return False elif self.exp.is_negative: return self.base.is_infinite elif self.exp.is_nonnegative: return False elif self.exp.is_infinite and self.exp.is_extended_real: if (1 - abs(self.base)).is_extended_positive: return self.exp.is_extended_positive elif (1 - abs(self.base)).is_extended_negative: return self.exp.is_extended_negative elif self.base.is_finite and self.exp.is_negative: # when self.base.is_zero is None return False def _eval_is_integer(self): b, e = self.args if b.is_rational: if b.is_integer is False and e.is_positive: return False # rat**nonneg if b.is_integer and e.is_integer: if b is S.NegativeOne: return True if e.is_nonnegative or e.is_positive: return True if b.is_integer and e.is_negative and (e.is_finite or e.is_integer): if fuzzy_not((b - 1).is_zero) and fuzzy_not((b + 1).is_zero): return False if b.is_Number and e.is_Number: check = self.func(*self.args) return check.is_Integer if e.is_negative and b.is_positive and (b - 1).is_positive: return False if e.is_negative and b.is_negative and (b + 1).is_negative: return False def _eval_is_extended_real(self): if self.base is S.Exp1: if self.exp.is_extended_real: return True elif self.exp.is_imaginary: return (2*S.ImaginaryUnit*self.exp/S.Pi).is_even from sympy.functions.elementary.exponential import log, exp real_b = self.base.is_extended_real if real_b is None: if self.base.func == exp and self.base.exp.is_imaginary: return self.exp.is_imaginary if self.base.func == Pow and self.base.base is S.Exp1 and self.base.exp.is_imaginary: return self.exp.is_imaginary return real_e = self.exp.is_extended_real if real_e is None: return if real_b and real_e: if self.base.is_extended_positive: return True elif self.base.is_extended_nonnegative and self.exp.is_extended_nonnegative: return True elif self.exp.is_integer and self.base.is_extended_nonzero: return True elif self.exp.is_integer and self.exp.is_nonnegative: return True elif self.base.is_extended_negative: if self.exp.is_Rational: return False if real_e and self.exp.is_extended_negative and self.base.is_zero is False: return Pow(self.base, -self.exp).is_extended_real im_b = self.base.is_imaginary im_e = self.exp.is_imaginary if im_b: if self.exp.is_integer: if self.exp.is_even: return True elif self.exp.is_odd: return False elif im_e and log(self.base).is_imaginary: return True elif self.exp.is_Add: c, a = self.exp.as_coeff_Add() if c and c.is_Integer: return Mul( self.base**c, self.base**a, evaluate=False).is_extended_real elif self.base in (-S.ImaginaryUnit, S.ImaginaryUnit): if (self.exp/2).is_integer is False: return False if real_b and im_e: if self.base is S.NegativeOne: return True c = self.exp.coeff(S.ImaginaryUnit) if c: if self.base.is_rational and c.is_rational: if self.base.is_nonzero and (self.base - 1).is_nonzero and c.is_nonzero: return False ok = (c*log(self.base)/S.Pi).is_integer if ok is not None: return ok if real_b is False and real_e: # we already know it's not imag from sympy.functions.elementary.complexes import arg i = arg(self.base)*self.exp/S.Pi if i.is_complex: # finite return i.is_integer def _eval_is_complex(self): if self.base == S.Exp1: return fuzzy_or([self.exp.is_complex, self.exp.is_extended_negative]) if all(a.is_complex for a in self.args) and self._eval_is_finite(): return True def _eval_is_imaginary(self): if self.base.is_commutative is False: return False if self.base.is_imaginary: if self.exp.is_integer: odd = self.exp.is_odd if odd is not None: return odd return if self.base == S.Exp1: f = 2 * self.exp / (S.Pi*S.ImaginaryUnit) # exp(pi*integer) = 1 or -1, so not imaginary if f.is_even: return False # exp(pi*integer + pi/2) = I or -I, so it is imaginary if f.is_odd: return True return None if self.exp.is_imaginary: from sympy.functions.elementary.exponential import log imlog = log(self.base).is_imaginary if imlog is not None: return False # I**i -> real; (2*I)**i -> complex ==> not imaginary if self.base.is_extended_real and self.exp.is_extended_real: if self.base.is_positive: return False else: rat = self.exp.is_rational if not rat: return rat if self.exp.is_integer: return False else: half = (2*self.exp).is_integer if half: return self.base.is_negative return half if self.base.is_extended_real is False: # we already know it's not imag from sympy.functions.elementary.complexes import arg i = arg(self.base)*self.exp/S.Pi isodd = (2*i).is_odd if isodd is not None: return isodd def _eval_is_odd(self): if self.exp.is_integer: if self.exp.is_positive: return self.base.is_odd elif self.exp.is_nonnegative and self.base.is_odd: return True elif self.base is S.NegativeOne: return True def _eval_is_finite(self): if self.exp.is_negative: if self.base.is_zero: return False if self.base.is_infinite or self.base.is_nonzero: return True c1 = self.base.is_finite if c1 is None: return c2 = self.exp.is_finite if c2 is None: return if c1 and c2: if self.exp.is_nonnegative or fuzzy_not(self.base.is_zero): return True def _eval_is_prime(self): ''' An integer raised to the n(>=2)-th power cannot be a prime. ''' if self.base.is_integer and self.exp.is_integer and (self.exp - 1).is_positive: return False def _eval_is_composite(self): """ A power is composite if both base and exponent are greater than 1 """ if (self.base.is_integer and self.exp.is_integer and ((self.base - 1).is_positive and (self.exp - 1).is_positive or (self.base + 1).is_negative and self.exp.is_positive and self.exp.is_even)): return True def _eval_is_polar(self): return self.base.is_polar def _eval_subs(self, old, new): from sympy.calculus.accumulationbounds import AccumBounds if isinstance(self.exp, AccumBounds): b = self.base.subs(old, new) e = self.exp.subs(old, new) if isinstance(e, AccumBounds): return e.__rpow__(b) return self.func(b, e) from sympy.functions.elementary.exponential import exp, log def _check(ct1, ct2, old): """Return (bool, pow, remainder_pow) where, if bool is True, then the exponent of Pow `old` will combine with `pow` so the substitution is valid, otherwise bool will be False. For noncommutative objects, `pow` will be an integer, and a factor `Pow(old.base, remainder_pow)` needs to be included. If there is no such factor, None is returned. For commutative objects, remainder_pow is always None. cti are the coefficient and terms of an exponent of self or old In this _eval_subs routine a change like (b**(2*x)).subs(b**x, y) will give y**2 since (b**x)**2 == b**(2*x); if that equality does not hold then the substitution should not occur so `bool` will be False. """ coeff1, terms1 = ct1 coeff2, terms2 = ct2 if terms1 == terms2: if old.is_commutative: # Allow fractional powers for commutative objects pow = coeff1/coeff2 try: as_int(pow, strict=False) combines = True except ValueError: b, e = old.as_base_exp() # These conditions ensure that (b**e)**f == b**(e*f) for any f combines = b.is_positive and e.is_real or b.is_nonnegative and e.is_nonnegative return combines, pow, None else: # With noncommutative symbols, substitute only integer powers if not isinstance(terms1, tuple): terms1 = (terms1,) if not all(term.is_integer for term in terms1): return False, None, None try: # Round pow toward zero pow, remainder = divmod(as_int(coeff1), as_int(coeff2)) if pow < 0 and remainder != 0: pow += 1 remainder -= as_int(coeff2) if remainder == 0: remainder_pow = None else: remainder_pow = Mul(remainder, *terms1) return True, pow, remainder_pow except ValueError: # Can't substitute pass return False, None, None if old == self.base or (old == exp and self.base == S.Exp1): if new.is_Function and isinstance(new, Callable): return new(self.exp._subs(old, new)) else: return new**self.exp._subs(old, new) # issue 10829: (4**x - 3*y + 2).subs(2**x, y) -> y**2 - 3*y + 2 if isinstance(old, self.func) and self.exp == old.exp: l = log(self.base, old.base) if l.is_Number: return Pow(new, l) if isinstance(old, self.func) and self.base == old.base: if self.exp.is_Add is False: ct1 = self.exp.as_independent(Symbol, as_Add=False) ct2 = old.exp.as_independent(Symbol, as_Add=False) ok, pow, remainder_pow = _check(ct1, ct2, old) if ok: # issue 5180: (x**(6*y)).subs(x**(3*y),z)->z**2 result = self.func(new, pow) if remainder_pow is not None: result = Mul(result, Pow(old.base, remainder_pow)) return result else: # b**(6*x + a).subs(b**(3*x), y) -> y**2 * b**a # exp(exp(x) + exp(x**2)).subs(exp(exp(x)), w) -> w * exp(exp(x**2)) oarg = old.exp new_l = [] o_al = [] ct2 = oarg.as_coeff_mul() for a in self.exp.args: newa = a._subs(old, new) ct1 = newa.as_coeff_mul() ok, pow, remainder_pow = _check(ct1, ct2, old) if ok: new_l.append(new**pow) if remainder_pow is not None: o_al.append(remainder_pow) continue elif not old.is_commutative and not newa.is_integer: # If any term in the exponent is non-integer, # we do not do any substitutions in the noncommutative case return o_al.append(newa) if new_l: expo = Add(*o_al) new_l.append(Pow(self.base, expo, evaluate=False) if expo != 1 else self.base) return Mul(*new_l) if (isinstance(old, exp) or (old.is_Pow and old.base is S.Exp1)) and self.exp.is_extended_real and self.base.is_positive: ct1 = old.exp.as_independent(Symbol, as_Add=False) ct2 = (self.exp*log(self.base)).as_independent( Symbol, as_Add=False) ok, pow, remainder_pow = _check(ct1, ct2, old) if ok: result = self.func(new, pow) # (2**x).subs(exp(x*log(2)), z) -> z if remainder_pow is not None: result = Mul(result, Pow(old.base, remainder_pow)) return result def as_base_exp(self): """Return base and exp of self. Explanation =========== If base is 1/Integer, then return Integer, -exp. If this extra processing is not needed, the base and exp properties will give the raw arguments Examples ======== >>> from sympy import Pow, S >>> p = Pow(S.Half, 2, evaluate=False) >>> p.as_base_exp() (2, -2) >>> p.args (1/2, 2) """ b, e = self.args if b.is_Rational and b.p == 1 and b.q != 1: return Integer(b.q), -e return b, e def _eval_adjoint(self): from sympy.functions.elementary.complexes import adjoint i, p = self.exp.is_integer, self.base.is_positive if i: return adjoint(self.base)**self.exp if p: return self.base**adjoint(self.exp) if i is False and p is False: expanded = expand_complex(self) if expanded != self: return adjoint(expanded) def _eval_conjugate(self): from sympy.functions.elementary.complexes import conjugate as c i, p = self.exp.is_integer, self.base.is_positive if i: return c(self.base)**self.exp if p: return self.base**c(self.exp) if i is False and p is False: expanded = expand_complex(self) if expanded != self: return c(expanded) if self.is_extended_real: return self def _eval_transpose(self): from sympy.functions.elementary.complexes import transpose if self.base == S.Exp1: return self.func(S.Exp1, self.exp.transpose()) i, p = self.exp.is_integer, (self.base.is_complex or self.base.is_infinite) if p: return self.base**self.exp if i: return transpose(self.base)**self.exp if i is False and p is False: expanded = expand_complex(self) if expanded != self: return transpose(expanded) def _eval_expand_power_exp(self, **hints): """a**(n + m) -> a**n*a**m""" b = self.base e = self.exp if b == S.Exp1: from sympy.concrete.summations import Sum if isinstance(e, Sum) and e.is_commutative: from sympy.concrete.products import Product return Product(self.func(b, e.function), *e.limits) if e.is_Add and e.is_commutative: return Mul(*[self.func(b, x) for x in e.args]) return self.func(b, e) def _eval_expand_power_base(self, **hints): """(a*b)**n -> a**n * b**n""" force = hints.get('force', False) b = self.base e = self.exp if not b.is_Mul: return self cargs, nc = b.args_cnc(split_1=False) # expand each term - this is top-level-only # expansion but we have to watch out for things # that don't have an _eval_expand method if nc: nc = [i._eval_expand_power_base(**hints) if hasattr(i, '_eval_expand_power_base') else i for i in nc] if e.is_Integer: if e.is_positive: rv = Mul(*nc*e) else: rv = Mul(*[i**-1 for i in nc[::-1]]*-e) if cargs: rv *= Mul(*cargs)**e return rv if not cargs: return self.func(Mul(*nc), e, evaluate=False) nc = [Mul(*nc)] # sift the commutative bases other, maybe_real = sift(cargs, lambda x: x.is_extended_real is False, binary=True) def pred(x): if x is S.ImaginaryUnit: return S.ImaginaryUnit polar = x.is_polar if polar: return True if polar is None: return fuzzy_bool(x.is_extended_nonnegative) sifted = sift(maybe_real, pred) nonneg = sifted[True] other += sifted[None] neg = sifted[False] imag = sifted[S.ImaginaryUnit] if imag: I = S.ImaginaryUnit i = len(imag) % 4 if i == 0: pass elif i == 1: other.append(I) elif i == 2: if neg: nonn = -neg.pop() if nonn is not S.One: nonneg.append(nonn) else: neg.append(S.NegativeOne) else: if neg: nonn = -neg.pop() if nonn is not S.One: nonneg.append(nonn) else: neg.append(S.NegativeOne) other.append(I) del imag # bring out the bases that can be separated from the base if force or e.is_integer: # treat all commutatives the same and put nc in other cargs = nonneg + neg + other other = nc else: # this is just like what is happening automatically, except # that now we are doing it for an arbitrary exponent for which # no automatic expansion is done assert not e.is_Integer # handle negatives by making them all positive and putting # the residual -1 in other if len(neg) > 1: o = S.One if not other and neg[0].is_Number: o *= neg.pop(0) if len(neg) % 2: o = -o for n in neg: nonneg.append(-n) if o is not S.One: other.append(o) elif neg and other: if neg[0].is_Number and neg[0] is not S.NegativeOne: other.append(S.NegativeOne) nonneg.append(-neg[0]) else: other.extend(neg) else: other.extend(neg) del neg cargs = nonneg other += nc rv = S.One if cargs: if e.is_Rational: npow, cargs = sift(cargs, lambda x: x.is_Pow and x.exp.is_Rational and x.base.is_number, binary=True) rv = Mul(*[self.func(b.func(*b.args), e) for b in npow]) rv *= Mul(*[self.func(b, e, evaluate=False) for b in cargs]) if other: rv *= self.func(Mul(*other), e, evaluate=False) return rv def _eval_expand_multinomial(self, **hints): """(a + b + ..)**n -> a**n + n*a**(n-1)*b + .., n is nonzero integer""" base, exp = self.args result = self if exp.is_Rational and exp.p > 0 and base.is_Add: if not exp.is_Integer: n = Integer(exp.p // exp.q) if not n: return result else: radical, result = self.func(base, exp - n), [] expanded_base_n = self.func(base, n) if expanded_base_n.is_Pow: expanded_base_n = \ expanded_base_n._eval_expand_multinomial() for term in Add.make_args(expanded_base_n): result.append(term*radical) return Add(*result) n = int(exp) if base.is_commutative: order_terms, other_terms = [], [] for b in base.args: if b.is_Order: order_terms.append(b) else: other_terms.append(b) if order_terms: # (f(x) + O(x^n))^m -> f(x)^m + m*f(x)^{m-1} *O(x^n) f = Add(*other_terms) o = Add(*order_terms) if n == 2: return expand_multinomial(f**n, deep=False) + n*f*o else: g = expand_multinomial(f**(n - 1), deep=False) return expand_mul(f*g, deep=False) + n*g*o if base.is_number: # Efficiently expand expressions of the form (a + b*I)**n # where 'a' and 'b' are real numbers and 'n' is integer. a, b = base.as_real_imag() if a.is_Rational and b.is_Rational: if not a.is_Integer: if not b.is_Integer: k = self.func(a.q * b.q, n) a, b = a.p*b.q, a.q*b.p else: k = self.func(a.q, n) a, b = a.p, a.q*b elif not b.is_Integer: k = self.func(b.q, n) a, b = a*b.q, b.p else: k = 1 a, b, c, d = int(a), int(b), 1, 0 while n: if n & 1: c, d = a*c - b*d, b*c + a*d n -= 1 a, b = a*a - b*b, 2*a*b n //= 2 I = S.ImaginaryUnit if k == 1: return c + I*d else: return Integer(c)/k + I*d/k p = other_terms # (x + y)**3 -> x**3 + 3*x**2*y + 3*x*y**2 + y**3 # in this particular example: # p = [x,y]; n = 3 # so now it's easy to get the correct result -- we get the # coefficients first: from sympy.ntheory.multinomial import multinomial_coefficients from sympy.polys.polyutils import basic_from_dict expansion_dict = multinomial_coefficients(len(p), n) # in our example: {(3, 0): 1, (1, 2): 3, (0, 3): 1, (2, 1): 3} # and now construct the expression. return basic_from_dict(expansion_dict, *p) else: if n == 2: return Add(*[f*g for f in base.args for g in base.args]) else: multi = (base**(n - 1))._eval_expand_multinomial() if multi.is_Add: return Add(*[f*g for f in base.args for g in multi.args]) else: # XXX can this ever happen if base was an Add? return Add(*[f*multi for f in base.args]) elif (exp.is_Rational and exp.p < 0 and base.is_Add and abs(exp.p) > exp.q): return 1 / self.func(base, -exp)._eval_expand_multinomial() elif exp.is_Add and base.is_Number: # a + b a b # n --> n n, where n, a, b are Numbers coeff, tail = S.One, S.Zero for term in exp.args: if term.is_Number: coeff *= self.func(base, term) else: tail += term return coeff * self.func(base, tail) else: return result def as_real_imag(self, deep=True, **hints): if self.exp.is_Integer: from sympy.polys.polytools import poly exp = self.exp re_e, im_e = self.base.as_real_imag(deep=deep) if not im_e: return self, S.Zero a, b = symbols('a b', cls=Dummy) if exp >= 0: if re_e.is_Number and im_e.is_Number: # We can be more efficient in this case expr = expand_multinomial(self.base**exp) if expr != self: return expr.as_real_imag() expr = poly( (a + b)**exp) # a = re, b = im; expr = (a + b*I)**exp else: mag = re_e**2 + im_e**2 re_e, im_e = re_e/mag, -im_e/mag if re_e.is_Number and im_e.is_Number: # We can be more efficient in this case expr = expand_multinomial((re_e + im_e*S.ImaginaryUnit)**-exp) if expr != self: return expr.as_real_imag() expr = poly((a + b)**-exp) # Terms with even b powers will be real r = [i for i in expr.terms() if not i[0][1] % 2] re_part = Add(*[cc*a**aa*b**bb for (aa, bb), cc in r]) # Terms with odd b powers will be imaginary r = [i for i in expr.terms() if i[0][1] % 4 == 1] im_part1 = Add(*[cc*a**aa*b**bb for (aa, bb), cc in r]) r = [i for i in expr.terms() if i[0][1] % 4 == 3] im_part3 = Add(*[cc*a**aa*b**bb for (aa, bb), cc in r]) return (re_part.subs({a: re_e, b: S.ImaginaryUnit*im_e}), im_part1.subs({a: re_e, b: im_e}) + im_part3.subs({a: re_e, b: -im_e})) from sympy.functions.elementary.trigonometric import atan2, cos, sin if self.exp.is_Rational: re_e, im_e = self.base.as_real_imag(deep=deep) if im_e.is_zero and self.exp is S.Half: if re_e.is_extended_nonnegative: return self, S.Zero if re_e.is_extended_nonpositive: return S.Zero, (-self.base)**self.exp # XXX: This is not totally correct since for x**(p/q) with # x being imaginary there are actually q roots, but # only a single one is returned from here. r = self.func(self.func(re_e, 2) + self.func(im_e, 2), S.Half) t = atan2(im_e, re_e) rp, tp = self.func(r, self.exp), t*self.exp return rp*cos(tp), rp*sin(tp) elif self.base is S.Exp1: from sympy.functions.elementary.exponential import exp re_e, im_e = self.exp.as_real_imag() if deep: re_e = re_e.expand(deep, **hints) im_e = im_e.expand(deep, **hints) c, s = cos(im_e), sin(im_e) return exp(re_e)*c, exp(re_e)*s else: from sympy.functions.elementary.complexes import im, re if deep: hints['complex'] = False expanded = self.expand(deep, **hints) if hints.get('ignore') == expanded: return None else: return (re(expanded), im(expanded)) else: return re(self), im(self) def _eval_derivative(self, s): from sympy.functions.elementary.exponential import log dbase = self.base.diff(s) dexp = self.exp.diff(s) return self * (dexp * log(self.base) + dbase * self.exp/self.base) def _eval_evalf(self, prec): base, exp = self.as_base_exp() if base == S.Exp1: # Use mpmath function associated to class "exp": from sympy.functions.elementary.exponential import exp as exp_function return exp_function(self.exp, evaluate=False)._eval_evalf(prec) base = base._evalf(prec) if not exp.is_Integer: exp = exp._evalf(prec) if exp.is_negative and base.is_number and base.is_extended_real is False: base = base.conjugate() / (base * base.conjugate())._evalf(prec) exp = -exp return self.func(base, exp).expand() return self.func(base, exp) def _eval_is_polynomial(self, syms): if self.exp.has(*syms): return False if self.base.has(*syms): return bool(self.base._eval_is_polynomial(syms) and self.exp.is_Integer and (self.exp >= 0)) else: return True def _eval_is_rational(self): # The evaluation of self.func below can be very expensive in the case # of integer**integer if the exponent is large. We should try to exit # before that if possible: if (self.exp.is_integer and self.base.is_rational and fuzzy_not(fuzzy_and([self.exp.is_negative, self.base.is_zero]))): return True p = self.func(*self.as_base_exp()) # in case it's unevaluated if not p.is_Pow: return p.is_rational b, e = p.as_base_exp() if e.is_Rational and b.is_Rational: # we didn't check that e is not an Integer # because Rational**Integer autosimplifies return False if e.is_integer: if b.is_rational: if fuzzy_not(b.is_zero) or e.is_nonnegative: return True if b == e: # always rational, even for 0**0 return True elif b.is_irrational: return e.is_zero if b is S.Exp1: if e.is_rational and e.is_nonzero: return False def _eval_is_algebraic(self): def _is_one(expr): try: return (expr - 1).is_zero except ValueError: # when the operation is not allowed return False if self.base.is_zero or _is_one(self.base): return True elif self.base is S.Exp1: s = self.func(*self.args) if s.func == self.func: if self.exp.is_nonzero: if self.exp.is_algebraic: return False elif (self.exp/S.Pi).is_rational: return False elif (self.exp/(S.ImaginaryUnit*S.Pi)).is_rational: return True else: return s.is_algebraic elif self.exp.is_rational: if self.base.is_algebraic is False: return self.exp.is_zero if self.base.is_zero is False: if self.exp.is_nonzero: return self.base.is_algebraic elif self.base.is_algebraic: return True if self.exp.is_positive: return self.base.is_algebraic elif self.base.is_algebraic and self.exp.is_algebraic: if ((fuzzy_not(self.base.is_zero) and fuzzy_not(_is_one(self.base))) or self.base.is_integer is False or self.base.is_irrational): return self.exp.is_rational def _eval_is_rational_function(self, syms): if self.exp.has(*syms): return False if self.base.has(*syms): return self.base._eval_is_rational_function(syms) and \ self.exp.is_Integer else: return True def _eval_is_meromorphic(self, x, a): # f**g is meromorphic if g is an integer and f is meromorphic. # E**(log(f)*g) is meromorphic if log(f)*g is meromorphic # and finite. base_merom = self.base._eval_is_meromorphic(x, a) exp_integer = self.exp.is_Integer if exp_integer: return base_merom exp_merom = self.exp._eval_is_meromorphic(x, a) if base_merom is False: # f**g = E**(log(f)*g) may be meromorphic if the # singularities of log(f) and g cancel each other, # for example, if g = 1/log(f). Hence, return False if exp_merom else None elif base_merom is None: return None b = self.base.subs(x, a) # b is extended complex as base is meromorphic. # log(base) is finite and meromorphic when b != 0, zoo. b_zero = b.is_zero if b_zero: log_defined = False else: log_defined = fuzzy_and((b.is_finite, fuzzy_not(b_zero))) if log_defined is False: # zero or pole of base return exp_integer # False or None elif log_defined is None: return None if not exp_merom: return exp_merom # False or None return self.exp.subs(x, a).is_finite def _eval_is_algebraic_expr(self, syms): if self.exp.has(*syms): return False if self.base.has(*syms): return self.base._eval_is_algebraic_expr(syms) and \ self.exp.is_Rational else: return True def _eval_rewrite_as_exp(self, base, expo, **kwargs): from sympy.functions.elementary.exponential import exp, log if base.is_zero or base.has(exp) or expo.has(exp): return base**expo if base.has(Symbol): # delay evaluation if expo is non symbolic # (as exp(x*log(5)) automatically reduces to x**5) if global_parameters.exp_is_pow: return Pow(S.Exp1, log(base)*expo, evaluate=expo.has(Symbol)) else: return exp(log(base)*expo, evaluate=expo.has(Symbol)) else: from sympy.functions.elementary.complexes import arg, Abs return exp((log(Abs(base)) + S.ImaginaryUnit*arg(base))*expo) def as_numer_denom(self): if not self.is_commutative: return self, S.One base, exp = self.as_base_exp() n, d = base.as_numer_denom() # this should be the same as ExpBase.as_numer_denom wrt # exponent handling neg_exp = exp.is_negative if exp.is_Mul and not neg_exp and not exp.is_positive: neg_exp = exp.could_extract_minus_sign() int_exp = exp.is_integer # the denominator cannot be separated from the numerator if # its sign is unknown unless the exponent is an integer, e.g. # sqrt(a/b) != sqrt(a)/sqrt(b) when a=1 and b=-1. But if the # denominator is negative the numerator and denominator can # be negated and the denominator (now positive) separated. if not (d.is_extended_real or int_exp): n = base d = S.One dnonpos = d.is_nonpositive if dnonpos: n, d = -n, -d elif dnonpos is None and not int_exp: n = base d = S.One if neg_exp: n, d = d, n exp = -exp if exp.is_infinite: if n is S.One and d is not S.One: return n, self.func(d, exp) if n is not S.One and d is S.One: return self.func(n, exp), d return self.func(n, exp), self.func(d, exp) def matches(self, expr, repl_dict=None, old=False): expr = _sympify(expr) if repl_dict is None: repl_dict = {} # special case, pattern = 1 and expr.exp can match to 0 if expr is S.One: d = self.exp.matches(S.Zero, repl_dict) if d is not None: return d # make sure the expression to be matched is an Expr if not isinstance(expr, Expr): return None b, e = expr.as_base_exp() # special case number sb, se = self.as_base_exp() if sb.is_Symbol and se.is_Integer and expr: if e.is_rational: return sb.matches(b**(e/se), repl_dict) return sb.matches(expr**(1/se), repl_dict) d = repl_dict.copy() d = self.base.matches(b, d) if d is None: return None d = self.exp.xreplace(d).matches(e, d) if d is None: return Expr.matches(self, expr, repl_dict) return d def _eval_nseries(self, x, n, logx, cdir=0): # NOTE! This function is an important part of the gruntz algorithm # for computing limits. It has to return a generalized power # series with coefficients in C(log, log(x)). In more detail: # It has to return an expression # c_0*x**e_0 + c_1*x**e_1 + ... (finitely many terms) # where e_i are numbers (not necessarily integers) and c_i are # expressions involving only numbers, the log function, and log(x). # The series expansion of b**e is computed as follows: # 1) We express b as f*(1 + g) where f is the leading term of b. # g has order O(x**d) where d is strictly positive. # 2) Then b**e = (f**e)*((1 + g)**e). # (1 + g)**e is computed using binomial series. from sympy.functions.elementary.exponential import exp, log from sympy.series.limits import limit from sympy.series.order import Order if self.base is S.Exp1: e_series = self.exp.nseries(x, n=n, logx=logx) if e_series.is_Order: return 1 + e_series e0 = limit(e_series.removeO(), x, 0) if e0 is S.NegativeInfinity: return Order(x**n, x) if e0 is S.Infinity: return self t = e_series - e0 exp_series = term = exp(e0) # series of exp(e0 + t) in t for i in range(1, n): term *= t/i term = term.nseries(x, n=n, logx=logx) exp_series += term exp_series += Order(t**n, x) from sympy.simplify.powsimp import powsimp return powsimp(exp_series, deep=True, combine='exp') from sympy.simplify.powsimp import powdenest from .numbers import _illegal self = powdenest(self, force=True).trigsimp() b, e = self.as_base_exp() if e.has(*_illegal): raise PoleError() if e.has(x): return exp(e*log(b))._eval_nseries(x, n=n, logx=logx, cdir=cdir) if logx is not None and b.has(log): from .symbol import Wild c, ex = symbols('c, ex', cls=Wild, exclude=[x]) b = b.replace(log(c*x**ex), log(c) + ex*logx) self = b**e b = b.removeO() try: from sympy.functions.special.gamma_functions import polygamma if b.has(polygamma, S.EulerGamma) and logx is not None: raise ValueError() _, m = b.leadterm(x) except (ValueError, NotImplementedError, PoleError): b = b._eval_nseries(x, n=max(2, n), logx=logx, cdir=cdir).removeO() if b.has(S.NaN, S.ComplexInfinity): raise NotImplementedError() _, m = b.leadterm(x) if e.has(log): from sympy.simplify.simplify import logcombine e = logcombine(e).cancel() if not (m.is_zero or e.is_number and e.is_real): res = exp(e*log(b))._eval_nseries(x, n=n, logx=logx, cdir=cdir) if res is exp(e*log(b)): return self return res f = b.as_leading_term(x, logx=logx) g = (b/f - S.One).cancel(expand=False) if not m.is_number: raise NotImplementedError() maxpow = n - m*e if maxpow.is_negative: return Order(x**(m*e), x) if g.is_zero: r = f**e if r != self: r += Order(x**n, x) return r def coeff_exp(term, x): coeff, exp = S.One, S.Zero for factor in Mul.make_args(term): if factor.has(x): base, exp = factor.as_base_exp() if base != x: try: return term.leadterm(x) except ValueError: return term, S.Zero else: coeff *= factor return coeff, exp def mul(d1, d2): res = {} for e1, e2 in product(d1, d2): ex = e1 + e2 if ex < maxpow: res[ex] = res.get(ex, S.Zero) + d1[e1]*d2[e2] return res try: c, d = g.leadterm(x, logx=logx) except (ValueError, NotImplementedError): if limit(g/x**maxpow, x, 0) == 0: # g has higher order zero return f**e + e*f**e*g # first term of binomial series else: raise NotImplementedError() if c.is_Float and d == S.Zero: # Convert floats like 0.5 to exact SymPy numbers like S.Half, to # prevent rounding errors which can induce wrong values of d leading # to execution of an inappropriate code block (line 1741 - 1750) from sympy.simplify.simplify import nsimplify _, d = nsimplify(g).leadterm(x, logx=logx) if not d.is_positive: g = g.simplify() if g.is_zero: return f**e _, d = g.leadterm(x, logx=logx) if not d.is_positive: g = ((b - f)/f).expand() _, d = g.leadterm(x, logx=logx) if not d.is_positive: raise NotImplementedError() from sympy.functions.elementary.integers import ceiling gpoly = g._eval_nseries(x, n=ceiling(maxpow), logx=logx, cdir=cdir).removeO() gterms = {} for term in Add.make_args(gpoly): co1, e1 = coeff_exp(term, x) gterms[e1] = gterms.get(e1, S.Zero) + co1 k = S.One terms = {S.Zero: S.One} tk = gterms from sympy.functions.combinatorial.factorials import factorial, ff while (k*d - maxpow).is_negative: coeff = ff(e, k)/factorial(k) for ex in tk: terms[ex] = terms.get(ex, S.Zero) + coeff*tk[ex] tk = mul(tk, gterms) k += S.One from sympy.functions.elementary.complexes import im if not e.is_integer and m.is_zero and f.is_negative: ndir = (b - f).dir(x, cdir) if im(ndir).is_negative: inco, inex = coeff_exp(f**e*(-1)**(-2*e), x) elif im(ndir).is_zero: inco, inex = coeff_exp(exp(e*log(b)).as_leading_term(x, logx=logx, cdir=cdir), x) else: inco, inex = coeff_exp(f**e, x) else: inco, inex = coeff_exp(f**e, x) res = S.Zero for e1 in terms: ex = e1 + inex res += terms[e1]*inco*x**(ex) if not (e.is_integer and e.is_positive and (e*d - n).is_nonpositive and res == _mexpand(self)): res += Order(x**n, x) return res def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.functions.elementary.exponential import exp, log e = self.exp b = self.base if self.base is S.Exp1: arg = e.as_leading_term(x, logx=logx) arg0 = arg.subs(x, 0) if arg0 is S.NaN: arg0 = arg.limit(x, 0) if arg0.is_infinite is False: return S.Exp1**arg0 raise PoleError("Cannot expand %s around 0" % (self)) elif e.has(x): lt = exp(e * log(b)) return lt.as_leading_term(x, logx=logx, cdir=cdir) else: from sympy.functions.elementary.complexes import im try: f = b.as_leading_term(x, logx=logx, cdir=cdir) except PoleError: return self if not e.is_integer and f.is_negative: ndir = (b - f).dir(x, cdir) if im(ndir).is_negative: # Normally, f**e would evaluate to exp(e*log(f)) but on branch cuts # an other value is expected through the following computation # exp(e*(log(f) - 2*pi*I)) == f**e*exp(-2*e*pi*I) == f**e*(-1)**(-2*e). return self.func(f, e) * (-1)**(-2*e) elif im(ndir).is_zero: log_leadterm = log(b)._eval_as_leading_term(x, logx=logx, cdir=cdir) if log_leadterm.is_infinite is False: return exp(e*log_leadterm) return self.func(f, e) @cacheit def _taylor_term(self, n, x, *previous_terms): # of (1 + x)**e from sympy.functions.combinatorial.factorials import binomial return binomial(self.exp, n) * self.func(x, n) def taylor_term(self, n, x, *previous_terms): if self.base is not S.Exp1: return super().taylor_term(n, x, *previous_terms) if n < 0: return S.Zero if n == 0: return S.One from .sympify import sympify x = sympify(x) if previous_terms: p = previous_terms[-1] if p is not None: return p * x / n from sympy.functions.combinatorial.factorials import factorial return x**n/factorial(n) def _eval_rewrite_as_sin(self, base, exp): if self.base is S.Exp1: from sympy.functions.elementary.trigonometric import sin return sin(S.ImaginaryUnit*self.exp + S.Pi/2) - S.ImaginaryUnit*sin(S.ImaginaryUnit*self.exp) def _eval_rewrite_as_cos(self, base, exp): if self.base is S.Exp1: from sympy.functions.elementary.trigonometric import cos return cos(S.ImaginaryUnit*self.exp) + S.ImaginaryUnit*cos(S.ImaginaryUnit*self.exp + S.Pi/2) def _eval_rewrite_as_tanh(self, base, exp): if self.base is S.Exp1: from sympy.functions.elementary.hyperbolic import tanh return (1 + tanh(self.exp/2))/(1 - tanh(self.exp/2)) def _eval_rewrite_as_sqrt(self, base, exp, **kwargs): from sympy.functions.elementary.trigonometric import sin, cos if base is not S.Exp1: return None if exp.is_Mul: coeff = exp.coeff(S.Pi * S.ImaginaryUnit) if coeff and coeff.is_number: cosine, sine = cos(S.Pi*coeff), sin(S.Pi*coeff) if not isinstance(cosine, cos) and not isinstance (sine, sin): return cosine + S.ImaginaryUnit*sine def as_content_primitive(self, radical=False, clear=True): """Return the tuple (R, self/R) where R is the positive Rational extracted from self. Examples ======== >>> from sympy import sqrt >>> sqrt(4 + 4*sqrt(2)).as_content_primitive() (2, sqrt(1 + sqrt(2))) >>> sqrt(3 + 3*sqrt(2)).as_content_primitive() (1, sqrt(3)*sqrt(1 + sqrt(2))) >>> from sympy import expand_power_base, powsimp, Mul >>> from sympy.abc import x, y >>> ((2*x + 2)**2).as_content_primitive() (4, (x + 1)**2) >>> (4**((1 + y)/2)).as_content_primitive() (2, 4**(y/2)) >>> (3**((1 + y)/2)).as_content_primitive() (1, 3**((y + 1)/2)) >>> (3**((5 + y)/2)).as_content_primitive() (9, 3**((y + 1)/2)) >>> eq = 3**(2 + 2*x) >>> powsimp(eq) == eq True >>> eq.as_content_primitive() (9, 3**(2*x)) >>> powsimp(Mul(*_)) 3**(2*x + 2) >>> eq = (2 + 2*x)**y >>> s = expand_power_base(eq); s.is_Mul, s (False, (2*x + 2)**y) >>> eq.as_content_primitive() (1, (2*(x + 1))**y) >>> s = expand_power_base(_[1]); s.is_Mul, s (True, 2**y*(x + 1)**y) See docstring of Expr.as_content_primitive for more examples. """ b, e = self.as_base_exp() b = _keep_coeff(*b.as_content_primitive(radical=radical, clear=clear)) ce, pe = e.as_content_primitive(radical=radical, clear=clear) if b.is_Rational: #e #= ce*pe #= ce*(h + t) #= ce*h + ce*t #=> self #= b**(ce*h)*b**(ce*t) #= b**(cehp/cehq)*b**(ce*t) #= b**(iceh + r/cehq)*b**(ce*t) #= b**(iceh)*b**(r/cehq)*b**(ce*t) #= b**(iceh)*b**(ce*t + r/cehq) h, t = pe.as_coeff_Add() if h.is_Rational and b != S.Zero: ceh = ce*h c = self.func(b, ceh) r = S.Zero if not c.is_Rational: iceh, r = divmod(ceh.p, ceh.q) c = self.func(b, iceh) return c, self.func(b, _keep_coeff(ce, t + r/ce/ceh.q)) e = _keep_coeff(ce, pe) # b**e = (h*t)**e = h**e*t**e = c*m*t**e if e.is_Rational and b.is_Mul: h, t = b.as_content_primitive(radical=radical, clear=clear) # h is positive c, m = self.func(h, e).as_coeff_Mul() # so c is positive m, me = m.as_base_exp() if m is S.One or me == e: # probably always true # return the following, not return c, m*Pow(t, e) # which would change Pow into Mul; we let SymPy # decide what to do by using the unevaluated Mul, e.g # should it stay as sqrt(2 + 2*sqrt(5)) or become # sqrt(2)*sqrt(1 + sqrt(5)) return c, self.func(_keep_coeff(m, t), e) return S.One, self.func(b, e) def is_constant(self, *wrt, **flags): expr = self if flags.get('simplify', True): expr = expr.simplify() b, e = expr.as_base_exp() bz = b.equals(0) if bz: # recalculate with assumptions in case it's unevaluated new = b**e if new != expr: return new.is_constant() econ = e.is_constant(*wrt) bcon = b.is_constant(*wrt) if bcon: if econ: return True bz = b.equals(0) if bz is False: return False elif bcon is None: return None return e.equals(0) def _eval_difference_delta(self, n, step): b, e = self.args if e.has(n) and not b.has(n): new_e = e.subs(n, n + step) return (b**(new_e - e) - 1) * self power = Dispatcher('power') power.add((object, object), Pow) from .add import Add from .numbers import Integer from .mul import Mul, _keep_coeff from .symbol import Symbol, Dummy, symbols
271eb776d6045b85a1bd6f3f37a18ae4b3c3526fedf2b9056eb16f7312043ed5
"""Tools for manipulating of large commutative expressions. """ from .add import Add from .mul import Mul, _keep_coeff from .power import Pow from .basic import Basic from .expr import Expr from .sympify import sympify from .numbers import Rational, Integer, Number, I from .singleton import S from .sorting import default_sort_key, ordered from .symbol import Dummy from .traversal import preorder_traversal from .coreerrors import NonCommutativeExpression from .containers import Tuple, Dict from sympy.external.gmpy import SYMPY_INTS from sympy.utilities.iterables import (common_prefix, common_suffix, variations, iterable, is_sequence) from collections import defaultdict from typing import Tuple as tTuple _eps = Dummy(positive=True) def _isnumber(i): return isinstance(i, (SYMPY_INTS, float)) or i.is_Number def _monotonic_sign(self): """Return the value closest to 0 that ``self`` may have if all symbols are signed and the result is uniformly the same sign for all values of symbols. If a symbol is only signed but not known to be an integer or the result is 0 then a symbol representative of the sign of self will be returned. Otherwise, None is returned if a) the sign could be positive or negative or b) self is not in one of the following forms: - L(x, y, ...) + A: a function linear in all symbols x, y, ... with an additive constant; if A is zero then the function can be a monomial whose sign is monotonic over the range of the variables, e.g. (x + 1)**3 if x is nonnegative. - A/L(x, y, ...) + B: the inverse of a function linear in all symbols x, y, ... that does not have a sign change from positive to negative for any set of values for the variables. - M(x, y, ...) + A: a monomial M whose factors are all signed and a constant, A. - A/M(x, y, ...) + B: the inverse of a monomial and constants A and B. - P(x): a univariate polynomial Examples ======== >>> from sympy.core.exprtools import _monotonic_sign as F >>> from sympy import Dummy >>> nn = Dummy(integer=True, nonnegative=True) >>> p = Dummy(integer=True, positive=True) >>> p2 = Dummy(integer=True, positive=True) >>> F(nn + 1) 1 >>> F(p - 1) _nneg >>> F(nn*p + 1) 1 >>> F(p2*p + 1) 2 >>> F(nn - 1) # could be negative, zero or positive """ if not self.is_extended_real: return if (-self).is_Symbol: rv = _monotonic_sign(-self) return rv if rv is None else -rv if not self.is_Add and self.as_numer_denom()[1].is_number: s = self if s.is_prime: if s.is_odd: return Integer(3) else: return Integer(2) elif s.is_composite: if s.is_odd: return Integer(9) else: return Integer(4) elif s.is_positive: if s.is_even: if s.is_prime is False: return Integer(4) else: return Integer(2) elif s.is_integer: return S.One else: return _eps elif s.is_extended_negative: if s.is_even: return Integer(-2) elif s.is_integer: return S.NegativeOne else: return -_eps if s.is_zero or s.is_extended_nonpositive or s.is_extended_nonnegative: return S.Zero return None # univariate polynomial free = self.free_symbols if len(free) == 1: if self.is_polynomial(): from sympy.polys.polytools import real_roots from sympy.polys.polyroots import roots from sympy.polys.polyerrors import PolynomialError x = free.pop() x0 = _monotonic_sign(x) if x0 in (_eps, -_eps): x0 = S.Zero if x0 is not None: d = self.diff(x) if d.is_number: currentroots = [] else: try: currentroots = real_roots(d) except (PolynomialError, NotImplementedError): currentroots = [r for r in roots(d, x) if r.is_extended_real] y = self.subs(x, x0) if x.is_nonnegative and all( (r - x0).is_nonpositive for r in currentroots): if y.is_nonnegative and d.is_positive: if y: return y if y.is_positive else Dummy('pos', positive=True) else: return Dummy('nneg', nonnegative=True) if y.is_nonpositive and d.is_negative: if y: return y if y.is_negative else Dummy('neg', negative=True) else: return Dummy('npos', nonpositive=True) elif x.is_nonpositive and all( (r - x0).is_nonnegative for r in currentroots): if y.is_nonnegative and d.is_negative: if y: return Dummy('pos', positive=True) else: return Dummy('nneg', nonnegative=True) if y.is_nonpositive and d.is_positive: if y: return Dummy('neg', negative=True) else: return Dummy('npos', nonpositive=True) else: n, d = self.as_numer_denom() den = None if n.is_number: den = _monotonic_sign(d) elif not d.is_number: if _monotonic_sign(n) is not None: den = _monotonic_sign(d) if den is not None and (den.is_positive or den.is_negative): v = n*den if v.is_positive: return Dummy('pos', positive=True) elif v.is_nonnegative: return Dummy('nneg', nonnegative=True) elif v.is_negative: return Dummy('neg', negative=True) elif v.is_nonpositive: return Dummy('npos', nonpositive=True) return None # multivariate c, a = self.as_coeff_Add() v = None if not a.is_polynomial(): # F/A or A/F where A is a number and F is a signed, rational monomial n, d = a.as_numer_denom() if not (n.is_number or d.is_number): return if ( a.is_Mul or a.is_Pow) and \ a.is_rational and \ all(p.exp.is_Integer for p in a.atoms(Pow) if p.is_Pow) and \ (a.is_positive or a.is_negative): v = S.One for ai in Mul.make_args(a): if ai.is_number: v *= ai continue reps = {} for x in ai.free_symbols: reps[x] = _monotonic_sign(x) if reps[x] is None: return v *= ai.subs(reps) elif c: # signed linear expression if not any(p for p in a.atoms(Pow) if not p.is_number) and (a.is_nonpositive or a.is_nonnegative): free = list(a.free_symbols) p = {} for i in free: v = _monotonic_sign(i) if v is None: return p[i] = v or (_eps if i.is_nonnegative else -_eps) v = a.xreplace(p) if v is not None: rv = v + c if v.is_nonnegative and rv.is_positive: return rv.subs(_eps, 0) if v.is_nonpositive and rv.is_negative: return rv.subs(_eps, 0) def decompose_power(expr: Expr) -> tTuple[Expr, int]: """ Decompose power into symbolic base and integer exponent. Explanation =========== This is strictly only valid if the exponent from which the integer is extracted is itself an integer or the base is positive. These conditions are assumed and not checked here. Examples ======== >>> from sympy.core.exprtools import decompose_power >>> from sympy.abc import x, y >>> decompose_power(x) (x, 1) >>> decompose_power(x**2) (x, 2) >>> decompose_power(x**(2*y)) (x**y, 2) >>> decompose_power(x**(2*y/3)) (x**(y/3), 2) """ base, exp = expr.as_base_exp() if exp.is_Number: if exp.is_Rational: if not exp.is_Integer: base = Pow(base, Rational(1, exp.q)) # type: ignore e = exp.p # type: ignore else: base, e = expr, 1 else: exp, tail = exp.as_coeff_Mul(rational=True) if exp is S.NegativeOne: base, e = Pow(base, tail), -1 elif exp is not S.One: # todo: after dropping python 3.7 support, use overload and Literal # in as_coeff_Mul to make exp Rational, and remove these 2 ignores tail = _keep_coeff(Rational(1, exp.q), tail) # type: ignore base, e = Pow(base, tail), exp.p # type: ignore else: base, e = expr, 1 return base, e def decompose_power_rat(expr: Expr) -> tTuple[Expr, Rational]: """ Decompose power into symbolic base and rational exponent. """ base, exp = expr.as_base_exp() if exp.is_Number: if exp.is_Rational: e: Rational = exp # type: ignore else: base, e = expr, S.One else: exp, tail = exp.as_coeff_Mul(rational=True) if exp is S.NegativeOne: base, e = Pow(base, tail), S.NegativeOne elif exp is not S.One: tail = _keep_coeff(Rational(1, exp.q), tail) # type: ignore base, e = Pow(base, tail), Integer(exp.p) # type: ignore else: base, e = expr, S.One return base, e class Factors: """Efficient representation of ``f_1*f_2*...*f_n``.""" __slots__ = ('factors', 'gens') def __init__(self, factors=None): # Factors """Initialize Factors from dict or expr. Examples ======== >>> from sympy.core.exprtools import Factors >>> from sympy.abc import x >>> from sympy import I >>> e = 2*x**3 >>> Factors(e) Factors({2: 1, x: 3}) >>> Factors(e.as_powers_dict()) Factors({2: 1, x: 3}) >>> f = _ >>> f.factors # underlying dictionary {2: 1, x: 3} >>> f.gens # base of each factor frozenset({2, x}) >>> Factors(0) Factors({0: 1}) >>> Factors(I) Factors({I: 1}) Notes ===== Although a dictionary can be passed, only minimal checking is performed: powers of -1 and I are made canonical. """ if isinstance(factors, (SYMPY_INTS, float)): factors = S(factors) if isinstance(factors, Factors): factors = factors.factors.copy() elif factors in (None, S.One): factors = {} elif factors is S.Zero or factors == 0: factors = {S.Zero: S.One} elif isinstance(factors, Number): n = factors factors = {} if n < 0: factors[S.NegativeOne] = S.One n = -n if n is not S.One: if n.is_Float or n.is_Integer or n is S.Infinity: factors[n] = S.One elif n.is_Rational: # since we're processing Numbers, the denominator is # stored with a negative exponent; all other factors # are left . if n.p != 1: factors[Integer(n.p)] = S.One factors[Integer(n.q)] = S.NegativeOne else: raise ValueError('Expected Float|Rational|Integer, not %s' % n) elif isinstance(factors, Basic) and not factors.args: factors = {factors: S.One} elif isinstance(factors, Expr): c, nc = factors.args_cnc() i = c.count(I) for _ in range(i): c.remove(I) factors = dict(Mul._from_args(c).as_powers_dict()) # Handle all rational Coefficients for f in list(factors.keys()): if isinstance(f, Rational) and not isinstance(f, Integer): p, q = Integer(f.p), Integer(f.q) factors[p] = (factors[p] if p in factors else S.Zero) + factors[f] factors[q] = (factors[q] if q in factors else S.Zero) - factors[f] factors.pop(f) if i: factors[I] = factors.get(I, S.Zero) + i if nc: factors[Mul(*nc, evaluate=False)] = S.One else: factors = factors.copy() # /!\ should be dict-like # tidy up -/+1 and I exponents if Rational handle = [k for k in factors if k is I or k in (-1, 1)] if handle: i1 = S.One for k in handle: if not _isnumber(factors[k]): continue i1 *= k**factors.pop(k) if i1 is not S.One: for a in i1.args if i1.is_Mul else [i1]: # at worst, -1.0*I*(-1)**e if a is S.NegativeOne: factors[a] = S.One elif a is I: factors[I] = S.One elif a.is_Pow: factors[a.base] = factors.get(a.base, S.Zero) + a.exp elif a == 1: factors[a] = S.One elif a == -1: factors[-a] = S.One factors[S.NegativeOne] = S.One else: raise ValueError('unexpected factor in i1: %s' % a) self.factors = factors keys = getattr(factors, 'keys', None) if keys is None: raise TypeError('expecting Expr or dictionary') self.gens = frozenset(keys()) def __hash__(self): # Factors keys = tuple(ordered(self.factors.keys())) values = [self.factors[k] for k in keys] return hash((keys, values)) def __repr__(self): # Factors return "Factors({%s})" % ', '.join( ['%s: %s' % (k, v) for k, v in ordered(self.factors.items())]) @property def is_zero(self): # Factors """ >>> from sympy.core.exprtools import Factors >>> Factors(0).is_zero True """ f = self.factors return len(f) == 1 and S.Zero in f @property def is_one(self): # Factors """ >>> from sympy.core.exprtools import Factors >>> Factors(1).is_one True """ return not self.factors def as_expr(self): # Factors """Return the underlying expression. Examples ======== >>> from sympy.core.exprtools import Factors >>> from sympy.abc import x, y >>> Factors((x*y**2).as_powers_dict()).as_expr() x*y**2 """ args = [] for factor, exp in self.factors.items(): if exp != 1: if isinstance(exp, Integer): b, e = factor.as_base_exp() e = _keep_coeff(exp, e) args.append(b**e) else: args.append(factor**exp) else: args.append(factor) return Mul(*args) def mul(self, other): # Factors """Return Factors of ``self * other``. Examples ======== >>> from sympy.core.exprtools import Factors >>> from sympy.abc import x, y, z >>> a = Factors((x*y**2).as_powers_dict()) >>> b = Factors((x*y/z).as_powers_dict()) >>> a.mul(b) Factors({x: 2, y: 3, z: -1}) >>> a*b Factors({x: 2, y: 3, z: -1}) """ if not isinstance(other, Factors): other = Factors(other) if any(f.is_zero for f in (self, other)): return Factors(S.Zero) factors = dict(self.factors) for factor, exp in other.factors.items(): if factor in factors: exp = factors[factor] + exp if not exp: del factors[factor] continue factors[factor] = exp return Factors(factors) def normal(self, other): """Return ``self`` and ``other`` with ``gcd`` removed from each. The only differences between this and method ``div`` is that this is 1) optimized for the case when there are few factors in common and 2) this does not raise an error if ``other`` is zero. See Also ======== div """ if not isinstance(other, Factors): other = Factors(other) if other.is_zero: return (Factors(), Factors(S.Zero)) if self.is_zero: return (Factors(S.Zero), Factors()) self_factors = dict(self.factors) other_factors = dict(other.factors) for factor, self_exp in self.factors.items(): try: other_exp = other.factors[factor] except KeyError: continue exp = self_exp - other_exp if not exp: del self_factors[factor] del other_factors[factor] elif _isnumber(exp): if exp > 0: self_factors[factor] = exp del other_factors[factor] else: del self_factors[factor] other_factors[factor] = -exp else: r = self_exp.extract_additively(other_exp) if r is not None: if r: self_factors[factor] = r del other_factors[factor] else: # should be handled already del self_factors[factor] del other_factors[factor] else: sc, sa = self_exp.as_coeff_Add() if sc: oc, oa = other_exp.as_coeff_Add() diff = sc - oc if diff > 0: self_factors[factor] -= oc other_exp = oa elif diff < 0: self_factors[factor] -= sc other_factors[factor] -= sc other_exp = oa - diff else: self_factors[factor] = sa other_exp = oa if other_exp: other_factors[factor] = other_exp else: del other_factors[factor] return Factors(self_factors), Factors(other_factors) def div(self, other): # Factors """Return ``self`` and ``other`` with ``gcd`` removed from each. This is optimized for the case when there are many factors in common. Examples ======== >>> from sympy.core.exprtools import Factors >>> from sympy.abc import x, y, z >>> from sympy import S >>> a = Factors((x*y**2).as_powers_dict()) >>> a.div(a) (Factors({}), Factors({})) >>> a.div(x*z) (Factors({y: 2}), Factors({z: 1})) The ``/`` operator only gives ``quo``: >>> a/x Factors({y: 2}) Factors treats its factors as though they are all in the numerator, so if you violate this assumption the results will be correct but will not strictly correspond to the numerator and denominator of the ratio: >>> a.div(x/z) (Factors({y: 2}), Factors({z: -1})) Factors is also naive about bases: it does not attempt any denesting of Rational-base terms, for example the following does not become 2**(2*x)/2. >>> Factors(2**(2*x + 2)).div(S(8)) (Factors({2: 2*x + 2}), Factors({8: 1})) factor_terms can clean up such Rational-bases powers: >>> from sympy import factor_terms >>> n, d = Factors(2**(2*x + 2)).div(S(8)) >>> n.as_expr()/d.as_expr() 2**(2*x + 2)/8 >>> factor_terms(_) 2**(2*x)/2 """ quo, rem = dict(self.factors), {} if not isinstance(other, Factors): other = Factors(other) if other.is_zero: raise ZeroDivisionError if self.is_zero: return (Factors(S.Zero), Factors()) for factor, exp in other.factors.items(): if factor in quo: d = quo[factor] - exp if _isnumber(d): if d <= 0: del quo[factor] if d >= 0: if d: quo[factor] = d continue exp = -d else: r = quo[factor].extract_additively(exp) if r is not None: if r: quo[factor] = r else: # should be handled already del quo[factor] else: other_exp = exp sc, sa = quo[factor].as_coeff_Add() if sc: oc, oa = other_exp.as_coeff_Add() diff = sc - oc if diff > 0: quo[factor] -= oc other_exp = oa elif diff < 0: quo[factor] -= sc other_exp = oa - diff else: quo[factor] = sa other_exp = oa if other_exp: rem[factor] = other_exp else: assert factor not in rem continue rem[factor] = exp return Factors(quo), Factors(rem) def quo(self, other): # Factors """Return numerator Factor of ``self / other``. Examples ======== >>> from sympy.core.exprtools import Factors >>> from sympy.abc import x, y, z >>> a = Factors((x*y**2).as_powers_dict()) >>> b = Factors((x*y/z).as_powers_dict()) >>> a.quo(b) # same as a/b Factors({y: 1}) """ return self.div(other)[0] def rem(self, other): # Factors """Return denominator Factors of ``self / other``. Examples ======== >>> from sympy.core.exprtools import Factors >>> from sympy.abc import x, y, z >>> a = Factors((x*y**2).as_powers_dict()) >>> b = Factors((x*y/z).as_powers_dict()) >>> a.rem(b) Factors({z: -1}) >>> a.rem(a) Factors({}) """ return self.div(other)[1] def pow(self, other): # Factors """Return self raised to a non-negative integer power. Examples ======== >>> from sympy.core.exprtools import Factors >>> from sympy.abc import x, y >>> a = Factors((x*y**2).as_powers_dict()) >>> a**2 Factors({x: 2, y: 4}) """ if isinstance(other, Factors): other = other.as_expr() if other.is_Integer: other = int(other) if isinstance(other, SYMPY_INTS) and other >= 0: factors = {} if other: for factor, exp in self.factors.items(): factors[factor] = exp*other return Factors(factors) else: raise ValueError("expected non-negative integer, got %s" % other) def gcd(self, other): # Factors """Return Factors of ``gcd(self, other)``. The keys are the intersection of factors with the minimum exponent for each factor. Examples ======== >>> from sympy.core.exprtools import Factors >>> from sympy.abc import x, y, z >>> a = Factors((x*y**2).as_powers_dict()) >>> b = Factors((x*y/z).as_powers_dict()) >>> a.gcd(b) Factors({x: 1, y: 1}) """ if not isinstance(other, Factors): other = Factors(other) if other.is_zero: return Factors(self.factors) factors = {} for factor, exp in self.factors.items(): factor, exp = sympify(factor), sympify(exp) if factor in other.factors: lt = (exp - other.factors[factor]).is_negative if lt == True: factors[factor] = exp elif lt == False: factors[factor] = other.factors[factor] return Factors(factors) def lcm(self, other): # Factors """Return Factors of ``lcm(self, other)`` which are the union of factors with the maximum exponent for each factor. Examples ======== >>> from sympy.core.exprtools import Factors >>> from sympy.abc import x, y, z >>> a = Factors((x*y**2).as_powers_dict()) >>> b = Factors((x*y/z).as_powers_dict()) >>> a.lcm(b) Factors({x: 1, y: 2, z: -1}) """ if not isinstance(other, Factors): other = Factors(other) if any(f.is_zero for f in (self, other)): return Factors(S.Zero) factors = dict(self.factors) for factor, exp in other.factors.items(): if factor in factors: exp = max(exp, factors[factor]) factors[factor] = exp return Factors(factors) def __mul__(self, other): # Factors return self.mul(other) def __divmod__(self, other): # Factors return self.div(other) def __truediv__(self, other): # Factors return self.quo(other) def __mod__(self, other): # Factors return self.rem(other) def __pow__(self, other): # Factors return self.pow(other) def __eq__(self, other): # Factors if not isinstance(other, Factors): other = Factors(other) return self.factors == other.factors def __ne__(self, other): # Factors return not self == other class Term: """Efficient representation of ``coeff*(numer/denom)``. """ __slots__ = ('coeff', 'numer', 'denom') def __init__(self, term, numer=None, denom=None): # Term if numer is None and denom is None: if not term.is_commutative: raise NonCommutativeExpression( 'commutative expression expected') coeff, factors = term.as_coeff_mul() numer, denom = defaultdict(int), defaultdict(int) for factor in factors: base, exp = decompose_power(factor) if base.is_Add: cont, base = base.primitive() coeff *= cont**exp if exp > 0: numer[base] += exp else: denom[base] += -exp numer = Factors(numer) denom = Factors(denom) else: coeff = term if numer is None: numer = Factors() if denom is None: denom = Factors() self.coeff = coeff self.numer = numer self.denom = denom def __hash__(self): # Term return hash((self.coeff, self.numer, self.denom)) def __repr__(self): # Term return "Term(%s, %s, %s)" % (self.coeff, self.numer, self.denom) def as_expr(self): # Term return self.coeff*(self.numer.as_expr()/self.denom.as_expr()) def mul(self, other): # Term coeff = self.coeff*other.coeff numer = self.numer.mul(other.numer) denom = self.denom.mul(other.denom) numer, denom = numer.normal(denom) return Term(coeff, numer, denom) def inv(self): # Term return Term(1/self.coeff, self.denom, self.numer) def quo(self, other): # Term return self.mul(other.inv()) def pow(self, other): # Term if other < 0: return self.inv().pow(-other) else: return Term(self.coeff ** other, self.numer.pow(other), self.denom.pow(other)) def gcd(self, other): # Term return Term(self.coeff.gcd(other.coeff), self.numer.gcd(other.numer), self.denom.gcd(other.denom)) def lcm(self, other): # Term return Term(self.coeff.lcm(other.coeff), self.numer.lcm(other.numer), self.denom.lcm(other.denom)) def __mul__(self, other): # Term if isinstance(other, Term): return self.mul(other) else: return NotImplemented def __truediv__(self, other): # Term if isinstance(other, Term): return self.quo(other) else: return NotImplemented def __pow__(self, other): # Term if isinstance(other, SYMPY_INTS): return self.pow(other) else: return NotImplemented def __eq__(self, other): # Term return (self.coeff == other.coeff and self.numer == other.numer and self.denom == other.denom) def __ne__(self, other): # Term return not self == other def _gcd_terms(terms, isprimitive=False, fraction=True): """Helper function for :func:`gcd_terms`. Parameters ========== isprimitive : boolean, optional If ``isprimitive`` is True then the call to primitive for an Add will be skipped. This is useful when the content has already been extrated. fraction : boolean, optional If ``fraction`` is True then the expression will appear over a common denominator, the lcm of all term denominators. """ if isinstance(terms, Basic) and not isinstance(terms, Tuple): terms = Add.make_args(terms) terms = list(map(Term, [t for t in terms if t])) # there is some simplification that may happen if we leave this # here rather than duplicate it before the mapping of Term onto # the terms if len(terms) == 0: return S.Zero, S.Zero, S.One if len(terms) == 1: cont = terms[0].coeff numer = terms[0].numer.as_expr() denom = terms[0].denom.as_expr() else: cont = terms[0] for term in terms[1:]: cont = cont.gcd(term) for i, term in enumerate(terms): terms[i] = term.quo(cont) if fraction: denom = terms[0].denom for term in terms[1:]: denom = denom.lcm(term.denom) numers = [] for term in terms: numer = term.numer.mul(denom.quo(term.denom)) numers.append(term.coeff*numer.as_expr()) else: numers = [t.as_expr() for t in terms] denom = Term(S.One).numer cont = cont.as_expr() numer = Add(*numers) denom = denom.as_expr() if not isprimitive and numer.is_Add: _cont, numer = numer.primitive() cont *= _cont return cont, numer, denom def gcd_terms(terms, isprimitive=False, clear=True, fraction=True): """Compute the GCD of ``terms`` and put them together. Parameters ========== terms : Expr Can be an expression or a non-Basic sequence of expressions which will be handled as though they are terms from a sum. isprimitive : bool, optional If ``isprimitive`` is True the _gcd_terms will not run the primitive method on the terms. clear : bool, optional It controls the removal of integers from the denominator of an Add expression. When True (default), all numerical denominator will be cleared; when False the denominators will be cleared only if all terms had numerical denominators other than 1. fraction : bool, optional When True (default), will put the expression over a common denominator. Examples ======== >>> from sympy import gcd_terms >>> from sympy.abc import x, y >>> gcd_terms((x + 1)**2*y + (x + 1)*y**2) y*(x + 1)*(x + y + 1) >>> gcd_terms(x/2 + 1) (x + 2)/2 >>> gcd_terms(x/2 + 1, clear=False) x/2 + 1 >>> gcd_terms(x/2 + y/2, clear=False) (x + y)/2 >>> gcd_terms(x/2 + 1/x) (x**2 + 2)/(2*x) >>> gcd_terms(x/2 + 1/x, fraction=False) (x + 2/x)/2 >>> gcd_terms(x/2 + 1/x, fraction=False, clear=False) x/2 + 1/x >>> gcd_terms(x/2/y + 1/x/y) (x**2 + 2)/(2*x*y) >>> gcd_terms(x/2/y + 1/x/y, clear=False) (x**2/2 + 1)/(x*y) >>> gcd_terms(x/2/y + 1/x/y, clear=False, fraction=False) (x/2 + 1/x)/y The ``clear`` flag was ignored in this case because the returned expression was a rational expression, not a simple sum. See Also ======== factor_terms, sympy.polys.polytools.terms_gcd """ def mask(terms): """replace nc portions of each term with a unique Dummy symbols and return the replacements to restore them""" args = [(a, []) if a.is_commutative else a.args_cnc() for a in terms] reps = [] for i, (c, nc) in enumerate(args): if nc: nc = Mul(*nc) d = Dummy() reps.append((d, nc)) c.append(d) args[i] = Mul(*c) else: args[i] = c return args, dict(reps) isadd = isinstance(terms, Add) addlike = isadd or not isinstance(terms, Basic) and \ is_sequence(terms, include=set) and \ not isinstance(terms, Dict) if addlike: if isadd: # i.e. an Add terms = list(terms.args) else: terms = sympify(terms) terms, reps = mask(terms) cont, numer, denom = _gcd_terms(terms, isprimitive, fraction) numer = numer.xreplace(reps) coeff, factors = cont.as_coeff_Mul() if not clear: c, _coeff = coeff.as_coeff_Mul() if not c.is_Integer and not clear and numer.is_Add: n, d = c.as_numer_denom() _numer = numer/d if any(a.as_coeff_Mul()[0].is_Integer for a in _numer.args): numer = _numer coeff = n*_coeff return _keep_coeff(coeff, factors*numer/denom, clear=clear) if not isinstance(terms, Basic): return terms if terms.is_Atom: return terms if terms.is_Mul: c, args = terms.as_coeff_mul() return _keep_coeff(c, Mul(*[gcd_terms(i, isprimitive, clear, fraction) for i in args]), clear=clear) def handle(a): # don't treat internal args like terms of an Add if not isinstance(a, Expr): if isinstance(a, Basic): if not a.args: return a return a.func(*[handle(i) for i in a.args]) return type(a)([handle(i) for i in a]) return gcd_terms(a, isprimitive, clear, fraction) if isinstance(terms, Dict): return Dict(*[(k, handle(v)) for k, v in terms.args]) return terms.func(*[handle(i) for i in terms.args]) def _factor_sum_int(expr, **kwargs): """Return Sum or Integral object with factors that are not in the wrt variables removed. In cases where there are additive terms in the function of the object that are independent, the object will be separated into two objects. Examples ======== >>> from sympy import Sum, factor_terms >>> from sympy.abc import x, y >>> factor_terms(Sum(x + y, (x, 1, 3))) y*Sum(1, (x, 1, 3)) + Sum(x, (x, 1, 3)) >>> factor_terms(Sum(x*y, (x, 1, 3))) y*Sum(x, (x, 1, 3)) Notes ===== If a function in the summand or integrand is replaced with a symbol, then this simplification should not be done or else an incorrect result will be obtained when the symbol is replaced with an expression that depends on the variables of summation/integration: >>> eq = Sum(y, (x, 1, 3)) >>> factor_terms(eq).subs(y, x).doit() 3*x >>> eq.subs(y, x).doit() 6 """ result = expr.function if result == 0: return S.Zero limits = expr.limits # get the wrt variables wrt = {i.args[0] for i in limits} # factor out any common terms that are independent of wrt f = factor_terms(result, **kwargs) i, d = f.as_independent(*wrt) if isinstance(f, Add): return i * expr.func(1, *limits) + expr.func(d, *limits) else: return i * expr.func(d, *limits) def factor_terms(expr, radical=False, clear=False, fraction=False, sign=True): """Remove common factors from terms in all arguments without changing the underlying structure of the expr. No expansion or simplification (and no processing of non-commutatives) is performed. Parameters ========== radical: bool, optional If radical=True then a radical common to all terms will be factored out of any Add sub-expressions of the expr. clear : bool, optional If clear=False (default) then coefficients will not be separated from a single Add if they can be distributed to leave one or more terms with integer coefficients. fraction : bool, optional If fraction=True (default is False) then a common denominator will be constructed for the expression. sign : bool, optional If sign=True (default) then even if the only factor in common is a -1, it will be factored out of the expression. Examples ======== >>> from sympy import factor_terms, Symbol >>> from sympy.abc import x, y >>> factor_terms(x + x*(2 + 4*y)**3) x*(8*(2*y + 1)**3 + 1) >>> A = Symbol('A', commutative=False) >>> factor_terms(x*A + x*A + x*y*A) x*(y*A + 2*A) When ``clear`` is False, a rational will only be factored out of an Add expression if all terms of the Add have coefficients that are fractions: >>> factor_terms(x/2 + 1, clear=False) x/2 + 1 >>> factor_terms(x/2 + 1, clear=True) (x + 2)/2 If a -1 is all that can be factored out, to *not* factor it out, the flag ``sign`` must be False: >>> factor_terms(-x - y) -(x + y) >>> factor_terms(-x - y, sign=False) -x - y >>> factor_terms(-2*x - 2*y, sign=False) -2*(x + y) See Also ======== gcd_terms, sympy.polys.polytools.terms_gcd """ def do(expr): from sympy.concrete.summations import Sum from sympy.integrals.integrals import Integral is_iterable = iterable(expr) if not isinstance(expr, Basic) or expr.is_Atom: if is_iterable: return type(expr)([do(i) for i in expr]) return expr if expr.is_Pow or expr.is_Function or \ is_iterable or not hasattr(expr, 'args_cnc'): args = expr.args newargs = tuple([do(i) for i in args]) if newargs == args: return expr return expr.func(*newargs) if isinstance(expr, (Sum, Integral)): return _factor_sum_int(expr, radical=radical, clear=clear, fraction=fraction, sign=sign) cont, p = expr.as_content_primitive(radical=radical, clear=clear) if p.is_Add: list_args = [do(a) for a in Add.make_args(p)] # get a common negative (if there) which gcd_terms does not remove if not any(a.as_coeff_Mul()[0].extract_multiplicatively(-1) is None for a in list_args): cont = -cont list_args = [-a for a in list_args] # watch out for exp(-(x+2)) which gcd_terms will change to exp(-x-2) special = {} for i, a in enumerate(list_args): b, e = a.as_base_exp() if e.is_Mul and e != Mul(*e.args): list_args[i] = Dummy() special[list_args[i]] = a # rebuild p not worrying about the order which gcd_terms will fix p = Add._from_args(list_args) p = gcd_terms(p, isprimitive=True, clear=clear, fraction=fraction).xreplace(special) elif p.args: p = p.func( *[do(a) for a in p.args]) rv = _keep_coeff(cont, p, clear=clear, sign=sign) return rv expr = sympify(expr) return do(expr) def _mask_nc(eq, name=None): """ Return ``eq`` with non-commutative objects replaced with Dummy symbols. A dictionary that can be used to restore the original values is returned: if it is None, the expression is noncommutative and cannot be made commutative. The third value returned is a list of any non-commutative symbols that appear in the returned equation. Explanation =========== All non-commutative objects other than Symbols are replaced with a non-commutative Symbol. Identical objects will be identified by identical symbols. If there is only 1 non-commutative object in an expression it will be replaced with a commutative symbol. Otherwise, the non-commutative entities are retained and the calling routine should handle replacements in this case since some care must be taken to keep track of the ordering of symbols when they occur within Muls. Parameters ========== name : str ``name``, if given, is the name that will be used with numbered Dummy variables that will replace the non-commutative objects and is mainly used for doctesting purposes. Examples ======== >>> from sympy.physics.secondquant import Commutator, NO, F, Fd >>> from sympy import symbols >>> from sympy.core.exprtools import _mask_nc >>> from sympy.abc import x, y >>> A, B, C = symbols('A,B,C', commutative=False) One nc-symbol: >>> _mask_nc(A**2 - x**2, 'd') (_d0**2 - x**2, {_d0: A}, []) Multiple nc-symbols: >>> _mask_nc(A**2 - B**2, 'd') (A**2 - B**2, {}, [A, B]) An nc-object with nc-symbols but no others outside of it: >>> _mask_nc(1 + x*Commutator(A, B), 'd') (_d0*x + 1, {_d0: Commutator(A, B)}, []) >>> _mask_nc(NO(Fd(x)*F(y)), 'd') (_d0, {_d0: NO(CreateFermion(x)*AnnihilateFermion(y))}, []) Multiple nc-objects: >>> eq = x*Commutator(A, B) + x*Commutator(A, C)*Commutator(A, B) >>> _mask_nc(eq, 'd') (x*_d0 + x*_d1*_d0, {_d0: Commutator(A, B), _d1: Commutator(A, C)}, [_d0, _d1]) Multiple nc-objects and nc-symbols: >>> eq = A*Commutator(A, B) + B*Commutator(A, C) >>> _mask_nc(eq, 'd') (A*_d0 + B*_d1, {_d0: Commutator(A, B), _d1: Commutator(A, C)}, [_d0, _d1, A, B]) """ name = name or 'mask' # Make Dummy() append sequential numbers to the name def numbered_names(): i = 0 while True: yield name + str(i) i += 1 names = numbered_names() def Dummy(*args, **kwargs): from .symbol import Dummy return Dummy(next(names), *args, **kwargs) expr = eq if expr.is_commutative: return eq, {}, [] # identify nc-objects; symbols and other rep = [] nc_obj = set() nc_syms = set() pot = preorder_traversal(expr, keys=default_sort_key) for i, a in enumerate(pot): if any(a == r[0] for r in rep): pot.skip() elif not a.is_commutative: if a.is_symbol: nc_syms.add(a) pot.skip() elif not (a.is_Add or a.is_Mul or a.is_Pow): nc_obj.add(a) pot.skip() # If there is only one nc symbol or object, it can be factored regularly # but polys is going to complain, so replace it with a Dummy. if len(nc_obj) == 1 and not nc_syms: rep.append((nc_obj.pop(), Dummy())) elif len(nc_syms) == 1 and not nc_obj: rep.append((nc_syms.pop(), Dummy())) # Any remaining nc-objects will be replaced with an nc-Dummy and # identified as an nc-Symbol to watch out for nc_obj = sorted(nc_obj, key=default_sort_key) for n in nc_obj: nc = Dummy(commutative=False) rep.append((n, nc)) nc_syms.add(nc) expr = expr.subs(rep) nc_syms = list(nc_syms) nc_syms.sort(key=default_sort_key) return expr, {v: k for k, v in rep}, nc_syms def factor_nc(expr): """Return the factored form of ``expr`` while handling non-commutative expressions. Examples ======== >>> from sympy import factor_nc, Symbol >>> from sympy.abc import x >>> A = Symbol('A', commutative=False) >>> B = Symbol('B', commutative=False) >>> factor_nc((x**2 + 2*A*x + A**2).expand()) (x + A)**2 >>> factor_nc(((x + A)*(x + B)).expand()) (x + A)*(x + B) """ expr = sympify(expr) if not isinstance(expr, Expr) or not expr.args: return expr if not expr.is_Add: return expr.func(*[factor_nc(a) for a in expr.args]) from sympy.polys.polytools import gcd, factor expr, rep, nc_symbols = _mask_nc(expr) if rep: return factor(expr).subs(rep) else: args = [a.args_cnc() for a in Add.make_args(expr)] c = g = l = r = S.One hit = False # find any commutative gcd term for i, a in enumerate(args): if i == 0: c = Mul._from_args(a[0]) elif a[0]: c = gcd(c, Mul._from_args(a[0])) else: c = S.One if c is not S.One: hit = True c, g = c.as_coeff_Mul() if g is not S.One: for i, (cc, _) in enumerate(args): cc = list(Mul.make_args(Mul._from_args(list(cc))/g)) args[i][0] = cc for i, (cc, _) in enumerate(args): if cc: cc[0] = cc[0]/c else: cc = [1/c] args[i][0] = cc # find any noncommutative common prefix for i, a in enumerate(args): if i == 0: n = a[1][:] else: n = common_prefix(n, a[1]) if not n: # is there a power that can be extracted? if not args[0][1]: break b, e = args[0][1][0].as_base_exp() ok = False if e.is_Integer: for t in args: if not t[1]: break bt, et = t[1][0].as_base_exp() if et.is_Integer and bt == b: e = min(e, et) else: break else: ok = hit = True l = b**e il = b**-e for _ in args: _[1][0] = il*_[1][0] break if not ok: break else: hit = True lenn = len(n) l = Mul(*n) for _ in args: _[1] = _[1][lenn:] # find any noncommutative common suffix for i, a in enumerate(args): if i == 0: n = a[1][:] else: n = common_suffix(n, a[1]) if not n: # is there a power that can be extracted? if not args[0][1]: break b, e = args[0][1][-1].as_base_exp() ok = False if e.is_Integer: for t in args: if not t[1]: break bt, et = t[1][-1].as_base_exp() if et.is_Integer and bt == b: e = min(e, et) else: break else: ok = hit = True r = b**e il = b**-e for _ in args: _[1][-1] = _[1][-1]*il break if not ok: break else: hit = True lenn = len(n) r = Mul(*n) for _ in args: _[1] = _[1][:len(_[1]) - lenn] if hit: mid = Add(*[Mul(*cc)*Mul(*nc) for cc, nc in args]) else: mid = expr from sympy.simplify.powsimp import powsimp # sort the symbols so the Dummys would appear in the same # order as the original symbols, otherwise you may introduce # a factor of -1, e.g. A**2 - B**2) -- {A:y, B:x} --> y**2 - x**2 # and the former factors into two terms, (A - B)*(A + B) while the # latter factors into 3 terms, (-1)*(x - y)*(x + y) rep1 = [(n, Dummy()) for n in sorted(nc_symbols, key=default_sort_key)] unrep1 = [(v, k) for k, v in rep1] unrep1.reverse() new_mid, r2, _ = _mask_nc(mid.subs(rep1)) new_mid = powsimp(factor(new_mid)) new_mid = new_mid.subs(r2).subs(unrep1) if new_mid.is_Pow: return _keep_coeff(c, g*l*new_mid*r) if new_mid.is_Mul: def _pemexpand(expr): "Expand with the minimal set of hints necessary to check the result." return expr.expand(deep=True, mul=True, power_exp=True, power_base=False, basic=False, multinomial=True, log=False) # XXX TODO there should be a way to inspect what order the terms # must be in and just select the plausible ordering without # checking permutations cfac = [] ncfac = [] for f in new_mid.args: if f.is_commutative: cfac.append(f) else: b, e = f.as_base_exp() if e.is_Integer: ncfac.extend([b]*e) else: ncfac.append(f) pre_mid = g*Mul(*cfac)*l target = _pemexpand(expr/c) for s in variations(ncfac, len(ncfac)): ok = pre_mid*Mul(*s)*r if _pemexpand(ok) == target: return _keep_coeff(c, ok) # mid was an Add that didn't factor successfully return _keep_coeff(c, g*l*mid*r)
16dbeeb638073ed49a33b2fb53ea0b8d68390141d7314902d638e9e52612f48b
from collections import defaultdict from .sympify import sympify, SympifyError from sympy.utilities.iterables import iterable, uniq __all__ = ['default_sort_key', 'ordered'] def default_sort_key(item, order=None): """Return a key that can be used for sorting. The key has the structure: (class_key, (len(args), args), exponent.sort_key(), coefficient) This key is supplied by the sort_key routine of Basic objects when ``item`` is a Basic object or an object (other than a string) that sympifies to a Basic object. Otherwise, this function produces the key. The ``order`` argument is passed along to the sort_key routine and is used to determine how the terms *within* an expression are ordered. (See examples below) ``order`` options are: 'lex', 'grlex', 'grevlex', and reversed values of the same (e.g. 'rev-lex'). The default order value is None (which translates to 'lex'). Examples ======== >>> from sympy import S, I, default_sort_key, sin, cos, sqrt >>> from sympy.core.function import UndefinedFunction >>> from sympy.abc import x The following are equivalent ways of getting the key for an object: >>> x.sort_key() == default_sort_key(x) True Here are some examples of the key that is produced: >>> default_sort_key(UndefinedFunction('f')) ((0, 0, 'UndefinedFunction'), (1, ('f',)), ((1, 0, 'Number'), (0, ()), (), 1), 1) >>> default_sort_key('1') ((0, 0, 'str'), (1, ('1',)), ((1, 0, 'Number'), (0, ()), (), 1), 1) >>> default_sort_key(S.One) ((1, 0, 'Number'), (0, ()), (), 1) >>> default_sort_key(2) ((1, 0, 'Number'), (0, ()), (), 2) While sort_key is a method only defined for SymPy objects, default_sort_key will accept anything as an argument so it is more robust as a sorting key. For the following, using key= lambda i: i.sort_key() would fail because 2 does not have a sort_key method; that's why default_sort_key is used. Note, that it also handles sympification of non-string items likes ints: >>> a = [2, I, -I] >>> sorted(a, key=default_sort_key) [2, -I, I] The returned key can be used anywhere that a key can be specified for a function, e.g. sort, min, max, etc...: >>> a.sort(key=default_sort_key); a[0] 2 >>> min(a, key=default_sort_key) 2 Note ---- The key returned is useful for getting items into a canonical order that will be the same across platforms. It is not directly useful for sorting lists of expressions: >>> a, b = x, 1/x Since ``a`` has only 1 term, its value of sort_key is unaffected by ``order``: >>> a.sort_key() == a.sort_key('rev-lex') True If ``a`` and ``b`` are combined then the key will differ because there are terms that can be ordered: >>> eq = a + b >>> eq.sort_key() == eq.sort_key('rev-lex') False >>> eq.as_ordered_terms() [x, 1/x] >>> eq.as_ordered_terms('rev-lex') [1/x, x] But since the keys for each of these terms are independent of ``order``'s value, they do not sort differently when they appear separately in a list: >>> sorted(eq.args, key=default_sort_key) [1/x, x] >>> sorted(eq.args, key=lambda i: default_sort_key(i, order='rev-lex')) [1/x, x] The order of terms obtained when using these keys is the order that would be obtained if those terms were *factors* in a product. Although it is useful for quickly putting expressions in canonical order, it does not sort expressions based on their complexity defined by the number of operations, power of variables and others: >>> sorted([sin(x)*cos(x), sin(x)], key=default_sort_key) [sin(x)*cos(x), sin(x)] >>> sorted([x, x**2, sqrt(x), x**3], key=default_sort_key) [sqrt(x), x, x**2, x**3] See Also ======== ordered, sympy.core.expr.Expr.as_ordered_factors, sympy.core.expr.Expr.as_ordered_terms """ from .basic import Basic from .singleton import S if isinstance(item, Basic): return item.sort_key(order=order) if iterable(item, exclude=str): if isinstance(item, dict): args = item.items() unordered = True elif isinstance(item, set): args = item unordered = True else: # e.g. tuple, list args = list(item) unordered = False args = [default_sort_key(arg, order=order) for arg in args] if unordered: # e.g. dict, set args = sorted(args) cls_index, args = 10, (len(args), tuple(args)) else: if not isinstance(item, str): try: item = sympify(item, strict=True) except SympifyError: # e.g. lambda x: x pass else: if isinstance(item, Basic): # e.g int -> Integer return default_sort_key(item) # e.g. UndefinedFunction # e.g. str cls_index, args = 0, (1, (str(item),)) return (cls_index, 0, item.__class__.__name__ ), args, S.One.sort_key(), S.One def _node_count(e): # this not only counts nodes, it affirms that the # args are Basic (i.e. have an args property). If # some object has a non-Basic arg, it needs to be # fixed since it is intended that all Basic args # are of Basic type (though this is not easy to enforce). if e.is_Float: return 0.5 return 1 + sum(map(_node_count, e.args)) def _nodes(e): """ A helper for ordered() which returns the node count of ``e`` which for Basic objects is the number of Basic nodes in the expression tree but for other objects is 1 (unless the object is an iterable or dict for which the sum of nodes is returned). """ from .basic import Basic from .function import Derivative if isinstance(e, Basic): if isinstance(e, Derivative): return _nodes(e.expr) + sum(i[1] if i[1].is_Number else _nodes(i[1]) for i in e.variable_count) return _node_count(e) elif iterable(e): return 1 + sum(_nodes(ei) for ei in e) elif isinstance(e, dict): return 1 + sum(_nodes(k) + _nodes(v) for k, v in e.items()) else: return 1 def ordered(seq, keys=None, default=True, warn=False): """Return an iterator of the seq where keys are used to break ties in a conservative fashion: if, after applying a key, there are no ties then no other keys will be computed. Two default keys will be applied if 1) keys are not provided or 2) the given keys do not resolve all ties (but only if ``default`` is True). The two keys are ``_nodes`` (which places smaller expressions before large) and ``default_sort_key`` which (if the ``sort_key`` for an object is defined properly) should resolve any ties. If ``warn`` is True then an error will be raised if there were no keys remaining to break ties. This can be used if it was expected that there should be no ties between items that are not identical. Examples ======== >>> from sympy import ordered, count_ops >>> from sympy.abc import x, y The count_ops is not sufficient to break ties in this list and the first two items appear in their original order (i.e. the sorting is stable): >>> list(ordered([y + 2, x + 2, x**2 + y + 3], ... count_ops, default=False, warn=False)) ... [y + 2, x + 2, x**2 + y + 3] The default_sort_key allows the tie to be broken: >>> list(ordered([y + 2, x + 2, x**2 + y + 3])) ... [x + 2, y + 2, x**2 + y + 3] Here, sequences are sorted by length, then sum: >>> seq, keys = [[[1, 2, 1], [0, 3, 1], [1, 1, 3], [2], [1]], [ ... lambda x: len(x), ... lambda x: sum(x)]] ... >>> list(ordered(seq, keys, default=False, warn=False)) [[1], [2], [1, 2, 1], [0, 3, 1], [1, 1, 3]] If ``warn`` is True, an error will be raised if there were not enough keys to break ties: >>> list(ordered(seq, keys, default=False, warn=True)) Traceback (most recent call last): ... ValueError: not enough keys to break ties Notes ===== The decorated sort is one of the fastest ways to sort a sequence for which special item comparison is desired: the sequence is decorated, sorted on the basis of the decoration (e.g. making all letters lower case) and then undecorated. If one wants to break ties for items that have the same decorated value, a second key can be used. But if the second key is expensive to compute then it is inefficient to decorate all items with both keys: only those items having identical first key values need to be decorated. This function applies keys successively only when needed to break ties. By yielding an iterator, use of the tie-breaker is delayed as long as possible. This function is best used in cases when use of the first key is expected to be a good hashing function; if there are no unique hashes from application of a key, then that key should not have been used. The exception, however, is that even if there are many collisions, if the first group is small and one does not need to process all items in the list then time will not be wasted sorting what one was not interested in. For example, if one were looking for the minimum in a list and there were several criteria used to define the sort order, then this function would be good at returning that quickly if the first group of candidates is small relative to the number of items being processed. """ d = defaultdict(list) if keys: if isinstance(keys, (list, tuple)): keys = list(keys) f = keys.pop(0) else: f = keys keys = [] for a in seq: d[f(a)].append(a) else: if not default: raise ValueError('if default=False then keys must be provided') d[None].extend(seq) for k, value in sorted(d.items()): if len(value) > 1: if keys: value = ordered(value, keys, default, warn) elif default: value = ordered(value, (_nodes, default_sort_key,), default=False, warn=warn) elif warn: u = list(uniq(value)) if len(u) > 1: raise ValueError( 'not enough keys to break ties: %s' % u) yield from value
da96cfc463ad314db4a124b7061fd5d70df8cbf00bfc538f96a4048647a06354
""" This module contains the machinery handling assumptions. Do also consider the guide :ref:`assumptions-guide`. All symbolic objects have assumption attributes that can be accessed via ``.is_<assumption name>`` attribute. Assumptions determine certain properties of symbolic objects and can have 3 possible values: ``True``, ``False``, ``None``. ``True`` is returned if the object has the property and ``False`` is returned if it does not or cannot (i.e. does not make sense): >>> from sympy import I >>> I.is_algebraic True >>> I.is_real False >>> I.is_prime False When the property cannot be determined (or when a method is not implemented) ``None`` will be returned. For example, a generic symbol, ``x``, may or may not be positive so a value of ``None`` is returned for ``x.is_positive``. By default, all symbolic values are in the largest set in the given context without specifying the property. For example, a symbol that has a property being integer, is also real, complex, etc. Here follows a list of possible assumption names: .. glossary:: commutative object commutes with any other object with respect to multiplication operation. See [12]_. complex object can have only values from the set of complex numbers. See [13]_. imaginary object value is a number that can be written as a real number multiplied by the imaginary unit ``I``. See [3]_. Please note that ``0`` is not considered to be an imaginary number, see `issue #7649 <https://github.com/sympy/sympy/issues/7649>`_. real object can have only values from the set of real numbers. extended_real object can have only values from the set of real numbers, ``oo`` and ``-oo``. integer object can have only values from the set of integers. odd even object can have only values from the set of odd (even) integers [2]_. prime object is a natural number greater than 1 that has no positive divisors other than 1 and itself. See [6]_. composite object is a positive integer that has at least one positive divisor other than 1 or the number itself. See [4]_. zero object has the value of 0. nonzero object is a real number that is not zero. rational object can have only values from the set of rationals. algebraic object can have only values from the set of algebraic numbers [11]_. transcendental object can have only values from the set of transcendental numbers [10]_. irrational object value cannot be represented exactly by :class:`~.Rational`, see [5]_. finite infinite object absolute value is bounded (arbitrarily large). See [7]_, [8]_, [9]_. negative nonnegative object can have only negative (nonnegative) values [1]_. positive nonpositive object can have only positive (nonpositive) values. extended_negative extended_nonnegative extended_positive extended_nonpositive extended_nonzero as without the extended part, but also including infinity with corresponding sign, e.g., extended_positive includes ``oo`` hermitian antihermitian object belongs to the field of Hermitian (antihermitian) operators. Examples ======== >>> from sympy import Symbol >>> x = Symbol('x', real=True); x x >>> x.is_real True >>> x.is_complex True See Also ======== .. seealso:: :py:class:`sympy.core.numbers.ImaginaryUnit` :py:class:`sympy.core.numbers.Zero` :py:class:`sympy.core.numbers.One` :py:class:`sympy.core.numbers.Infinity` :py:class:`sympy.core.numbers.NegativeInfinity` :py:class:`sympy.core.numbers.ComplexInfinity` Notes ===== The fully-resolved assumptions for any SymPy expression can be obtained as follows: >>> from sympy.core.assumptions import assumptions >>> x = Symbol('x',positive=True) >>> assumptions(x + I) {'commutative': True, 'complex': True, 'composite': False, 'even': False, 'extended_negative': False, 'extended_nonnegative': False, 'extended_nonpositive': False, 'extended_nonzero': False, 'extended_positive': False, 'extended_real': False, 'finite': True, 'imaginary': False, 'infinite': False, 'integer': False, 'irrational': False, 'negative': False, 'noninteger': False, 'nonnegative': False, 'nonpositive': False, 'nonzero': False, 'odd': False, 'positive': False, 'prime': False, 'rational': False, 'real': False, 'zero': False} Developers Notes ================ The current (and possibly incomplete) values are stored in the ``obj._assumptions dictionary``; queries to getter methods (with property decorators) or attributes of objects/classes will return values and update the dictionary. >>> eq = x**2 + I >>> eq._assumptions {} >>> eq.is_finite True >>> eq._assumptions {'finite': True, 'infinite': False} For a :class:`~.Symbol`, there are two locations for assumptions that may be of interest. The ``assumptions0`` attribute gives the full set of assumptions derived from a given set of initial assumptions. The latter assumptions are stored as ``Symbol._assumptions.generator`` >>> Symbol('x', prime=True, even=True)._assumptions.generator {'even': True, 'prime': True} The ``generator`` is not necessarily canonical nor is it filtered in any way: it records the assumptions used to instantiate a Symbol and (for storage purposes) represents a more compact representation of the assumptions needed to recreate the full set in ``Symbol.assumptions0``. References ========== .. [1] https://en.wikipedia.org/wiki/Negative_number .. [2] https://en.wikipedia.org/wiki/Parity_%28mathematics%29 .. [3] https://en.wikipedia.org/wiki/Imaginary_number .. [4] https://en.wikipedia.org/wiki/Composite_number .. [5] https://en.wikipedia.org/wiki/Irrational_number .. [6] https://en.wikipedia.org/wiki/Prime_number .. [7] https://en.wikipedia.org/wiki/Finite .. [8] https://docs.python.org/3/library/math.html#math.isfinite .. [9] http://docs.scipy.org/doc/numpy/reference/generated/numpy.isfinite.html .. [10] https://en.wikipedia.org/wiki/Transcendental_number .. [11] https://en.wikipedia.org/wiki/Algebraic_number .. [12] https://en.wikipedia.org/wiki/Commutative_property .. [13] https://en.wikipedia.org/wiki/Complex_number """ from .facts import FactRules, FactKB from .core import BasicMeta from .sympify import sympify from sympy.core.random import shuffle _assume_rules = FactRules([ 'integer -> rational', 'rational -> real', 'rational -> algebraic', 'algebraic -> complex', 'transcendental == complex & !algebraic', 'real -> hermitian', 'imaginary -> complex', 'imaginary -> antihermitian', 'extended_real -> commutative', 'complex -> commutative', 'complex -> finite', 'odd == integer & !even', 'even == integer & !odd', 'real -> complex', 'extended_real -> real | infinite', 'real == extended_real & finite', 'extended_real == extended_negative | zero | extended_positive', 'extended_negative == extended_nonpositive & extended_nonzero', 'extended_positive == extended_nonnegative & extended_nonzero', 'extended_nonpositive == extended_real & !extended_positive', 'extended_nonnegative == extended_real & !extended_negative', 'real == negative | zero | positive', 'negative == nonpositive & nonzero', 'positive == nonnegative & nonzero', 'nonpositive == real & !positive', 'nonnegative == real & !negative', 'positive == extended_positive & finite', 'negative == extended_negative & finite', 'nonpositive == extended_nonpositive & finite', 'nonnegative == extended_nonnegative & finite', 'nonzero == extended_nonzero & finite', 'zero -> even & finite', 'zero == extended_nonnegative & extended_nonpositive', 'zero == nonnegative & nonpositive', 'nonzero -> real', 'prime -> integer & positive', 'composite -> integer & positive & !prime', '!composite -> !positive | !even | prime', 'irrational == real & !rational', 'imaginary -> !extended_real', 'infinite == !finite', 'noninteger == extended_real & !integer', 'extended_nonzero == extended_real & !zero', ]) _assume_defined = _assume_rules.defined_facts.copy() _assume_defined.add('polar') _assume_defined = frozenset(_assume_defined) def assumptions(expr, _check=None): """return the T/F assumptions of ``expr``""" n = sympify(expr) if n.is_Symbol: rv = n.assumptions0 # are any important ones missing? if _check is not None: rv = {k: rv[k] for k in set(rv) & set(_check)} return rv rv = {} for k in _assume_defined if _check is None else _check: v = getattr(n, 'is_{}'.format(k)) if v is not None: rv[k] = v return rv def common_assumptions(exprs, check=None): """return those assumptions which have the same True or False value for all the given expressions. Examples ======== >>> from sympy.core import common_assumptions >>> from sympy import oo, pi, sqrt >>> common_assumptions([-4, 0, sqrt(2), 2, pi, oo]) {'commutative': True, 'composite': False, 'extended_real': True, 'imaginary': False, 'odd': False} By default, all assumptions are tested; pass an iterable of the assumptions to limit those that are reported: >>> common_assumptions([0, 1, 2], ['positive', 'integer']) {'integer': True} """ check = _assume_defined if check is None else set(check) if not check or not exprs: return {} # get all assumptions for each assume = [assumptions(i, _check=check) for i in sympify(exprs)] # focus on those of interest that are True for i, e in enumerate(assume): assume[i] = {k: e[k] for k in set(e) & check} # what assumptions are in common? common = set.intersection(*[set(i) for i in assume]) # which ones hold the same value a = assume[0] return {k: a[k] for k in common if all(a[k] == b[k] for b in assume)} def failing_assumptions(expr, **assumptions): """ Return a dictionary containing assumptions with values not matching those of the passed assumptions. Examples ======== >>> from sympy import failing_assumptions, Symbol >>> x = Symbol('x', positive=True) >>> y = Symbol('y') >>> failing_assumptions(6*x + y, positive=True) {'positive': None} >>> failing_assumptions(x**2 - 1, positive=True) {'positive': None} If *expr* satisfies all of the assumptions, an empty dictionary is returned. >>> failing_assumptions(x**2, positive=True) {} """ expr = sympify(expr) failed = {} for k in assumptions: test = getattr(expr, 'is_%s' % k, None) if test is not assumptions[k]: failed[k] = test return failed # {} or {assumption: value != desired} def check_assumptions(expr, against=None, **assume): """ Checks whether assumptions of ``expr`` match the T/F assumptions given (or possessed by ``against``). True is returned if all assumptions match; False is returned if there is a mismatch and the assumption in ``expr`` is not None; else None is returned. Explanation =========== *assume* is a dict of assumptions with True or False values Examples ======== >>> from sympy import Symbol, pi, I, exp, check_assumptions >>> check_assumptions(-5, integer=True) True >>> check_assumptions(pi, real=True, integer=False) True >>> check_assumptions(pi, negative=True) False >>> check_assumptions(exp(I*pi/7), real=False) True >>> x = Symbol('x', positive=True) >>> check_assumptions(2*x + 1, positive=True) True >>> check_assumptions(-2*x - 5, positive=True) False To check assumptions of *expr* against another variable or expression, pass the expression or variable as ``against``. >>> check_assumptions(2*x + 1, x) True To see if a number matches the assumptions of an expression, pass the number as the first argument, else its specific assumptions may not have a non-None value in the expression: >>> check_assumptions(x, 3) >>> check_assumptions(3, x) True ``None`` is returned if ``check_assumptions()`` could not conclude. >>> check_assumptions(2*x - 1, x) >>> z = Symbol('z') >>> check_assumptions(z, real=True) See Also ======== failing_assumptions """ expr = sympify(expr) if against is not None: if assume: raise ValueError( 'Expecting `against` or `assume`, not both.') assume = assumptions(against) known = True for k, v in assume.items(): if v is None: continue e = getattr(expr, 'is_' + k, None) if e is None: known = None elif v != e: return False return known class StdFactKB(FactKB): """A FactKB specialized for the built-in rules This is the only kind of FactKB that Basic objects should use. """ def __init__(self, facts=None): super().__init__(_assume_rules) # save a copy of the facts dict if not facts: self._generator = {} elif not isinstance(facts, FactKB): self._generator = facts.copy() else: self._generator = facts.generator if facts: self.deduce_all_facts(facts) def copy(self): return self.__class__(self) @property def generator(self): return self._generator.copy() def as_property(fact): """Convert a fact name to the name of the corresponding property""" return 'is_%s' % fact def make_property(fact): """Create the automagic property corresponding to a fact.""" def getit(self): try: return self._assumptions[fact] except KeyError: if self._assumptions is self.default_assumptions: self._assumptions = self.default_assumptions.copy() return _ask(fact, self) getit.func_name = as_property(fact) return property(getit) def _ask(fact, obj): """ Find the truth value for a property of an object. This function is called when a request is made to see what a fact value is. For this we use several techniques: First, the fact-evaluation function is tried, if it exists (for example _eval_is_integer). Then we try related facts. For example rational --> integer another example is joined rule: integer & !odd --> even so in the latter case if we are looking at what 'even' value is, 'integer' and 'odd' facts will be asked. In all cases, when we settle on some fact value, its implications are deduced, and the result is cached in ._assumptions. """ # FactKB which is dict-like and maps facts to their known values: assumptions = obj._assumptions # A dict that maps facts to their handlers: handler_map = obj._prop_handler # This is our queue of facts to check: facts_to_check = [fact] facts_queued = {fact} # Loop over the queue as it extends for fact_i in facts_to_check: # If fact_i has already been determined then we don't need to rerun the # handler. There is a potential race condition for multithreaded code # though because it's possible that fact_i was checked in another # thread. The main logic of the loop below would potentially skip # checking assumptions[fact] in this case so we check it once after the # loop to be sure. if fact_i in assumptions: continue # Now we call the associated handler for fact_i if it exists. fact_i_value = None handler_i = handler_map.get(fact_i) if handler_i is not None: fact_i_value = handler_i(obj) # If we get a new value for fact_i then we should update our knowledge # of fact_i as well as any related facts that can be inferred using the # inference rules connecting the fact_i and any other fact values that # are already known. if fact_i_value is not None: assumptions.deduce_all_facts(((fact_i, fact_i_value),)) # Usually if assumptions[fact] is now not None then that is because of # the call to deduce_all_facts above. The handler for fact_i returned # True or False and knowing fact_i (which is equal to fact in the first # iteration) implies knowing a value for fact. It is also possible # though that independent code e.g. called indirectly by the handler or # called in another thread in a multithreaded context might have # resulted in assumptions[fact] being set. Either way we return it. fact_value = assumptions.get(fact) if fact_value is not None: return fact_value # Extend the queue with other facts that might determine fact_i. Here # we randomise the order of the facts that are checked. This should not # lead to any non-determinism if all handlers are logically consistent # with the inference rules for the facts. Non-deterministic assumptions # queries can result from bugs in the handlers that are exposed by this # call to shuffle. These are pushed to the back of the queue meaning # that the inference graph is traversed in breadth-first order. new_facts_to_check = list(_assume_rules.prereq[fact_i] - facts_queued) shuffle(new_facts_to_check) facts_to_check.extend(new_facts_to_check) facts_queued.update(new_facts_to_check) # The above loop should be able to handle everything fine in a # single-threaded context but in multithreaded code it is possible that # this thread skipped computing a particular fact that was computed in # another thread (due to the continue). In that case it is possible that # fact was inferred and is now stored in the assumptions dict but it wasn't # checked for in the body of the loop. This is an obscure case but to make # sure we catch it we check once here at the end of the loop. if fact in assumptions: return assumptions[fact] # This query can not be answered. It's possible that e.g. another thread # has already stored None for fact but assumptions._tell does not mind if # we call _tell twice setting the same value. If this raises # InconsistentAssumptions then it probably means that another thread # attempted to compute this and got a value of True or False rather than # None. In that case there must be a bug in at least one of the handlers. # If the handlers are all deterministic and are consistent with the # inference rules then the same value should be computed for fact in all # threads. assumptions._tell(fact, None) return None class ManagedProperties(BasicMeta): """Metaclass for classes with old-style assumptions""" def __init__(cls, *args, **kws): BasicMeta.__init__(cls, *args, **kws) local_defs = {} for k in _assume_defined: attrname = as_property(k) v = cls.__dict__.get(attrname, '') if isinstance(v, (bool, int, type(None))): if v is not None: v = bool(v) local_defs[k] = v defs = {} for base in reversed(cls.__bases__): assumptions = getattr(base, '_explicit_class_assumptions', None) if assumptions is not None: defs.update(assumptions) defs.update(local_defs) cls._explicit_class_assumptions = defs cls.default_assumptions = StdFactKB(defs) cls._prop_handler = {} for k in _assume_defined: eval_is_meth = getattr(cls, '_eval_is_%s' % k, None) if eval_is_meth is not None: cls._prop_handler[k] = eval_is_meth # Put definite results directly into the class dict, for speed for k, v in cls.default_assumptions.items(): setattr(cls, as_property(k), v) # protection e.g. for Integer.is_even=F <- (Rational.is_integer=F) derived_from_bases = set() for base in cls.__bases__: default_assumptions = getattr(base, 'default_assumptions', None) # is an assumption-aware class if default_assumptions is not None: derived_from_bases.update(default_assumptions) for fact in derived_from_bases - set(cls.default_assumptions): pname = as_property(fact) if pname not in cls.__dict__: setattr(cls, pname, make_property(fact)) # Finally, add any missing automagic property (e.g. for Basic) for fact in _assume_defined: pname = as_property(fact) if not hasattr(cls, pname): setattr(cls, pname, make_property(fact))