hash
stringlengths
64
64
content
stringlengths
0
1.51M
218a9b36e89d6f7aa788e7a6eb3bb43fe5a74ace1a22e66ef12f36ae9002cf33
"""Implementation of :class:`QuotientRing` class.""" from sympy.polys.agca.modules import FreeModuleQuotientRing from sympy.polys.domains.ring import Ring from sympy.polys.polyerrors import NotReversible, CoercionFailed from sympy.utilities import public # TODO # - successive quotients (when quotient ideals are implemented) # - poly rings over quotients? # - division by non-units in integral domains? @public class QuotientRingElement: """ Class representing elements of (commutative) quotient rings. Attributes: - ring - containing ring - data - element of ring.ring (i.e. base ring) representing self """ def __init__(self, ring, data): self.ring = ring self.data = data def __str__(self): from sympy import sstr return sstr(self.data) + " + " + str(self.ring.base_ideal) __repr__ = __str__ def __bool__(self): return not self.ring.is_zero(self) def __add__(self, om): if not isinstance(om, self.__class__) or om.ring != self.ring: try: om = self.ring.convert(om) except (NotImplementedError, CoercionFailed): return NotImplemented return self.ring(self.data + om.data) __radd__ = __add__ def __neg__(self): return self.ring(self.data*self.ring.ring.convert(-1)) def __sub__(self, om): return self.__add__(-om) def __rsub__(self, om): return (-self).__add__(om) def __mul__(self, o): if not isinstance(o, self.__class__): try: o = self.ring.convert(o) except (NotImplementedError, CoercionFailed): return NotImplemented return self.ring(self.data*o.data) __rmul__ = __mul__ def __rtruediv__(self, o): return self.ring.revert(self)*o def __truediv__(self, o): if not isinstance(o, self.__class__): try: o = self.ring.convert(o) except (NotImplementedError, CoercionFailed): return NotImplemented return self.ring.revert(o)*self def __pow__(self, oth): if oth < 0: return self.ring.revert(self) ** -oth return self.ring(self.data ** oth) def __eq__(self, om): if not isinstance(om, self.__class__) or om.ring != self.ring: return False return self.ring.is_zero(self - om) def __ne__(self, om): return not self == om class QuotientRing(Ring): """ Class representing (commutative) quotient rings. You should not usually instantiate this by hand, instead use the constructor from the base ring in the construction. >>> from sympy.abc import x >>> from sympy import QQ >>> I = QQ.old_poly_ring(x).ideal(x**3 + 1) >>> QQ.old_poly_ring(x).quotient_ring(I) QQ[x]/<x**3 + 1> Shorter versions are possible: >>> QQ.old_poly_ring(x)/I QQ[x]/<x**3 + 1> >>> QQ.old_poly_ring(x)/[x**3 + 1] QQ[x]/<x**3 + 1> Attributes: - ring - the base ring - base_ideal - the ideal used to form the quotient """ has_assoc_Ring = True has_assoc_Field = False dtype = QuotientRingElement def __init__(self, ring, ideal): if not ideal.ring == ring: raise ValueError('Ideal must belong to %s, got %s' % (ring, ideal)) self.ring = ring self.base_ideal = ideal self.zero = self(self.ring.zero) self.one = self(self.ring.one) def __str__(self): return str(self.ring) + "/" + str(self.base_ideal) def __hash__(self): return hash((self.__class__.__name__, self.dtype, self.ring, self.base_ideal)) def new(self, a): """Construct an element of ``self`` domain from ``a``. """ if not isinstance(a, self.ring.dtype): a = self.ring(a) # TODO optionally disable reduction? return self.dtype(self, self.base_ideal.reduce_element(a)) def __eq__(self, other): """Returns ``True`` if two domains are equivalent. """ return isinstance(other, QuotientRing) and \ self.ring == other.ring and self.base_ideal == other.base_ideal def from_ZZ(K1, a, K0): """Convert a Python ``int`` object to ``dtype``. """ return K1(K1.ring.convert(a, K0)) from_ZZ_python = from_ZZ from_QQ_python = from_ZZ_python from_ZZ_gmpy = from_ZZ_python from_QQ_gmpy = from_ZZ_python from_RealField = from_ZZ_python from_GlobalPolynomialRing = from_ZZ_python from_FractionField = from_ZZ_python def from_sympy(self, a): return self(self.ring.from_sympy(a)) def to_sympy(self, a): return self.ring.to_sympy(a.data) def from_QuotientRing(self, a, K0): if K0 == self: return a def poly_ring(self, *gens): """Returns a polynomial ring, i.e. ``K[X]``. """ raise NotImplementedError('nested domains not allowed') def frac_field(self, *gens): """Returns a fraction field, i.e. ``K(X)``. """ raise NotImplementedError('nested domains not allowed') def revert(self, a): """ Compute a**(-1), if possible. """ I = self.ring.ideal(a.data) + self.base_ideal try: return self(I.in_terms_of_generators(1)[0]) except ValueError: # 1 not in I raise NotReversible('%s not a unit in %r' % (a, self)) def is_zero(self, a): return self.base_ideal.contains(a.data) def free_module(self, rank): """ Generate a free module of rank ``rank`` over ``self``. >>> from sympy.abc import x >>> from sympy import QQ >>> (QQ.old_poly_ring(x)/[x**2 + 1]).free_module(2) (QQ[x]/<x**2 + 1>)**2 """ return FreeModuleQuotientRing(self, rank)
5ade7fcbb1d30def2ed6a19a9613614d3ed1c3709089592681db90ee37290fd7
"""Implementation of :class:`RealField` class. """ from sympy.core.numbers import Float from sympy.polys.domains.field import Field from sympy.polys.domains.simpledomain import SimpleDomain from sympy.polys.domains.characteristiczero import CharacteristicZero from sympy.polys.domains.mpelements import MPContext from sympy.polys.polyerrors import CoercionFailed from sympy.utilities import public @public class RealField(Field, CharacteristicZero, SimpleDomain): """Real numbers up to the given precision. """ rep = 'RR' is_RealField = is_RR = True is_Exact = False is_Numerical = True is_PID = False has_assoc_Ring = False has_assoc_Field = True _default_precision = 53 @property def has_default_precision(self): return self.precision == self._default_precision @property def precision(self): return self._context.prec @property def dps(self): return self._context.dps @property def tolerance(self): return self._context.tolerance def __init__(self, prec=_default_precision, dps=None, tol=None): context = MPContext(prec, dps, tol, True) context._parent = self self._context = context self.dtype = context.mpf self.zero = self.dtype(0) self.one = self.dtype(1) def __eq__(self, other): return (isinstance(other, RealField) and self.precision == other.precision and self.tolerance == other.tolerance) def __hash__(self): return hash((self.__class__.__name__, self.dtype, self.precision, self.tolerance)) def to_sympy(self, element): """Convert ``element`` to SymPy number. """ return Float(element, self.dps) def from_sympy(self, expr): """Convert SymPy's number to ``dtype``. """ number = expr.evalf(n=self.dps) if number.is_Number: return self.dtype(number) else: raise CoercionFailed("expected real number, got %s" % expr) def from_ZZ(self, element, base): return self.dtype(element) def from_ZZ_python(self, element, base): return self.dtype(element) def from_QQ(self, element, base): return self.dtype(element.numerator) / element.denominator def from_QQ_python(self, element, base): return self.dtype(element.numerator) / element.denominator def from_ZZ_gmpy(self, element, base): return self.dtype(int(element)) def from_QQ_gmpy(self, element, base): return self.dtype(int(element.numerator)) / int(element.denominator) def from_AlgebraicField(self, element, base): return self.from_sympy(base.to_sympy(element).evalf(self.dps)) def from_RealField(self, element, base): if self == base: return element else: return self.dtype(element) def from_ComplexField(self, element, base): if not element.imag: return self.dtype(element.real) def to_rational(self, element, limit=True): """Convert a real number to rational number. """ return self._context.to_rational(element, limit) def get_ring(self): """Returns a ring associated with ``self``. """ return self def get_exact(self): """Returns an exact domain associated with ``self``. """ from sympy.polys.domains import QQ return QQ def gcd(self, a, b): """Returns GCD of ``a`` and ``b``. """ return self.one def lcm(self, a, b): """Returns LCM of ``a`` and ``b``. """ return a*b def almosteq(self, a, b, tolerance=None): """Check if ``a`` and ``b`` are almost equal. """ return self._context.almosteq(a, b, tolerance) RR = RealField()
c7c04f9062a3d163eec09ccdda9cb997d6808c7698e1d8efeb9738b73513af76
"""Implementation of :class:`PythonRationalField` class. """ from sympy.polys.domains.groundtypes import PythonInteger, PythonRational, SymPyRational from sympy.polys.domains.rationalfield import RationalField from sympy.polys.polyerrors import CoercionFailed from sympy.utilities import public @public class PythonRationalField(RationalField): """Rational field based on :ref:`MPQ`. This will be used as :ref:`QQ` if ``gmpy`` and ``gmpy2`` are not installed. Elements are instances of :ref:`MPQ`. """ dtype = PythonRational zero = dtype(0) one = dtype(1) alias = 'QQ_python' def __init__(self): pass def get_ring(self): """Returns ring associated with ``self``. """ from sympy.polys.domains import PythonIntegerRing return PythonIntegerRing() def to_sympy(self, a): """Convert `a` to a SymPy object. """ return SymPyRational(a.numerator, a.denominator) def from_sympy(self, a): """Convert SymPy's Rational to `dtype`. """ if a.is_Rational: return PythonRational(a.p, a.q) elif a.is_Float: from sympy.polys.domains import RR p, q = RR.to_rational(a) return PythonRational(int(p), int(q)) else: raise CoercionFailed("expected `Rational` object, got %s" % a) def from_ZZ_python(K1, a, K0): """Convert a Python `int` object to `dtype`. """ return PythonRational(a) def from_QQ_python(K1, a, K0): """Convert a Python `Fraction` object to `dtype`. """ return a def from_ZZ_gmpy(K1, a, K0): """Convert a GMPY `mpz` object to `dtype`. """ return PythonRational(PythonInteger(a)) def from_QQ_gmpy(K1, a, K0): """Convert a GMPY `mpq` object to `dtype`. """ return PythonRational(PythonInteger(a.numer()), PythonInteger(a.denom())) def from_RealField(K1, a, K0): """Convert a mpmath `mpf` object to `dtype`. """ p, q = K0.to_rational(a) return PythonRational(int(p), int(q)) def numer(self, a): """Returns numerator of `a`. """ return a.numerator def denom(self, a): """Returns denominator of `a`. """ return a.denominator
e477003608edb5c0661c1686353ebb153c0429ad516d7ae54d7f76d307e27c05
"""Implementation of :class:`PolynomialRing` class. """ from sympy.core.compatibility import iterable from sympy.polys.agca.modules import FreeModulePolyRing from sympy.polys.domains.characteristiczero import CharacteristicZero from sympy.polys.domains.compositedomain import CompositeDomain from sympy.polys.domains.old_fractionfield import FractionField from sympy.polys.domains.ring import Ring from sympy.polys.orderings import monomial_key, build_product_order from sympy.polys.polyclasses import DMP, DMF from sympy.polys.polyerrors import (GeneratorsNeeded, PolynomialError, CoercionFailed, ExactQuotientFailed, NotReversible) from sympy.polys.polyutils import dict_from_basic, basic_from_dict, _dict_reorder from sympy.utilities import public # XXX why does this derive from CharacteristicZero??? @public class PolynomialRingBase(Ring, CharacteristicZero, CompositeDomain): """ Base class for generalized polynomial rings. This base class should be used for uniform access to generalized polynomial rings. Subclasses only supply information about the element storage etc. Do not instantiate. """ has_assoc_Ring = True has_assoc_Field = True default_order = "grevlex" def __init__(self, dom, *gens, **opts): if not gens: raise GeneratorsNeeded("generators not specified") lev = len(gens) - 1 self.ngens = len(gens) self.zero = self.dtype.zero(lev, dom, ring=self) self.one = self.dtype.one(lev, dom, ring=self) self.domain = self.dom = dom self.symbols = self.gens = gens # NOTE 'order' may not be set if inject was called through CompositeDomain self.order = opts.get('order', monomial_key(self.default_order)) def new(self, element): return self.dtype(element, self.dom, len(self.gens) - 1, ring=self) def __str__(self): s_order = str(self.order) orderstr = ( " order=" + s_order) if s_order != self.default_order else "" return str(self.dom) + '[' + ','.join(map(str, self.gens)) + orderstr + ']' def __hash__(self): return hash((self.__class__.__name__, self.dtype, self.dom, self.gens, self.order)) def __eq__(self, other): """Returns ``True`` if two domains are equivalent. """ return isinstance(other, PolynomialRingBase) and \ self.dtype == other.dtype and self.dom == other.dom and \ self.gens == other.gens and self.order == other.order def from_ZZ(K1, a, K0): """Convert a Python ``int`` object to ``dtype``. """ return K1(K1.dom.convert(a, K0)) def from_ZZ_python(K1, a, K0): """Convert a Python ``int`` object to ``dtype``. """ return K1(K1.dom.convert(a, K0)) def from_QQ(K1, a, K0): """Convert a Python ``Fraction`` object to ``dtype``. """ return K1(K1.dom.convert(a, K0)) def from_QQ_python(K1, a, K0): """Convert a Python ``Fraction`` object to ``dtype``. """ return K1(K1.dom.convert(a, K0)) def from_ZZ_gmpy(K1, a, K0): """Convert a GMPY ``mpz`` object to ``dtype``. """ return K1(K1.dom.convert(a, K0)) def from_QQ_gmpy(K1, a, K0): """Convert a GMPY ``mpq`` object to ``dtype``. """ return K1(K1.dom.convert(a, K0)) def from_RealField(K1, a, K0): """Convert a mpmath ``mpf`` object to ``dtype``. """ return K1(K1.dom.convert(a, K0)) def from_AlgebraicField(K1, a, K0): """Convert a ``ANP`` object to ``dtype``. """ if K1.dom == K0: return K1(a) def from_PolynomialRing(K1, a, K0): """Convert a ``PolyElement`` object to ``dtype``. """ if K1.gens == K0.symbols: if K1.dom == K0.dom: return K1(dict(a)) # set the correct ring else: convert_dom = lambda c: K1.dom.convert_from(c, K0.dom) return K1({m: convert_dom(c) for m, c in a.items()}) else: monoms, coeffs = _dict_reorder(a.to_dict(), K0.symbols, K1.gens) if K1.dom != K0.dom: coeffs = [ K1.dom.convert(c, K0.dom) for c in coeffs ] return K1(dict(zip(monoms, coeffs))) def from_GlobalPolynomialRing(K1, a, K0): """Convert a ``DMP`` object to ``dtype``. """ if K1.gens == K0.gens: if K1.dom == K0.dom: return K1(a.rep) # set the correct ring else: return K1(a.convert(K1.dom).rep) else: monoms, coeffs = _dict_reorder(a.to_dict(), K0.gens, K1.gens) if K1.dom != K0.dom: coeffs = [ K1.dom.convert(c, K0.dom) for c in coeffs ] return K1(dict(zip(monoms, coeffs))) def get_field(self): """Returns a field associated with ``self``. """ return FractionField(self.dom, *self.gens) def poly_ring(self, *gens): """Returns a polynomial ring, i.e. ``K[X]``. """ raise NotImplementedError('nested domains not allowed') def frac_field(self, *gens): """Returns a fraction field, i.e. ``K(X)``. """ raise NotImplementedError('nested domains not allowed') def revert(self, a): try: return 1/a except (ExactQuotientFailed, ZeroDivisionError): raise NotReversible('%s is not a unit' % a) def gcdex(self, a, b): """Extended GCD of ``a`` and ``b``. """ return a.gcdex(b) def gcd(self, a, b): """Returns GCD of ``a`` and ``b``. """ return a.gcd(b) def lcm(self, a, b): """Returns LCM of ``a`` and ``b``. """ return a.lcm(b) def factorial(self, a): """Returns factorial of ``a``. """ return self.dtype(self.dom.factorial(a)) def _vector_to_sdm(self, v, order): """ For internal use by the modules class. Convert an iterable of elements of this ring into a sparse distributed module element. """ raise NotImplementedError def _sdm_to_dics(self, s, n): """Helper for _sdm_to_vector.""" from sympy.polys.distributedmodules import sdm_to_dict dic = sdm_to_dict(s) res = [{} for _ in range(n)] for k, v in dic.items(): res[k[0]][k[1:]] = v return res def _sdm_to_vector(self, s, n): """ For internal use by the modules class. Convert a sparse distributed module into a list of length ``n``. Examples ======== >>> from sympy import QQ, ilex >>> from sympy.abc import x, y >>> R = QQ.old_poly_ring(x, y, order=ilex) >>> L = [((1, 1, 1), QQ(1)), ((0, 1, 0), QQ(1)), ((0, 0, 1), QQ(2))] >>> R._sdm_to_vector(L, 2) [x + 2*y, x*y] """ dics = self._sdm_to_dics(s, n) # NOTE this works for global and local rings! return [self(x) for x in dics] def free_module(self, rank): """ Generate a free module of rank ``rank`` over ``self``. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> QQ.old_poly_ring(x).free_module(2) QQ[x]**2 """ return FreeModulePolyRing(self, rank) def _vector_to_sdm_helper(v, order): """Helper method for common code in Global and Local poly rings.""" from sympy.polys.distributedmodules import sdm_from_dict d = {} for i, e in enumerate(v): for key, value in e.to_dict().items(): d[(i,) + key] = value return sdm_from_dict(d, order) @public class GlobalPolynomialRing(PolynomialRingBase): """A true polynomial ring, with objects DMP. """ is_PolynomialRing = is_Poly = True dtype = DMP def from_FractionField(K1, a, K0): """ Convert a ``DMF`` object to ``DMP``. Examples ======== >>> from sympy.polys.polyclasses import DMP, DMF >>> from sympy.polys.domains import ZZ >>> from sympy.abc import x >>> f = DMF(([ZZ(1), ZZ(1)], [ZZ(1)]), ZZ) >>> K = ZZ.old_frac_field(x) >>> F = ZZ.old_poly_ring(x).from_FractionField(f, K) >>> F == DMP([ZZ(1), ZZ(1)], ZZ) True >>> type(F) <class 'sympy.polys.polyclasses.DMP'> """ if a.denom().is_one: return K1.from_GlobalPolynomialRing(a.numer(), K0) def to_sympy(self, a): """Convert ``a`` to a SymPy object. """ return basic_from_dict(a.to_sympy_dict(), *self.gens) def from_sympy(self, a): """Convert SymPy's expression to ``dtype``. """ try: rep, _ = dict_from_basic(a, gens=self.gens) except PolynomialError: raise CoercionFailed("can't convert %s to type %s" % (a, self)) for k, v in rep.items(): rep[k] = self.dom.from_sympy(v) return self(rep) def is_positive(self, a): """Returns True if ``LC(a)`` is positive. """ return self.dom.is_positive(a.LC()) def is_negative(self, a): """Returns True if ``LC(a)`` is negative. """ return self.dom.is_negative(a.LC()) def is_nonpositive(self, a): """Returns True if ``LC(a)`` is non-positive. """ return self.dom.is_nonpositive(a.LC()) def is_nonnegative(self, a): """Returns True if ``LC(a)`` is non-negative. """ return self.dom.is_nonnegative(a.LC()) def _vector_to_sdm(self, v, order): """ Examples ======== >>> from sympy import lex, QQ >>> from sympy.abc import x, y >>> R = QQ.old_poly_ring(x, y) >>> f = R.convert(x + 2*y) >>> g = R.convert(x * y) >>> R._vector_to_sdm([f, g], lex) [((1, 1, 1), 1), ((0, 1, 0), 1), ((0, 0, 1), 2)] """ return _vector_to_sdm_helper(v, order) class GeneralizedPolynomialRing(PolynomialRingBase): """A generalized polynomial ring, with objects DMF. """ dtype = DMF def new(self, a): """Construct an element of ``self`` domain from ``a``. """ res = self.dtype(a, self.dom, len(self.gens) - 1, ring=self) # make sure res is actually in our ring if res.denom().terms(order=self.order)[0][0] != (0,)*len(self.gens): from sympy.printing.str import sstr raise CoercionFailed("denominator %s not allowed in %s" % (sstr(res), self)) return res def __contains__(self, a): try: a = self.convert(a) except CoercionFailed: return False return a.denom().terms(order=self.order)[0][0] == (0,)*len(self.gens) def from_FractionField(K1, a, K0): dmf = K1.get_field().from_FractionField(a, K0) return K1((dmf.num, dmf.den)) def to_sympy(self, a): """Convert ``a`` to a SymPy object. """ return (basic_from_dict(a.numer().to_sympy_dict(), *self.gens) / basic_from_dict(a.denom().to_sympy_dict(), *self.gens)) def from_sympy(self, a): """Convert SymPy's expression to ``dtype``. """ p, q = a.as_numer_denom() num, _ = dict_from_basic(p, gens=self.gens) den, _ = dict_from_basic(q, gens=self.gens) for k, v in num.items(): num[k] = self.dom.from_sympy(v) for k, v in den.items(): den[k] = self.dom.from_sympy(v) return self((num, den)).cancel() def _vector_to_sdm(self, v, order): """ Turn an iterable into a sparse distributed module. Note that the vector is multiplied by a unit first to make all entries polynomials. Examples ======== >>> from sympy import ilex, QQ >>> from sympy.abc import x, y >>> R = QQ.old_poly_ring(x, y, order=ilex) >>> f = R.convert((x + 2*y) / (1 + x)) >>> g = R.convert(x * y) >>> R._vector_to_sdm([f, g], ilex) [((0, 0, 1), 2), ((0, 1, 0), 1), ((1, 1, 1), 1), ((1, 2, 1), 1)] """ # NOTE this is quite inefficient... u = self.one.numer() for x in v: u *= x.denom() return _vector_to_sdm_helper([x.numer()*u/x.denom() for x in v], order) @public def PolynomialRing(dom, *gens, **opts): r""" Create a generalized multivariate polynomial ring. A generalized polynomial ring is defined by a ground field `K`, a set of generators (typically `x_1, \ldots, x_n`) and a monomial order `<`. The monomial order can be global, local or mixed. In any case it induces a total ordering on the monomials, and there exists for every (non-zero) polynomial `f \in K[x_1, \ldots, x_n]` a well-defined "leading monomial" `LM(f) = LM(f, >)`. One can then define a multiplicative subset `S = S_> = \{f \in K[x_1, \ldots, x_n] | LM(f) = 1\}`. The generalized polynomial ring corresponding to the monomial order is `R = S^{-1}K[x_1, \ldots, x_n]`. If `>` is a so-called global order, that is `1` is the smallest monomial, then we just have `S = K` and `R = K[x_1, \ldots, x_n]`. Examples ======== A few examples may make this clearer. >>> from sympy.abc import x, y >>> from sympy import QQ Our first ring uses global lexicographic order. >>> R1 = QQ.old_poly_ring(x, y, order=(("lex", x, y),)) The second ring uses local lexicographic order. Note that when using a single (non-product) order, you can just specify the name and omit the variables: >>> R2 = QQ.old_poly_ring(x, y, order="ilex") The third and fourth rings use a mixed orders: >>> o1 = (("ilex", x), ("lex", y)) >>> o2 = (("lex", x), ("ilex", y)) >>> R3 = QQ.old_poly_ring(x, y, order=o1) >>> R4 = QQ.old_poly_ring(x, y, order=o2) We will investigate what elements of `K(x, y)` are contained in the various rings. >>> L = [x, 1/x, y/(1 + x), 1/(1 + y), 1/(1 + x*y)] >>> test = lambda R: [f in R for f in L] The first ring is just `K[x, y]`: >>> test(R1) [True, False, False, False, False] The second ring is R1 localised at the maximal ideal (x, y): >>> test(R2) [True, False, True, True, True] The third ring is R1 localised at the prime ideal (x): >>> test(R3) [True, False, True, False, True] Finally the fourth ring is R1 localised at `S = K[x, y] \setminus yK[y]`: >>> test(R4) [True, False, False, True, False] """ order = opts.get("order", GeneralizedPolynomialRing.default_order) if iterable(order): order = build_product_order(order, gens) order = monomial_key(order) opts['order'] = order if order.is_global: return GlobalPolynomialRing(dom, *gens, **opts) else: return GeneralizedPolynomialRing(dom, *gens, **opts)
ea509c88ec0c6008e55048a6cef9f8b928d2153c9aa732a1b0572b65987eaf41
"""Implementation of :class:`PolynomialRing` class. """ from sympy.polys.domains.ring import Ring from sympy.polys.domains.compositedomain import CompositeDomain from sympy.polys.polyerrors import CoercionFailed, GeneratorsError from sympy.utilities import public @public class PolynomialRing(Ring, CompositeDomain): """A class for representing multivariate polynomial rings. """ is_PolynomialRing = is_Poly = True has_assoc_Ring = True has_assoc_Field = True def __init__(self, domain_or_ring, symbols=None, order=None): from sympy.polys.rings import PolyRing if isinstance(domain_or_ring, PolyRing) and symbols is None and order is None: ring = domain_or_ring else: ring = PolyRing(symbols, domain_or_ring, order) self.ring = ring self.dtype = ring.dtype self.gens = ring.gens self.ngens = ring.ngens self.symbols = ring.symbols self.domain = ring.domain if symbols: if ring.domain.is_Field and ring.domain.is_Exact and len(symbols)==1: self.is_PID = True # TODO: remove this self.dom = self.domain def new(self, element): return self.ring.ring_new(element) @property def zero(self): return self.ring.zero @property def one(self): return self.ring.one @property def order(self): return self.ring.order def __str__(self): return str(self.domain) + '[' + ','.join(map(str, self.symbols)) + ']' def __hash__(self): return hash((self.__class__.__name__, self.dtype.ring, self.domain, self.symbols)) def __eq__(self, other): """Returns `True` if two domains are equivalent. """ return isinstance(other, PolynomialRing) and \ (self.dtype.ring, self.domain, self.symbols) == \ (other.dtype.ring, other.domain, other.symbols) def is_unit(self, a): """Returns ``True`` if ``a`` is a unit of ``self``""" if not a.is_ground: return False K = self.domain return K.is_unit(K.convert_from(a, self)) def canonical_unit(self, a): u = self.domain.canonical_unit(a.LC) return self.ring.ground_new(u) def to_sympy(self, a): """Convert `a` to a SymPy object. """ return a.as_expr() def from_sympy(self, a): """Convert SymPy's expression to `dtype`. """ return self.ring.from_expr(a) def from_ZZ(K1, a, K0): """Convert a Python `int` object to `dtype`. """ return K1(K1.domain.convert(a, K0)) def from_ZZ_python(K1, a, K0): """Convert a Python `int` object to `dtype`. """ return K1(K1.domain.convert(a, K0)) def from_QQ(K1, a, K0): """Convert a Python `Fraction` object to `dtype`. """ return K1(K1.domain.convert(a, K0)) def from_QQ_python(K1, a, K0): """Convert a Python `Fraction` object to `dtype`. """ return K1(K1.domain.convert(a, K0)) def from_ZZ_gmpy(K1, a, K0): """Convert a GMPY `mpz` object to `dtype`. """ return K1(K1.domain.convert(a, K0)) def from_QQ_gmpy(K1, a, K0): """Convert a GMPY `mpq` object to `dtype`. """ return K1(K1.domain.convert(a, K0)) def from_GaussianIntegerRing(K1, a, K0): """Convert a `GaussianInteger` object to `dtype`. """ return K1(K1.domain.convert(a, K0)) def from_GaussianRationalField(K1, a, K0): """Convert a `GaussianRational` object to `dtype`. """ return K1(K1.domain.convert(a, K0)) def from_RealField(K1, a, K0): """Convert a mpmath `mpf` object to `dtype`. """ return K1(K1.domain.convert(a, K0)) def from_ComplexField(K1, a, K0): """Convert a mpmath `mpf` object to `dtype`. """ return K1(K1.domain.convert(a, K0)) def from_AlgebraicField(K1, a, K0): """Convert an algebraic number to ``dtype``. """ if K1.domain != K0: a = K1.domain.convert_from(a, K0) if a is not None: return K1.new(a) def from_PolynomialRing(K1, a, K0): """Convert a polynomial to ``dtype``. """ try: return a.set_ring(K1.ring) except (CoercionFailed, GeneratorsError): return None def from_FractionField(K1, a, K0): """Convert a rational function to ``dtype``. """ q, r = K0.numer(a).div(K0.denom(a)) if r.is_zero: return K1.from_PolynomialRing(q, K0.field.ring.to_domain()) else: return None def from_GlobalPolynomialRing(K1, a, K0): """Convert from old poly ring to ``dtype``. """ if K1.symbols == K0.gens: ad = a.to_dict() if K1.domain != K0.domain: ad = {m: K1.domain.convert(c) for m, c in ad.items()} return K1(ad) elif a.is_ground and K0.domain == K1: return K1.convert_from(a.to_list()[0], K0.domain) def get_field(self): """Returns a field associated with `self`. """ return self.ring.to_field().to_domain() def is_positive(self, a): """Returns True if `LC(a)` is positive. """ return self.domain.is_positive(a.LC) def is_negative(self, a): """Returns True if `LC(a)` is negative. """ return self.domain.is_negative(a.LC) def is_nonpositive(self, a): """Returns True if `LC(a)` is non-positive. """ return self.domain.is_nonpositive(a.LC) def is_nonnegative(self, a): """Returns True if `LC(a)` is non-negative. """ return self.domain.is_nonnegative(a.LC) def gcdex(self, a, b): """Extended GCD of `a` and `b`. """ return a.gcdex(b) def gcd(self, a, b): """Returns GCD of `a` and `b`. """ return a.gcd(b) def lcm(self, a, b): """Returns LCM of `a` and `b`. """ return a.lcm(b) def factorial(self, a): """Returns factorial of `a`. """ return self.dtype(self.domain.factorial(a))
5034f1e28b00604dc2b2977140d02204d37feef1a79a75ff33aa4752de9a6e17
"""Implementation of :class:`IntegerRing` class. """ from sympy.external.gmpy import MPZ, HAS_GMPY from sympy.polys.domains.groundtypes import ( SymPyInteger, factorial, gcdex, gcd, lcm, sqrt, ) from sympy.polys.domains.characteristiczero import CharacteristicZero from sympy.polys.domains.ring import Ring from sympy.polys.domains.simpledomain import SimpleDomain from sympy.polys.polyerrors import CoercionFailed from sympy.utilities import public import math @public class IntegerRing(Ring, CharacteristicZero, SimpleDomain): r"""The domain ``ZZ`` representing the integers `\mathbb{Z}`. The :py:class:`IntegerRing` class represents the ring of integers as a :py:class:`~.Domain` in the domain system. :py:class:`IntegerRing` is a super class of :py:class:`PythonIntegerRing` and :py:class:`GMPYIntegerRing` one of which will be the implementation for :ref:`ZZ` depending on whether or not ``gmpy`` or ``gmpy2`` is installed. See also ======== Domain """ rep = 'ZZ' alias = 'ZZ' dtype = MPZ zero = dtype(0) one = dtype(1) tp = type(one) is_IntegerRing = is_ZZ = True is_Numerical = True is_PID = True has_assoc_Ring = True has_assoc_Field = True def __init__(self): """Allow instantiation of this domain. """ def to_sympy(self, a): """Convert ``a`` to a SymPy object. """ return SymPyInteger(int(a)) def from_sympy(self, a): """Convert SymPy's Integer to ``dtype``. """ if a.is_Integer: return MPZ(a.p) elif a.is_Float and int(a) == a: return MPZ(int(a)) else: raise CoercionFailed("expected an integer, got %s" % a) def get_field(self): r"""Return the associated field of fractions :ref:`QQ` Returns ======= :ref:`QQ`: The associated field of fractions :ref:`QQ`, a :py:class:`~.Domain` representing the rational numbers `\mathbb{Q}`. Examples ======== >>> from sympy import ZZ >>> ZZ.get_field() QQ """ from sympy.polys.domains import QQ return QQ def algebraic_field(self, *extension): r"""Returns an algebraic field, i.e. `\mathbb{Q}(\alpha, \ldots)`. Parameters ========== *extension: One or more Expr. Generators of the extension. These should be expressions that are algebraic over `\mathbb{Q}`. Returns ======= :py:class:`~.AlgebraicField` A :py:class:`~.Domain` representing the algebraic field extension. Examples ======== >>> from sympy import ZZ, sqrt >>> ZZ.algebraic_field(sqrt(2)) QQ<sqrt(2)> """ return self.get_field().algebraic_field(*extension) def from_AlgebraicField(K1, a, K0): """Convert a :py:class:`~.ANP` object to :ref:`ZZ`. See :py:meth:`~.Domain.convert`. """ if a.is_ground: return K1.convert(a.LC(), K0.dom) def log(self, a, b): r"""logarithm of *a* to the base *b* Parameters ========== a: number b: number Returns ======= $\\lfloor\log(a, b)\\rfloor$: Floor of the logarithm of *a* to the base *b* Examples ======== >>> from sympy import ZZ >>> ZZ.log(ZZ(8), ZZ(2)) 3 >>> ZZ.log(ZZ(9), ZZ(2)) 3 Notes ===== This function uses ``math.log`` which is based on ``float`` so it will fail for large integer arguments. """ return self.dtype(math.log(int(a), b)) def from_FF(K1, a, K0): """Convert ``ModularInteger(int)`` to GMPY's ``mpz``. """ return MPZ(a.to_int()) def from_FF_python(K1, a, K0): """Convert ``ModularInteger(int)`` to GMPY's ``mpz``. """ return MPZ(a.to_int()) def from_ZZ(K1, a, K0): """Convert Python's ``int`` to GMPY's ``mpz``. """ return MPZ(a) def from_ZZ_python(K1, a, K0): """Convert Python's ``int`` to GMPY's ``mpz``. """ return MPZ(a) def from_QQ(K1, a, K0): """Convert Python's ``Fraction`` to GMPY's ``mpz``. """ if a.denominator == 1: return MPZ(a.numerator) def from_QQ_python(K1, a, K0): """Convert Python's ``Fraction`` to GMPY's ``mpz``. """ if a.denominator == 1: return MPZ(a.numerator) def from_FF_gmpy(K1, a, K0): """Convert ``ModularInteger(mpz)`` to GMPY's ``mpz``. """ return a.to_int() def from_ZZ_gmpy(K1, a, K0): """Convert GMPY's ``mpz`` to GMPY's ``mpz``. """ return a def from_QQ_gmpy(K1, a, K0): """Convert GMPY ``mpq`` to GMPY's ``mpz``. """ if a.denominator == 1: return a.numerator def from_RealField(K1, a, K0): """Convert mpmath's ``mpf`` to GMPY's ``mpz``. """ p, q = K0.to_rational(a) if q == 1: return MPZ(p) def from_GaussianIntegerRing(K1, a, K0): if a.y == 0: return a.x def gcdex(self, a, b): """Compute extended GCD of ``a`` and ``b``. """ h, s, t = gcdex(a, b) if HAS_GMPY: return s, t, h else: return h, s, t def gcd(self, a, b): """Compute GCD of ``a`` and ``b``. """ return gcd(a, b) def lcm(self, a, b): """Compute LCM of ``a`` and ``b``. """ return lcm(a, b) def sqrt(self, a): """Compute square root of ``a``. """ return sqrt(a) def factorial(self, a): """Compute factorial of ``a``. """ return factorial(a) ZZ = IntegerRing()
d868de34c79b4d7c4b1c390a62a6eb3fe859a815c7a1cfd4bfb924ef12323dcc
"""Implementation of :class:`ComplexField` class. """ from sympy.core.numbers import Float, I from sympy.polys.domains.characteristiczero import CharacteristicZero from sympy.polys.domains.field import Field from sympy.polys.domains.mpelements import MPContext from sympy.polys.domains.simpledomain import SimpleDomain from sympy.polys.polyerrors import DomainError, CoercionFailed from sympy.utilities import public @public class ComplexField(Field, CharacteristicZero, SimpleDomain): """Complex numbers up to the given precision. """ rep = 'CC' is_ComplexField = is_CC = True is_Exact = False is_Numerical = True has_assoc_Ring = False has_assoc_Field = True _default_precision = 53 @property def has_default_precision(self): return self.precision == self._default_precision @property def precision(self): return self._context.prec @property def dps(self): return self._context.dps @property def tolerance(self): return self._context.tolerance def __init__(self, prec=_default_precision, dps=None, tol=None): context = MPContext(prec, dps, tol, False) context._parent = self self._context = context self.dtype = context.mpc self.zero = self.dtype(0) self.one = self.dtype(1) def __eq__(self, other): return (isinstance(other, ComplexField) and self.precision == other.precision and self.tolerance == other.tolerance) def __hash__(self): return hash((self.__class__.__name__, self.dtype, self.precision, self.tolerance)) def to_sympy(self, element): """Convert ``element`` to SymPy number. """ return Float(element.real, self.dps) + I*Float(element.imag, self.dps) def from_sympy(self, expr): """Convert SymPy's number to ``dtype``. """ number = expr.evalf(n=self.dps) real, imag = number.as_real_imag() if real.is_Number and imag.is_Number: return self.dtype(real, imag) else: raise CoercionFailed("expected complex number, got %s" % expr) def from_ZZ(self, element, base): return self.dtype(element) def from_QQ(self, element, base): return self.dtype(int(element.numerator)) / int(element.denominator) def from_ZZ_python(self, element, base): return self.dtype(element) def from_QQ_python(self, element, base): return self.dtype(element.numerator) / element.denominator def from_ZZ_gmpy(self, element, base): return self.dtype(int(element)) def from_QQ_gmpy(self, element, base): return self.dtype(int(element.numerator)) / int(element.denominator) def from_GaussianIntegerRing(self, element, base): return self.dtype(int(element.x), int(element.y)) def from_GaussianRationalField(self, element, base): x = element.x y = element.y return (self.dtype(int(x.numerator)) / int(x.denominator) + self.dtype(0, int(y.numerator)) / int(y.denominator)) def from_AlgebraicField(self, element, base): return self.from_sympy(base.to_sympy(element).evalf(self.dps)) def from_RealField(self, element, base): return self.dtype(element) def from_ComplexField(self, element, base): if self == base: return element else: return self.dtype(element) def get_ring(self): """Returns a ring associated with ``self``. """ raise DomainError("there is no ring associated with %s" % self) def get_exact(self): """Returns an exact domain associated with ``self``. """ raise DomainError("there is no exact domain associated with %s" % self) def is_negative(self, element): """Returns ``False`` for any ``ComplexElement``. """ return False def is_positive(self, element): """Returns ``False`` for any ``ComplexElement``. """ return False def is_nonnegative(self, element): """Returns ``False`` for any ``ComplexElement``. """ return False def is_nonpositive(self, element): """Returns ``False`` for any ``ComplexElement``. """ return False def gcd(self, a, b): """Returns GCD of ``a`` and ``b``. """ return self.one def lcm(self, a, b): """Returns LCM of ``a`` and ``b``. """ return a*b def almosteq(self, a, b, tolerance=None): """Check if ``a`` and ``b`` are almost equal. """ return self._context.almosteq(a, b, tolerance) CC = ComplexField()
c37709713edaa8b2c79f77e01710b9fe51b0b96b0214978b7e8abefc43c3d8f6
"""Implementation of :class:`FractionField` class. """ from sympy.polys.domains.compositedomain import CompositeDomain from sympy.polys.domains.field import Field from sympy.polys.polyerrors import CoercionFailed, GeneratorsError from sympy.utilities import public @public class FractionField(Field, CompositeDomain): """A class for representing multivariate rational function fields. """ is_FractionField = is_Frac = True has_assoc_Ring = True has_assoc_Field = True def __init__(self, domain_or_field, symbols=None, order=None): from sympy.polys.fields import FracField if isinstance(domain_or_field, FracField) and symbols is None and order is None: field = domain_or_field else: field = FracField(symbols, domain_or_field, order) self.field = field self.dtype = field.dtype self.gens = field.gens self.ngens = field.ngens self.symbols = field.symbols self.domain = field.domain # TODO: remove this self.dom = self.domain def new(self, element): return self.field.field_new(element) @property def zero(self): return self.field.zero @property def one(self): return self.field.one @property def order(self): return self.field.order @property def is_Exact(self): return self.domain.is_Exact def get_exact(self): return FractionField(self.domain.get_exact(), self.symbols) def __str__(self): return str(self.domain) + '(' + ','.join(map(str, self.symbols)) + ')' def __hash__(self): return hash((self.__class__.__name__, self.dtype.field, self.domain, self.symbols)) def __eq__(self, other): """Returns ``True`` if two domains are equivalent. """ return isinstance(other, FractionField) and \ (self.dtype.field, self.domain, self.symbols) ==\ (other.dtype.field, other.domain, other.symbols) def to_sympy(self, a): """Convert ``a`` to a SymPy object. """ return a.as_expr() def from_sympy(self, a): """Convert SymPy's expression to ``dtype``. """ return self.field.from_expr(a) def from_ZZ(K1, a, K0): """Convert a Python ``int`` object to ``dtype``. """ return K1(K1.domain.convert(a, K0)) def from_ZZ_python(K1, a, K0): """Convert a Python ``int`` object to ``dtype``. """ return K1(K1.domain.convert(a, K0)) def from_QQ(K1, a, K0): """Convert a Python ``Fraction`` object to ``dtype``. """ return K1(K1.domain.convert(a, K0)) def from_QQ_python(K1, a, K0): """Convert a Python ``Fraction`` object to ``dtype``. """ return K1(K1.domain.convert(a, K0)) def from_ZZ_gmpy(K1, a, K0): """Convert a GMPY ``mpz`` object to ``dtype``. """ return K1(K1.domain.convert(a, K0)) def from_QQ_gmpy(K1, a, K0): """Convert a GMPY ``mpq`` object to ``dtype``. """ return K1(K1.domain.convert(a, K0)) def from_GaussianRationalField(K1, a, K0): """Convert a ``GaussianRational`` object to ``dtype``. """ return K1(K1.domain.convert(a, K0)) def from_GaussianIntegerRing(K1, a, K0): """Convert a ``GaussianInteger`` object to ``dtype``. """ return K1(K1.domain.convert(a, K0)) def from_RealField(K1, a, K0): """Convert a mpmath ``mpf`` object to ``dtype``. """ return K1(K1.domain.convert(a, K0)) def from_ComplexField(K1, a, K0): """Convert a mpmath ``mpf`` object to ``dtype``. """ return K1(K1.domain.convert(a, K0)) def from_AlgebraicField(K1, a, K0): """Convert an algebraic number to ``dtype``. """ if K1.domain != K0: a = K1.domain.convert_from(a, K0) if a is not None: return K1.new(a) def from_PolynomialRing(K1, a, K0): """Convert a polynomial to ``dtype``. """ try: return K1.new(a.set_ring(K1.field.ring)) except (CoercionFailed, GeneratorsError): # XXX: We get here if K1=ZZ(x,y) and K0=QQ[x,y] # and the poly a in K0 has non-integer coefficients. # It seems that K1.new can handle this but K1.new doesn't work # when K0.domain is an algebraic field... try: return K1.new(a) except (CoercionFailed, GeneratorsError): return None def from_FractionField(K1, a, K0): """Convert a rational function to ``dtype``. """ try: return a.set_field(K1.field) except (CoercionFailed, GeneratorsError): return None def get_ring(self): """Returns a field associated with ``self``. """ return self.field.to_ring().to_domain() def is_positive(self, a): """Returns True if ``LC(a)`` is positive. """ return self.domain.is_positive(a.numer.LC) def is_negative(self, a): """Returns True if ``LC(a)`` is negative. """ return self.domain.is_negative(a.numer.LC) def is_nonpositive(self, a): """Returns True if ``LC(a)`` is non-positive. """ return self.domain.is_nonpositive(a.numer.LC) def is_nonnegative(self, a): """Returns True if ``LC(a)`` is non-negative. """ return self.domain.is_nonnegative(a.numer.LC) def numer(self, a): """Returns numerator of ``a``. """ return a.numer def denom(self, a): """Returns denominator of ``a``. """ return a.denom def factorial(self, a): """Returns factorial of ``a``. """ return self.dtype(self.domain.factorial(a))
81e47de0c7a489d9bbdb6578ed1a0a303af23505bc0cbffca5129a35f85f2742
"""Implementation of :class:`ExpressionDomain` class. """ from sympy.core import sympify, SympifyError from sympy.polys.domains.characteristiczero import CharacteristicZero from sympy.polys.domains.field import Field from sympy.polys.domains.simpledomain import SimpleDomain from sympy.polys.polyutils import PicklableWithSlots from sympy.utilities import public eflags = dict(deep=False, mul=True, power_exp=False, power_base=False, basic=False, multinomial=False, log=False) @public class ExpressionDomain(Field, CharacteristicZero, SimpleDomain): """A class for arbitrary expressions. """ is_SymbolicDomain = is_EX = True class Expression(PicklableWithSlots): """An arbitrary expression. """ __slots__ = ('ex',) def __init__(self, ex): if not isinstance(ex, self.__class__): self.ex = sympify(ex) else: self.ex = ex.ex def __repr__(f): return 'EX(%s)' % repr(f.ex) def __str__(f): return 'EX(%s)' % str(f.ex) def __hash__(self): return hash((self.__class__.__name__, self.ex)) def as_expr(f): return f.ex def numer(f): return f.__class__(f.ex.as_numer_denom()[0]) def denom(f): return f.__class__(f.ex.as_numer_denom()[1]) def simplify(f, ex): return f.__class__(ex.cancel().expand(**eflags)) def __abs__(f): return f.__class__(abs(f.ex)) def __neg__(f): return f.__class__(-f.ex) def _to_ex(f, g): try: return f.__class__(g) except SympifyError: return None def __add__(f, g): g = f._to_ex(g) if g is not None: return f.simplify(f.ex + g.ex) else: return NotImplemented def __radd__(f, g): return f.simplify(f.__class__(g).ex + f.ex) def __sub__(f, g): g = f._to_ex(g) if g is not None: return f.simplify(f.ex - g.ex) else: return NotImplemented def __rsub__(f, g): return f.simplify(f.__class__(g).ex - f.ex) def __mul__(f, g): g = f._to_ex(g) if g is not None: return f.simplify(f.ex*g.ex) else: return NotImplemented def __rmul__(f, g): return f.simplify(f.__class__(g).ex*f.ex) def __pow__(f, n): n = f._to_ex(n) if n is not None: return f.simplify(f.ex**n.ex) else: return NotImplemented def __truediv__(f, g): g = f._to_ex(g) if g is not None: return f.simplify(f.ex/g.ex) else: return NotImplemented def __rtruediv__(f, g): return f.simplify(f.__class__(g).ex/f.ex) def __eq__(f, g): return f.ex == f.__class__(g).ex def __ne__(f, g): return not f == g def __bool__(f): return not f.ex.is_zero def gcd(f, g): from sympy.polys import gcd return f.__class__(gcd(f.ex, f.__class__(g).ex)) def lcm(f, g): from sympy.polys import lcm return f.__class__(lcm(f.ex, f.__class__(g).ex)) dtype = Expression zero = Expression(0) one = Expression(1) rep = 'EX' has_assoc_Ring = False has_assoc_Field = True def __init__(self): pass def to_sympy(self, a): """Convert ``a`` to a SymPy object. """ return a.as_expr() def from_sympy(self, a): """Convert SymPy's expression to ``dtype``. """ return self.dtype(a) def from_ZZ(K1, a, K0): """Convert a Python ``int`` object to ``dtype``. """ return K1(K0.to_sympy(a)) def from_ZZ_python(K1, a, K0): """Convert a Python ``int`` object to ``dtype``. """ return K1(K0.to_sympy(a)) def from_QQ(K1, a, K0): """Convert a Python ``Fraction`` object to ``dtype``. """ return K1(K0.to_sympy(a)) def from_QQ_python(K1, a, K0): """Convert a Python ``Fraction`` object to ``dtype``. """ return K1(K0.to_sympy(a)) def from_ZZ_gmpy(K1, a, K0): """Convert a GMPY ``mpz`` object to ``dtype``. """ return K1(K0.to_sympy(a)) def from_QQ_gmpy(K1, a, K0): """Convert a GMPY ``mpq`` object to ``dtype``. """ return K1(K0.to_sympy(a)) def from_GaussianIntegerRing(K1, a, K0): """Convert a ``GaussianRational`` object to ``dtype``. """ return K1(K0.to_sympy(a)) def from_GaussianRationalField(K1, a, K0): """Convert a ``GaussianRational`` object to ``dtype``. """ return K1(K0.to_sympy(a)) def from_RealField(K1, a, K0): """Convert a mpmath ``mpf`` object to ``dtype``. """ return K1(K0.to_sympy(a)) def from_PolynomialRing(K1, a, K0): """Convert a ``DMP`` object to ``dtype``. """ return K1(K0.to_sympy(a)) def from_FractionField(K1, a, K0): """Convert a ``DMF`` object to ``dtype``. """ return K1(K0.to_sympy(a)) def from_ExpressionDomain(K1, a, K0): """Convert a ``EX`` object to ``dtype``. """ return a def get_ring(self): """Returns a ring associated with ``self``. """ return self # XXX: EX is not a ring but we don't have much choice here. def get_field(self): """Returns a field associated with ``self``. """ return self def is_positive(self, a): """Returns True if ``a`` is positive. """ return a.ex.as_coeff_mul()[0].is_positive def is_negative(self, a): """Returns True if ``a`` is negative. """ return a.ex.could_extract_minus_sign() def is_nonpositive(self, a): """Returns True if ``a`` is non-positive. """ return a.ex.as_coeff_mul()[0].is_nonpositive def is_nonnegative(self, a): """Returns True if ``a`` is non-negative. """ return a.ex.as_coeff_mul()[0].is_nonnegative def numer(self, a): """Returns numerator of ``a``. """ return a.numer() def denom(self, a): """Returns denominator of ``a``. """ return a.denom() def gcd(self, a, b): return self(1) def lcm(self, a, b): return a.lcm(b) EX = ExpressionDomain()
d2f7764242e2daae27a62b38c11d703057c7185197abb2c97be90951df0e61cd
"""Domains of Gaussian type.""" from sympy.core.numbers import I from sympy.polys.polyerrors import CoercionFailed from sympy.polys.domains.integerring import ZZ from sympy.polys.domains.rationalfield import QQ from sympy.polys.domains.algebraicfield import AlgebraicField from sympy.polys.domains.domain import Domain from sympy.polys.domains.domainelement import DomainElement from sympy.polys.domains.field import Field from sympy.polys.domains.ring import Ring class GaussianElement(DomainElement): """Base class for elements of Gaussian type domains.""" base = None # type: Domain _parent = None # type: Domain __slots__ = ('x', 'y') def __init__(self, x, y=0): conv = self.base.convert self.x = conv(x) self.y = conv(y) @classmethod def new(cls, x, y): """Create a new GaussianElement of the same domain.""" return cls(x, y) def parent(self): """The domain that this is an element of (ZZ_I or QQ_I)""" return self._parent def __hash__(self): return hash((self.x, self.y)) def __eq__(self, other): if isinstance(other, self.__class__): return self.x == other.x and self.y == other.y else: return NotImplemented def __lt__(self, other): if not isinstance(other, GaussianElement): return NotImplemented return [self.y, self.x] < [other.y, other.x] def __pos__(self): return self def __neg__(self): return self.new(-self.x, -self.y) def __repr__(self): return "%s(%s, %s)" % (self._parent.rep, self.x, self.y) def __str__(self): return str(self._parent.to_sympy(self)) @classmethod def _get_xy(cls, other): if not isinstance(other, cls): try: other = cls._parent.convert(other) except CoercionFailed: return None, None return other.x, other.y def __add__(self, other): x, y = self._get_xy(other) if x is not None: return self.new(self.x + x, self.y + y) else: return NotImplemented __radd__ = __add__ def __sub__(self, other): x, y = self._get_xy(other) if x is not None: return self.new(self.x - x, self.y - y) else: return NotImplemented def __rsub__(self, other): x, y = self._get_xy(other) if x is not None: return self.new(x - self.x, y - self.y) else: return NotImplemented def __mul__(self, other): x, y = self._get_xy(other) if x is not None: return self.new(self.x*x - self.y*y, self.x*y + self.y*x) else: return NotImplemented __rmul__ = __mul__ def __pow__(self, exp): if exp == 0: return self.new(1, 0) if exp < 0: self, exp = 1/self, -exp if exp == 1: return self pow2 = self prod = self if exp % 2 else self._parent.one exp //= 2 while exp: pow2 *= pow2 if exp % 2: prod *= pow2 exp //= 2 return prod def __bool__(self): return bool(self.x) or bool(self.y) def quadrant(self): """Return quadrant index 0-3. 0 is included in quadrant 0. """ if self.y > 0: return 0 if self.x > 0 else 1 elif self.y < 0: return 2 if self.x < 0 else 3 else: return 0 if self.x >= 0 else 2 def __rdivmod__(self, other): try: other = self._parent.convert(other) except CoercionFailed: return NotImplemented else: return other.__divmod__(self) def __rtruediv__(self, other): try: other = QQ_I.convert(other) except CoercionFailed: return NotImplemented else: return other.__truediv__(self) def __floordiv__(self, other): qr = self.__divmod__(other) return qr if qr is NotImplemented else qr[0] def __rfloordiv__(self, other): qr = self.__rdivmod__(other) return qr if qr is NotImplemented else qr[0] def __mod__(self, other): qr = self.__divmod__(other) return qr if qr is NotImplemented else qr[1] def __rmod__(self, other): qr = self.__rdivmod__(other) return qr if qr is NotImplemented else qr[1] class GaussianInteger(GaussianElement): """Gaussian integer: domain element for :ref:`ZZ_I` >>> from sympy import ZZ_I >>> z = ZZ_I(2, 3) >>> z (2 + 3*I) >>> type(z) <class 'sympy.polys.domains.gaussiandomains.GaussianInteger'> """ base = ZZ def __truediv__(self, other): """Return a Gaussian rational.""" return QQ_I.convert(self)/other def __divmod__(self, other): if not other: raise ZeroDivisionError('divmod({}, 0)'.format(self)) x, y = self._get_xy(other) if x is None: return NotImplemented # multiply self and other by x - I*y # self/other == (a + I*b)/c a, b = self.x*x + self.y*y, -self.x*y + self.y*x c = x*x + y*y # find integers qx and qy such that # |a - qx*c| <= c/2 and |b - qy*c| <= c/2 qx = (2*a + c) // (2*c) # -c <= 2*a - qx*2*c < c qy = (2*b + c) // (2*c) q = GaussianInteger(qx, qy) # |self/other - q| < 1 since # |a/c - qx|**2 + |b/c - qy|**2 <= 1/4 + 1/4 < 1 return q, self - q*other # |r| < |other| class GaussianRational(GaussianElement): """Gaussian rational: domain element for :ref:`QQ_I` >>> from sympy import QQ_I, QQ >>> z = QQ_I(QQ(2, 3), QQ(4, 5)) >>> z (2/3 + 4/5*I) >>> type(z) <class 'sympy.polys.domains.gaussiandomains.GaussianRational'> """ base = QQ def __truediv__(self, other): """Return a Gaussian rational.""" if not other: raise ZeroDivisionError('{} / 0'.format(self)) x, y = self._get_xy(other) if x is None: return NotImplemented c = x*x + y*y return GaussianRational((self.x*x + self.y*y)/c, (-self.x*y + self.y*x)/c) def __divmod__(self, other): try: other = self._parent.convert(other) except CoercionFailed: return NotImplemented if not other: raise ZeroDivisionError('{} % 0'.format(self)) else: return self/other, QQ_I.zero class GaussianDomain(): """Base class for Gaussian domains.""" dom = None # type: Domain is_Numerical = True is_Exact = True has_assoc_Ring = True has_assoc_Field = True def to_sympy(self, a): """Convert ``a`` to a SymPy object. """ conv = self.dom.to_sympy return conv(a.x) + I*conv(a.y) def from_sympy(self, a): """Convert a SymPy object to ``self.dtype``.""" r, b = a.as_coeff_Add() x = self.dom.from_sympy(r) # may raise CoercionFailed if not b: return self.new(x, 0) r, b = b.as_coeff_Mul() y = self.dom.from_sympy(r) if b is I: return self.new(x, y) else: raise CoercionFailed("{} is not Gaussian".format(a)) def inject(self, *gens): """Inject generators into this domain. """ return self.poly_ring(*gens) def canonical_unit(self, d): unit = self.units[-d.quadrant()] # - for inverse power return unit def is_negative(self, element): """Returns ``False`` for any ``GaussianElement``. """ return False def is_positive(self, element): """Returns ``False`` for any ``GaussianElement``. """ return False def is_nonnegative(self, element): """Returns ``False`` for any ``GaussianElement``. """ return False def is_nonpositive(self, element): """Returns ``False`` for any ``GaussianElement``. """ return False def from_ZZ_gmpy(K1, a, K0): """Convert a GMPY mpz to ``self.dtype``.""" return K1(a) def from_ZZ(K1, a, K0): """Convert a ZZ_python element to ``self.dtype``.""" return K1(a) def from_ZZ_python(K1, a, K0): """Convert a ZZ_python element to ``self.dtype``.""" return K1(a) def from_QQ(K1, a, K0): """Convert a GMPY mpq to ``self.dtype``.""" return K1(a) def from_QQ_gmpy(K1, a, K0): """Convert a GMPY mpq to ``self.dtype``.""" return K1(a) def from_QQ_python(K1, a, K0): """Convert a QQ_python element to ``self.dtype``.""" return K1(a) def from_AlgebraicField(K1, a, K0): """Convert an element from ZZ<I> or QQ<I> to ``self.dtype``.""" if K0.ext.args[0] == I: return K1.from_sympy(K0.to_sympy(a)) class GaussianIntegerRing(GaussianDomain, Ring): r"""Ring of Gaussian integers ``ZZ_I`` The :ref:`ZZ_I` domain represents the `Gaussian integers`_ `\mathbb{Z}[i]` as a :py:class:`~.Domain` in the domain system (see :ref:`polys-domainsintro`). By default a :py:class:`~.Poly` created from an expression with coefficients that are combinations of integers and ``I`` (`\sqrt{-1}`) will have the domain :ref:`ZZ_I`. >>> from sympy import Poly, Symbol, I >>> x = Symbol('x') >>> p = Poly(x**2 + I) >>> p Poly(x**2 + I, x, domain='ZZ_I') >>> p.domain ZZ_I The :ref:`ZZ_I` domain can be used to factorise polynomials that are reducible over the Gaussian integers. >>> from sympy import factor >>> factor(x**2 + 1) x**2 + 1 >>> factor(x**2 + 1, domain='ZZ_I') (x - I)*(x + I) The corresponding `field of fractions`_ is the domain of the Gaussian rationals :ref:`QQ_I`. Conversely :ref:`ZZ_I` is the `ring of integers`_ of :ref:`QQ_I`. >>> from sympy import ZZ_I, QQ_I >>> ZZ_I.get_field() QQ_I >>> QQ_I.get_ring() ZZ_I When using the domain directly :ref:`ZZ_I` can be used as a constructor. >>> ZZ_I(3, 4) (3 + 4*I) >>> ZZ_I(5) (5 + 0*I) The domain elements of :ref:`ZZ_I` are instances of :py:class:`~.GaussianInteger` which support the rings operations ``+,-,*,**``. >>> z1 = ZZ_I(5, 1) >>> z2 = ZZ_I(2, 3) >>> z1 (5 + 1*I) >>> z2 (2 + 3*I) >>> z1 + z2 (7 + 4*I) >>> z1 * z2 (7 + 17*I) >>> z1 ** 2 (24 + 10*I) Both floor (``//``) and modulo (``%``) division work with :py:class:`~.GaussianInteger` (see the :py:meth:`~.Domain.div` method). >>> z3, z4 = ZZ_I(5), ZZ_I(1, 3) >>> z3 // z4 # floor division (1 + -1*I) >>> z3 % z4 # modulo division (remainder) (1 + -2*I) >>> (z3//z4)*z4 + z3%z4 == z3 True True division (``/``) in :ref:`ZZ_I` gives an element of :ref:`QQ_I`. The :py:meth:`~.Domain.exquo` method can be used to divide in :ref:`ZZ_I` when exact division is possible. >>> z1 / z2 (1 + -1*I) >>> ZZ_I.exquo(z1, z2) (1 + -1*I) >>> z3 / z4 (1/2 + -3/2*I) >>> ZZ_I.exquo(z3, z4) Traceback (most recent call last): ... ExactQuotientFailed: (1 + 3*I) does not divide (5 + 0*I) in ZZ_I The :py:meth:`~.Domain.gcd` method can be used to compute the `gcd`_ of any two elements. >>> ZZ_I.gcd(ZZ_I(10), ZZ_I(2)) (2 + 0*I) >>> ZZ_I.gcd(ZZ_I(5), ZZ_I(2, 1)) (2 + 1*I) .. _Gaussian integers: https://en.wikipedia.org/wiki/Gaussian_integer .. _gcd: https://en.wikipedia.org/wiki/Greatest_common_divisor """ dom = ZZ dtype = GaussianInteger zero = dtype(ZZ(0), ZZ(0)) one = dtype(ZZ(1), ZZ(0)) imag_unit = dtype(ZZ(0), ZZ(1)) units = (one, imag_unit, -one, -imag_unit) # powers of i rep = 'ZZ_I' is_GaussianRing = True is_ZZ_I = True def __init__(self): # override Domain.__init__ """For constructing ZZ_I.""" def get_ring(self): """Returns a ring associated with ``self``. """ return self def get_field(self): """Returns a field associated with ``self``. """ return QQ_I def normalize(self, d, *args): """Return first quadrant element associated with ``d``. Also multiply the other arguments by the same power of i. """ unit = self.canonical_unit(d) d *= unit args = tuple(a*unit for a in args) return (d,) + args if args else d def gcd(self, a, b): """Greatest common divisor of a and b over ZZ_I.""" while b: a, b = b, a % b return self.normalize(a) def lcm(self, a, b): """Least common multiple of a and b over ZZ_I.""" return (a * b) // self.gcd(a, b) def from_GaussianIntegerRing(K1, a, K0): """Convert a ZZ_I element to ZZ_I.""" return a def from_GaussianRationalField(K1, a, K0): """Convert a QQ_I element to ZZ_I.""" return K1.new(ZZ.convert(a.x), ZZ.convert(a.y)) ZZ_I = GaussianInteger._parent = GaussianIntegerRing() class GaussianRationalField(GaussianDomain, Field): r"""Field of Gaussian rationals ``QQ_I`` The :ref:`QQ_I` domain represents the `Gaussian rationals`_ `\mathbb{Q}(i)` as a :py:class:`~.Domain` in the domain system (see :ref:`polys-domainsintro`). By default a :py:class:`~.Poly` created from an expression with coefficients that are combinations of rationals and ``I`` (`\sqrt{-1}`) will have the domain :ref:`QQ_I`. >>> from sympy import Poly, Symbol, I >>> x = Symbol('x') >>> p = Poly(x**2 + I/2) >>> p Poly(x**2 + I/2, x, domain='QQ_I') >>> p.domain QQ_I The polys option ``gaussian=True`` can be used to specify that the domain should be :ref:`QQ_I` even if the coefficients do not contain ``I`` or are all integers. >>> Poly(x**2) Poly(x**2, x, domain='ZZ') >>> Poly(x**2 + I) Poly(x**2 + I, x, domain='ZZ_I') >>> Poly(x**2/2) Poly(1/2*x**2, x, domain='QQ') >>> Poly(x**2, gaussian=True) Poly(x**2, x, domain='QQ_I') >>> Poly(x**2 + I, gaussian=True) Poly(x**2 + I, x, domain='QQ_I') >>> Poly(x**2/2, gaussian=True) Poly(1/2*x**2, x, domain='QQ_I') The :ref:`QQ_I` domain can be used to factorise polynomials that are reducible over the Gaussian rationals. >>> from sympy import factor, QQ_I >>> factor(x**2/4 + 1) (x**2 + 4)/4 >>> factor(x**2/4 + 1, domain='QQ_I') (x - 2*I)*(x + 2*I)/4 >>> factor(x**2/4 + 1, domain=QQ_I) (x - 2*I)*(x + 2*I)/4 It is also possible to specify the :ref:`QQ_I` domain explicitly with polys functions like :py:func:`~.apart`. >>> from sympy import apart >>> apart(1/(1 + x**2)) 1/(x**2 + 1) >>> apart(1/(1 + x**2), domain=QQ_I) I/(2*(x + I)) - I/(2*(x - I)) The corresponding `ring of integers`_ is the domain of the Gaussian integers :ref:`ZZ_I`. Conversely :ref:`QQ_I` is the `field of fractions`_ of :ref:`ZZ_I`. >>> from sympy import ZZ_I, QQ_I, QQ >>> ZZ_I.get_field() QQ_I >>> QQ_I.get_ring() ZZ_I When using the domain directly :ref:`QQ_I` can be used as a constructor. >>> QQ_I(3, 4) (3 + 4*I) >>> QQ_I(5) (5 + 0*I) >>> QQ_I(QQ(2, 3), QQ(4, 5)) (2/3 + 4/5*I) The domain elements of :ref:`QQ_I` are instances of :py:class:`~.GaussianRational` which support the field operations ``+,-,*,**,/``. >>> z1 = QQ_I(5, 1) >>> z2 = QQ_I(2, QQ(1, 2)) >>> z1 (5 + 1*I) >>> z2 (2 + 1/2*I) >>> z1 + z2 (7 + 3/2*I) >>> z1 * z2 (19/2 + 9/2*I) >>> z2 ** 2 (15/4 + 2*I) True division (``/``) in :ref:`QQ_I` gives an element of :ref:`QQ_I` and is always exact. >>> z1 / z2 (42/17 + -2/17*I) >>> QQ_I.exquo(z1, z2) (42/17 + -2/17*I) >>> z1 == (z1/z2)*z2 True Both floor (``//``) and modulo (``%``) division can be used with :py:class:`~.GaussianRational` (see :py:meth:`~.Domain.div`) but division is always exact so there is no remainder. >>> z1 // z2 (42/17 + -2/17*I) >>> z1 % z2 (0 + 0*I) >>> QQ_I.div(z1, z2) ((42/17 + -2/17*I), (0 + 0*I)) >>> (z1//z2)*z2 + z1%z2 == z1 True .. _Gaussian rationals: https://en.wikipedia.org/wiki/Gaussian_rational """ dom = QQ dtype = GaussianRational zero = dtype(QQ(0), QQ(0)) one = dtype(QQ(1), QQ(0)) imag_unit = dtype(QQ(0), QQ(1)) units = (one, imag_unit, -one, -imag_unit) # powers of i rep = 'QQ_I' is_GaussianField = True is_QQ_I = True def __init__(self): # override Domain.__init__ """For constructing QQ_I.""" def get_ring(self): """Returns a ring associated with ``self``. """ return ZZ_I def get_field(self): """Returns a field associated with ``self``. """ return self def as_AlgebraicField(self): """Get equivalent domain as an ``AlgebraicField``. """ return AlgebraicField(self.dom, I) def numer(self, a): """Get the numerator of ``a``.""" ZZ_I = self.get_ring() return ZZ_I.convert(a * self.denom(a)) def denom(self, a): """Get the denominator of ``a``.""" ZZ = self.dom.get_ring() QQ = self.dom ZZ_I = self.get_ring() denom_ZZ = ZZ.lcm(QQ.denom(a.x), QQ.denom(a.y)) return ZZ_I(denom_ZZ, ZZ.zero) def from_GaussianIntegerRing(K1, a, K0): """Convert a ZZ_I element to QQ_I.""" return K1.new(a.x, a.y) def from_GaussianRationalField(K1, a, K0): """Convert a QQ_I element to QQ_I.""" return a QQ_I = GaussianRational._parent = GaussianRationalField()
7580b76333fa009aa668ca30d2adbdc5b847dd78e8b8a1639bb222f47d5a10d7
"""Ground types for various mathematical domains in SymPy. """ import builtins from sympy.external.gmpy import HAS_GMPY, factorial, sqrt PythonInteger = builtins.int PythonReal = builtins.float PythonComplex = builtins.complex from .pythonrational import PythonRational from sympy.core.numbers import ( igcdex as python_gcdex, igcd2 as python_gcd, ilcm as python_lcm, ) from sympy import ( Float as SymPyReal, Integer as SymPyInteger, Rational as SymPyRational, ) if HAS_GMPY == 2: from gmpy2 import ( mpz as GMPYInteger, mpq as GMPYRational, numer as gmpy_numer, denom as gmpy_denom, gcdext as gmpy_gcdex, gcd as gmpy_gcd, lcm as gmpy_lcm, qdiv as gmpy_qdiv, ) gcdex = gmpy_gcdex gcd = gmpy_gcd lcm = gmpy_lcm else: class _GMPYInteger: def __init__(self, obj): pass class _GMPYRational: def __init__(self, obj): pass GMPYInteger = _GMPYInteger GMPYRational = _GMPYRational gmpy_numer = None gmpy_denom = None gmpy_gcdex = None gmpy_gcd = None gmpy_lcm = None gmpy_qdiv = None gcdex = python_gcdex gcd = python_gcd lcm = python_lcm __all__ = [ 'PythonInteger', 'PythonReal', 'PythonComplex', 'PythonRational', 'python_gcdex', 'python_gcd', 'python_lcm', 'SymPyReal', 'SymPyInteger', 'SymPyRational', 'GMPYInteger', 'GMPYRational', 'gmpy_numer', 'gmpy_denom', 'gmpy_gcdex', 'gmpy_gcd', 'gmpy_lcm', 'gmpy_qdiv', 'factorial', 'sqrt', 'GMPYInteger', 'GMPYRational', ]
53a3e1d7fe44cf96d737825c1764ecab51540c4c18b06c749d44fe8190ef3b95
"""Implementation of :class:`GMPYIntegerRing` class. """ from sympy.polys.domains.groundtypes import ( GMPYInteger, SymPyInteger, factorial as gmpy_factorial, gmpy_gcdex, gmpy_gcd, gmpy_lcm, sqrt as gmpy_sqrt, ) from sympy.polys.domains.integerring import IntegerRing from sympy.polys.polyerrors import CoercionFailed from sympy.utilities import public @public class GMPYIntegerRing(IntegerRing): """Integer ring based on GMPY's ``mpz`` type. This will be the implementation of :ref:`ZZ` if ``gmpy`` or ``gmpy2`` is installed. Elements will be of type ``gmpy.mpz``. """ dtype = GMPYInteger zero = dtype(0) one = dtype(1) tp = type(one) alias = 'ZZ_gmpy' def __init__(self): """Allow instantiation of this domain. """ def to_sympy(self, a): """Convert ``a`` to a SymPy object. """ return SymPyInteger(int(a)) def from_sympy(self, a): """Convert SymPy's Integer to ``dtype``. """ if a.is_Integer: return GMPYInteger(a.p) elif a.is_Float and int(a) == a: return GMPYInteger(int(a)) else: raise CoercionFailed("expected an integer, got %s" % a) def from_FF_python(K1, a, K0): """Convert ``ModularInteger(int)`` to GMPY's ``mpz``. """ return GMPYInteger(a.to_int()) def from_ZZ_python(K1, a, K0): """Convert Python's ``int`` to GMPY's ``mpz``. """ return GMPYInteger(a) def from_QQ(K1, a, K0): """Convert Python's ``Fraction`` to GMPY's ``mpz``. """ if a.denominator == 1: return GMPYInteger(a.numerator) def from_QQ_python(K1, a, K0): """Convert Python's ``Fraction`` to GMPY's ``mpz``. """ if a.denominator == 1: return GMPYInteger(a.numerator) def from_FF_gmpy(K1, a, K0): """Convert ``ModularInteger(mpz)`` to GMPY's ``mpz``. """ return a.to_int() def from_ZZ_gmpy(K1, a, K0): """Convert GMPY's ``mpz`` to GMPY's ``mpz``. """ return a def from_QQ_gmpy(K1, a, K0): """Convert GMPY ``mpq`` to GMPY's ``mpz``. """ if a.denominator == 1: return a.numerator def from_RealField(K1, a, K0): """Convert mpmath's ``mpf`` to GMPY's ``mpz``. """ p, q = K0.to_rational(a) if q == 1: return GMPYInteger(p) def from_GaussianIntegerRing(K1, a, K0): if a.y == 0: return a.x def gcdex(self, a, b): """Compute extended GCD of ``a`` and ``b``. """ h, s, t = gmpy_gcdex(a, b) return s, t, h def gcd(self, a, b): """Compute GCD of ``a`` and ``b``. """ return gmpy_gcd(a, b) def lcm(self, a, b): """Compute LCM of ``a`` and ``b``. """ return gmpy_lcm(a, b) def sqrt(self, a): """Compute square root of ``a``. """ return gmpy_sqrt(a) def factorial(self, a): """Compute factorial of ``a``. """ return gmpy_factorial(a)
aa9b463dddb40f744cecae51473098df801cf7a775bd4a54b691f7ae6692efcf
"""Implementation of :class:`Domain` class. """ from typing import Any, Optional, Type from sympy.core import Basic, sympify from sympy.core.compatibility import HAS_GMPY, is_sequence, ordered from sympy.core.decorators import deprecated from sympy.polys.domains.domainelement import DomainElement from sympy.polys.orderings import lex from sympy.polys.polyerrors import UnificationFailed, CoercionFailed, DomainError from sympy.polys.polyutils import _unify_gens, _not_a_coeff from sympy.utilities import default_sort_key, public @public class Domain: """Superclass for all domains in the polys domains system. See :ref:`polys-domainsintro` for an introductory explanation of the domains system. The :py:class:`~.Domain` class is an abstract base class for all of the concrete domain types. There are many different :py:class:`~.Domain` subclasses each of which has an associated ``dtype`` which is a class representing the elements of the domain. The coefficients of a :py:class:`~.Poly` are elements of a domain which must be a subclass of :py:class:`~.Domain`. Examples ======== The most common example domains are the integers :ref:`ZZ` and the rationals :ref:`QQ`. >>> from sympy import Poly, symbols, Domain >>> x, y = symbols('x, y') >>> p = Poly(x**2 + y) >>> p Poly(x**2 + y, x, y, domain='ZZ') >>> p.domain ZZ >>> isinstance(p.domain, Domain) True >>> Poly(x**2 + y/2) Poly(x**2 + 1/2*y, x, y, domain='QQ') The domains can be used directly in which case the domain object e.g. (:ref:`ZZ` or :ref:`QQ`) can be used as a constructor for elements of ``dtype``. >>> from sympy import ZZ, QQ >>> ZZ(2) 2 >>> ZZ.dtype # doctest: +SKIP <class 'int'> >>> type(ZZ(2)) # doctest: +SKIP <class 'int'> >>> QQ(1, 2) 1/2 >>> type(QQ(1, 2)) # doctest: +SKIP <class 'sympy.polys.domains.pythonrational.PythonRational'> The corresponding domain elements can be used with the arithmetic operations ``+,-,*,**`` and depending on the domain some combination of ``/,//,%`` might be usable. For example in :ref:`ZZ` both ``//`` (floor division) and ``%`` (modulo division) can be used but ``/`` (true division) can not. Since :ref:`QQ` is a :py:class:`~.Field` its elements can be used with ``/`` but ``//`` and ``%`` should not be used. Some domains have a :py:meth:`~.Domain.gcd` method. >>> ZZ(2) + ZZ(3) 5 >>> ZZ(5) // ZZ(2) 2 >>> ZZ(5) % ZZ(2) 1 >>> QQ(1, 2) / QQ(2, 3) 3/4 >>> ZZ.gcd(ZZ(4), ZZ(2)) 2 >>> QQ.gcd(QQ(2,7), QQ(5,3)) 1/21 >>> ZZ.is_Field False >>> QQ.is_Field True There are also many other domains including: 1. :ref:`GF(p)` for finite fields of prime order. 2. :ref:`RR` for real (floating point) numbers. 3. :ref:`CC` for complex (floating point) numbers. 4. :ref:`QQ(a)` for algebraic number fields. 5. :ref:`K[x]` for polynomial rings. 6. :ref:`K(x)` for rational function fields. 7. :ref:`EX` for arbitrary expressions. Each domain is represented by a domain object and also an implementation class (``dtype``) for the elements of the domain. For example the :ref:`K[x]` domains are represented by a domain object which is an instance of :py:class:`~.PolynomialRing` and the elements are always instances of :py:class:`~.PolyElement`. The implementation class represents particular types of mathematical expressions in a way that is more efficient than a normal SymPy expression which is of type :py:class:`~.Expr`. The domain methods :py:meth:`~.Domain.from_sympy` and :py:meth:`~.Domain.to_sympy` are used to convert from :py:class:`~.Expr` to a domain element and vice versa. >>> from sympy import Symbol, ZZ, Expr >>> x = Symbol('x') >>> K = ZZ[x] # polynomial ring domain >>> K ZZ[x] >>> type(K) # class of the domain <class 'sympy.polys.domains.polynomialring.PolynomialRing'> >>> K.dtype # class of the elements <class 'sympy.polys.rings.PolyElement'> >>> p_expr = x**2 + 1 # Expr >>> p_expr x**2 + 1 >>> type(p_expr) <class 'sympy.core.add.Add'> >>> isinstance(p_expr, Expr) True >>> p_domain = K.from_sympy(p_expr) >>> p_domain # domain element x**2 + 1 >>> type(p_domain) <class 'sympy.polys.rings.PolyElement'> >>> K.to_sympy(p_domain) == p_expr True The :py:meth:`~.Domain.convert_from` method is used to convert domain elements from one domain to another. >>> from sympy import ZZ, QQ >>> ez = ZZ(2) >>> eq = QQ.convert_from(ez, ZZ) >>> type(ez) # doctest: +SKIP <class 'int'> >>> type(eq) # doctest: +SKIP <class 'sympy.polys.domains.pythonrational.PythonRational'> Elements from different domains should not be mixed in arithmetic or other operations: they should be converted to a common domain first. The domain method :py:meth:`~.Domain.unify` is used to find a domain that can represent all the elements of two given domains. >>> from sympy import ZZ, QQ, symbols >>> x, y = symbols('x, y') >>> ZZ.unify(QQ) QQ >>> ZZ[x].unify(QQ) QQ[x] >>> ZZ[x].unify(QQ[y]) QQ[x,y] If a domain is a :py:class:`~.Ring` then is might have an associated :py:class:`~.Field` and vice versa. The :py:meth:`~.Domain.get_field` and :py:meth:`~.Domain.get_ring` methods will find or create the associated domain. >>> from sympy import ZZ, QQ, Symbol >>> x = Symbol('x') >>> ZZ.has_assoc_Field True >>> ZZ.get_field() QQ >>> QQ.has_assoc_Ring True >>> QQ.get_ring() ZZ >>> K = QQ[x] >>> K QQ[x] >>> K.get_field() QQ(x) See also ======== DomainElement: abstract base class for domain elements construct_domain: construct a minimal domain for some expressions """ dtype = None # type: Optional[Type] """The type (class) of the elements of this :py:class:`~.Domain`: >>> from sympy import ZZ, QQ, Symbol >>> ZZ.dtype <class 'int'> >>> z = ZZ(2) >>> z 2 >>> type(z) <class 'int'> >>> type(z) == ZZ.dtype True Every domain has an associated **dtype** ("datatype") which is the class of the associated domain elements. See also ======== of_type """ zero = None # type: Optional[Any] """The zero element of the :py:class:`~.Domain`: >>> from sympy import QQ >>> QQ.zero 0 >>> QQ.of_type(QQ.zero) True See also ======== of_type one """ one = None # type: Optional[Any] """The one element of the :py:class:`~.Domain`: >>> from sympy import QQ >>> QQ.one 1 >>> QQ.of_type(QQ.one) True See also ======== of_type zero """ is_Ring = False """Boolean flag indicating if the domain is a :py:class:`~.Ring`. >>> from sympy import ZZ >>> ZZ.is_Ring True Basically every :py:class:`~.Domain` represents a ring so this flag is not that useful. See also ======== is_PID is_Field get_ring has_assoc_Ring """ is_Field = False """Boolean flag indicating if the domain is a :py:class:`~.Field`. >>> from sympy import ZZ, QQ >>> ZZ.is_Field False >>> QQ.is_Field True See also ======== is_PID is_Ring get_field has_assoc_Field """ has_assoc_Ring = False """Boolean flag indicating if the domain has an associated :py:class:`~.Ring`. >>> from sympy import QQ >>> QQ.has_assoc_Ring True >>> QQ.get_ring() ZZ See also ======== is_Field get_ring """ has_assoc_Field = False """Boolean flag indicating if the domain has an associated :py:class:`~.Field`. >>> from sympy import ZZ >>> ZZ.has_assoc_Field True >>> ZZ.get_field() QQ See also ======== is_Field get_field """ is_FiniteField = is_FF = False is_IntegerRing = is_ZZ = False is_RationalField = is_QQ = False is_GaussianRing = is_ZZ_I = False is_GaussianField = is_QQ_I = False is_RealField = is_RR = False is_ComplexField = is_CC = False is_AlgebraicField = is_Algebraic = False is_PolynomialRing = is_Poly = False is_FractionField = is_Frac = False is_SymbolicDomain = is_EX = False is_FiniteExtension = False is_Exact = True is_Numerical = False is_Simple = False is_Composite = False is_PID = False """Boolean flag indicating if the domain is a `principal ideal domain`_. >>> from sympy import ZZ >>> ZZ.has_assoc_Field True >>> ZZ.get_field() QQ .. _principal ideal domain: https://en.wikipedia.org/wiki/Principal_ideal_domain See also ======== is_Field get_field """ has_CharacteristicZero = False rep = None # type: Optional[str] alias = None # type: Optional[str] @property # type: ignore @deprecated(useinstead="is_Field", issue=12723, deprecated_since_version="1.1") def has_Field(self): return self.is_Field @property # type: ignore @deprecated(useinstead="is_Ring", issue=12723, deprecated_since_version="1.1") def has_Ring(self): return self.is_Ring def __init__(self): raise NotImplementedError def __str__(self): return self.rep def __repr__(self): return str(self) def __hash__(self): return hash((self.__class__.__name__, self.dtype)) def new(self, *args): return self.dtype(*args) @property def tp(self): """Alias for :py:attr:`~.Domain.dtype`""" return self.dtype def __call__(self, *args): """Construct an element of ``self`` domain from ``args``. """ return self.new(*args) def normal(self, *args): return self.dtype(*args) def convert_from(self, element, base): """Convert ``element`` to ``self.dtype`` given the base domain. """ if base.alias is not None: method = "from_" + base.alias else: method = "from_" + base.__class__.__name__ _convert = getattr(self, method) if _convert is not None: result = _convert(element, base) if result is not None: return result raise CoercionFailed("can't convert %s of type %s from %s to %s" % (element, type(element), base, self)) def convert(self, element, base=None): """Convert ``element`` to ``self.dtype``. """ if _not_a_coeff(element): raise CoercionFailed('%s is not in any domain' % element) if base is not None: return self.convert_from(element, base) if self.of_type(element): return element from sympy.polys.domains import ZZ, QQ, RealField, ComplexField if ZZ.of_type(element): return self.convert_from(element, ZZ) if isinstance(element, int): return self.convert_from(ZZ(element), ZZ) if HAS_GMPY: integers = ZZ if isinstance(element, integers.tp): return self.convert_from(element, integers) rationals = QQ if isinstance(element, rationals.tp): return self.convert_from(element, rationals) if isinstance(element, float): parent = RealField(tol=False) return self.convert_from(parent(element), parent) if isinstance(element, complex): parent = ComplexField(tol=False) return self.convert_from(parent(element), parent) if isinstance(element, DomainElement): return self.convert_from(element, element.parent()) # TODO: implement this in from_ methods if self.is_Numerical and getattr(element, 'is_ground', False): return self.convert(element.LC()) if isinstance(element, Basic): try: return self.from_sympy(element) except (TypeError, ValueError): pass else: # TODO: remove this branch if not is_sequence(element): try: element = sympify(element, strict=True) if isinstance(element, Basic): return self.from_sympy(element) except (TypeError, ValueError): pass raise CoercionFailed("can't convert %s of type %s to %s" % (element, type(element), self)) def of_type(self, element): """Check if ``a`` is of type ``dtype``. """ return isinstance(element, self.tp) # XXX: this isn't correct, e.g. PolyElement def __contains__(self, a): """Check if ``a`` belongs to this domain. """ try: if _not_a_coeff(a): raise CoercionFailed self.convert(a) # this might raise, too except CoercionFailed: return False return True def to_sympy(self, a): """Convert domain element *a* to a SymPy expression (Expr). Explanation =========== Convert a :py:class:`~.Domain` element *a* to :py:class:`~.Expr`. Most public SymPy functions work with objects of type :py:class:`~.Expr`. The elements of a :py:class:`~.Domain` have a different internal representation. It is not possible to mix domain elements with :py:class:`~.Expr` so each domain has :py:meth:`~.Domain.to_sympy` and :py:meth:`~.Domain.from_sympy` methods to convert its domain elements to and from :py:class:`~.Expr`. Parameters ========== a: domain element An element of this :py:class:`~.Domain`. Returns ======= expr: Expr A normal sympy expression of type :py:class:`~.Expr`. Examples ======== Construct an element of the :ref:`QQ` domain and then convert it to :py:class:`~.Expr`. >>> from sympy import QQ, Expr >>> q_domain = QQ(2) >>> q_domain 2 >>> q_expr = QQ.to_sympy(q_domain) >>> q_expr 2 Although the printed forms look similar these objects are not of the same type. >>> isinstance(q_domain, Expr) False >>> isinstance(q_expr, Expr) True Construct an element of :ref:`K[x]` and convert to :py:class:`~.Expr`. >>> from sympy import Symbol >>> x = Symbol('x') >>> K = QQ[x] >>> x_domain = K.gens[0] # generator x as a domain element >>> p_domain = x_domain**2/3 + 1 >>> p_domain 1/3*x**2 + 1 >>> p_expr = K.to_sympy(p_domain) >>> p_expr x**2/3 + 1 The :py:meth:`~.Domain.from_sympy` method is used for the opposite conversion from a normal SymPy expression to a domain element. >>> p_domain == p_expr False >>> K.from_sympy(p_expr) == p_domain True >>> K.to_sympy(p_domain) == p_expr True >>> K.from_sympy(K.to_sympy(p_domain)) == p_domain True >>> K.to_sympy(K.from_sympy(p_expr)) == p_expr True The :py:meth:`~.Domain.from_sympy` method makes it easier to construct domain elements interactively. >>> from sympy import Symbol >>> x = Symbol('x') >>> K = QQ[x] >>> K.from_sympy(x**2/3 + 1) 1/3*x**2 + 1 See also ======== from_sympy convert_from """ raise NotImplementedError def from_sympy(self, a): """Convert a SymPy expression to an element of this domain. Explanation =========== See :py:meth:`~.Domain.to_sympy` for explanation and examples. Parameters ========== expr: Expr A normal sympy expression of type :py:class:`~.Expr`. Returns ======= a: domain element An element of this :py:class:`~.Domain`. See also ======== to_sympy convert_from """ raise NotImplementedError def from_FF(K1, a, K0): """Convert ``ModularInteger(int)`` to ``dtype``. """ return None def from_FF_python(K1, a, K0): """Convert ``ModularInteger(int)`` to ``dtype``. """ return None def from_ZZ_python(K1, a, K0): """Convert a Python ``int`` object to ``dtype``. """ return None def from_QQ_python(K1, a, K0): """Convert a Python ``Fraction`` object to ``dtype``. """ return None def from_FF_gmpy(K1, a, K0): """Convert ``ModularInteger(mpz)`` to ``dtype``. """ return None def from_ZZ_gmpy(K1, a, K0): """Convert a GMPY ``mpz`` object to ``dtype``. """ return None def from_QQ_gmpy(K1, a, K0): """Convert a GMPY ``mpq`` object to ``dtype``. """ return None def from_RealField(K1, a, K0): """Convert a real element object to ``dtype``. """ return None def from_ComplexField(K1, a, K0): """Convert a complex element to ``dtype``. """ return None def from_AlgebraicField(K1, a, K0): """Convert an algebraic number to ``dtype``. """ return None def from_PolynomialRing(K1, a, K0): """Convert a polynomial to ``dtype``. """ if a.is_ground: return K1.convert(a.LC, K0.dom) def from_FractionField(K1, a, K0): """Convert a rational function to ``dtype``. """ return None def from_MonogenicFiniteExtension(K1, a, K0): """Convert an ``ExtensionElement`` to ``dtype``. """ return K1.convert_from(a.rep, K0.ring) def from_ExpressionDomain(K1, a, K0): """Convert a ``EX`` object to ``dtype``. """ return K1.from_sympy(a.ex) def from_GlobalPolynomialRing(K1, a, K0): """Convert a polynomial to ``dtype``. """ if a.degree() <= 0: return K1.convert(a.LC(), K0.dom) def from_GeneralizedPolynomialRing(K1, a, K0): return K1.from_FractionField(a, K0) def unify_with_symbols(K0, K1, symbols): if (K0.is_Composite and (set(K0.symbols) & set(symbols))) or (K1.is_Composite and (set(K1.symbols) & set(symbols))): raise UnificationFailed("can't unify %s with %s, given %s generators" % (K0, K1, tuple(symbols))) return K0.unify(K1) def unify(K0, K1, symbols=None): """ Construct a minimal domain that contains elements of ``K0`` and ``K1``. Known domains (from smallest to largest): - ``GF(p)`` - ``ZZ`` - ``QQ`` - ``RR(prec, tol)`` - ``CC(prec, tol)`` - ``ALG(a, b, c)`` - ``K[x, y, z]`` - ``K(x, y, z)`` - ``EX`` """ if symbols is not None: return K0.unify_with_symbols(K1, symbols) if K0 == K1: return K0 if K0.is_EX: return K0 if K1.is_EX: return K1 if K0.is_FiniteExtension or K1.is_FiniteExtension: if K1.is_FiniteExtension: K0, K1 = K1, K0 if K1.is_FiniteExtension: # Unifying two extensions. # Try to ensure that K0.unify(K1) == K1.unify(K0) if list(ordered([K0.modulus, K1.modulus]))[1] == K0.modulus: K0, K1 = K1, K0 return K1.set_domain(K0) else: # Drop the generator from other and unify with the base domain K1 = K1.drop(K0.symbol) K1 = K0.domain.unify(K1) return K0.set_domain(K1) if K0.is_Composite or K1.is_Composite: K0_ground = K0.dom if K0.is_Composite else K0 K1_ground = K1.dom if K1.is_Composite else K1 K0_symbols = K0.symbols if K0.is_Composite else () K1_symbols = K1.symbols if K1.is_Composite else () domain = K0_ground.unify(K1_ground) symbols = _unify_gens(K0_symbols, K1_symbols) order = K0.order if K0.is_Composite else K1.order if ((K0.is_FractionField and K1.is_PolynomialRing or K1.is_FractionField and K0.is_PolynomialRing) and (not K0_ground.is_Field or not K1_ground.is_Field) and domain.is_Field and domain.has_assoc_Ring): domain = domain.get_ring() if K0.is_Composite and (not K1.is_Composite or K0.is_FractionField or K1.is_PolynomialRing): cls = K0.__class__ else: cls = K1.__class__ from sympy.polys.domains.old_polynomialring import GlobalPolynomialRing if cls == GlobalPolynomialRing: return cls(domain, symbols) return cls(domain, symbols, order) def mkinexact(cls, K0, K1): prec = max(K0.precision, K1.precision) tol = max(K0.tolerance, K1.tolerance) return cls(prec=prec, tol=tol) if K1.is_ComplexField: K0, K1 = K1, K0 if K0.is_ComplexField: if K1.is_ComplexField or K1.is_RealField: return mkinexact(K0.__class__, K0, K1) else: return K0 if K1.is_RealField: K0, K1 = K1, K0 if K0.is_RealField: if K1.is_RealField: return mkinexact(K0.__class__, K0, K1) elif K1.is_GaussianRing or K1.is_GaussianField: from sympy.polys.domains.complexfield import ComplexField return ComplexField(prec=K0.precision, tol=K0.tolerance) else: return K0 if K1.is_AlgebraicField: K0, K1 = K1, K0 if K0.is_AlgebraicField: if K1.is_GaussianRing: K1 = K1.get_field() if K1.is_GaussianField: K1 = K1.as_AlgebraicField() if K1.is_AlgebraicField: return K0.__class__(K0.dom.unify(K1.dom), *_unify_gens(K0.orig_ext, K1.orig_ext)) else: return K0 if K0.is_GaussianField: return K0 if K1.is_GaussianField: return K1 if K0.is_GaussianRing: if K1.is_RationalField: K0 = K0.get_field() return K0 if K1.is_GaussianRing: if K0.is_RationalField: K1 = K1.get_field() return K1 if K0.is_RationalField: return K0 if K1.is_RationalField: return K1 if K0.is_IntegerRing: return K0 if K1.is_IntegerRing: return K1 if K0.is_FiniteField and K1.is_FiniteField: return K0.__class__(max(K0.mod, K1.mod, key=default_sort_key)) from sympy.polys.domains import EX return EX def __eq__(self, other): """Returns ``True`` if two domains are equivalent. """ return isinstance(other, Domain) and self.dtype == other.dtype def __ne__(self, other): """Returns ``False`` if two domains are equivalent. """ return not self == other def map(self, seq): """Rersively apply ``self`` to all elements of ``seq``. """ result = [] for elt in seq: if isinstance(elt, list): result.append(self.map(elt)) else: result.append(self(elt)) return result def get_ring(self): """Returns a ring associated with ``self``. """ raise DomainError('there is no ring associated with %s' % self) def get_field(self): """Returns a field associated with ``self``. """ raise DomainError('there is no field associated with %s' % self) def get_exact(self): """Returns an exact domain associated with ``self``. """ return self def __getitem__(self, symbols): """The mathematical way to make a polynomial ring. """ if hasattr(symbols, '__iter__'): return self.poly_ring(*symbols) else: return self.poly_ring(symbols) def poly_ring(self, *symbols, order=lex): """Returns a polynomial ring, i.e. `K[X]`. """ from sympy.polys.domains.polynomialring import PolynomialRing return PolynomialRing(self, symbols, order) def frac_field(self, *symbols, order=lex): """Returns a fraction field, i.e. `K(X)`. """ from sympy.polys.domains.fractionfield import FractionField return FractionField(self, symbols, order) def old_poly_ring(self, *symbols, **kwargs): """Returns a polynomial ring, i.e. `K[X]`. """ from sympy.polys.domains.old_polynomialring import PolynomialRing return PolynomialRing(self, *symbols, **kwargs) def old_frac_field(self, *symbols, **kwargs): """Returns a fraction field, i.e. `K(X)`. """ from sympy.polys.domains.old_fractionfield import FractionField return FractionField(self, *symbols, **kwargs) def algebraic_field(self, *extension): r"""Returns an algebraic field, i.e. `K(\alpha, \ldots)`. """ raise DomainError("can't create algebraic field over %s" % self) def inject(self, *symbols): """Inject generators into this domain. """ raise NotImplementedError def drop(self, *symbols): """Drop generators from this domain. """ if self.is_Simple: return self raise NotImplementedError # pragma: no cover def is_zero(self, a): """Returns True if ``a`` is zero. """ return not a def is_one(self, a): """Returns True if ``a`` is one. """ return a == self.one def is_positive(self, a): """Returns True if ``a`` is positive. """ return a > 0 def is_negative(self, a): """Returns True if ``a`` is negative. """ return a < 0 def is_nonpositive(self, a): """Returns True if ``a`` is non-positive. """ return a <= 0 def is_nonnegative(self, a): """Returns True if ``a`` is non-negative. """ return a >= 0 def canonical_unit(self, a): if self.is_negative(a): return -self.one else: return self.one def abs(self, a): """Absolute value of ``a``, implies ``__abs__``. """ return abs(a) def neg(self, a): """Returns ``a`` negated, implies ``__neg__``. """ return -a def pos(self, a): """Returns ``a`` positive, implies ``__pos__``. """ return +a def add(self, a, b): """Sum of ``a`` and ``b``, implies ``__add__``. """ return a + b def sub(self, a, b): """Difference of ``a`` and ``b``, implies ``__sub__``. """ return a - b def mul(self, a, b): """Product of ``a`` and ``b``, implies ``__mul__``. """ return a * b def pow(self, a, b): """Raise ``a`` to power ``b``, implies ``__pow__``. """ return a ** b def exquo(self, a, b): """Exact quotient of *a* and *b*. Analogue of ``a / b``. Explanation =========== This is essentially the same as ``a / b`` except that an error will be raised if the division is inexact (if there is any remainder) and the result will always be a domain element. When working in a :py:class:`~.Domain` that is not a :py:class:`~.Field` (e.g. :ref:`ZZ` or :ref:`K[x]`) ``exquo`` should be used instead of ``/``. The key invariant is that if ``q = K.exquo(a, b)`` (and ``exquo`` does not raise an exception) then ``a == b*q``. Examples ======== We can use ``K.exquo`` instead of ``/`` for exact division. >>> from sympy import ZZ >>> ZZ.exquo(ZZ(4), ZZ(2)) 2 >>> ZZ.exquo(ZZ(5), ZZ(2)) Traceback (most recent call last): ... ExactQuotientFailed: 2 does not divide 5 in ZZ Over a :py:class:`~.Field` such as :ref:`QQ`, division (with nonzero divisor) is always exact so in that case ``/`` can be used instead of :py:meth:`~.Domain.exquo`. >>> from sympy import QQ >>> QQ.exquo(QQ(5), QQ(2)) 5/2 >>> QQ(5) / QQ(2) 5/2 Parameters ========== a: domain element The dividend b: domain element The divisor Returns ======= q: domain element The exact quotient Raises ====== ExactQuotientFailed: if exact division is not possible. ZeroDivisionError: when the divisor is zero. See also ======== quo: Analogue of ``a // b`` rem: Analogue of ``a % b`` div: Analogue of ``divmod(a, b)`` Notes ===== Since the default :py:attr:`~.Domain.dtype` for :ref:`ZZ` is ``int`` (or ``mpz``) division as ``a / b`` should not be used as it would give a ``float``. >>> ZZ(4) / ZZ(2) 2.0 >>> ZZ(5) / ZZ(2) 2.5 Using ``/`` with :ref:`ZZ` will lead to incorrect results so :py:meth:`~.Domain.exquo` should be used instead. """ raise NotImplementedError def quo(self, a, b): """Quotient of *a* and *b*. Analogue of ``a // b``. ``K.quo(a, b)`` is equivalent to ``K.div(a, b)[0]``. See :py:meth:`~.Domain.div` for more explanation. See also ======== rem: Analogue of ``a % b`` div: Analogue of ``divmod(a, b)`` exquo: Analogue of ``a / b`` """ raise NotImplementedError def rem(self, a, b): """Modulo division of *a* and *b*. Analogue of ``a % b``. ``K.rem(a, b)`` is equivalent to ``K.div(a, b)[1]``. See :py:meth:`~.Domain.div` for more explanation. See also ======== quo: Analogue of ``a // b`` div: Analogue of ``divmod(a, b)`` exquo: Analogue of ``a / b`` """ raise NotImplementedError def div(self, a, b): """Quotient and remainder for *a* and *b*. Analogue of ``divmod(a, b)`` Explanation =========== This is essentially the same as ``divmod(a, b)`` except that is more consistent when working over some :py:class:`~.Field` domains such as :ref:`QQ`. When working over an arbitrary :py:class:`~.Domain` the :py:meth:`~.Domain.div` method should be used instead of ``divmod``. The key invariant is that if ``q, r = K.div(a, b)`` then ``a == b*q + r``. The result of ``K.div(a, b)`` is the same as the tuple ``(K.quo(a, b), K.rem(a, b))`` except that if both quotient and remainder are needed then it is more efficient to use :py:meth:`~.Domain.div`. Examples ======== We can use ``K.div`` instead of ``divmod`` for floor division and remainder. >>> from sympy import ZZ, QQ >>> ZZ.div(ZZ(5), ZZ(2)) (2, 1) If ``K`` is a :py:class:`~.Field` then the division is always exact with a remainder of :py:attr:`~.Domain.zero`. >>> QQ.div(QQ(5), QQ(2)) (5/2, 0) Parameters ========== a: domain element The dividend b: domain element The divisor Returns ======= (q, r): tuple of domain elements The quotient and remainder Raises ====== ZeroDivisionError: when the divisor is zero. See also ======== quo: Analogue of ``a // b`` rem: Analogue of ``a % b`` exquo: Analogue of ``a / b`` Notes ===== If ``gmpy`` is installed then the ``gmpy.mpq`` type will be used as the :py:attr:`~.Domain.dtype` for :ref:`QQ`. The ``gmpy.mpq`` type defines ``divmod`` in a way that is undesirable so :py:meth:`~.Domain.div` should be used instead of ``divmod``. >>> a = QQ(1) >>> b = QQ(3, 2) >>> a # doctest: +SKIP mpq(1,1) >>> b # doctest: +SKIP mpq(3,2) >>> divmod(a, b) # doctest: +SKIP (mpz(0), mpq(1,1)) >>> QQ.div(a, b) # doctest: +SKIP (mpq(2,3), mpq(0,1)) Using ``//`` or ``%`` with :ref:`QQ` will lead to incorrect results so :py:meth:`~.Domain.div` should be used instead. """ raise NotImplementedError def invert(self, a, b): """Returns inversion of ``a mod b``, implies something. """ raise NotImplementedError def revert(self, a): """Returns ``a**(-1)`` if possible. """ raise NotImplementedError def numer(self, a): """Returns numerator of ``a``. """ raise NotImplementedError def denom(self, a): """Returns denominator of ``a``. """ raise NotImplementedError def half_gcdex(self, a, b): """Half extended GCD of ``a`` and ``b``. """ s, t, h = self.gcdex(a, b) return s, h def gcdex(self, a, b): """Extended GCD of ``a`` and ``b``. """ raise NotImplementedError def cofactors(self, a, b): """Returns GCD and cofactors of ``a`` and ``b``. """ gcd = self.gcd(a, b) cfa = self.quo(a, gcd) cfb = self.quo(b, gcd) return gcd, cfa, cfb def gcd(self, a, b): """Returns GCD of ``a`` and ``b``. """ raise NotImplementedError def lcm(self, a, b): """Returns LCM of ``a`` and ``b``. """ raise NotImplementedError def log(self, a, b): """Returns b-base logarithm of ``a``. """ raise NotImplementedError def sqrt(self, a): """Returns square root of ``a``. """ raise NotImplementedError def evalf(self, a, prec=None, **options): """Returns numerical approximation of ``a``. """ return self.to_sympy(a).evalf(prec, **options) n = evalf def real(self, a): return a def imag(self, a): return self.zero def almosteq(self, a, b, tolerance=None): """Check if ``a`` and ``b`` are almost equal. """ return a == b def characteristic(self): """Return the characteristic of this domain. """ raise NotImplementedError('characteristic()') __all__ = ['Domain']
362c97c49bcc9fc873a0d0f509fea6bc747651ce7fe5222909797d8351392e35
"""Tests for the implementation of RootOf class and related tools. """ from sympy.polys.polytools import Poly from sympy.polys.rootoftools import (rootof, RootOf, CRootOf, RootSum, _pure_key_dict as D) from sympy.polys.polyerrors import ( MultivariatePolynomialError, GeneratorsNeeded, PolynomialError, ) from sympy import ( S, sqrt, I, Rational, Float, Lambda, log, exp, tan, Function, Eq, solve, legendre_poly, Integral ) from sympy.testing.pytest import raises, slow from sympy.core.expr import unchanged from sympy.abc import a, b, x, y, z, r def test_CRootOf___new__(): assert rootof(x, 0) == 0 assert rootof(x, -1) == 0 assert rootof(x, S.Zero) == 0 assert rootof(x - 1, 0) == 1 assert rootof(x - 1, -1) == 1 assert rootof(x + 1, 0) == -1 assert rootof(x + 1, -1) == -1 assert rootof(x**2 + 2*x + 3, 0) == -1 - I*sqrt(2) assert rootof(x**2 + 2*x + 3, 1) == -1 + I*sqrt(2) assert rootof(x**2 + 2*x + 3, -1) == -1 + I*sqrt(2) assert rootof(x**2 + 2*x + 3, -2) == -1 - I*sqrt(2) r = rootof(x**2 + 2*x + 3, 0, radicals=False) assert isinstance(r, RootOf) is True r = rootof(x**2 + 2*x + 3, 1, radicals=False) assert isinstance(r, RootOf) is True r = rootof(x**2 + 2*x + 3, -1, radicals=False) assert isinstance(r, RootOf) is True r = rootof(x**2 + 2*x + 3, -2, radicals=False) assert isinstance(r, RootOf) is True assert rootof((x - 1)*(x + 1), 0, radicals=False) == -1 assert rootof((x - 1)*(x + 1), 1, radicals=False) == 1 assert rootof((x - 1)*(x + 1), -1, radicals=False) == 1 assert rootof((x - 1)*(x + 1), -2, radicals=False) == -1 assert rootof((x - 1)*(x + 1), 0, radicals=True) == -1 assert rootof((x - 1)*(x + 1), 1, radicals=True) == 1 assert rootof((x - 1)*(x + 1), -1, radicals=True) == 1 assert rootof((x - 1)*(x + 1), -2, radicals=True) == -1 assert rootof((x - 1)*(x**3 + x + 3), 0) == rootof(x**3 + x + 3, 0) assert rootof((x - 1)*(x**3 + x + 3), 1) == 1 assert rootof((x - 1)*(x**3 + x + 3), 2) == rootof(x**3 + x + 3, 1) assert rootof((x - 1)*(x**3 + x + 3), 3) == rootof(x**3 + x + 3, 2) assert rootof((x - 1)*(x**3 + x + 3), -1) == rootof(x**3 + x + 3, 2) assert rootof((x - 1)*(x**3 + x + 3), -2) == rootof(x**3 + x + 3, 1) assert rootof((x - 1)*(x**3 + x + 3), -3) == 1 assert rootof((x - 1)*(x**3 + x + 3), -4) == rootof(x**3 + x + 3, 0) assert rootof(x**4 + 3*x**3, 0) == -3 assert rootof(x**4 + 3*x**3, 1) == 0 assert rootof(x**4 + 3*x**3, 2) == 0 assert rootof(x**4 + 3*x**3, 3) == 0 raises(GeneratorsNeeded, lambda: rootof(0, 0)) raises(GeneratorsNeeded, lambda: rootof(1, 0)) raises(PolynomialError, lambda: rootof(Poly(0, x), 0)) raises(PolynomialError, lambda: rootof(Poly(1, x), 0)) raises(PolynomialError, lambda: rootof(x - y, 0)) # issue 8617 raises(PolynomialError, lambda: rootof(exp(x), 0)) raises(NotImplementedError, lambda: rootof(x**3 - x + sqrt(2), 0)) raises(NotImplementedError, lambda: rootof(x**3 - x + I, 0)) raises(IndexError, lambda: rootof(x**2 - 1, -4)) raises(IndexError, lambda: rootof(x**2 - 1, -3)) raises(IndexError, lambda: rootof(x**2 - 1, 2)) raises(IndexError, lambda: rootof(x**2 - 1, 3)) raises(ValueError, lambda: rootof(x**2 - 1, x)) assert rootof(Poly(x - y, x), 0) == y assert rootof(Poly(x**2 - y, x), 0) == -sqrt(y) assert rootof(Poly(x**2 - y, x), 1) == sqrt(y) assert rootof(Poly(x**3 - y, x), 0) == y**Rational(1, 3) assert rootof(y*x**3 + y*x + 2*y, x, 0) == -1 raises(NotImplementedError, lambda: rootof(x**3 + x + 2*y, x, 0)) assert rootof(x**3 + x + 1, 0).is_commutative is True def test_CRootOf_attributes(): r = rootof(x**3 + x + 3, 0) assert r.is_number assert r.free_symbols == set() # if the following assertion fails then multivariate polynomials # are apparently supported and the RootOf.free_symbols routine # should be changed to return whatever symbols would not be # the PurePoly dummy symbol raises(NotImplementedError, lambda: rootof(Poly(x**3 + y*x + 1, x), 0)) def test_CRootOf___eq__(): assert (rootof(x**3 + x + 3, 0) == rootof(x**3 + x + 3, 0)) is True assert (rootof(x**3 + x + 3, 0) == rootof(x**3 + x + 3, 1)) is False assert (rootof(x**3 + x + 3, 1) == rootof(x**3 + x + 3, 1)) is True assert (rootof(x**3 + x + 3, 1) == rootof(x**3 + x + 3, 2)) is False assert (rootof(x**3 + x + 3, 2) == rootof(x**3 + x + 3, 2)) is True assert (rootof(x**3 + x + 3, 0) == rootof(y**3 + y + 3, 0)) is True assert (rootof(x**3 + x + 3, 0) == rootof(y**3 + y + 3, 1)) is False assert (rootof(x**3 + x + 3, 1) == rootof(y**3 + y + 3, 1)) is True assert (rootof(x**3 + x + 3, 1) == rootof(y**3 + y + 3, 2)) is False assert (rootof(x**3 + x + 3, 2) == rootof(y**3 + y + 3, 2)) is True def test_CRootOf___eval_Eq__(): f = Function('f') eq = x**3 + x + 3 r = rootof(eq, 2) r1 = rootof(eq, 1) assert Eq(r, r1) is S.false assert Eq(r, r) is S.true assert unchanged(Eq, r, x) assert Eq(r, 0) is S.false assert Eq(r, S.Infinity) is S.false assert Eq(r, I) is S.false assert unchanged(Eq, r, f(0)) sol = solve(eq) for s in sol: if s.is_real: assert Eq(r, s) is S.false r = rootof(eq, 0) for s in sol: if s.is_real: assert Eq(r, s) is S.true eq = x**3 + x + 1 sol = solve(eq) assert [Eq(rootof(eq, i), j) for i in range(3) for j in sol] == [ False, False, True, False, True, False, True, False, False] assert Eq(rootof(eq, 0), 1 + S.ImaginaryUnit) == False def test_CRootOf_is_real(): assert rootof(x**3 + x + 3, 0).is_real is True assert rootof(x**3 + x + 3, 1).is_real is False assert rootof(x**3 + x + 3, 2).is_real is False def test_CRootOf_is_complex(): assert rootof(x**3 + x + 3, 0).is_complex is True def test_CRootOf_subs(): assert rootof(x**3 + x + 1, 0).subs(x, y) == rootof(y**3 + y + 1, 0) def test_CRootOf_diff(): assert rootof(x**3 + x + 1, 0).diff(x) == 0 assert rootof(x**3 + x + 1, 0).diff(y) == 0 @slow def test_CRootOf_evalf(): real = rootof(x**3 + x + 3, 0).evalf(n=20) assert real.epsilon_eq(Float("-1.2134116627622296341")) re, im = rootof(x**3 + x + 3, 1).evalf(n=20).as_real_imag() assert re.epsilon_eq( Float("0.60670583138111481707")) assert im.epsilon_eq(-Float("1.45061224918844152650")) re, im = rootof(x**3 + x + 3, 2).evalf(n=20).as_real_imag() assert re.epsilon_eq(Float("0.60670583138111481707")) assert im.epsilon_eq(Float("1.45061224918844152650")) p = legendre_poly(4, x, polys=True) roots = [str(r.n(17)) for r in p.real_roots()] # magnitudes are given by # sqrt(3/S(7) - 2*sqrt(6/S(5))/7) # and # sqrt(3/S(7) + 2*sqrt(6/S(5))/7) assert roots == [ "-0.86113631159405258", "-0.33998104358485626", "0.33998104358485626", "0.86113631159405258", ] re = rootof(x**5 - 5*x + 12, 0).evalf(n=20) assert re.epsilon_eq(Float("-1.84208596619025438271")) re, im = rootof(x**5 - 5*x + 12, 1).evalf(n=20).as_real_imag() assert re.epsilon_eq(Float("-0.351854240827371999559")) assert im.epsilon_eq(Float("-1.709561043370328882010")) re, im = rootof(x**5 - 5*x + 12, 2).evalf(n=20).as_real_imag() assert re.epsilon_eq(Float("-0.351854240827371999559")) assert im.epsilon_eq(Float("+1.709561043370328882010")) re, im = rootof(x**5 - 5*x + 12, 3).evalf(n=20).as_real_imag() assert re.epsilon_eq(Float("+1.272897223922499190910")) assert im.epsilon_eq(Float("-0.719798681483861386681")) re, im = rootof(x**5 - 5*x + 12, 4).evalf(n=20).as_real_imag() assert re.epsilon_eq(Float("+1.272897223922499190910")) assert im.epsilon_eq(Float("+0.719798681483861386681")) # issue 6393 assert str(rootof(x**5 + 2*x**4 + x**3 - 68719476736, 0).n(3)) == '147.' eq = (531441*x**11 + 3857868*x**10 + 13730229*x**9 + 32597882*x**8 + 55077472*x**7 + 60452000*x**6 + 32172064*x**5 - 4383808*x**4 - 11942912*x**3 - 1506304*x**2 + 1453312*x + 512) a, b = rootof(eq, 1).n(2).as_real_imag() c, d = rootof(eq, 2).n(2).as_real_imag() assert a == c assert b < d assert b == -d # issue 6451 r = rootof(legendre_poly(64, x), 7) assert r.n(2) == r.n(100).n(2) # issue 9019 r0 = rootof(x**2 + 1, 0, radicals=False) r1 = rootof(x**2 + 1, 1, radicals=False) assert r0.n(4) == -1.0*I assert r1.n(4) == 1.0*I # make sure verification is used in case a max/min traps the "root" assert str(rootof(4*x**5 + 16*x**3 + 12*x**2 + 7, 0).n(3)) == '-0.976' # watch out for UnboundLocalError c = CRootOf(90720*x**6 - 4032*x**4 + 84*x**2 - 1, 0) assert c._eval_evalf(2) # doesn't fail # watch out for imaginary parts that don't want to evaluate assert str(RootOf(x**16 + 32*x**14 + 508*x**12 + 5440*x**10 + 39510*x**8 + 204320*x**6 + 755548*x**4 + 1434496*x**2 + 877969, 10).n(2)) == '-3.4*I' assert abs(RootOf(x**4 + 10*x**2 + 1, 0).n(2)) < 0.4 # check reset and args r = [RootOf(x**3 + x + 3, i) for i in range(3)] r[0]._reset() for ri in r: i = ri._get_interval() ri.n(2) assert i != ri._get_interval() ri._reset() assert i == ri._get_interval() assert i == i.func(*i.args) def test_CRootOf_evalf_caching_bug(): r = rootof(x**5 - 5*x + 12, 1) r.n() a = r._get_interval() r = rootof(x**5 - 5*x + 12, 1) r.n() b = r._get_interval() assert a == b def test_CRootOf_real_roots(): assert Poly(x**5 + x + 1).real_roots() == [rootof(x**3 - x**2 + 1, 0)] assert Poly(x**5 + x + 1).real_roots(radicals=False) == [rootof( x**3 - x**2 + 1, 0)] # https://github.com/sympy/sympy/issues/20902 p = Poly(-3*x**4 - 10*x**3 - 12*x**2 - 6*x - 1, x, domain='ZZ') assert CRootOf.real_roots(p) == [S(-1), S(-1), S(-1), S(-1)/3] def test_CRootOf_all_roots(): assert Poly(x**5 + x + 1).all_roots() == [ rootof(x**3 - x**2 + 1, 0), Rational(-1, 2) - sqrt(3)*I/2, Rational(-1, 2) + sqrt(3)*I/2, rootof(x**3 - x**2 + 1, 1), rootof(x**3 - x**2 + 1, 2), ] assert Poly(x**5 + x + 1).all_roots(radicals=False) == [ rootof(x**3 - x**2 + 1, 0), rootof(x**2 + x + 1, 0, radicals=False), rootof(x**2 + x + 1, 1, radicals=False), rootof(x**3 - x**2 + 1, 1), rootof(x**3 - x**2 + 1, 2), ] def test_CRootOf_eval_rational(): p = legendre_poly(4, x, polys=True) roots = [r.eval_rational(n=18) for r in p.real_roots()] for root in roots: assert isinstance(root, Rational) roots = [str(root.n(17)) for root in roots] assert roots == [ "-0.86113631159405258", "-0.33998104358485626", "0.33998104358485626", "0.86113631159405258", ] def test_RootSum___new__(): f = x**3 + x + 3 g = Lambda(r, log(r*x)) s = RootSum(f, g) assert isinstance(s, RootSum) is True assert RootSum(f**2, g) == 2*RootSum(f, g) assert RootSum((x - 7)*f**3, g) == log(7*x) + 3*RootSum(f, g) # issue 5571 assert hash(RootSum((x - 7)*f**3, g)) == hash(log(7*x) + 3*RootSum(f, g)) raises(MultivariatePolynomialError, lambda: RootSum(x**3 + x + y)) raises(ValueError, lambda: RootSum(x**2 + 3, lambda x: x)) assert RootSum(f, exp) == RootSum(f, Lambda(x, exp(x))) assert RootSum(f, log) == RootSum(f, Lambda(x, log(x))) assert isinstance(RootSum(f, auto=False), RootSum) is True assert RootSum(f) == 0 assert RootSum(f, Lambda(x, x)) == 0 assert RootSum(f, Lambda(x, x**2)) == -2 assert RootSum(f, Lambda(x, 1)) == 3 assert RootSum(f, Lambda(x, 2)) == 6 assert RootSum(f, auto=False).is_commutative is True assert RootSum(f, Lambda(x, 1/(x + x**2))) == Rational(11, 3) assert RootSum(f, Lambda(x, y/(x + x**2))) == Rational(11, 3)*y assert RootSum(x**2 - 1, Lambda(x, 3*x**2), x) == 6 assert RootSum(x**2 - y, Lambda(x, 3*x**2), x) == 6*y assert RootSum(x**2 - 1, Lambda(x, z*x**2), x) == 2*z assert RootSum(x**2 - y, Lambda(x, z*x**2), x) == 2*z*y assert RootSum( x**2 - 1, Lambda(x, exp(x)), quadratic=True) == exp(-1) + exp(1) assert RootSum(x**3 + a*x + a**3, tan, x) == \ RootSum(x**3 + x + 1, Lambda(x, tan(a*x))) assert RootSum(a**3*x**3 + a*x + 1, tan, x) == \ RootSum(x**3 + x + 1, Lambda(x, tan(x/a))) def test_RootSum_free_symbols(): assert RootSum(x**3 + x + 3, Lambda(r, exp(r))).free_symbols == set() assert RootSum(x**3 + x + 3, Lambda(r, exp(a*r))).free_symbols == {a} assert RootSum( x**3 + x + y, Lambda(r, exp(a*r)), x).free_symbols == {a, y} def test_RootSum___eq__(): f = Lambda(x, exp(x)) assert (RootSum(x**3 + x + 1, f) == RootSum(x**3 + x + 1, f)) is True assert (RootSum(x**3 + x + 1, f) == RootSum(y**3 + y + 1, f)) is True assert (RootSum(x**3 + x + 1, f) == RootSum(x**3 + x + 2, f)) is False assert (RootSum(x**3 + x + 1, f) == RootSum(y**3 + y + 2, f)) is False def test_RootSum_doit(): rs = RootSum(x**2 + 1, exp) assert isinstance(rs, RootSum) is True assert rs.doit() == exp(-I) + exp(I) rs = RootSum(x**2 + a, exp, x) assert isinstance(rs, RootSum) is True assert rs.doit() == exp(-sqrt(-a)) + exp(sqrt(-a)) def test_RootSum_evalf(): rs = RootSum(x**2 + 1, exp) assert rs.evalf(n=20, chop=True).epsilon_eq(Float("1.0806046117362794348")) assert rs.evalf(n=15, chop=True).epsilon_eq(Float("1.08060461173628")) rs = RootSum(x**2 + a, exp, x) assert rs.evalf() == rs def test_RootSum_diff(): f = x**3 + x + 3 g = Lambda(r, exp(r*x)) h = Lambda(r, r*exp(r*x)) assert RootSum(f, g).diff(x) == RootSum(f, h) def test_RootSum_subs(): f = x**3 + x + 3 g = Lambda(r, exp(r*x)) F = y**3 + y + 3 G = Lambda(r, exp(r*y)) assert RootSum(f, g).subs(y, 1) == RootSum(f, g) assert RootSum(f, g).subs(x, y) == RootSum(F, G) def test_RootSum_rational(): assert RootSum( z**5 - z + 1, Lambda(z, z/(x - z))) == (4*x - 5)/(x**5 - x + 1) f = 161*z**3 + 115*z**2 + 19*z + 1 g = Lambda(z, z*log( -3381*z**4/4 - 3381*z**3/4 - 625*z**2/2 - z*Rational(125, 2) - 5 + exp(x))) assert RootSum(f, g).diff(x) == -( (5*exp(2*x) - 6*exp(x) + 4)*exp(x)/(exp(3*x) - exp(2*x) + 1))/7 def test_RootSum_independent(): f = (x**3 - a)**2*(x**4 - b)**3 g = Lambda(x, 5*tan(x) + 7) h = Lambda(x, tan(x)) r0 = RootSum(x**3 - a, h, x) r1 = RootSum(x**4 - b, h, x) assert RootSum(f, g, x).as_ordered_terms() == [10*r0, 15*r1, 126] def test_issue_7876(): l1 = Poly(x**6 - x + 1, x).all_roots() l2 = [rootof(x**6 - x + 1, i) for i in range(6)] assert frozenset(l1) == frozenset(l2) def test_issue_8316(): f = Poly(7*x**8 - 9) assert len(f.all_roots()) == 8 f = Poly(7*x**8 - 10) assert len(f.all_roots()) == 8 def test__imag_count(): from sympy.polys.rootoftools import _imag_count_of_factor def imag_count(p): return sum([_imag_count_of_factor(f)*m for f, m in p.factor_list()[1]]) assert imag_count(Poly(x**6 + 10*x**2 + 1)) == 2 assert imag_count(Poly(x**2)) == 0 assert imag_count(Poly([1]*3 + [-1], x)) == 0 assert imag_count(Poly(x**3 + 1)) == 0 assert imag_count(Poly(x**2 + 1)) == 2 assert imag_count(Poly(x**2 - 1)) == 0 assert imag_count(Poly(x**4 - 1)) == 2 assert imag_count(Poly(x**4 + 1)) == 0 assert imag_count(Poly([1, 2, 3], x)) == 0 assert imag_count(Poly(x**3 + x + 1)) == 0 assert imag_count(Poly(x**4 + x + 1)) == 0 def q(r1, r2, p): return Poly(((x - r1)*(x - r2)).subs(x, x**p), x) assert imag_count(q(-1, -2, 2)) == 4 assert imag_count(q(-1, 2, 2)) == 2 assert imag_count(q(1, 2, 2)) == 0 assert imag_count(q(1, 2, 4)) == 4 assert imag_count(q(-1, 2, 4)) == 2 assert imag_count(q(-1, -2, 4)) == 0 def test_RootOf_is_imaginary(): r = RootOf(x**4 + 4*x**2 + 1, 1) i = r._get_interval() assert r.is_imaginary and i.ax*i.bx <= 0 def test_is_disjoint(): eq = x**3 + 5*x + 1 ir = rootof(eq, 0)._get_interval() ii = rootof(eq, 1)._get_interval() assert ir.is_disjoint(ii) assert ii.is_disjoint(ir) def test_pure_key_dict(): p = D() assert (x in p) is False assert (1 in p) is False p[x] = 1 assert x in p assert y in p assert p[y] == 1 raises(KeyError, lambda: p[1]) def dont(k): p[k] = 2 raises(ValueError, lambda: dont(1)) @slow def test_eval_approx_relative(): CRootOf.clear_cache() t = [CRootOf(x**3 + 10*x + 1, i) for i in range(3)] assert [i.eval_rational(1e-1) for i in t] == [ Rational(-21, 220), Rational(15, 256) - I*Rational(805, 256), Rational(15, 256) + I*Rational(805, 256)] t[0]._reset() assert [i.eval_rational(1e-1, 1e-4) for i in t] == [ Rational(-21, 220), Rational(3275, 65536) - I*Rational(414645, 131072), Rational(3275, 65536) + I*Rational(414645, 131072)] assert S(t[0]._get_interval().dx) < 1e-1 assert S(t[1]._get_interval().dx) < 1e-1 assert S(t[1]._get_interval().dy) < 1e-4 assert S(t[2]._get_interval().dx) < 1e-1 assert S(t[2]._get_interval().dy) < 1e-4 t[0]._reset() assert [i.eval_rational(1e-4, 1e-4) for i in t] == [ Rational(-2001, 20020), Rational(6545, 131072) - I*Rational(414645, 131072), Rational(6545, 131072) + I*Rational(414645, 131072)] assert S(t[0]._get_interval().dx) < 1e-4 assert S(t[1]._get_interval().dx) < 1e-4 assert S(t[1]._get_interval().dy) < 1e-4 assert S(t[2]._get_interval().dx) < 1e-4 assert S(t[2]._get_interval().dy) < 1e-4 # in the following, the actual relative precision is # less than tested, but it should never be greater t[0]._reset() assert [i.eval_rational(n=2) for i in t] == [ Rational(-202201, 2024022), Rational(104755, 2097152) - I*Rational(6634255, 2097152), Rational(104755, 2097152) + I*Rational(6634255, 2097152)] assert abs(S(t[0]._get_interval().dx)/t[0]) < 1e-2 assert abs(S(t[1]._get_interval().dx)/t[1]).n() < 1e-2 assert abs(S(t[1]._get_interval().dy)/t[1]).n() < 1e-2 assert abs(S(t[2]._get_interval().dx)/t[2]).n() < 1e-2 assert abs(S(t[2]._get_interval().dy)/t[2]).n() < 1e-2 t[0]._reset() assert [i.eval_rational(n=3) for i in t] == [ Rational(-202201, 2024022), Rational(1676045, 33554432) - I*Rational(106148135, 33554432), Rational(1676045, 33554432) + I*Rational(106148135, 33554432)] assert abs(S(t[0]._get_interval().dx)/t[0]) < 1e-3 assert abs(S(t[1]._get_interval().dx)/t[1]).n() < 1e-3 assert abs(S(t[1]._get_interval().dy)/t[1]).n() < 1e-3 assert abs(S(t[2]._get_interval().dx)/t[2]).n() < 1e-3 assert abs(S(t[2]._get_interval().dy)/t[2]).n() < 1e-3 t[0]._reset() a = [i.eval_approx(2) for i in t] assert [str(i) for i in a] == [ '-0.10', '0.05 - 3.2*I', '0.05 + 3.2*I'] assert all(abs(((a[i] - t[i])/t[i]).n()) < 1e-2 for i in range(len(a))) def test_issue_15920(): r = rootof(x**5 - x + 1, 0) p = Integral(x, (x, 1, y)) assert unchanged(Eq, r, p) def test_issue_19113(): eq = y**3 - y + 1 # generator is a canonical x in RootOf assert str(Poly(eq).real_roots()) == '[CRootOf(x**3 - x + 1, 0)]' assert str(Poly(eq.subs(y, tan(y))).real_roots() ) == '[CRootOf(x**3 - x + 1, 0)]' assert str(Poly(eq.subs(y, tan(x))).real_roots() ) == '[CRootOf(x**3 - x + 1, 0)]'
c0d182603659e0bea6d4748f157f72a71503e754796730345e39ea25db4ee171
"""Tests for user-friendly public interface to polynomial functions. """ import pickle from sympy.polys.polytools import ( Poly, PurePoly, poly, parallel_poly_from_expr, degree, degree_list, total_degree, LC, LM, LT, pdiv, prem, pquo, pexquo, div, rem, quo, exquo, half_gcdex, gcdex, invert, subresultants, resultant, discriminant, terms_gcd, cofactors, gcd, gcd_list, lcm, lcm_list, trunc, monic, content, primitive, compose, decompose, sturm, gff_list, gff, sqf_norm, sqf_part, sqf_list, sqf, factor_list, factor, intervals, refine_root, count_roots, real_roots, nroots, ground_roots, nth_power_roots_poly, cancel, reduced, groebner, GroebnerBasis, is_zero_dimensional, _torational_factor_list, to_rational_coeffs) from sympy.polys.polyerrors import ( MultivariatePolynomialError, ExactQuotientFailed, PolificationFailed, ComputationFailed, UnificationFailed, RefinementFailed, GeneratorsNeeded, GeneratorsError, PolynomialError, CoercionFailed, DomainError, OptionError, FlagError) from sympy.polys.polyclasses import DMP from sympy.polys.fields import field from sympy.polys.domains import FF, ZZ, QQ, ZZ_I, QQ_I, RR, EX from sympy.polys.domains.realfield import RealField from sympy.polys.orderings import lex, grlex, grevlex from sympy import ( S, Integer, Rational, Float, Mul, Symbol, sqrt, Piecewise, Derivative, exp, sin, tanh, expand, oo, I, pi, re, im, rootof, Eq, Tuple, Expr, diff) from sympy.core.basic import _aresame from sympy.core.compatibility import iterable from sympy.core.mul import _keep_coeff from sympy.testing.pytest import raises, warns_deprecated_sympy from sympy.abc import a, b, c, d, p, q, t, w, x, y, z from sympy import MatrixSymbol, Matrix def _epsilon_eq(a, b): for u, v in zip(a, b): if abs(u - v) > 1e-10: return False return True def _strict_eq(a, b): if type(a) == type(b): if iterable(a): if len(a) == len(b): return all(_strict_eq(c, d) for c, d in zip(a, b)) else: return False else: return isinstance(a, Poly) and a.eq(b, strict=True) else: return False def test_Poly_mixed_operations(): p = Poly(x, x) with warns_deprecated_sympy(): p * exp(x) with warns_deprecated_sympy(): p + exp(x) with warns_deprecated_sympy(): p - exp(x) def test_Poly_from_dict(): K = FF(3) assert Poly.from_dict( {0: 1, 1: 2}, gens=x, domain=K).rep == DMP([K(2), K(1)], K) assert Poly.from_dict( {0: 1, 1: 5}, gens=x, domain=K).rep == DMP([K(2), K(1)], K) assert Poly.from_dict( {(0,): 1, (1,): 2}, gens=x, domain=K).rep == DMP([K(2), K(1)], K) assert Poly.from_dict( {(0,): 1, (1,): 5}, gens=x, domain=K).rep == DMP([K(2), K(1)], K) assert Poly.from_dict({(0, 0): 1, (1, 1): 2}, gens=( x, y), domain=K).rep == DMP([[K(2), K(0)], [K(1)]], K) assert Poly.from_dict({0: 1, 1: 2}, gens=x).rep == DMP([ZZ(2), ZZ(1)], ZZ) assert Poly.from_dict( {0: 1, 1: 2}, gens=x, field=True).rep == DMP([QQ(2), QQ(1)], QQ) assert Poly.from_dict( {0: 1, 1: 2}, gens=x, domain=ZZ).rep == DMP([ZZ(2), ZZ(1)], ZZ) assert Poly.from_dict( {0: 1, 1: 2}, gens=x, domain=QQ).rep == DMP([QQ(2), QQ(1)], QQ) assert Poly.from_dict( {(0,): 1, (1,): 2}, gens=x).rep == DMP([ZZ(2), ZZ(1)], ZZ) assert Poly.from_dict( {(0,): 1, (1,): 2}, gens=x, field=True).rep == DMP([QQ(2), QQ(1)], QQ) assert Poly.from_dict( {(0,): 1, (1,): 2}, gens=x, domain=ZZ).rep == DMP([ZZ(2), ZZ(1)], ZZ) assert Poly.from_dict( {(0,): 1, (1,): 2}, gens=x, domain=QQ).rep == DMP([QQ(2), QQ(1)], QQ) assert Poly.from_dict({(1,): sin(y)}, gens=x, composite=False) == \ Poly(sin(y)*x, x, domain='EX') assert Poly.from_dict({(1,): y}, gens=x, composite=False) == \ Poly(y*x, x, domain='EX') assert Poly.from_dict({(1, 1): 1}, gens=(x, y), composite=False) == \ Poly(x*y, x, y, domain='ZZ') assert Poly.from_dict({(1, 0): y}, gens=(x, z), composite=False) == \ Poly(y*x, x, z, domain='EX') def test_Poly_from_list(): K = FF(3) assert Poly.from_list([2, 1], gens=x, domain=K).rep == DMP([K(2), K(1)], K) assert Poly.from_list([5, 1], gens=x, domain=K).rep == DMP([K(2), K(1)], K) assert Poly.from_list([2, 1], gens=x).rep == DMP([ZZ(2), ZZ(1)], ZZ) assert Poly.from_list([2, 1], gens=x, field=True).rep == DMP([QQ(2), QQ(1)], QQ) assert Poly.from_list([2, 1], gens=x, domain=ZZ).rep == DMP([ZZ(2), ZZ(1)], ZZ) assert Poly.from_list([2, 1], gens=x, domain=QQ).rep == DMP([QQ(2), QQ(1)], QQ) assert Poly.from_list([0, 1.0], gens=x).rep == DMP([RR(1.0)], RR) assert Poly.from_list([1.0, 0], gens=x).rep == DMP([RR(1.0), RR(0.0)], RR) raises(MultivariatePolynomialError, lambda: Poly.from_list([[]], gens=(x, y))) def test_Poly_from_poly(): f = Poly(x + 7, x, domain=ZZ) g = Poly(x + 2, x, modulus=3) h = Poly(x + y, x, y, domain=ZZ) K = FF(3) assert Poly.from_poly(f) == f assert Poly.from_poly(f, domain=K).rep == DMP([K(1), K(1)], K) assert Poly.from_poly(f, domain=ZZ).rep == DMP([1, 7], ZZ) assert Poly.from_poly(f, domain=QQ).rep == DMP([1, 7], QQ) assert Poly.from_poly(f, gens=x) == f assert Poly.from_poly(f, gens=x, domain=K).rep == DMP([K(1), K(1)], K) assert Poly.from_poly(f, gens=x, domain=ZZ).rep == DMP([1, 7], ZZ) assert Poly.from_poly(f, gens=x, domain=QQ).rep == DMP([1, 7], QQ) assert Poly.from_poly(f, gens=y) == Poly(x + 7, y, domain='ZZ[x]') raises(CoercionFailed, lambda: Poly.from_poly(f, gens=y, domain=K)) raises(CoercionFailed, lambda: Poly.from_poly(f, gens=y, domain=ZZ)) raises(CoercionFailed, lambda: Poly.from_poly(f, gens=y, domain=QQ)) assert Poly.from_poly(f, gens=(x, y)) == Poly(x + 7, x, y, domain='ZZ') assert Poly.from_poly( f, gens=(x, y), domain=ZZ) == Poly(x + 7, x, y, domain='ZZ') assert Poly.from_poly( f, gens=(x, y), domain=QQ) == Poly(x + 7, x, y, domain='QQ') assert Poly.from_poly( f, gens=(x, y), modulus=3) == Poly(x + 7, x, y, domain='FF(3)') K = FF(2) assert Poly.from_poly(g) == g assert Poly.from_poly(g, domain=ZZ).rep == DMP([1, -1], ZZ) raises(CoercionFailed, lambda: Poly.from_poly(g, domain=QQ)) assert Poly.from_poly(g, domain=K).rep == DMP([K(1), K(0)], K) assert Poly.from_poly(g, gens=x) == g assert Poly.from_poly(g, gens=x, domain=ZZ).rep == DMP([1, -1], ZZ) raises(CoercionFailed, lambda: Poly.from_poly(g, gens=x, domain=QQ)) assert Poly.from_poly(g, gens=x, domain=K).rep == DMP([K(1), K(0)], K) K = FF(3) assert Poly.from_poly(h) == h assert Poly.from_poly( h, domain=ZZ).rep == DMP([[ZZ(1)], [ZZ(1), ZZ(0)]], ZZ) assert Poly.from_poly( h, domain=QQ).rep == DMP([[QQ(1)], [QQ(1), QQ(0)]], QQ) assert Poly.from_poly(h, domain=K).rep == DMP([[K(1)], [K(1), K(0)]], K) assert Poly.from_poly(h, gens=x) == Poly(x + y, x, domain=ZZ[y]) raises(CoercionFailed, lambda: Poly.from_poly(h, gens=x, domain=ZZ)) assert Poly.from_poly( h, gens=x, domain=ZZ[y]) == Poly(x + y, x, domain=ZZ[y]) raises(CoercionFailed, lambda: Poly.from_poly(h, gens=x, domain=QQ)) assert Poly.from_poly( h, gens=x, domain=QQ[y]) == Poly(x + y, x, domain=QQ[y]) raises(CoercionFailed, lambda: Poly.from_poly(h, gens=x, modulus=3)) assert Poly.from_poly(h, gens=y) == Poly(x + y, y, domain=ZZ[x]) raises(CoercionFailed, lambda: Poly.from_poly(h, gens=y, domain=ZZ)) assert Poly.from_poly( h, gens=y, domain=ZZ[x]) == Poly(x + y, y, domain=ZZ[x]) raises(CoercionFailed, lambda: Poly.from_poly(h, gens=y, domain=QQ)) assert Poly.from_poly( h, gens=y, domain=QQ[x]) == Poly(x + y, y, domain=QQ[x]) raises(CoercionFailed, lambda: Poly.from_poly(h, gens=y, modulus=3)) assert Poly.from_poly(h, gens=(x, y)) == h assert Poly.from_poly( h, gens=(x, y), domain=ZZ).rep == DMP([[ZZ(1)], [ZZ(1), ZZ(0)]], ZZ) assert Poly.from_poly( h, gens=(x, y), domain=QQ).rep == DMP([[QQ(1)], [QQ(1), QQ(0)]], QQ) assert Poly.from_poly( h, gens=(x, y), domain=K).rep == DMP([[K(1)], [K(1), K(0)]], K) assert Poly.from_poly( h, gens=(y, x)).rep == DMP([[ZZ(1)], [ZZ(1), ZZ(0)]], ZZ) assert Poly.from_poly( h, gens=(y, x), domain=ZZ).rep == DMP([[ZZ(1)], [ZZ(1), ZZ(0)]], ZZ) assert Poly.from_poly( h, gens=(y, x), domain=QQ).rep == DMP([[QQ(1)], [QQ(1), QQ(0)]], QQ) assert Poly.from_poly( h, gens=(y, x), domain=K).rep == DMP([[K(1)], [K(1), K(0)]], K) assert Poly.from_poly( h, gens=(x, y), field=True).rep == DMP([[QQ(1)], [QQ(1), QQ(0)]], QQ) assert Poly.from_poly( h, gens=(x, y), field=True).rep == DMP([[QQ(1)], [QQ(1), QQ(0)]], QQ) def test_Poly_from_expr(): raises(GeneratorsNeeded, lambda: Poly.from_expr(S.Zero)) raises(GeneratorsNeeded, lambda: Poly.from_expr(S(7))) F3 = FF(3) assert Poly.from_expr(x + 5, domain=F3).rep == DMP([F3(1), F3(2)], F3) assert Poly.from_expr(y + 5, domain=F3).rep == DMP([F3(1), F3(2)], F3) assert Poly.from_expr(x + 5, x, domain=F3).rep == DMP([F3(1), F3(2)], F3) assert Poly.from_expr(y + 5, y, domain=F3).rep == DMP([F3(1), F3(2)], F3) assert Poly.from_expr(x + y, domain=F3).rep == DMP([[F3(1)], [F3(1), F3(0)]], F3) assert Poly.from_expr(x + y, x, y, domain=F3).rep == DMP([[F3(1)], [F3(1), F3(0)]], F3) assert Poly.from_expr(x + 5).rep == DMP([1, 5], ZZ) assert Poly.from_expr(y + 5).rep == DMP([1, 5], ZZ) assert Poly.from_expr(x + 5, x).rep == DMP([1, 5], ZZ) assert Poly.from_expr(y + 5, y).rep == DMP([1, 5], ZZ) assert Poly.from_expr(x + 5, domain=ZZ).rep == DMP([1, 5], ZZ) assert Poly.from_expr(y + 5, domain=ZZ).rep == DMP([1, 5], ZZ) assert Poly.from_expr(x + 5, x, domain=ZZ).rep == DMP([1, 5], ZZ) assert Poly.from_expr(y + 5, y, domain=ZZ).rep == DMP([1, 5], ZZ) assert Poly.from_expr(x + 5, x, y, domain=ZZ).rep == DMP([[1], [5]], ZZ) assert Poly.from_expr(y + 5, x, y, domain=ZZ).rep == DMP([[1, 5]], ZZ) def test_poly_from_domain_element(): dom = ZZ[x] assert Poly(dom(x+1), y, domain=dom).rep == DMP([dom(x+1)], dom) dom = dom.get_field() assert Poly(dom(x+1), y, domain=dom).rep == DMP([dom(x+1)], dom) dom = QQ[x] assert Poly(dom(x+1), y, domain=dom).rep == DMP([dom(x+1)], dom) dom = dom.get_field() assert Poly(dom(x+1), y, domain=dom).rep == DMP([dom(x+1)], dom) dom = ZZ.old_poly_ring(x) assert Poly(dom([1, 1]), y, domain=dom).rep == DMP([dom([1, 1])], dom) dom = dom.get_field() assert Poly(dom([1, 1]), y, domain=dom).rep == DMP([dom([1, 1])], dom) dom = QQ.old_poly_ring(x) assert Poly(dom([1, 1]), y, domain=dom).rep == DMP([dom([1, 1])], dom) dom = dom.get_field() assert Poly(dom([1, 1]), y, domain=dom).rep == DMP([dom([1, 1])], dom) dom = QQ.algebraic_field(I) assert Poly(dom([1, 1]), x, domain=dom).rep == DMP([dom([1, 1])], dom) def test_Poly__new__(): raises(GeneratorsError, lambda: Poly(x + 1, x, x)) raises(GeneratorsError, lambda: Poly(x + y, x, y, domain=ZZ[x])) raises(GeneratorsError, lambda: Poly(x + y, x, y, domain=ZZ[y])) raises(OptionError, lambda: Poly(x, x, symmetric=True)) raises(OptionError, lambda: Poly(x + 2, x, modulus=3, domain=QQ)) raises(OptionError, lambda: Poly(x + 2, x, domain=ZZ, gaussian=True)) raises(OptionError, lambda: Poly(x + 2, x, modulus=3, gaussian=True)) raises(OptionError, lambda: Poly(x + 2, x, domain=ZZ, extension=[sqrt(3)])) raises(OptionError, lambda: Poly(x + 2, x, modulus=3, extension=[sqrt(3)])) raises(OptionError, lambda: Poly(x + 2, x, domain=ZZ, extension=True)) raises(OptionError, lambda: Poly(x + 2, x, modulus=3, extension=True)) raises(OptionError, lambda: Poly(x + 2, x, domain=ZZ, greedy=True)) raises(OptionError, lambda: Poly(x + 2, x, domain=QQ, field=True)) raises(OptionError, lambda: Poly(x + 2, x, domain=ZZ, greedy=False)) raises(OptionError, lambda: Poly(x + 2, x, domain=QQ, field=False)) raises(NotImplementedError, lambda: Poly(x + 1, x, modulus=3, order='grlex')) raises(NotImplementedError, lambda: Poly(x + 1, x, order='grlex')) raises(GeneratorsNeeded, lambda: Poly({1: 2, 0: 1})) raises(GeneratorsNeeded, lambda: Poly([2, 1])) raises(GeneratorsNeeded, lambda: Poly((2, 1))) raises(GeneratorsNeeded, lambda: Poly(1)) f = a*x**2 + b*x + c assert Poly({2: a, 1: b, 0: c}, x) == f assert Poly(iter([a, b, c]), x) == f assert Poly([a, b, c], x) == f assert Poly((a, b, c), x) == f f = Poly({}, x, y, z) assert f.gens == (x, y, z) and f.as_expr() == 0 assert Poly(Poly(a*x + b*y, x, y), x) == Poly(a*x + b*y, x) assert Poly(3*x**2 + 2*x + 1, domain='ZZ').all_coeffs() == [3, 2, 1] assert Poly(3*x**2 + 2*x + 1, domain='QQ').all_coeffs() == [3, 2, 1] assert Poly(3*x**2 + 2*x + 1, domain='RR').all_coeffs() == [3.0, 2.0, 1.0] raises(CoercionFailed, lambda: Poly(3*x**2/5 + x*Rational(2, 5) + 1, domain='ZZ')) assert Poly( 3*x**2/5 + x*Rational(2, 5) + 1, domain='QQ').all_coeffs() == [Rational(3, 5), Rational(2, 5), 1] assert _epsilon_eq( Poly(3*x**2/5 + x*Rational(2, 5) + 1, domain='RR').all_coeffs(), [0.6, 0.4, 1.0]) assert Poly(3.0*x**2 + 2.0*x + 1, domain='ZZ').all_coeffs() == [3, 2, 1] assert Poly(3.0*x**2 + 2.0*x + 1, domain='QQ').all_coeffs() == [3, 2, 1] assert Poly( 3.0*x**2 + 2.0*x + 1, domain='RR').all_coeffs() == [3.0, 2.0, 1.0] raises(CoercionFailed, lambda: Poly(3.1*x**2 + 2.1*x + 1, domain='ZZ')) assert Poly(3.1*x**2 + 2.1*x + 1, domain='QQ').all_coeffs() == [Rational(31, 10), Rational(21, 10), 1] assert Poly(3.1*x**2 + 2.1*x + 1, domain='RR').all_coeffs() == [3.1, 2.1, 1.0] assert Poly({(2, 1): 1, (1, 2): 2, (1, 1): 3}, x, y) == \ Poly(x**2*y + 2*x*y**2 + 3*x*y, x, y) assert Poly(x**2 + 1, extension=I).get_domain() == QQ.algebraic_field(I) f = 3*x**5 - x**4 + x**3 - x** 2 + 65538 assert Poly(f, x, modulus=65537, symmetric=True) == \ Poly(3*x**5 - x**4 + x**3 - x** 2 + 1, x, modulus=65537, symmetric=True) assert Poly(f, x, modulus=65537, symmetric=False) == \ Poly(3*x**5 + 65536*x**4 + x**3 + 65536*x** 2 + 1, x, modulus=65537, symmetric=False) assert isinstance(Poly(x**2 + x + 1.0).get_domain(), RealField) def test_Poly__args(): assert Poly(x**2 + 1).args == (x**2 + 1, x) def test_Poly__gens(): assert Poly((x - p)*(x - q), x).gens == (x,) assert Poly((x - p)*(x - q), p).gens == (p,) assert Poly((x - p)*(x - q), q).gens == (q,) assert Poly((x - p)*(x - q), x, p).gens == (x, p) assert Poly((x - p)*(x - q), x, q).gens == (x, q) assert Poly((x - p)*(x - q), x, p, q).gens == (x, p, q) assert Poly((x - p)*(x - q), p, x, q).gens == (p, x, q) assert Poly((x - p)*(x - q), p, q, x).gens == (p, q, x) assert Poly((x - p)*(x - q)).gens == (x, p, q) assert Poly((x - p)*(x - q), sort='x > p > q').gens == (x, p, q) assert Poly((x - p)*(x - q), sort='p > x > q').gens == (p, x, q) assert Poly((x - p)*(x - q), sort='p > q > x').gens == (p, q, x) assert Poly((x - p)*(x - q), x, p, q, sort='p > q > x').gens == (x, p, q) assert Poly((x - p)*(x - q), wrt='x').gens == (x, p, q) assert Poly((x - p)*(x - q), wrt='p').gens == (p, x, q) assert Poly((x - p)*(x - q), wrt='q').gens == (q, x, p) assert Poly((x - p)*(x - q), wrt=x).gens == (x, p, q) assert Poly((x - p)*(x - q), wrt=p).gens == (p, x, q) assert Poly((x - p)*(x - q), wrt=q).gens == (q, x, p) assert Poly((x - p)*(x - q), x, p, q, wrt='p').gens == (x, p, q) assert Poly((x - p)*(x - q), wrt='p', sort='q > x').gens == (p, q, x) assert Poly((x - p)*(x - q), wrt='q', sort='p > x').gens == (q, p, x) def test_Poly_zero(): assert Poly(x).zero == Poly(0, x, domain=ZZ) assert Poly(x/2).zero == Poly(0, x, domain=QQ) def test_Poly_one(): assert Poly(x).one == Poly(1, x, domain=ZZ) assert Poly(x/2).one == Poly(1, x, domain=QQ) def test_Poly__unify(): raises(UnificationFailed, lambda: Poly(x)._unify(y)) F3 = FF(3) F5 = FF(5) assert Poly(x, x, modulus=3)._unify(Poly(y, y, modulus=3))[2:] == ( DMP([[F3(1)], []], F3), DMP([[F3(1), F3(0)]], F3)) assert Poly(x, x, modulus=3)._unify(Poly(y, y, modulus=5))[2:] == ( DMP([[F5(1)], []], F5), DMP([[F5(1), F5(0)]], F5)) assert Poly(y, x, y)._unify(Poly(x, x, modulus=3))[2:] == (DMP([[F3(1), F3(0)]], F3), DMP([[F3(1)], []], F3)) assert Poly(x, x, modulus=3)._unify(Poly(y, x, y))[2:] == (DMP([[F3(1)], []], F3), DMP([[F3(1), F3(0)]], F3)) assert Poly(x + 1, x)._unify(Poly(x + 2, x))[2:] == (DMP([1, 1], ZZ), DMP([1, 2], ZZ)) assert Poly(x + 1, x, domain='QQ')._unify(Poly(x + 2, x))[2:] == (DMP([1, 1], QQ), DMP([1, 2], QQ)) assert Poly(x + 1, x)._unify(Poly(x + 2, x, domain='QQ'))[2:] == (DMP([1, 1], QQ), DMP([1, 2], QQ)) assert Poly(x + 1, x)._unify(Poly(x + 2, x, y))[2:] == (DMP([[1], [1]], ZZ), DMP([[1], [2]], ZZ)) assert Poly(x + 1, x, domain='QQ')._unify(Poly(x + 2, x, y))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ)) assert Poly(x + 1, x)._unify(Poly(x + 2, x, y, domain='QQ'))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ)) assert Poly(x + 1, x, y)._unify(Poly(x + 2, x))[2:] == (DMP([[1], [1]], ZZ), DMP([[1], [2]], ZZ)) assert Poly(x + 1, x, y, domain='QQ')._unify(Poly(x + 2, x))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ)) assert Poly(x + 1, x, y)._unify(Poly(x + 2, x, domain='QQ'))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ)) assert Poly(x + 1, x, y)._unify(Poly(x + 2, x, y))[2:] == (DMP([[1], [1]], ZZ), DMP([[1], [2]], ZZ)) assert Poly(x + 1, x, y, domain='QQ')._unify(Poly(x + 2, x, y))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ)) assert Poly(x + 1, x, y)._unify(Poly(x + 2, x, y, domain='QQ'))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ)) assert Poly(x + 1, x)._unify(Poly(x + 2, y, x))[2:] == (DMP([[1, 1]], ZZ), DMP([[1, 2]], ZZ)) assert Poly(x + 1, x, domain='QQ')._unify(Poly(x + 2, y, x))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ)) assert Poly(x + 1, x)._unify(Poly(x + 2, y, x, domain='QQ'))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ)) assert Poly(x + 1, y, x)._unify(Poly(x + 2, x))[2:] == (DMP([[1, 1]], ZZ), DMP([[1, 2]], ZZ)) assert Poly(x + 1, y, x, domain='QQ')._unify(Poly(x + 2, x))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ)) assert Poly(x + 1, y, x)._unify(Poly(x + 2, x, domain='QQ'))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ)) assert Poly(x + 1, x, y)._unify(Poly(x + 2, y, x))[2:] == (DMP([[1], [1]], ZZ), DMP([[1], [2]], ZZ)) assert Poly(x + 1, x, y, domain='QQ')._unify(Poly(x + 2, y, x))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ)) assert Poly(x + 1, x, y)._unify(Poly(x + 2, y, x, domain='QQ'))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ)) assert Poly(x + 1, y, x)._unify(Poly(x + 2, x, y))[2:] == (DMP([[1, 1]], ZZ), DMP([[1, 2]], ZZ)) assert Poly(x + 1, y, x, domain='QQ')._unify(Poly(x + 2, x, y))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ)) assert Poly(x + 1, y, x)._unify(Poly(x + 2, x, y, domain='QQ'))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ)) assert Poly(x**2 + I, x, domain=ZZ_I).unify(Poly(x**2 + sqrt(2), x, extension=True)) == \ (Poly(x**2 + I, x, domain='QQ<sqrt(2) + I>'), Poly(x**2 + sqrt(2), x, domain='QQ<sqrt(2) + I>')) F, A, B = field("a,b", ZZ) assert Poly(a*x, x, domain='ZZ[a]')._unify(Poly(a*b*x, x, domain='ZZ(a,b)'))[2:] == \ (DMP([A, F(0)], F.to_domain()), DMP([A*B, F(0)], F.to_domain())) assert Poly(a*x, x, domain='ZZ(a)')._unify(Poly(a*b*x, x, domain='ZZ(a,b)'))[2:] == \ (DMP([A, F(0)], F.to_domain()), DMP([A*B, F(0)], F.to_domain())) raises(CoercionFailed, lambda: Poly(Poly(x**2 + x**2*z, y, field=True), domain='ZZ(x)')) f = Poly(t**2 + t/3 + x, t, domain='QQ(x)') g = Poly(t**2 + t/3 + x, t, domain='QQ[x]') assert f._unify(g)[2:] == (f.rep, f.rep) def test_Poly_free_symbols(): assert Poly(x**2 + 1).free_symbols == {x} assert Poly(x**2 + y*z).free_symbols == {x, y, z} assert Poly(x**2 + y*z, x).free_symbols == {x, y, z} assert Poly(x**2 + sin(y*z)).free_symbols == {x, y, z} assert Poly(x**2 + sin(y*z), x).free_symbols == {x, y, z} assert Poly(x**2 + sin(y*z), x, domain=EX).free_symbols == {x, y, z} assert Poly(1 + x + x**2, x, y, z).free_symbols == {x} assert Poly(x + sin(y), z).free_symbols == {x, y} def test_PurePoly_free_symbols(): assert PurePoly(x**2 + 1).free_symbols == set() assert PurePoly(x**2 + y*z).free_symbols == set() assert PurePoly(x**2 + y*z, x).free_symbols == {y, z} assert PurePoly(x**2 + sin(y*z)).free_symbols == set() assert PurePoly(x**2 + sin(y*z), x).free_symbols == {y, z} assert PurePoly(x**2 + sin(y*z), x, domain=EX).free_symbols == {y, z} def test_Poly__eq__(): assert (Poly(x, x) == Poly(x, x)) is True assert (Poly(x, x, domain=QQ) == Poly(x, x)) is False assert (Poly(x, x) == Poly(x, x, domain=QQ)) is False assert (Poly(x, x, domain=ZZ[a]) == Poly(x, x)) is False assert (Poly(x, x) == Poly(x, x, domain=ZZ[a])) is False assert (Poly(x*y, x, y) == Poly(x, x)) is False assert (Poly(x, x, y) == Poly(x, x)) is False assert (Poly(x, x) == Poly(x, x, y)) is False assert (Poly(x**2 + 1, x) == Poly(y**2 + 1, y)) is False assert (Poly(y**2 + 1, y) == Poly(x**2 + 1, x)) is False f = Poly(x, x, domain=ZZ) g = Poly(x, x, domain=QQ) assert f.eq(g) is False assert f.ne(g) is True assert f.eq(g, strict=True) is False assert f.ne(g, strict=True) is True t0 = Symbol('t0') f = Poly((t0/2 + x**2)*t**2 - x**2*t, t, domain='QQ[x,t0]') g = Poly((t0/2 + x**2)*t**2 - x**2*t, t, domain='ZZ(x,t0)') assert (f == g) is False def test_PurePoly__eq__(): assert (PurePoly(x, x) == PurePoly(x, x)) is True assert (PurePoly(x, x, domain=QQ) == PurePoly(x, x)) is True assert (PurePoly(x, x) == PurePoly(x, x, domain=QQ)) is True assert (PurePoly(x, x, domain=ZZ[a]) == PurePoly(x, x)) is True assert (PurePoly(x, x) == PurePoly(x, x, domain=ZZ[a])) is True assert (PurePoly(x*y, x, y) == PurePoly(x, x)) is False assert (PurePoly(x, x, y) == PurePoly(x, x)) is False assert (PurePoly(x, x) == PurePoly(x, x, y)) is False assert (PurePoly(x**2 + 1, x) == PurePoly(y**2 + 1, y)) is True assert (PurePoly(y**2 + 1, y) == PurePoly(x**2 + 1, x)) is True f = PurePoly(x, x, domain=ZZ) g = PurePoly(x, x, domain=QQ) assert f.eq(g) is True assert f.ne(g) is False assert f.eq(g, strict=True) is False assert f.ne(g, strict=True) is True f = PurePoly(x, x, domain=ZZ) g = PurePoly(y, y, domain=QQ) assert f.eq(g) is True assert f.ne(g) is False assert f.eq(g, strict=True) is False assert f.ne(g, strict=True) is True def test_PurePoly_Poly(): assert isinstance(PurePoly(Poly(x**2 + 1)), PurePoly) is True assert isinstance(Poly(PurePoly(x**2 + 1)), Poly) is True def test_Poly_get_domain(): assert Poly(2*x).get_domain() == ZZ assert Poly(2*x, domain='ZZ').get_domain() == ZZ assert Poly(2*x, domain='QQ').get_domain() == QQ assert Poly(x/2).get_domain() == QQ raises(CoercionFailed, lambda: Poly(x/2, domain='ZZ')) assert Poly(x/2, domain='QQ').get_domain() == QQ assert isinstance(Poly(0.2*x).get_domain(), RealField) def test_Poly_set_domain(): assert Poly(2*x + 1).set_domain(ZZ) == Poly(2*x + 1) assert Poly(2*x + 1).set_domain('ZZ') == Poly(2*x + 1) assert Poly(2*x + 1).set_domain(QQ) == Poly(2*x + 1, domain='QQ') assert Poly(2*x + 1).set_domain('QQ') == Poly(2*x + 1, domain='QQ') assert Poly(Rational(2, 10)*x + Rational(1, 10)).set_domain('RR') == Poly(0.2*x + 0.1) assert Poly(0.2*x + 0.1).set_domain('QQ') == Poly(Rational(2, 10)*x + Rational(1, 10)) raises(CoercionFailed, lambda: Poly(x/2 + 1).set_domain(ZZ)) raises(CoercionFailed, lambda: Poly(x + 1, modulus=2).set_domain(QQ)) raises(GeneratorsError, lambda: Poly(x*y, x, y).set_domain(ZZ[y])) def test_Poly_get_modulus(): assert Poly(x**2 + 1, modulus=2).get_modulus() == 2 raises(PolynomialError, lambda: Poly(x**2 + 1).get_modulus()) def test_Poly_set_modulus(): assert Poly( x**2 + 1, modulus=2).set_modulus(7) == Poly(x**2 + 1, modulus=7) assert Poly( x**2 + 5, modulus=7).set_modulus(2) == Poly(x**2 + 1, modulus=2) assert Poly(x**2 + 1).set_modulus(2) == Poly(x**2 + 1, modulus=2) raises(CoercionFailed, lambda: Poly(x/2 + 1).set_modulus(2)) def test_Poly_add_ground(): assert Poly(x + 1).add_ground(2) == Poly(x + 3) def test_Poly_sub_ground(): assert Poly(x + 1).sub_ground(2) == Poly(x - 1) def test_Poly_mul_ground(): assert Poly(x + 1).mul_ground(2) == Poly(2*x + 2) def test_Poly_quo_ground(): assert Poly(2*x + 4).quo_ground(2) == Poly(x + 2) assert Poly(2*x + 3).quo_ground(2) == Poly(x + 1) def test_Poly_exquo_ground(): assert Poly(2*x + 4).exquo_ground(2) == Poly(x + 2) raises(ExactQuotientFailed, lambda: Poly(2*x + 3).exquo_ground(2)) def test_Poly_abs(): assert Poly(-x + 1, x).abs() == abs(Poly(-x + 1, x)) == Poly(x + 1, x) def test_Poly_neg(): assert Poly(-x + 1, x).neg() == -Poly(-x + 1, x) == Poly(x - 1, x) def test_Poly_add(): assert Poly(0, x).add(Poly(0, x)) == Poly(0, x) assert Poly(0, x) + Poly(0, x) == Poly(0, x) assert Poly(1, x).add(Poly(0, x)) == Poly(1, x) assert Poly(1, x, y) + Poly(0, x) == Poly(1, x, y) assert Poly(0, x).add(Poly(1, x, y)) == Poly(1, x, y) assert Poly(0, x, y) + Poly(1, x, y) == Poly(1, x, y) assert Poly(1, x) + x == Poly(x + 1, x) with warns_deprecated_sympy(): Poly(1, x) + sin(x) assert Poly(x, x) + 1 == Poly(x + 1, x) assert 1 + Poly(x, x) == Poly(x + 1, x) def test_Poly_sub(): assert Poly(0, x).sub(Poly(0, x)) == Poly(0, x) assert Poly(0, x) - Poly(0, x) == Poly(0, x) assert Poly(1, x).sub(Poly(0, x)) == Poly(1, x) assert Poly(1, x, y) - Poly(0, x) == Poly(1, x, y) assert Poly(0, x).sub(Poly(1, x, y)) == Poly(-1, x, y) assert Poly(0, x, y) - Poly(1, x, y) == Poly(-1, x, y) assert Poly(1, x) - x == Poly(1 - x, x) with warns_deprecated_sympy(): Poly(1, x) - sin(x) assert Poly(x, x) - 1 == Poly(x - 1, x) assert 1 - Poly(x, x) == Poly(1 - x, x) def test_Poly_mul(): assert Poly(0, x).mul(Poly(0, x)) == Poly(0, x) assert Poly(0, x) * Poly(0, x) == Poly(0, x) assert Poly(2, x).mul(Poly(4, x)) == Poly(8, x) assert Poly(2, x, y) * Poly(4, x) == Poly(8, x, y) assert Poly(4, x).mul(Poly(2, x, y)) == Poly(8, x, y) assert Poly(4, x, y) * Poly(2, x, y) == Poly(8, x, y) assert Poly(1, x) * x == Poly(x, x) with warns_deprecated_sympy(): Poly(1, x) * sin(x) assert Poly(x, x) * 2 == Poly(2*x, x) assert 2 * Poly(x, x) == Poly(2*x, x) def test_issue_13079(): assert Poly(x)*x == Poly(x**2, x, domain='ZZ') assert x*Poly(x) == Poly(x**2, x, domain='ZZ') assert -2*Poly(x) == Poly(-2*x, x, domain='ZZ') assert S(-2)*Poly(x) == Poly(-2*x, x, domain='ZZ') assert Poly(x)*S(-2) == Poly(-2*x, x, domain='ZZ') def test_Poly_sqr(): assert Poly(x*y, x, y).sqr() == Poly(x**2*y**2, x, y) def test_Poly_pow(): assert Poly(x, x).pow(10) == Poly(x**10, x) assert Poly(x, x).pow(Integer(10)) == Poly(x**10, x) assert Poly(2*y, x, y).pow(4) == Poly(16*y**4, x, y) assert Poly(2*y, x, y).pow(Integer(4)) == Poly(16*y**4, x, y) assert Poly(7*x*y, x, y)**3 == Poly(343*x**3*y**3, x, y) raises(TypeError, lambda: Poly(x*y + 1, x, y)**(-1)) raises(TypeError, lambda: Poly(x*y + 1, x, y)**x) def test_Poly_divmod(): f, g = Poly(x**2), Poly(x) q, r = g, Poly(0, x) assert divmod(f, g) == (q, r) assert f // g == q assert f % g == r assert divmod(f, x) == (q, r) assert f // x == q assert f % x == r q, r = Poly(0, x), Poly(2, x) assert divmod(2, g) == (q, r) assert 2 // g == q assert 2 % g == r assert Poly(x)/Poly(x) == 1 assert Poly(x**2)/Poly(x) == x assert Poly(x)/Poly(x**2) == 1/x def test_Poly_eq_ne(): assert (Poly(x + y, x, y) == Poly(x + y, x, y)) is True assert (Poly(x + y, x) == Poly(x + y, x, y)) is False assert (Poly(x + y, x, y) == Poly(x + y, x)) is False assert (Poly(x + y, x) == Poly(x + y, x)) is True assert (Poly(x + y, y) == Poly(x + y, y)) is True assert (Poly(x + y, x, y) == x + y) is True assert (Poly(x + y, x) == x + y) is True assert (Poly(x + y, x, y) == x + y) is True assert (Poly(x + y, x) == x + y) is True assert (Poly(x + y, y) == x + y) is True assert (Poly(x + y, x, y) != Poly(x + y, x, y)) is False assert (Poly(x + y, x) != Poly(x + y, x, y)) is True assert (Poly(x + y, x, y) != Poly(x + y, x)) is True assert (Poly(x + y, x) != Poly(x + y, x)) is False assert (Poly(x + y, y) != Poly(x + y, y)) is False assert (Poly(x + y, x, y) != x + y) is False assert (Poly(x + y, x) != x + y) is False assert (Poly(x + y, x, y) != x + y) is False assert (Poly(x + y, x) != x + y) is False assert (Poly(x + y, y) != x + y) is False assert (Poly(x, x) == sin(x)) is False assert (Poly(x, x) != sin(x)) is True def test_Poly_nonzero(): assert not bool(Poly(0, x)) is True assert not bool(Poly(1, x)) is False def test_Poly_properties(): assert Poly(0, x).is_zero is True assert Poly(1, x).is_zero is False assert Poly(1, x).is_one is True assert Poly(2, x).is_one is False assert Poly(x - 1, x).is_sqf is True assert Poly((x - 1)**2, x).is_sqf is False assert Poly(x - 1, x).is_monic is True assert Poly(2*x - 1, x).is_monic is False assert Poly(3*x + 2, x).is_primitive is True assert Poly(4*x + 2, x).is_primitive is False assert Poly(1, x).is_ground is True assert Poly(x, x).is_ground is False assert Poly(x + y + z + 1).is_linear is True assert Poly(x*y*z + 1).is_linear is False assert Poly(x*y + z + 1).is_quadratic is True assert Poly(x*y*z + 1).is_quadratic is False assert Poly(x*y).is_monomial is True assert Poly(x*y + 1).is_monomial is False assert Poly(x**2 + x*y).is_homogeneous is True assert Poly(x**3 + x*y).is_homogeneous is False assert Poly(x).is_univariate is True assert Poly(x*y).is_univariate is False assert Poly(x*y).is_multivariate is True assert Poly(x).is_multivariate is False assert Poly( x**16 + x**14 - x**10 + x**8 - x**6 + x**2 + 1).is_cyclotomic is False assert Poly( x**16 + x**14 - x**10 - x**8 - x**6 + x**2 + 1).is_cyclotomic is True def test_Poly_is_irreducible(): assert Poly(x**2 + x + 1).is_irreducible is True assert Poly(x**2 + 2*x + 1).is_irreducible is False assert Poly(7*x + 3, modulus=11).is_irreducible is True assert Poly(7*x**2 + 3*x + 1, modulus=11).is_irreducible is False def test_Poly_subs(): assert Poly(x + 1).subs(x, 0) == 1 assert Poly(x + 1).subs(x, x) == Poly(x + 1) assert Poly(x + 1).subs(x, y) == Poly(y + 1) assert Poly(x*y, x).subs(y, x) == x**2 assert Poly(x*y, x).subs(x, y) == y**2 def test_Poly_replace(): assert Poly(x + 1).replace(x) == Poly(x + 1) assert Poly(x + 1).replace(y) == Poly(y + 1) raises(PolynomialError, lambda: Poly(x + y).replace(z)) assert Poly(x + 1).replace(x, x) == Poly(x + 1) assert Poly(x + 1).replace(x, y) == Poly(y + 1) assert Poly(x + y).replace(x, x) == Poly(x + y) assert Poly(x + y).replace(x, z) == Poly(z + y, z, y) assert Poly(x + y).replace(y, y) == Poly(x + y) assert Poly(x + y).replace(y, z) == Poly(x + z, x, z) assert Poly(x + y).replace(z, t) == Poly(x + y) raises(PolynomialError, lambda: Poly(x + y).replace(x, y)) assert Poly(x + y, x).replace(x, z) == Poly(z + y, z) assert Poly(x + y, y).replace(y, z) == Poly(x + z, z) raises(PolynomialError, lambda: Poly(x + y, x).replace(x, y)) raises(PolynomialError, lambda: Poly(x + y, y).replace(y, x)) def test_Poly_reorder(): raises(PolynomialError, lambda: Poly(x + y).reorder(x, z)) assert Poly(x + y, x, y).reorder(x, y) == Poly(x + y, x, y) assert Poly(x + y, x, y).reorder(y, x) == Poly(x + y, y, x) assert Poly(x + y, y, x).reorder(x, y) == Poly(x + y, x, y) assert Poly(x + y, y, x).reorder(y, x) == Poly(x + y, y, x) assert Poly(x + y, x, y).reorder(wrt=x) == Poly(x + y, x, y) assert Poly(x + y, x, y).reorder(wrt=y) == Poly(x + y, y, x) def test_Poly_ltrim(): f = Poly(y**2 + y*z**2, x, y, z).ltrim(y) assert f.as_expr() == y**2 + y*z**2 and f.gens == (y, z) assert Poly(x*y - x, z, x, y).ltrim(1) == Poly(x*y - x, x, y) raises(PolynomialError, lambda: Poly(x*y**2 + y**2, x, y).ltrim(y)) raises(PolynomialError, lambda: Poly(x*y - x, x, y).ltrim(-1)) def test_Poly_has_only_gens(): assert Poly(x*y + 1, x, y, z).has_only_gens(x, y) is True assert Poly(x*y + z, x, y, z).has_only_gens(x, y) is False raises(GeneratorsError, lambda: Poly(x*y**2 + y**2, x, y).has_only_gens(t)) def test_Poly_to_ring(): assert Poly(2*x + 1, domain='ZZ').to_ring() == Poly(2*x + 1, domain='ZZ') assert Poly(2*x + 1, domain='QQ').to_ring() == Poly(2*x + 1, domain='ZZ') raises(CoercionFailed, lambda: Poly(x/2 + 1).to_ring()) raises(DomainError, lambda: Poly(2*x + 1, modulus=3).to_ring()) def test_Poly_to_field(): assert Poly(2*x + 1, domain='ZZ').to_field() == Poly(2*x + 1, domain='QQ') assert Poly(2*x + 1, domain='QQ').to_field() == Poly(2*x + 1, domain='QQ') assert Poly(x/2 + 1, domain='QQ').to_field() == Poly(x/2 + 1, domain='QQ') assert Poly(2*x + 1, modulus=3).to_field() == Poly(2*x + 1, modulus=3) assert Poly(2.0*x + 1.0).to_field() == Poly(2.0*x + 1.0) def test_Poly_to_exact(): assert Poly(2*x).to_exact() == Poly(2*x) assert Poly(x/2).to_exact() == Poly(x/2) assert Poly(0.1*x).to_exact() == Poly(x/10) def test_Poly_retract(): f = Poly(x**2 + 1, x, domain=QQ[y]) assert f.retract() == Poly(x**2 + 1, x, domain='ZZ') assert f.retract(field=True) == Poly(x**2 + 1, x, domain='QQ') assert Poly(0, x, y).retract() == Poly(0, x, y) def test_Poly_slice(): f = Poly(x**3 + 2*x**2 + 3*x + 4) assert f.slice(0, 0) == Poly(0, x) assert f.slice(0, 1) == Poly(4, x) assert f.slice(0, 2) == Poly(3*x + 4, x) assert f.slice(0, 3) == Poly(2*x**2 + 3*x + 4, x) assert f.slice(0, 4) == Poly(x**3 + 2*x**2 + 3*x + 4, x) assert f.slice(x, 0, 0) == Poly(0, x) assert f.slice(x, 0, 1) == Poly(4, x) assert f.slice(x, 0, 2) == Poly(3*x + 4, x) assert f.slice(x, 0, 3) == Poly(2*x**2 + 3*x + 4, x) assert f.slice(x, 0, 4) == Poly(x**3 + 2*x**2 + 3*x + 4, x) def test_Poly_coeffs(): assert Poly(0, x).coeffs() == [0] assert Poly(1, x).coeffs() == [1] assert Poly(2*x + 1, x).coeffs() == [2, 1] assert Poly(7*x**2 + 2*x + 1, x).coeffs() == [7, 2, 1] assert Poly(7*x**4 + 2*x + 1, x).coeffs() == [7, 2, 1] assert Poly(x*y**7 + 2*x**2*y**3).coeffs('lex') == [2, 1] assert Poly(x*y**7 + 2*x**2*y**3).coeffs('grlex') == [1, 2] def test_Poly_monoms(): assert Poly(0, x).monoms() == [(0,)] assert Poly(1, x).monoms() == [(0,)] assert Poly(2*x + 1, x).monoms() == [(1,), (0,)] assert Poly(7*x**2 + 2*x + 1, x).monoms() == [(2,), (1,), (0,)] assert Poly(7*x**4 + 2*x + 1, x).monoms() == [(4,), (1,), (0,)] assert Poly(x*y**7 + 2*x**2*y**3).monoms('lex') == [(2, 3), (1, 7)] assert Poly(x*y**7 + 2*x**2*y**3).monoms('grlex') == [(1, 7), (2, 3)] def test_Poly_terms(): assert Poly(0, x).terms() == [((0,), 0)] assert Poly(1, x).terms() == [((0,), 1)] assert Poly(2*x + 1, x).terms() == [((1,), 2), ((0,), 1)] assert Poly(7*x**2 + 2*x + 1, x).terms() == [((2,), 7), ((1,), 2), ((0,), 1)] assert Poly(7*x**4 + 2*x + 1, x).terms() == [((4,), 7), ((1,), 2), ((0,), 1)] assert Poly( x*y**7 + 2*x**2*y**3).terms('lex') == [((2, 3), 2), ((1, 7), 1)] assert Poly( x*y**7 + 2*x**2*y**3).terms('grlex') == [((1, 7), 1), ((2, 3), 2)] def test_Poly_all_coeffs(): assert Poly(0, x).all_coeffs() == [0] assert Poly(1, x).all_coeffs() == [1] assert Poly(2*x + 1, x).all_coeffs() == [2, 1] assert Poly(7*x**2 + 2*x + 1, x).all_coeffs() == [7, 2, 1] assert Poly(7*x**4 + 2*x + 1, x).all_coeffs() == [7, 0, 0, 2, 1] def test_Poly_all_monoms(): assert Poly(0, x).all_monoms() == [(0,)] assert Poly(1, x).all_monoms() == [(0,)] assert Poly(2*x + 1, x).all_monoms() == [(1,), (0,)] assert Poly(7*x**2 + 2*x + 1, x).all_monoms() == [(2,), (1,), (0,)] assert Poly(7*x**4 + 2*x + 1, x).all_monoms() == [(4,), (3,), (2,), (1,), (0,)] def test_Poly_all_terms(): assert Poly(0, x).all_terms() == [((0,), 0)] assert Poly(1, x).all_terms() == [((0,), 1)] assert Poly(2*x + 1, x).all_terms() == [((1,), 2), ((0,), 1)] assert Poly(7*x**2 + 2*x + 1, x).all_terms() == \ [((2,), 7), ((1,), 2), ((0,), 1)] assert Poly(7*x**4 + 2*x + 1, x).all_terms() == \ [((4,), 7), ((3,), 0), ((2,), 0), ((1,), 2), ((0,), 1)] def test_Poly_termwise(): f = Poly(x**2 + 20*x + 400) g = Poly(x**2 + 2*x + 4) def func(monom, coeff): (k,) = monom return coeff//10**(2 - k) assert f.termwise(func) == g def func(monom, coeff): (k,) = monom return (k,), coeff//10**(2 - k) assert f.termwise(func) == g def test_Poly_length(): assert Poly(0, x).length() == 0 assert Poly(1, x).length() == 1 assert Poly(x, x).length() == 1 assert Poly(x + 1, x).length() == 2 assert Poly(x**2 + 1, x).length() == 2 assert Poly(x**2 + x + 1, x).length() == 3 def test_Poly_as_dict(): assert Poly(0, x).as_dict() == {} assert Poly(0, x, y, z).as_dict() == {} assert Poly(1, x).as_dict() == {(0,): 1} assert Poly(1, x, y, z).as_dict() == {(0, 0, 0): 1} assert Poly(x**2 + 3, x).as_dict() == {(2,): 1, (0,): 3} assert Poly(x**2 + 3, x, y, z).as_dict() == {(2, 0, 0): 1, (0, 0, 0): 3} assert Poly(3*x**2*y*z**3 + 4*x*y + 5*x*z).as_dict() == {(2, 1, 3): 3, (1, 1, 0): 4, (1, 0, 1): 5} def test_Poly_as_expr(): assert Poly(0, x).as_expr() == 0 assert Poly(0, x, y, z).as_expr() == 0 assert Poly(1, x).as_expr() == 1 assert Poly(1, x, y, z).as_expr() == 1 assert Poly(x**2 + 3, x).as_expr() == x**2 + 3 assert Poly(x**2 + 3, x, y, z).as_expr() == x**2 + 3 assert Poly( 3*x**2*y*z**3 + 4*x*y + 5*x*z).as_expr() == 3*x**2*y*z**3 + 4*x*y + 5*x*z f = Poly(x**2 + 2*x*y**2 - y, x, y) assert f.as_expr() == -y + x**2 + 2*x*y**2 assert f.as_expr({x: 5}) == 25 - y + 10*y**2 assert f.as_expr({y: 6}) == -6 + 72*x + x**2 assert f.as_expr({x: 5, y: 6}) == 379 assert f.as_expr(5, 6) == 379 raises(GeneratorsError, lambda: f.as_expr({z: 7})) def test_Poly_lift(): assert Poly(x**4 - I*x + 17*I, x, gaussian=True).lift() == \ Poly(x**16 + 2*x**10 + 578*x**8 + x**4 - 578*x**2 + 83521, x, domain='QQ') def test_Poly_deflate(): assert Poly(0, x).deflate() == ((1,), Poly(0, x)) assert Poly(1, x).deflate() == ((1,), Poly(1, x)) assert Poly(x, x).deflate() == ((1,), Poly(x, x)) assert Poly(x**2, x).deflate() == ((2,), Poly(x, x)) assert Poly(x**17, x).deflate() == ((17,), Poly(x, x)) assert Poly( x**2*y*z**11 + x**4*z**11).deflate() == ((2, 1, 11), Poly(x*y*z + x**2*z)) def test_Poly_inject(): f = Poly(x**2*y + x*y**3 + x*y + 1, x) assert f.inject() == Poly(x**2*y + x*y**3 + x*y + 1, x, y) assert f.inject(front=True) == Poly(y**3*x + y*x**2 + y*x + 1, y, x) def test_Poly_eject(): f = Poly(x**2*y + x*y**3 + x*y + 1, x, y) assert f.eject(x) == Poly(x*y**3 + (x**2 + x)*y + 1, y, domain='ZZ[x]') assert f.eject(y) == Poly(y*x**2 + (y**3 + y)*x + 1, x, domain='ZZ[y]') ex = x + y + z + t + w g = Poly(ex, x, y, z, t, w) assert g.eject(x) == Poly(ex, y, z, t, w, domain='ZZ[x]') assert g.eject(x, y) == Poly(ex, z, t, w, domain='ZZ[x, y]') assert g.eject(x, y, z) == Poly(ex, t, w, domain='ZZ[x, y, z]') assert g.eject(w) == Poly(ex, x, y, z, t, domain='ZZ[w]') assert g.eject(t, w) == Poly(ex, x, y, z, domain='ZZ[t, w]') assert g.eject(z, t, w) == Poly(ex, x, y, domain='ZZ[z, t, w]') raises(DomainError, lambda: Poly(x*y, x, y, domain=ZZ[z]).eject(y)) raises(NotImplementedError, lambda: Poly(x*y, x, y, z).eject(y)) def test_Poly_exclude(): assert Poly(x, x, y).exclude() == Poly(x, x) assert Poly(x*y, x, y).exclude() == Poly(x*y, x, y) assert Poly(1, x, y).exclude() == Poly(1, x, y) def test_Poly__gen_to_level(): assert Poly(1, x, y)._gen_to_level(-2) == 0 assert Poly(1, x, y)._gen_to_level(-1) == 1 assert Poly(1, x, y)._gen_to_level( 0) == 0 assert Poly(1, x, y)._gen_to_level( 1) == 1 raises(PolynomialError, lambda: Poly(1, x, y)._gen_to_level(-3)) raises(PolynomialError, lambda: Poly(1, x, y)._gen_to_level( 2)) assert Poly(1, x, y)._gen_to_level(x) == 0 assert Poly(1, x, y)._gen_to_level(y) == 1 assert Poly(1, x, y)._gen_to_level('x') == 0 assert Poly(1, x, y)._gen_to_level('y') == 1 raises(PolynomialError, lambda: Poly(1, x, y)._gen_to_level(z)) raises(PolynomialError, lambda: Poly(1, x, y)._gen_to_level('z')) def test_Poly_degree(): assert Poly(0, x).degree() is -oo assert Poly(1, x).degree() == 0 assert Poly(x, x).degree() == 1 assert Poly(0, x).degree(gen=0) is -oo assert Poly(1, x).degree(gen=0) == 0 assert Poly(x, x).degree(gen=0) == 1 assert Poly(0, x).degree(gen=x) is -oo assert Poly(1, x).degree(gen=x) == 0 assert Poly(x, x).degree(gen=x) == 1 assert Poly(0, x).degree(gen='x') is -oo assert Poly(1, x).degree(gen='x') == 0 assert Poly(x, x).degree(gen='x') == 1 raises(PolynomialError, lambda: Poly(1, x).degree(gen=1)) raises(PolynomialError, lambda: Poly(1, x).degree(gen=y)) raises(PolynomialError, lambda: Poly(1, x).degree(gen='y')) assert Poly(1, x, y).degree() == 0 assert Poly(2*y, x, y).degree() == 0 assert Poly(x*y, x, y).degree() == 1 assert Poly(1, x, y).degree(gen=x) == 0 assert Poly(2*y, x, y).degree(gen=x) == 0 assert Poly(x*y, x, y).degree(gen=x) == 1 assert Poly(1, x, y).degree(gen=y) == 0 assert Poly(2*y, x, y).degree(gen=y) == 1 assert Poly(x*y, x, y).degree(gen=y) == 1 assert degree(0, x) is -oo assert degree(1, x) == 0 assert degree(x, x) == 1 assert degree(x*y**2, x) == 1 assert degree(x*y**2, y) == 2 assert degree(x*y**2, z) == 0 assert degree(pi) == 1 raises(TypeError, lambda: degree(y**2 + x**3)) raises(TypeError, lambda: degree(y**2 + x**3, 1)) raises(PolynomialError, lambda: degree(x, 1.1)) raises(PolynomialError, lambda: degree(x**2/(x**3 + 1), x)) assert degree(Poly(0,x),z) is -oo assert degree(Poly(1,x),z) == 0 assert degree(Poly(x**2+y**3,y)) == 3 assert degree(Poly(y**2 + x**3, y, x), 1) == 3 assert degree(Poly(y**2 + x**3, x), z) == 0 assert degree(Poly(y**2 + x**3 + z**4, x), z) == 4 def test_Poly_degree_list(): assert Poly(0, x).degree_list() == (-oo,) assert Poly(0, x, y).degree_list() == (-oo, -oo) assert Poly(0, x, y, z).degree_list() == (-oo, -oo, -oo) assert Poly(1, x).degree_list() == (0,) assert Poly(1, x, y).degree_list() == (0, 0) assert Poly(1, x, y, z).degree_list() == (0, 0, 0) assert Poly(x**2*y + x**3*z**2 + 1).degree_list() == (3, 1, 2) assert degree_list(1, x) == (0,) assert degree_list(x, x) == (1,) assert degree_list(x*y**2) == (1, 2) raises(ComputationFailed, lambda: degree_list(1)) def test_Poly_total_degree(): assert Poly(x**2*y + x**3*z**2 + 1).total_degree() == 5 assert Poly(x**2 + z**3).total_degree() == 3 assert Poly(x*y*z + z**4).total_degree() == 4 assert Poly(x**3 + x + 1).total_degree() == 3 assert total_degree(x*y + z**3) == 3 assert total_degree(x*y + z**3, x, y) == 2 assert total_degree(1) == 0 assert total_degree(Poly(y**2 + x**3 + z**4)) == 4 assert total_degree(Poly(y**2 + x**3 + z**4, x)) == 3 assert total_degree(Poly(y**2 + x**3 + z**4, x), z) == 4 assert total_degree(Poly(x**9 + x*z*y + x**3*z**2 + z**7,x), z) == 7 def test_Poly_homogenize(): assert Poly(x**2+y).homogenize(z) == Poly(x**2+y*z) assert Poly(x+y).homogenize(z) == Poly(x+y, x, y, z) assert Poly(x+y**2).homogenize(y) == Poly(x*y+y**2) def test_Poly_homogeneous_order(): assert Poly(0, x, y).homogeneous_order() is -oo assert Poly(1, x, y).homogeneous_order() == 0 assert Poly(x, x, y).homogeneous_order() == 1 assert Poly(x*y, x, y).homogeneous_order() == 2 assert Poly(x + 1, x, y).homogeneous_order() is None assert Poly(x*y + x, x, y).homogeneous_order() is None assert Poly(x**5 + 2*x**3*y**2 + 9*x*y**4).homogeneous_order() == 5 assert Poly(x**5 + 2*x**3*y**3 + 9*x*y**4).homogeneous_order() is None def test_Poly_LC(): assert Poly(0, x).LC() == 0 assert Poly(1, x).LC() == 1 assert Poly(2*x**2 + x, x).LC() == 2 assert Poly(x*y**7 + 2*x**2*y**3).LC('lex') == 2 assert Poly(x*y**7 + 2*x**2*y**3).LC('grlex') == 1 assert LC(x*y**7 + 2*x**2*y**3, order='lex') == 2 assert LC(x*y**7 + 2*x**2*y**3, order='grlex') == 1 def test_Poly_TC(): assert Poly(0, x).TC() == 0 assert Poly(1, x).TC() == 1 assert Poly(2*x**2 + x, x).TC() == 0 def test_Poly_EC(): assert Poly(0, x).EC() == 0 assert Poly(1, x).EC() == 1 assert Poly(2*x**2 + x, x).EC() == 1 assert Poly(x*y**7 + 2*x**2*y**3).EC('lex') == 1 assert Poly(x*y**7 + 2*x**2*y**3).EC('grlex') == 2 def test_Poly_coeff(): assert Poly(0, x).coeff_monomial(1) == 0 assert Poly(0, x).coeff_monomial(x) == 0 assert Poly(1, x).coeff_monomial(1) == 1 assert Poly(1, x).coeff_monomial(x) == 0 assert Poly(x**8, x).coeff_monomial(1) == 0 assert Poly(x**8, x).coeff_monomial(x**7) == 0 assert Poly(x**8, x).coeff_monomial(x**8) == 1 assert Poly(x**8, x).coeff_monomial(x**9) == 0 assert Poly(3*x*y**2 + 1, x, y).coeff_monomial(1) == 1 assert Poly(3*x*y**2 + 1, x, y).coeff_monomial(x*y**2) == 3 p = Poly(24*x*y*exp(8) + 23*x, x, y) assert p.coeff_monomial(x) == 23 assert p.coeff_monomial(y) == 0 assert p.coeff_monomial(x*y) == 24*exp(8) assert p.as_expr().coeff(x) == 24*y*exp(8) + 23 raises(NotImplementedError, lambda: p.coeff(x)) raises(ValueError, lambda: Poly(x + 1).coeff_monomial(0)) raises(ValueError, lambda: Poly(x + 1).coeff_monomial(3*x)) raises(ValueError, lambda: Poly(x + 1).coeff_monomial(3*x*y)) def test_Poly_nth(): assert Poly(0, x).nth(0) == 0 assert Poly(0, x).nth(1) == 0 assert Poly(1, x).nth(0) == 1 assert Poly(1, x).nth(1) == 0 assert Poly(x**8, x).nth(0) == 0 assert Poly(x**8, x).nth(7) == 0 assert Poly(x**8, x).nth(8) == 1 assert Poly(x**8, x).nth(9) == 0 assert Poly(3*x*y**2 + 1, x, y).nth(0, 0) == 1 assert Poly(3*x*y**2 + 1, x, y).nth(1, 2) == 3 raises(ValueError, lambda: Poly(x*y + 1, x, y).nth(1)) def test_Poly_LM(): assert Poly(0, x).LM() == (0,) assert Poly(1, x).LM() == (0,) assert Poly(2*x**2 + x, x).LM() == (2,) assert Poly(x*y**7 + 2*x**2*y**3).LM('lex') == (2, 3) assert Poly(x*y**7 + 2*x**2*y**3).LM('grlex') == (1, 7) assert LM(x*y**7 + 2*x**2*y**3, order='lex') == x**2*y**3 assert LM(x*y**7 + 2*x**2*y**3, order='grlex') == x*y**7 def test_Poly_LM_custom_order(): f = Poly(x**2*y**3*z + x**2*y*z**3 + x*y*z + 1) rev_lex = lambda monom: tuple(reversed(monom)) assert f.LM(order='lex') == (2, 3, 1) assert f.LM(order=rev_lex) == (2, 1, 3) def test_Poly_EM(): assert Poly(0, x).EM() == (0,) assert Poly(1, x).EM() == (0,) assert Poly(2*x**2 + x, x).EM() == (1,) assert Poly(x*y**7 + 2*x**2*y**3).EM('lex') == (1, 7) assert Poly(x*y**7 + 2*x**2*y**3).EM('grlex') == (2, 3) def test_Poly_LT(): assert Poly(0, x).LT() == ((0,), 0) assert Poly(1, x).LT() == ((0,), 1) assert Poly(2*x**2 + x, x).LT() == ((2,), 2) assert Poly(x*y**7 + 2*x**2*y**3).LT('lex') == ((2, 3), 2) assert Poly(x*y**7 + 2*x**2*y**3).LT('grlex') == ((1, 7), 1) assert LT(x*y**7 + 2*x**2*y**3, order='lex') == 2*x**2*y**3 assert LT(x*y**7 + 2*x**2*y**3, order='grlex') == x*y**7 def test_Poly_ET(): assert Poly(0, x).ET() == ((0,), 0) assert Poly(1, x).ET() == ((0,), 1) assert Poly(2*x**2 + x, x).ET() == ((1,), 1) assert Poly(x*y**7 + 2*x**2*y**3).ET('lex') == ((1, 7), 1) assert Poly(x*y**7 + 2*x**2*y**3).ET('grlex') == ((2, 3), 2) def test_Poly_max_norm(): assert Poly(-1, x).max_norm() == 1 assert Poly( 0, x).max_norm() == 0 assert Poly( 1, x).max_norm() == 1 def test_Poly_l1_norm(): assert Poly(-1, x).l1_norm() == 1 assert Poly( 0, x).l1_norm() == 0 assert Poly( 1, x).l1_norm() == 1 def test_Poly_clear_denoms(): coeff, poly = Poly(x + 2, x).clear_denoms() assert coeff == 1 and poly == Poly( x + 2, x, domain='ZZ') and poly.get_domain() == ZZ coeff, poly = Poly(x/2 + 1, x).clear_denoms() assert coeff == 2 and poly == Poly( x + 2, x, domain='QQ') and poly.get_domain() == QQ coeff, poly = Poly(x/2 + 1, x).clear_denoms(convert=True) assert coeff == 2 and poly == Poly( x + 2, x, domain='ZZ') and poly.get_domain() == ZZ coeff, poly = Poly(x/y + 1, x).clear_denoms(convert=True) assert coeff == y and poly == Poly( x + y, x, domain='ZZ[y]') and poly.get_domain() == ZZ[y] coeff, poly = Poly(x/3 + sqrt(2), x, domain='EX').clear_denoms() assert coeff == 3 and poly == Poly( x + 3*sqrt(2), x, domain='EX') and poly.get_domain() == EX coeff, poly = Poly( x/3 + sqrt(2), x, domain='EX').clear_denoms(convert=True) assert coeff == 3 and poly == Poly( x + 3*sqrt(2), x, domain='EX') and poly.get_domain() == EX def test_Poly_rat_clear_denoms(): f = Poly(x**2/y + 1, x) g = Poly(x**3 + y, x) assert f.rat_clear_denoms(g) == \ (Poly(x**2 + y, x), Poly(y*x**3 + y**2, x)) f = f.set_domain(EX) g = g.set_domain(EX) assert f.rat_clear_denoms(g) == (f, g) def test_issue_20427(): f = Poly(-117968192370600*18**(S(1)/3)/(217603955769048*(24201 + 253*sqrt(9165))**(S(1)/3) + 2273005839412*sqrt(9165)*(24201 + 253*sqrt(9165))**(S(1)/3)) - 15720318185*2**(S(2)/3)*3**(S(1)/3)*(24201 + 253*sqrt(9165))**(S(2)/3)/(217603955769048*(24201 + 253*sqrt(9165))** (S(1)/3) + 2273005839412*sqrt(9165)*(24201 + 253*sqrt(9165))**(S(1)/3)) + 15720318185*12**(S(1)/3)*(24201 + 253*sqrt(9165))**(S(2)/3)/( 217603955769048*(24201 + 253*sqrt(9165))**(S(1)/3) + 2273005839412* sqrt(9165)*(24201 + 253*sqrt(9165))**(S(1)/3)) + 117968192370600*2**( S(1)/3)*3**(S(2)/3)/(217603955769048*(24201 + 253*sqrt(9165))**(S(1)/3) + 2273005839412*sqrt(9165)*(24201 + 253*sqrt(9165))**(S(1)/3)), x) assert f == Poly(0, x, domain='EX') def test_Poly_integrate(): assert Poly(x + 1).integrate() == Poly(x**2/2 + x) assert Poly(x + 1).integrate(x) == Poly(x**2/2 + x) assert Poly(x + 1).integrate((x, 1)) == Poly(x**2/2 + x) assert Poly(x*y + 1).integrate(x) == Poly(x**2*y/2 + x) assert Poly(x*y + 1).integrate(y) == Poly(x*y**2/2 + y) assert Poly(x*y + 1).integrate(x, x) == Poly(x**3*y/6 + x**2/2) assert Poly(x*y + 1).integrate(y, y) == Poly(x*y**3/6 + y**2/2) assert Poly(x*y + 1).integrate((x, 2)) == Poly(x**3*y/6 + x**2/2) assert Poly(x*y + 1).integrate((y, 2)) == Poly(x*y**3/6 + y**2/2) assert Poly(x*y + 1).integrate(x, y) == Poly(x**2*y**2/4 + x*y) assert Poly(x*y + 1).integrate(y, x) == Poly(x**2*y**2/4 + x*y) def test_Poly_diff(): assert Poly(x**2 + x).diff() == Poly(2*x + 1) assert Poly(x**2 + x).diff(x) == Poly(2*x + 1) assert Poly(x**2 + x).diff((x, 1)) == Poly(2*x + 1) assert Poly(x**2*y**2 + x*y).diff(x) == Poly(2*x*y**2 + y) assert Poly(x**2*y**2 + x*y).diff(y) == Poly(2*x**2*y + x) assert Poly(x**2*y**2 + x*y).diff(x, x) == Poly(2*y**2, x, y) assert Poly(x**2*y**2 + x*y).diff(y, y) == Poly(2*x**2, x, y) assert Poly(x**2*y**2 + x*y).diff((x, 2)) == Poly(2*y**2, x, y) assert Poly(x**2*y**2 + x*y).diff((y, 2)) == Poly(2*x**2, x, y) assert Poly(x**2*y**2 + x*y).diff(x, y) == Poly(4*x*y + 1) assert Poly(x**2*y**2 + x*y).diff(y, x) == Poly(4*x*y + 1) def test_issue_9585(): assert diff(Poly(x**2 + x)) == Poly(2*x + 1) assert diff(Poly(x**2 + x), x, evaluate=False) == \ Derivative(Poly(x**2 + x), x) assert Derivative(Poly(x**2 + x), x).doit() == Poly(2*x + 1) def test_Poly_eval(): assert Poly(0, x).eval(7) == 0 assert Poly(1, x).eval(7) == 1 assert Poly(x, x).eval(7) == 7 assert Poly(0, x).eval(0, 7) == 0 assert Poly(1, x).eval(0, 7) == 1 assert Poly(x, x).eval(0, 7) == 7 assert Poly(0, x).eval(x, 7) == 0 assert Poly(1, x).eval(x, 7) == 1 assert Poly(x, x).eval(x, 7) == 7 assert Poly(0, x).eval('x', 7) == 0 assert Poly(1, x).eval('x', 7) == 1 assert Poly(x, x).eval('x', 7) == 7 raises(PolynomialError, lambda: Poly(1, x).eval(1, 7)) raises(PolynomialError, lambda: Poly(1, x).eval(y, 7)) raises(PolynomialError, lambda: Poly(1, x).eval('y', 7)) assert Poly(123, x, y).eval(7) == Poly(123, y) assert Poly(2*y, x, y).eval(7) == Poly(2*y, y) assert Poly(x*y, x, y).eval(7) == Poly(7*y, y) assert Poly(123, x, y).eval(x, 7) == Poly(123, y) assert Poly(2*y, x, y).eval(x, 7) == Poly(2*y, y) assert Poly(x*y, x, y).eval(x, 7) == Poly(7*y, y) assert Poly(123, x, y).eval(y, 7) == Poly(123, x) assert Poly(2*y, x, y).eval(y, 7) == Poly(14, x) assert Poly(x*y, x, y).eval(y, 7) == Poly(7*x, x) assert Poly(x*y + y, x, y).eval({x: 7}) == Poly(8*y, y) assert Poly(x*y + y, x, y).eval({y: 7}) == Poly(7*x + 7, x) assert Poly(x*y + y, x, y).eval({x: 6, y: 7}) == 49 assert Poly(x*y + y, x, y).eval({x: 7, y: 6}) == 48 assert Poly(x*y + y, x, y).eval((6, 7)) == 49 assert Poly(x*y + y, x, y).eval([6, 7]) == 49 assert Poly(x + 1, domain='ZZ').eval(S.Half) == Rational(3, 2) assert Poly(x + 1, domain='ZZ').eval(sqrt(2)) == sqrt(2) + 1 raises(ValueError, lambda: Poly(x*y + y, x, y).eval((6, 7, 8))) raises(DomainError, lambda: Poly(x + 1, domain='ZZ').eval(S.Half, auto=False)) # issue 6344 alpha = Symbol('alpha') result = (2*alpha*z - 2*alpha + z**2 + 3)/(z**2 - 2*z + 1) f = Poly(x**2 + (alpha - 1)*x - alpha + 1, x, domain='ZZ[alpha]') assert f.eval((z + 1)/(z - 1)) == result g = Poly(x**2 + (alpha - 1)*x - alpha + 1, x, y, domain='ZZ[alpha]') assert g.eval((z + 1)/(z - 1)) == Poly(result, y, domain='ZZ(alpha,z)') def test_Poly___call__(): f = Poly(2*x*y + 3*x + y + 2*z) assert f(2) == Poly(5*y + 2*z + 6) assert f(2, 5) == Poly(2*z + 31) assert f(2, 5, 7) == 45 def test_parallel_poly_from_expr(): assert parallel_poly_from_expr( [x - 1, x**2 - 1], x)[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [Poly(x - 1, x), x**2 - 1], x)[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [x - 1, Poly(x**2 - 1, x)], x)[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr([Poly( x - 1, x), Poly(x**2 - 1, x)], x)[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [x - 1, x**2 - 1], x, y)[0] == [Poly(x - 1, x, y), Poly(x**2 - 1, x, y)] assert parallel_poly_from_expr([Poly( x - 1, x), x**2 - 1], x, y)[0] == [Poly(x - 1, x, y), Poly(x**2 - 1, x, y)] assert parallel_poly_from_expr([x - 1, Poly( x**2 - 1, x)], x, y)[0] == [Poly(x - 1, x, y), Poly(x**2 - 1, x, y)] assert parallel_poly_from_expr([Poly(x - 1, x), Poly( x**2 - 1, x)], x, y)[0] == [Poly(x - 1, x, y), Poly(x**2 - 1, x, y)] assert parallel_poly_from_expr( [x - 1, x**2 - 1])[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [Poly(x - 1, x), x**2 - 1])[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [x - 1, Poly(x**2 - 1, x)])[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [Poly(x - 1, x), Poly(x**2 - 1, x)])[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [1, x**2 - 1])[0] == [Poly(1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [1, x**2 - 1])[0] == [Poly(1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [1, Poly(x**2 - 1, x)])[0] == [Poly(1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [1, Poly(x**2 - 1, x)])[0] == [Poly(1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [x**2 - 1, 1])[0] == [Poly(x**2 - 1, x), Poly(1, x)] assert parallel_poly_from_expr( [x**2 - 1, 1])[0] == [Poly(x**2 - 1, x), Poly(1, x)] assert parallel_poly_from_expr( [Poly(x**2 - 1, x), 1])[0] == [Poly(x**2 - 1, x), Poly(1, x)] assert parallel_poly_from_expr( [Poly(x**2 - 1, x), 1])[0] == [Poly(x**2 - 1, x), Poly(1, x)] assert parallel_poly_from_expr([Poly(x, x, y), Poly(y, x, y)], x, y, order='lex')[0] == \ [Poly(x, x, y, domain='ZZ'), Poly(y, x, y, domain='ZZ')] raises(PolificationFailed, lambda: parallel_poly_from_expr([0, 1])) def test_pdiv(): f, g = x**2 - y**2, x - y q, r = x + y, 0 F, G, Q, R = [ Poly(h, x, y) for h in (f, g, q, r) ] assert F.pdiv(G) == (Q, R) assert F.prem(G) == R assert F.pquo(G) == Q assert F.pexquo(G) == Q assert pdiv(f, g) == (q, r) assert prem(f, g) == r assert pquo(f, g) == q assert pexquo(f, g) == q assert pdiv(f, g, x, y) == (q, r) assert prem(f, g, x, y) == r assert pquo(f, g, x, y) == q assert pexquo(f, g, x, y) == q assert pdiv(f, g, (x, y)) == (q, r) assert prem(f, g, (x, y)) == r assert pquo(f, g, (x, y)) == q assert pexquo(f, g, (x, y)) == q assert pdiv(F, G) == (Q, R) assert prem(F, G) == R assert pquo(F, G) == Q assert pexquo(F, G) == Q assert pdiv(f, g, polys=True) == (Q, R) assert prem(f, g, polys=True) == R assert pquo(f, g, polys=True) == Q assert pexquo(f, g, polys=True) == Q assert pdiv(F, G, polys=False) == (q, r) assert prem(F, G, polys=False) == r assert pquo(F, G, polys=False) == q assert pexquo(F, G, polys=False) == q raises(ComputationFailed, lambda: pdiv(4, 2)) raises(ComputationFailed, lambda: prem(4, 2)) raises(ComputationFailed, lambda: pquo(4, 2)) raises(ComputationFailed, lambda: pexquo(4, 2)) def test_div(): f, g = x**2 - y**2, x - y q, r = x + y, 0 F, G, Q, R = [ Poly(h, x, y) for h in (f, g, q, r) ] assert F.div(G) == (Q, R) assert F.rem(G) == R assert F.quo(G) == Q assert F.exquo(G) == Q assert div(f, g) == (q, r) assert rem(f, g) == r assert quo(f, g) == q assert exquo(f, g) == q assert div(f, g, x, y) == (q, r) assert rem(f, g, x, y) == r assert quo(f, g, x, y) == q assert exquo(f, g, x, y) == q assert div(f, g, (x, y)) == (q, r) assert rem(f, g, (x, y)) == r assert quo(f, g, (x, y)) == q assert exquo(f, g, (x, y)) == q assert div(F, G) == (Q, R) assert rem(F, G) == R assert quo(F, G) == Q assert exquo(F, G) == Q assert div(f, g, polys=True) == (Q, R) assert rem(f, g, polys=True) == R assert quo(f, g, polys=True) == Q assert exquo(f, g, polys=True) == Q assert div(F, G, polys=False) == (q, r) assert rem(F, G, polys=False) == r assert quo(F, G, polys=False) == q assert exquo(F, G, polys=False) == q raises(ComputationFailed, lambda: div(4, 2)) raises(ComputationFailed, lambda: rem(4, 2)) raises(ComputationFailed, lambda: quo(4, 2)) raises(ComputationFailed, lambda: exquo(4, 2)) f, g = x**2 + 1, 2*x - 4 qz, rz = 0, x**2 + 1 qq, rq = x/2 + 1, 5 assert div(f, g) == (qq, rq) assert div(f, g, auto=True) == (qq, rq) assert div(f, g, auto=False) == (qz, rz) assert div(f, g, domain=ZZ) == (qz, rz) assert div(f, g, domain=QQ) == (qq, rq) assert div(f, g, domain=ZZ, auto=True) == (qq, rq) assert div(f, g, domain=ZZ, auto=False) == (qz, rz) assert div(f, g, domain=QQ, auto=True) == (qq, rq) assert div(f, g, domain=QQ, auto=False) == (qq, rq) assert rem(f, g) == rq assert rem(f, g, auto=True) == rq assert rem(f, g, auto=False) == rz assert rem(f, g, domain=ZZ) == rz assert rem(f, g, domain=QQ) == rq assert rem(f, g, domain=ZZ, auto=True) == rq assert rem(f, g, domain=ZZ, auto=False) == rz assert rem(f, g, domain=QQ, auto=True) == rq assert rem(f, g, domain=QQ, auto=False) == rq assert quo(f, g) == qq assert quo(f, g, auto=True) == qq assert quo(f, g, auto=False) == qz assert quo(f, g, domain=ZZ) == qz assert quo(f, g, domain=QQ) == qq assert quo(f, g, domain=ZZ, auto=True) == qq assert quo(f, g, domain=ZZ, auto=False) == qz assert quo(f, g, domain=QQ, auto=True) == qq assert quo(f, g, domain=QQ, auto=False) == qq f, g, q = x**2, 2*x, x/2 assert exquo(f, g) == q assert exquo(f, g, auto=True) == q raises(ExactQuotientFailed, lambda: exquo(f, g, auto=False)) raises(ExactQuotientFailed, lambda: exquo(f, g, domain=ZZ)) assert exquo(f, g, domain=QQ) == q assert exquo(f, g, domain=ZZ, auto=True) == q raises(ExactQuotientFailed, lambda: exquo(f, g, domain=ZZ, auto=False)) assert exquo(f, g, domain=QQ, auto=True) == q assert exquo(f, g, domain=QQ, auto=False) == q f, g = Poly(x**2), Poly(x) q, r = f.div(g) assert q.get_domain().is_ZZ and r.get_domain().is_ZZ r = f.rem(g) assert r.get_domain().is_ZZ q = f.quo(g) assert q.get_domain().is_ZZ q = f.exquo(g) assert q.get_domain().is_ZZ f, g = Poly(x+y, x), Poly(2*x+y, x) q, r = f.div(g) assert q.get_domain().is_Frac and r.get_domain().is_Frac # https://github.com/sympy/sympy/issues/19579 p = Poly(2+3*I, x, domain=ZZ_I) q = Poly(1-I, x, domain=ZZ_I) assert p.div(q, auto=False) == \ (Poly(0, x, domain='ZZ_I'), Poly(2 + 3*I, x, domain='ZZ_I')) assert p.div(q, auto=True) == \ (Poly(-S(1)/2 + 5*I/2, x, domain='QQ_I'), Poly(0, x, domain='QQ_I')) def test_issue_7864(): q, r = div(a, .408248290463863*a) assert abs(q - 2.44948974278318) < 1e-14 assert r == 0 def test_gcdex(): f, g = 2*x, x**2 - 16 s, t, h = x/32, Rational(-1, 16), 1 F, G, S, T, H = [ Poly(u, x, domain='QQ') for u in (f, g, s, t, h) ] assert F.half_gcdex(G) == (S, H) assert F.gcdex(G) == (S, T, H) assert F.invert(G) == S assert half_gcdex(f, g) == (s, h) assert gcdex(f, g) == (s, t, h) assert invert(f, g) == s assert half_gcdex(f, g, x) == (s, h) assert gcdex(f, g, x) == (s, t, h) assert invert(f, g, x) == s assert half_gcdex(f, g, (x,)) == (s, h) assert gcdex(f, g, (x,)) == (s, t, h) assert invert(f, g, (x,)) == s assert half_gcdex(F, G) == (S, H) assert gcdex(F, G) == (S, T, H) assert invert(F, G) == S assert half_gcdex(f, g, polys=True) == (S, H) assert gcdex(f, g, polys=True) == (S, T, H) assert invert(f, g, polys=True) == S assert half_gcdex(F, G, polys=False) == (s, h) assert gcdex(F, G, polys=False) == (s, t, h) assert invert(F, G, polys=False) == s assert half_gcdex(100, 2004) == (-20, 4) assert gcdex(100, 2004) == (-20, 1, 4) assert invert(3, 7) == 5 raises(DomainError, lambda: half_gcdex(x + 1, 2*x + 1, auto=False)) raises(DomainError, lambda: gcdex(x + 1, 2*x + 1, auto=False)) raises(DomainError, lambda: invert(x + 1, 2*x + 1, auto=False)) def test_revert(): f = Poly(1 - x**2/2 + x**4/24 - x**6/720) g = Poly(61*x**6/720 + 5*x**4/24 + x**2/2 + 1) assert f.revert(8) == g def test_subresultants(): f, g, h = x**2 - 2*x + 1, x**2 - 1, 2*x - 2 F, G, H = Poly(f), Poly(g), Poly(h) assert F.subresultants(G) == [F, G, H] assert subresultants(f, g) == [f, g, h] assert subresultants(f, g, x) == [f, g, h] assert subresultants(f, g, (x,)) == [f, g, h] assert subresultants(F, G) == [F, G, H] assert subresultants(f, g, polys=True) == [F, G, H] assert subresultants(F, G, polys=False) == [f, g, h] raises(ComputationFailed, lambda: subresultants(4, 2)) def test_resultant(): f, g, h = x**2 - 2*x + 1, x**2 - 1, 0 F, G = Poly(f), Poly(g) assert F.resultant(G) == h assert resultant(f, g) == h assert resultant(f, g, x) == h assert resultant(f, g, (x,)) == h assert resultant(F, G) == h assert resultant(f, g, polys=True) == h assert resultant(F, G, polys=False) == h assert resultant(f, g, includePRS=True) == (h, [f, g, 2*x - 2]) f, g, h = x - a, x - b, a - b F, G, H = Poly(f), Poly(g), Poly(h) assert F.resultant(G) == H assert resultant(f, g) == h assert resultant(f, g, x) == h assert resultant(f, g, (x,)) == h assert resultant(F, G) == H assert resultant(f, g, polys=True) == H assert resultant(F, G, polys=False) == h raises(ComputationFailed, lambda: resultant(4, 2)) def test_discriminant(): f, g = x**3 + 3*x**2 + 9*x - 13, -11664 F = Poly(f) assert F.discriminant() == g assert discriminant(f) == g assert discriminant(f, x) == g assert discriminant(f, (x,)) == g assert discriminant(F) == g assert discriminant(f, polys=True) == g assert discriminant(F, polys=False) == g f, g = a*x**2 + b*x + c, b**2 - 4*a*c F, G = Poly(f), Poly(g) assert F.discriminant() == G assert discriminant(f) == g assert discriminant(f, x, a, b, c) == g assert discriminant(f, (x, a, b, c)) == g assert discriminant(F) == G assert discriminant(f, polys=True) == G assert discriminant(F, polys=False) == g raises(ComputationFailed, lambda: discriminant(4)) def test_dispersion(): # We test only the API here. For more mathematical # tests see the dedicated test file. fp = poly((x + 1)*(x + 2), x) assert sorted(fp.dispersionset()) == [0, 1] assert fp.dispersion() == 1 fp = poly(x**4 - 3*x**2 + 1, x) gp = fp.shift(-3) assert sorted(fp.dispersionset(gp)) == [2, 3, 4] assert fp.dispersion(gp) == 4 def test_gcd_list(): F = [x**3 - 1, x**2 - 1, x**2 - 3*x + 2] assert gcd_list(F) == x - 1 assert gcd_list(F, polys=True) == Poly(x - 1) assert gcd_list([]) == 0 assert gcd_list([1, 2]) == 1 assert gcd_list([4, 6, 8]) == 2 assert gcd_list([x*(y + 42) - x*y - x*42]) == 0 gcd = gcd_list([], x) assert gcd.is_Number and gcd is S.Zero gcd = gcd_list([], x, polys=True) assert gcd.is_Poly and gcd.is_zero a = sqrt(2) assert gcd_list([a, -a]) == gcd_list([-a, a]) == a raises(ComputationFailed, lambda: gcd_list([], polys=True)) def test_lcm_list(): F = [x**3 - 1, x**2 - 1, x**2 - 3*x + 2] assert lcm_list(F) == x**5 - x**4 - 2*x**3 - x**2 + x + 2 assert lcm_list(F, polys=True) == Poly(x**5 - x**4 - 2*x**3 - x**2 + x + 2) assert lcm_list([]) == 1 assert lcm_list([1, 2]) == 2 assert lcm_list([4, 6, 8]) == 24 assert lcm_list([x*(y + 42) - x*y - x*42]) == 0 lcm = lcm_list([], x) assert lcm.is_Number and lcm is S.One lcm = lcm_list([], x, polys=True) assert lcm.is_Poly and lcm.is_one raises(ComputationFailed, lambda: lcm_list([], polys=True)) def test_gcd(): f, g = x**3 - 1, x**2 - 1 s, t = x**2 + x + 1, x + 1 h, r = x - 1, x**4 + x**3 - x - 1 F, G, S, T, H, R = [ Poly(u) for u in (f, g, s, t, h, r) ] assert F.cofactors(G) == (H, S, T) assert F.gcd(G) == H assert F.lcm(G) == R assert cofactors(f, g) == (h, s, t) assert gcd(f, g) == h assert lcm(f, g) == r assert cofactors(f, g, x) == (h, s, t) assert gcd(f, g, x) == h assert lcm(f, g, x) == r assert cofactors(f, g, (x,)) == (h, s, t) assert gcd(f, g, (x,)) == h assert lcm(f, g, (x,)) == r assert cofactors(F, G) == (H, S, T) assert gcd(F, G) == H assert lcm(F, G) == R assert cofactors(f, g, polys=True) == (H, S, T) assert gcd(f, g, polys=True) == H assert lcm(f, g, polys=True) == R assert cofactors(F, G, polys=False) == (h, s, t) assert gcd(F, G, polys=False) == h assert lcm(F, G, polys=False) == r f, g = 1.0*x**2 - 1.0, 1.0*x - 1.0 h, s, t = g, 1.0*x + 1.0, 1.0 assert cofactors(f, g) == (h, s, t) assert gcd(f, g) == h assert lcm(f, g) == f f, g = 1.0*x**2 - 1.0, 1.0*x - 1.0 h, s, t = g, 1.0*x + 1.0, 1.0 assert cofactors(f, g) == (h, s, t) assert gcd(f, g) == h assert lcm(f, g) == f assert cofactors(8, 6) == (2, 4, 3) assert gcd(8, 6) == 2 assert lcm(8, 6) == 24 f, g = x**2 - 3*x - 4, x**3 - 4*x**2 + x - 4 l = x**4 - 3*x**3 - 3*x**2 - 3*x - 4 h, s, t = x - 4, x + 1, x**2 + 1 assert cofactors(f, g, modulus=11) == (h, s, t) assert gcd(f, g, modulus=11) == h assert lcm(f, g, modulus=11) == l f, g = x**2 + 8*x + 7, x**3 + 7*x**2 + x + 7 l = x**4 + 8*x**3 + 8*x**2 + 8*x + 7 h, s, t = x + 7, x + 1, x**2 + 1 assert cofactors(f, g, modulus=11, symmetric=False) == (h, s, t) assert gcd(f, g, modulus=11, symmetric=False) == h assert lcm(f, g, modulus=11, symmetric=False) == l a, b = sqrt(2), -sqrt(2) assert gcd(a, b) == gcd(b, a) == sqrt(2) a, b = sqrt(-2), -sqrt(-2) assert gcd(a, b) == gcd(b, a) == sqrt(2) assert gcd(Poly(x - 2, x), Poly(I*x, x)) == Poly(1, x, domain=ZZ_I) raises(TypeError, lambda: gcd(x)) raises(TypeError, lambda: lcm(x)) def test_gcd_numbers_vs_polys(): assert isinstance(gcd(3, 9), Integer) assert isinstance(gcd(3*x, 9), Integer) assert gcd(3, 9) == 3 assert gcd(3*x, 9) == 3 assert isinstance(gcd(Rational(3, 2), Rational(9, 4)), Rational) assert isinstance(gcd(Rational(3, 2)*x, Rational(9, 4)), Rational) assert gcd(Rational(3, 2), Rational(9, 4)) == Rational(3, 4) assert gcd(Rational(3, 2)*x, Rational(9, 4)) == 1 assert isinstance(gcd(3.0, 9.0), Float) assert isinstance(gcd(3.0*x, 9.0), Float) assert gcd(3.0, 9.0) == 1.0 assert gcd(3.0*x, 9.0) == 1.0 # partial fix of 20597 assert gcd(Mul(2, 3, evaluate=False), 2) == 2 def test_terms_gcd(): assert terms_gcd(1) == 1 assert terms_gcd(1, x) == 1 assert terms_gcd(x - 1) == x - 1 assert terms_gcd(-x - 1) == -x - 1 assert terms_gcd(2*x + 3) == 2*x + 3 assert terms_gcd(6*x + 4) == Mul(2, 3*x + 2, evaluate=False) assert terms_gcd(x**3*y + x*y**3) == x*y*(x**2 + y**2) assert terms_gcd(2*x**3*y + 2*x*y**3) == 2*x*y*(x**2 + y**2) assert terms_gcd(x**3*y/2 + x*y**3/2) == x*y/2*(x**2 + y**2) assert terms_gcd(x**3*y + 2*x*y**3) == x*y*(x**2 + 2*y**2) assert terms_gcd(2*x**3*y + 4*x*y**3) == 2*x*y*(x**2 + 2*y**2) assert terms_gcd(2*x**3*y/3 + 4*x*y**3/5) == x*y*Rational(2, 15)*(5*x**2 + 6*y**2) assert terms_gcd(2.0*x**3*y + 4.1*x*y**3) == x*y*(2.0*x**2 + 4.1*y**2) assert _aresame(terms_gcd(2.0*x + 3), 2.0*x + 3) assert terms_gcd((3 + 3*x)*(x + x*y), expand=False) == \ (3*x + 3)*(x*y + x) assert terms_gcd((3 + 3*x)*(x + x*sin(3 + 3*y)), expand=False, deep=True) == \ 3*x*(x + 1)*(sin(Mul(3, y + 1, evaluate=False)) + 1) assert terms_gcd(sin(x + x*y), deep=True) == \ sin(x*(y + 1)) eq = Eq(2*x, 2*y + 2*z*y) assert terms_gcd(eq) == Eq(2*x, 2*y*(z + 1)) assert terms_gcd(eq, deep=True) == Eq(2*x, 2*y*(z + 1)) raises(TypeError, lambda: terms_gcd(x < 2)) def test_trunc(): f, g = x**5 + 2*x**4 + 3*x**3 + 4*x**2 + 5*x + 6, x**5 - x**4 + x**2 - x F, G = Poly(f), Poly(g) assert F.trunc(3) == G assert trunc(f, 3) == g assert trunc(f, 3, x) == g assert trunc(f, 3, (x,)) == g assert trunc(F, 3) == G assert trunc(f, 3, polys=True) == G assert trunc(F, 3, polys=False) == g f, g = 6*x**5 + 5*x**4 + 4*x**3 + 3*x**2 + 2*x + 1, -x**4 + x**3 - x + 1 F, G = Poly(f), Poly(g) assert F.trunc(3) == G assert trunc(f, 3) == g assert trunc(f, 3, x) == g assert trunc(f, 3, (x,)) == g assert trunc(F, 3) == G assert trunc(f, 3, polys=True) == G assert trunc(F, 3, polys=False) == g f = Poly(x**2 + 2*x + 3, modulus=5) assert f.trunc(2) == Poly(x**2 + 1, modulus=5) def test_monic(): f, g = 2*x - 1, x - S.Half F, G = Poly(f, domain='QQ'), Poly(g) assert F.monic() == G assert monic(f) == g assert monic(f, x) == g assert monic(f, (x,)) == g assert monic(F) == G assert monic(f, polys=True) == G assert monic(F, polys=False) == g raises(ComputationFailed, lambda: monic(4)) assert monic(2*x**2 + 6*x + 4, auto=False) == x**2 + 3*x + 2 raises(ExactQuotientFailed, lambda: monic(2*x + 6*x + 1, auto=False)) assert monic(2.0*x**2 + 6.0*x + 4.0) == 1.0*x**2 + 3.0*x + 2.0 assert monic(2*x**2 + 3*x + 4, modulus=5) == x**2 - x + 2 def test_content(): f, F = 4*x + 2, Poly(4*x + 2) assert F.content() == 2 assert content(f) == 2 raises(ComputationFailed, lambda: content(4)) f = Poly(2*x, modulus=3) assert f.content() == 1 def test_primitive(): f, g = 4*x + 2, 2*x + 1 F, G = Poly(f), Poly(g) assert F.primitive() == (2, G) assert primitive(f) == (2, g) assert primitive(f, x) == (2, g) assert primitive(f, (x,)) == (2, g) assert primitive(F) == (2, G) assert primitive(f, polys=True) == (2, G) assert primitive(F, polys=False) == (2, g) raises(ComputationFailed, lambda: primitive(4)) f = Poly(2*x, modulus=3) g = Poly(2.0*x, domain=RR) assert f.primitive() == (1, f) assert g.primitive() == (1.0, g) assert primitive(S('-3*x/4 + y + 11/8')) == \ S('(1/8, -6*x + 8*y + 11)') def test_compose(): f = x**12 + 20*x**10 + 150*x**8 + 500*x**6 + 625*x**4 - 2*x**3 - 10*x + 9 g = x**4 - 2*x + 9 h = x**3 + 5*x F, G, H = map(Poly, (f, g, h)) assert G.compose(H) == F assert compose(g, h) == f assert compose(g, h, x) == f assert compose(g, h, (x,)) == f assert compose(G, H) == F assert compose(g, h, polys=True) == F assert compose(G, H, polys=False) == f assert F.decompose() == [G, H] assert decompose(f) == [g, h] assert decompose(f, x) == [g, h] assert decompose(f, (x,)) == [g, h] assert decompose(F) == [G, H] assert decompose(f, polys=True) == [G, H] assert decompose(F, polys=False) == [g, h] raises(ComputationFailed, lambda: compose(4, 2)) raises(ComputationFailed, lambda: decompose(4)) assert compose(x**2 - y**2, x - y, x, y) == x**2 - 2*x*y assert compose(x**2 - y**2, x - y, y, x) == -y**2 + 2*x*y def test_shift(): assert Poly(x**2 - 2*x + 1, x).shift(2) == Poly(x**2 + 2*x + 1, x) def test_transform(): # Also test that 3-way unification is done correctly assert Poly(x**2 - 2*x + 1, x).transform(Poly(x + 1), Poly(x - 1)) == \ Poly(4, x) == \ cancel((x - 1)**2*(x**2 - 2*x + 1).subs(x, (x + 1)/(x - 1))) assert Poly(x**2 - x/2 + 1, x).transform(Poly(x + 1), Poly(x - 1)) == \ Poly(3*x**2/2 + Rational(5, 2), x) == \ cancel((x - 1)**2*(x**2 - x/2 + 1).subs(x, (x + 1)/(x - 1))) assert Poly(x**2 - 2*x + 1, x).transform(Poly(x + S.Half), Poly(x - 1)) == \ Poly(Rational(9, 4), x) == \ cancel((x - 1)**2*(x**2 - 2*x + 1).subs(x, (x + S.Half)/(x - 1))) assert Poly(x**2 - 2*x + 1, x).transform(Poly(x + 1), Poly(x - S.Half)) == \ Poly(Rational(9, 4), x) == \ cancel((x - S.Half)**2*(x**2 - 2*x + 1).subs(x, (x + 1)/(x - S.Half))) # Unify ZZ, QQ, and RR assert Poly(x**2 - 2*x + 1, x).transform(Poly(x + 1.0), Poly(x - S.Half)) == \ Poly(Rational(9, 4), x, domain='RR') == \ cancel((x - S.Half)**2*(x**2 - 2*x + 1).subs(x, (x + 1.0)/(x - S.Half))) raises(ValueError, lambda: Poly(x*y).transform(Poly(x + 1), Poly(x - 1))) raises(ValueError, lambda: Poly(x).transform(Poly(y + 1), Poly(x - 1))) raises(ValueError, lambda: Poly(x).transform(Poly(x + 1), Poly(y - 1))) raises(ValueError, lambda: Poly(x).transform(Poly(x*y + 1), Poly(x - 1))) raises(ValueError, lambda: Poly(x).transform(Poly(x + 1), Poly(x*y - 1))) def test_sturm(): f, F = x, Poly(x, domain='QQ') g, G = 1, Poly(1, x, domain='QQ') assert F.sturm() == [F, G] assert sturm(f) == [f, g] assert sturm(f, x) == [f, g] assert sturm(f, (x,)) == [f, g] assert sturm(F) == [F, G] assert sturm(f, polys=True) == [F, G] assert sturm(F, polys=False) == [f, g] raises(ComputationFailed, lambda: sturm(4)) raises(DomainError, lambda: sturm(f, auto=False)) f = Poly(S(1024)/(15625*pi**8)*x**5 - S(4096)/(625*pi**8)*x**4 + S(32)/(15625*pi**4)*x**3 - S(128)/(625*pi**4)*x**2 + Rational(1, 62500)*x - Rational(1, 625), x, domain='ZZ(pi)') assert sturm(f) == \ [Poly(x**3 - 100*x**2 + pi**4/64*x - 25*pi**4/16, x, domain='ZZ(pi)'), Poly(3*x**2 - 200*x + pi**4/64, x, domain='ZZ(pi)'), Poly((Rational(20000, 9) - pi**4/96)*x + 25*pi**4/18, x, domain='ZZ(pi)'), Poly((-3686400000000*pi**4 - 11520000*pi**8 - 9*pi**12)/(26214400000000 - 245760000*pi**4 + 576*pi**8), x, domain='ZZ(pi)')] def test_gff(): f = x**5 + 2*x**4 - x**3 - 2*x**2 assert Poly(f).gff_list() == [(Poly(x), 1), (Poly(x + 2), 4)] assert gff_list(f) == [(x, 1), (x + 2, 4)] raises(NotImplementedError, lambda: gff(f)) f = x*(x - 1)**3*(x - 2)**2*(x - 4)**2*(x - 5) assert Poly(f).gff_list() == [( Poly(x**2 - 5*x + 4), 1), (Poly(x**2 - 5*x + 4), 2), (Poly(x), 3)] assert gff_list(f) == [(x**2 - 5*x + 4, 1), (x**2 - 5*x + 4, 2), (x, 3)] raises(NotImplementedError, lambda: gff(f)) def test_norm(): a, b = sqrt(2), sqrt(3) f = Poly(a*x + b*y, x, y, extension=(a, b)) assert f.norm() == Poly(4*x**4 - 12*x**2*y**2 + 9*y**4, x, y, domain='QQ') def test_sqf_norm(): assert sqf_norm(x**2 - 2, extension=sqrt(3)) == \ (1, x**2 - 2*sqrt(3)*x + 1, x**4 - 10*x**2 + 1) assert sqf_norm(x**2 - 3, extension=sqrt(2)) == \ (1, x**2 - 2*sqrt(2)*x - 1, x**4 - 10*x**2 + 1) assert Poly(x**2 - 2, extension=sqrt(3)).sqf_norm() == \ (1, Poly(x**2 - 2*sqrt(3)*x + 1, x, extension=sqrt(3)), Poly(x**4 - 10*x**2 + 1, x, domain='QQ')) assert Poly(x**2 - 3, extension=sqrt(2)).sqf_norm() == \ (1, Poly(x**2 - 2*sqrt(2)*x - 1, x, extension=sqrt(2)), Poly(x**4 - 10*x**2 + 1, x, domain='QQ')) def test_sqf(): f = x**5 - x**3 - x**2 + 1 g = x**3 + 2*x**2 + 2*x + 1 h = x - 1 p = x**4 + x**3 - x - 1 F, G, H, P = map(Poly, (f, g, h, p)) assert F.sqf_part() == P assert sqf_part(f) == p assert sqf_part(f, x) == p assert sqf_part(f, (x,)) == p assert sqf_part(F) == P assert sqf_part(f, polys=True) == P assert sqf_part(F, polys=False) == p assert F.sqf_list() == (1, [(G, 1), (H, 2)]) assert sqf_list(f) == (1, [(g, 1), (h, 2)]) assert sqf_list(f, x) == (1, [(g, 1), (h, 2)]) assert sqf_list(f, (x,)) == (1, [(g, 1), (h, 2)]) assert sqf_list(F) == (1, [(G, 1), (H, 2)]) assert sqf_list(f, polys=True) == (1, [(G, 1), (H, 2)]) assert sqf_list(F, polys=False) == (1, [(g, 1), (h, 2)]) assert F.sqf_list_include() == [(G, 1), (H, 2)] raises(ComputationFailed, lambda: sqf_part(4)) assert sqf(1) == 1 assert sqf_list(1) == (1, []) assert sqf((2*x**2 + 2)**7) == 128*(x**2 + 1)**7 assert sqf(f) == g*h**2 assert sqf(f, x) == g*h**2 assert sqf(f, (x,)) == g*h**2 d = x**2 + y**2 assert sqf(f/d) == (g*h**2)/d assert sqf(f/d, x) == (g*h**2)/d assert sqf(f/d, (x,)) == (g*h**2)/d assert sqf(x - 1) == x - 1 assert sqf(-x - 1) == -x - 1 assert sqf(x - 1) == x - 1 assert sqf(6*x - 10) == Mul(2, 3*x - 5, evaluate=False) assert sqf((6*x - 10)/(3*x - 6)) == Rational(2, 3)*((3*x - 5)/(x - 2)) assert sqf(Poly(x**2 - 2*x + 1)) == (x - 1)**2 f = 3 + x - x*(1 + x) + x**2 assert sqf(f) == 3 f = (x**2 + 2*x + 1)**20000000000 assert sqf(f) == (x + 1)**40000000000 assert sqf_list(f) == (1, [(x + 1, 40000000000)]) def test_factor(): f = x**5 - x**3 - x**2 + 1 u = x + 1 v = x - 1 w = x**2 + x + 1 F, U, V, W = map(Poly, (f, u, v, w)) assert F.factor_list() == (1, [(U, 1), (V, 2), (W, 1)]) assert factor_list(f) == (1, [(u, 1), (v, 2), (w, 1)]) assert factor_list(f, x) == (1, [(u, 1), (v, 2), (w, 1)]) assert factor_list(f, (x,)) == (1, [(u, 1), (v, 2), (w, 1)]) assert factor_list(F) == (1, [(U, 1), (V, 2), (W, 1)]) assert factor_list(f, polys=True) == (1, [(U, 1), (V, 2), (W, 1)]) assert factor_list(F, polys=False) == (1, [(u, 1), (v, 2), (w, 1)]) assert F.factor_list_include() == [(U, 1), (V, 2), (W, 1)] assert factor_list(1) == (1, []) assert factor_list(6) == (6, []) assert factor_list(sqrt(3), x) == (sqrt(3), []) assert factor_list((-1)**x, x) == (1, [(-1, x)]) assert factor_list((2*x)**y, x) == (1, [(2, y), (x, y)]) assert factor_list(sqrt(x*y), x) == (1, [(x*y, S.Half)]) assert factor(6) == 6 and factor(6).is_Integer assert factor_list(3*x) == (3, [(x, 1)]) assert factor_list(3*x**2) == (3, [(x, 2)]) assert factor(3*x) == 3*x assert factor(3*x**2) == 3*x**2 assert factor((2*x**2 + 2)**7) == 128*(x**2 + 1)**7 assert factor(f) == u*v**2*w assert factor(f, x) == u*v**2*w assert factor(f, (x,)) == u*v**2*w g, p, q, r = x**2 - y**2, x - y, x + y, x**2 + 1 assert factor(f/g) == (u*v**2*w)/(p*q) assert factor(f/g, x) == (u*v**2*w)/(p*q) assert factor(f/g, (x,)) == (u*v**2*w)/(p*q) p = Symbol('p', positive=True) i = Symbol('i', integer=True) r = Symbol('r', real=True) assert factor(sqrt(x*y)).is_Pow is True assert factor(sqrt(3*x**2 - 3)) == sqrt(3)*sqrt((x - 1)*(x + 1)) assert factor(sqrt(3*x**2 + 3)) == sqrt(3)*sqrt(x**2 + 1) assert factor((y*x**2 - y)**i) == y**i*(x - 1)**i*(x + 1)**i assert factor((y*x**2 + y)**i) == y**i*(x**2 + 1)**i assert factor((y*x**2 - y)**t) == (y*(x - 1)*(x + 1))**t assert factor((y*x**2 + y)**t) == (y*(x**2 + 1))**t f = sqrt(expand((r**2 + 1)*(p + 1)*(p - 1)*(p - 2)**3)) g = sqrt((p - 2)**3*(p - 1))*sqrt(p + 1)*sqrt(r**2 + 1) assert factor(f) == g assert factor(g) == g g = (x - 1)**5*(r**2 + 1) f = sqrt(expand(g)) assert factor(f) == sqrt(g) f = Poly(sin(1)*x + 1, x, domain=EX) assert f.factor_list() == (1, [(f, 1)]) f = x**4 + 1 assert factor(f) == f assert factor(f, extension=I) == (x**2 - I)*(x**2 + I) assert factor(f, gaussian=True) == (x**2 - I)*(x**2 + I) assert factor( f, extension=sqrt(2)) == (x**2 + sqrt(2)*x + 1)*(x**2 - sqrt(2)*x + 1) assert factor(x**2 + 4*I*x - 4) == (x + 2*I)**2 f = x**2 + 2*I*x - 4 assert factor(f) == f f = 8192*x**2 + x*(22656 + 175232*I) - 921416 + 242313*I f_zzi = I*(x*(64 - 64*I) + 773 + 596*I)**2 f_qqi = 8192*(x + S(177)/128 + 1369*I/128)**2 assert factor(f) == f_zzi assert factor(f, domain=ZZ_I) == f_zzi assert factor(f, domain=QQ_I) == f_qqi f = x**2 + 2*sqrt(2)*x + 2 assert factor(f, extension=sqrt(2)) == (x + sqrt(2))**2 assert factor(f**3, extension=sqrt(2)) == (x + sqrt(2))**6 assert factor(x**2 - 2*y**2, extension=sqrt(2)) == \ (x + sqrt(2)*y)*(x - sqrt(2)*y) assert factor(2*x**2 - 4*y**2, extension=sqrt(2)) == \ 2*((x + sqrt(2)*y)*(x - sqrt(2)*y)) assert factor(x - 1) == x - 1 assert factor(-x - 1) == -x - 1 assert factor(x - 1) == x - 1 assert factor(6*x - 10) == Mul(2, 3*x - 5, evaluate=False) assert factor(x**11 + x + 1, modulus=65537, symmetric=True) == \ (x**2 + x + 1)*(x**9 - x**8 + x**6 - x**5 + x**3 - x** 2 + 1) assert factor(x**11 + x + 1, modulus=65537, symmetric=False) == \ (x**2 + x + 1)*(x**9 + 65536*x**8 + x**6 + 65536*x**5 + x**3 + 65536*x** 2 + 1) f = x/pi + x*sin(x)/pi g = y/(pi**2 + 2*pi + 1) + y*sin(x)/(pi**2 + 2*pi + 1) assert factor(f) == x*(sin(x) + 1)/pi assert factor(g) == y*(sin(x) + 1)/(pi + 1)**2 assert factor(Eq( x**2 + 2*x + 1, x**3 + 1)) == Eq((x + 1)**2, (x + 1)*(x**2 - x + 1)) f = (x**2 - 1)/(x**2 + 4*x + 4) assert factor(f) == (x + 1)*(x - 1)/(x + 2)**2 assert factor(f, x) == (x + 1)*(x - 1)/(x + 2)**2 f = 3 + x - x*(1 + x) + x**2 assert factor(f) == 3 assert factor(f, x) == 3 assert factor(1/(x**2 + 2*x + 1/x) - 1) == -((1 - x + 2*x**2 + x**3)/(1 + 2*x**2 + x**3)) assert factor(f, expand=False) == f raises(PolynomialError, lambda: factor(f, x, expand=False)) raises(FlagError, lambda: factor(x**2 - 1, polys=True)) assert factor([x, Eq(x**2 - y**2, Tuple(x**2 - z**2, 1/x + 1/y))]) == \ [x, Eq((x - y)*(x + y), Tuple((x - z)*(x + z), (x + y)/x/y))] assert not isinstance( Poly(x**3 + x + 1).factor_list()[1][0][0], PurePoly) is True assert isinstance( PurePoly(x**3 + x + 1).factor_list()[1][0][0], PurePoly) is True assert factor(sqrt(-x)) == sqrt(-x) # issue 5917 e = (-2*x*(-x + 1)*(x - 1)*(-x*(-x + 1)*(x - 1) - x*(x - 1)**2)*(x**2*(x - 1) - x*(x - 1) - x) - (-2*x**2*(x - 1)**2 - x*(-x + 1)*(-x*(-x + 1) + x*(x - 1)))*(x**2*(x - 1)**4 - x*(-x*(-x + 1)*(x - 1) - x*(x - 1)**2))) assert factor(e) == 0 # deep option assert factor(sin(x**2 + x) + x, deep=True) == sin(x*(x + 1)) + x assert factor(sin(x**2 + x)*x, deep=True) == sin(x*(x + 1))*x assert factor(sqrt(x**2)) == sqrt(x**2) # issue 13149 assert factor(expand((0.5*x+1)*(0.5*y+1))) == Mul(1.0, 0.5*x + 1.0, 0.5*y + 1.0, evaluate = False) assert factor(expand((0.5*x+0.5)**2)) == 0.25*(1.0*x + 1.0)**2 eq = x**2*y**2 + 11*x**2*y + 30*x**2 + 7*x*y**2 + 77*x*y + 210*x + 12*y**2 + 132*y + 360 assert factor(eq, x) == (x + 3)*(x + 4)*(y**2 + 11*y + 30) assert factor(eq, x, deep=True) == (x + 3)*(x + 4)*(y**2 + 11*y + 30) assert factor(eq, y, deep=True) == (y + 5)*(y + 6)*(x**2 + 7*x + 12) # fraction option f = 5*x + 3*exp(2 - 7*x) assert factor(f, deep=True) == factor(f, deep=True, fraction=True) assert factor(f, deep=True, fraction=False) == 5*x + 3*exp(2)*exp(-7*x) def test_factor_large(): f = (x**2 + 4*x + 4)**10000000*(x**2 + 1)*(x**2 + 2*x + 1)**1234567 g = ((x**2 + 2*x + 1)**3000*y**2 + (x**2 + 2*x + 1)**3000*2*y + ( x**2 + 2*x + 1)**3000) assert factor(f) == (x + 2)**20000000*(x**2 + 1)*(x + 1)**2469134 assert factor(g) == (x + 1)**6000*(y + 1)**2 assert factor_list( f) == (1, [(x + 1, 2469134), (x + 2, 20000000), (x**2 + 1, 1)]) assert factor_list(g) == (1, [(y + 1, 2), (x + 1, 6000)]) f = (x**2 - y**2)**200000*(x**7 + 1) g = (x**2 + y**2)**200000*(x**7 + 1) assert factor(f) == \ (x + 1)*(x - y)**200000*(x + y)**200000*(x**6 - x**5 + x**4 - x**3 + x**2 - x + 1) assert factor(g, gaussian=True) == \ (x + 1)*(x - I*y)**200000*(x + I*y)**200000*(x**6 - x**5 + x**4 - x**3 + x**2 - x + 1) assert factor_list(f) == \ (1, [(x + 1, 1), (x - y, 200000), (x + y, 200000), (x**6 - x**5 + x**4 - x**3 + x**2 - x + 1, 1)]) assert factor_list(g, gaussian=True) == \ (1, [(x + 1, 1), (x - I*y, 200000), (x + I*y, 200000), ( x**6 - x**5 + x**4 - x**3 + x**2 - x + 1, 1)]) def test_factor_noeval(): assert factor(6*x - 10) == Mul(2, 3*x - 5, evaluate=False) assert factor((6*x - 10)/(3*x - 6)) == Mul(Rational(2, 3), 3*x - 5, 1/(x - 2)) def test_intervals(): assert intervals(0) == [] assert intervals(1) == [] assert intervals(x, sqf=True) == [(0, 0)] assert intervals(x) == [((0, 0), 1)] assert intervals(x**128) == [((0, 0), 128)] assert intervals([x**2, x**4]) == [((0, 0), {0: 2, 1: 4})] f = Poly((x*Rational(2, 5) - Rational(17, 3))*(4*x + Rational(1, 257))) assert f.intervals(sqf=True) == [(-1, 0), (14, 15)] assert f.intervals() == [((-1, 0), 1), ((14, 15), 1)] assert f.intervals(fast=True, sqf=True) == [(-1, 0), (14, 15)] assert f.intervals(fast=True) == [((-1, 0), 1), ((14, 15), 1)] assert f.intervals(eps=Rational(1, 10)) == f.intervals(eps=0.1) == \ [((Rational(-1, 258), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)] assert f.intervals(eps=Rational(1, 100)) == f.intervals(eps=0.01) == \ [((Rational(-1, 258), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)] assert f.intervals(eps=Rational(1, 1000)) == f.intervals(eps=0.001) == \ [((Rational(-1, 1002), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)] assert f.intervals(eps=Rational(1, 10000)) == f.intervals(eps=0.0001) == \ [((Rational(-1, 1028), Rational(-1, 1028)), 1), ((Rational(85, 6), Rational(85, 6)), 1)] f = (x*Rational(2, 5) - Rational(17, 3))*(4*x + Rational(1, 257)) assert intervals(f, sqf=True) == [(-1, 0), (14, 15)] assert intervals(f) == [((-1, 0), 1), ((14, 15), 1)] assert intervals(f, eps=Rational(1, 10)) == intervals(f, eps=0.1) == \ [((Rational(-1, 258), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)] assert intervals(f, eps=Rational(1, 100)) == intervals(f, eps=0.01) == \ [((Rational(-1, 258), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)] assert intervals(f, eps=Rational(1, 1000)) == intervals(f, eps=0.001) == \ [((Rational(-1, 1002), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)] assert intervals(f, eps=Rational(1, 10000)) == intervals(f, eps=0.0001) == \ [((Rational(-1, 1028), Rational(-1, 1028)), 1), ((Rational(85, 6), Rational(85, 6)), 1)] f = Poly((x**2 - 2)*(x**2 - 3)**7*(x + 1)*(7*x + 3)**3) assert f.intervals() == \ [((-2, Rational(-3, 2)), 7), ((Rational(-3, 2), -1), 1), ((-1, -1), 1), ((-1, 0), 3), ((1, Rational(3, 2)), 1), ((Rational(3, 2), 2), 7)] assert intervals([x**5 - 200, x**5 - 201]) == \ [((Rational(75, 26), Rational(101, 35)), {0: 1}), ((Rational(309, 107), Rational(26, 9)), {1: 1})] assert intervals([x**5 - 200, x**5 - 201], fast=True) == \ [((Rational(75, 26), Rational(101, 35)), {0: 1}), ((Rational(309, 107), Rational(26, 9)), {1: 1})] assert intervals([x**2 - 200, x**2 - 201]) == \ [((Rational(-71, 5), Rational(-85, 6)), {1: 1}), ((Rational(-85, 6), -14), {0: 1}), ((14, Rational(85, 6)), {0: 1}), ((Rational(85, 6), Rational(71, 5)), {1: 1})] assert intervals([x + 1, x + 2, x - 1, x + 1, 1, x - 1, x - 1, (x - 2)**2]) == \ [((-2, -2), {1: 1}), ((-1, -1), {0: 1, 3: 1}), ((1, 1), {2: 1, 5: 1, 6: 1}), ((2, 2), {7: 2})] f, g, h = x**2 - 2, x**4 - 4*x**2 + 4, x - 1 assert intervals(f, inf=Rational(7, 4), sqf=True) == [] assert intervals(f, inf=Rational(7, 5), sqf=True) == [(Rational(7, 5), Rational(3, 2))] assert intervals(f, sup=Rational(7, 4), sqf=True) == [(-2, -1), (1, Rational(3, 2))] assert intervals(f, sup=Rational(7, 5), sqf=True) == [(-2, -1)] assert intervals(g, inf=Rational(7, 4)) == [] assert intervals(g, inf=Rational(7, 5)) == [((Rational(7, 5), Rational(3, 2)), 2)] assert intervals(g, sup=Rational(7, 4)) == [((-2, -1), 2), ((1, Rational(3, 2)), 2)] assert intervals(g, sup=Rational(7, 5)) == [((-2, -1), 2)] assert intervals([g, h], inf=Rational(7, 4)) == [] assert intervals([g, h], inf=Rational(7, 5)) == [((Rational(7, 5), Rational(3, 2)), {0: 2})] assert intervals([g, h], sup=S( 7)/4) == [((-2, -1), {0: 2}), ((1, 1), {1: 1}), ((1, Rational(3, 2)), {0: 2})] assert intervals( [g, h], sup=Rational(7, 5)) == [((-2, -1), {0: 2}), ((1, 1), {1: 1})] assert intervals([x + 2, x**2 - 2]) == \ [((-2, -2), {0: 1}), ((-2, -1), {1: 1}), ((1, 2), {1: 1})] assert intervals([x + 2, x**2 - 2], strict=True) == \ [((-2, -2), {0: 1}), ((Rational(-3, 2), -1), {1: 1}), ((1, 2), {1: 1})] f = 7*z**4 - 19*z**3 + 20*z**2 + 17*z + 20 assert intervals(f) == [] real_part, complex_part = intervals(f, all=True, sqf=True) assert real_part == [] assert all(re(a) < re(r) < re(b) and im( a) < im(r) < im(b) for (a, b), r in zip(complex_part, nroots(f))) assert complex_part == [(Rational(-40, 7) - I*Rational(40, 7), 0), (Rational(-40, 7), I*Rational(40, 7)), (I*Rational(-40, 7), Rational(40, 7)), (0, Rational(40, 7) + I*Rational(40, 7))] real_part, complex_part = intervals(f, all=True, sqf=True, eps=Rational(1, 10)) assert real_part == [] assert all(re(a) < re(r) < re(b) and im( a) < im(r) < im(b) for (a, b), r in zip(complex_part, nroots(f))) raises(ValueError, lambda: intervals(x**2 - 2, eps=10**-100000)) raises(ValueError, lambda: Poly(x**2 - 2).intervals(eps=10**-100000)) raises( ValueError, lambda: intervals([x**2 - 2, x**2 - 3], eps=10**-100000)) def test_refine_root(): f = Poly(x**2 - 2) assert f.refine_root(1, 2, steps=0) == (1, 2) assert f.refine_root(-2, -1, steps=0) == (-2, -1) assert f.refine_root(1, 2, steps=None) == (1, Rational(3, 2)) assert f.refine_root(-2, -1, steps=None) == (Rational(-3, 2), -1) assert f.refine_root(1, 2, steps=1) == (1, Rational(3, 2)) assert f.refine_root(-2, -1, steps=1) == (Rational(-3, 2), -1) assert f.refine_root(1, 2, steps=1, fast=True) == (1, Rational(3, 2)) assert f.refine_root(-2, -1, steps=1, fast=True) == (Rational(-3, 2), -1) assert f.refine_root(1, 2, eps=Rational(1, 100)) == (Rational(24, 17), Rational(17, 12)) assert f.refine_root(1, 2, eps=1e-2) == (Rational(24, 17), Rational(17, 12)) raises(PolynomialError, lambda: (f**2).refine_root(1, 2, check_sqf=True)) raises(RefinementFailed, lambda: (f**2).refine_root(1, 2)) raises(RefinementFailed, lambda: (f**2).refine_root(2, 3)) f = x**2 - 2 assert refine_root(f, 1, 2, steps=1) == (1, Rational(3, 2)) assert refine_root(f, -2, -1, steps=1) == (Rational(-3, 2), -1) assert refine_root(f, 1, 2, steps=1, fast=True) == (1, Rational(3, 2)) assert refine_root(f, -2, -1, steps=1, fast=True) == (Rational(-3, 2), -1) assert refine_root(f, 1, 2, eps=Rational(1, 100)) == (Rational(24, 17), Rational(17, 12)) assert refine_root(f, 1, 2, eps=1e-2) == (Rational(24, 17), Rational(17, 12)) raises(PolynomialError, lambda: refine_root(1, 7, 8, eps=Rational(1, 100))) raises(ValueError, lambda: Poly(f).refine_root(1, 2, eps=10**-100000)) raises(ValueError, lambda: refine_root(f, 1, 2, eps=10**-100000)) def test_count_roots(): assert count_roots(x**2 - 2) == 2 assert count_roots(x**2 - 2, inf=-oo) == 2 assert count_roots(x**2 - 2, sup=+oo) == 2 assert count_roots(x**2 - 2, inf=-oo, sup=+oo) == 2 assert count_roots(x**2 - 2, inf=-2) == 2 assert count_roots(x**2 - 2, inf=-1) == 1 assert count_roots(x**2 - 2, sup=1) == 1 assert count_roots(x**2 - 2, sup=2) == 2 assert count_roots(x**2 - 2, inf=-1, sup=1) == 0 assert count_roots(x**2 - 2, inf=-2, sup=2) == 2 assert count_roots(x**2 - 2, inf=-1, sup=1) == 0 assert count_roots(x**2 - 2, inf=-2, sup=2) == 2 assert count_roots(x**2 + 2) == 0 assert count_roots(x**2 + 2, inf=-2*I) == 2 assert count_roots(x**2 + 2, sup=+2*I) == 2 assert count_roots(x**2 + 2, inf=-2*I, sup=+2*I) == 2 assert count_roots(x**2 + 2, inf=0) == 0 assert count_roots(x**2 + 2, sup=0) == 0 assert count_roots(x**2 + 2, inf=-I) == 1 assert count_roots(x**2 + 2, sup=+I) == 1 assert count_roots(x**2 + 2, inf=+I/2, sup=+I) == 0 assert count_roots(x**2 + 2, inf=-I, sup=-I/2) == 0 raises(PolynomialError, lambda: count_roots(1)) def test_Poly_root(): f = Poly(2*x**3 - 7*x**2 + 4*x + 4) assert f.root(0) == Rational(-1, 2) assert f.root(1) == 2 assert f.root(2) == 2 raises(IndexError, lambda: f.root(3)) assert Poly(x**5 + x + 1).root(0) == rootof(x**3 - x**2 + 1, 0) def test_real_roots(): assert real_roots(x) == [0] assert real_roots(x, multiple=False) == [(0, 1)] assert real_roots(x**3) == [0, 0, 0] assert real_roots(x**3, multiple=False) == [(0, 3)] assert real_roots(x*(x**3 + x + 3)) == [rootof(x**3 + x + 3, 0), 0] assert real_roots(x*(x**3 + x + 3), multiple=False) == [(rootof( x**3 + x + 3, 0), 1), (0, 1)] assert real_roots( x**3*(x**3 + x + 3)) == [rootof(x**3 + x + 3, 0), 0, 0, 0] assert real_roots(x**3*(x**3 + x + 3), multiple=False) == [(rootof( x**3 + x + 3, 0), 1), (0, 3)] f = 2*x**3 - 7*x**2 + 4*x + 4 g = x**3 + x + 1 assert Poly(f).real_roots() == [Rational(-1, 2), 2, 2] assert Poly(g).real_roots() == [rootof(g, 0)] def test_all_roots(): f = 2*x**3 - 7*x**2 + 4*x + 4 g = x**3 + x + 1 assert Poly(f).all_roots() == [Rational(-1, 2), 2, 2] assert Poly(g).all_roots() == [rootof(g, 0), rootof(g, 1), rootof(g, 2)] def test_nroots(): assert Poly(0, x).nroots() == [] assert Poly(1, x).nroots() == [] assert Poly(x**2 - 1, x).nroots() == [-1.0, 1.0] assert Poly(x**2 + 1, x).nroots() == [-1.0*I, 1.0*I] roots = Poly(x**2 - 1, x).nroots() assert roots == [-1.0, 1.0] roots = Poly(x**2 + 1, x).nroots() assert roots == [-1.0*I, 1.0*I] roots = Poly(x**2/3 - Rational(1, 3), x).nroots() assert roots == [-1.0, 1.0] roots = Poly(x**2/3 + Rational(1, 3), x).nroots() assert roots == [-1.0*I, 1.0*I] assert Poly(x**2 + 2*I, x).nroots() == [-1.0 + 1.0*I, 1.0 - 1.0*I] assert Poly( x**2 + 2*I, x, extension=I).nroots() == [-1.0 + 1.0*I, 1.0 - 1.0*I] assert Poly(0.2*x + 0.1).nroots() == [-0.5] roots = nroots(x**5 + x + 1, n=5) eps = Float("1e-5") assert re(roots[0]).epsilon_eq(-0.75487, eps) is S.true assert im(roots[0]) == 0.0 assert re(roots[1]) == -0.5 assert im(roots[1]).epsilon_eq(-0.86602, eps) is S.true assert re(roots[2]) == -0.5 assert im(roots[2]).epsilon_eq(+0.86602, eps) is S.true assert re(roots[3]).epsilon_eq(+0.87743, eps) is S.true assert im(roots[3]).epsilon_eq(-0.74486, eps) is S.true assert re(roots[4]).epsilon_eq(+0.87743, eps) is S.true assert im(roots[4]).epsilon_eq(+0.74486, eps) is S.true eps = Float("1e-6") assert re(roots[0]).epsilon_eq(-0.75487, eps) is S.false assert im(roots[0]) == 0.0 assert re(roots[1]) == -0.5 assert im(roots[1]).epsilon_eq(-0.86602, eps) is S.false assert re(roots[2]) == -0.5 assert im(roots[2]).epsilon_eq(+0.86602, eps) is S.false assert re(roots[3]).epsilon_eq(+0.87743, eps) is S.false assert im(roots[3]).epsilon_eq(-0.74486, eps) is S.false assert re(roots[4]).epsilon_eq(+0.87743, eps) is S.false assert im(roots[4]).epsilon_eq(+0.74486, eps) is S.false raises(DomainError, lambda: Poly(x + y, x).nroots()) raises(MultivariatePolynomialError, lambda: Poly(x + y).nroots()) assert nroots(x**2 - 1) == [-1.0, 1.0] roots = nroots(x**2 - 1) assert roots == [-1.0, 1.0] assert nroots(x + I) == [-1.0*I] assert nroots(x + 2*I) == [-2.0*I] raises(PolynomialError, lambda: nroots(0)) # issue 8296 f = Poly(x**4 - 1) assert f.nroots(2) == [w.n(2) for w in f.all_roots()] assert str(Poly(x**16 + 32*x**14 + 508*x**12 + 5440*x**10 + 39510*x**8 + 204320*x**6 + 755548*x**4 + 1434496*x**2 + 877969).nroots(2)) == ('[-1.7 - 1.9*I, -1.7 + 1.9*I, -1.7 ' '- 2.5*I, -1.7 + 2.5*I, -1.0*I, 1.0*I, -1.7*I, 1.7*I, -2.8*I, ' '2.8*I, -3.4*I, 3.4*I, 1.7 - 1.9*I, 1.7 + 1.9*I, 1.7 - 2.5*I, ' '1.7 + 2.5*I]') def test_ground_roots(): f = x**6 - 4*x**4 + 4*x**3 - x**2 assert Poly(f).ground_roots() == {S.One: 2, S.Zero: 2} assert ground_roots(f) == {S.One: 2, S.Zero: 2} def test_nth_power_roots_poly(): f = x**4 - x**2 + 1 f_2 = (x**2 - x + 1)**2 f_3 = (x**2 + 1)**2 f_4 = (x**2 + x + 1)**2 f_12 = (x - 1)**4 assert nth_power_roots_poly(f, 1) == f raises(ValueError, lambda: nth_power_roots_poly(f, 0)) raises(ValueError, lambda: nth_power_roots_poly(f, x)) assert factor(nth_power_roots_poly(f, 2)) == f_2 assert factor(nth_power_roots_poly(f, 3)) == f_3 assert factor(nth_power_roots_poly(f, 4)) == f_4 assert factor(nth_power_roots_poly(f, 12)) == f_12 raises(MultivariatePolynomialError, lambda: nth_power_roots_poly( x + y, 2, x, y)) def test_torational_factor_list(): p = expand(((x**2-1)*(x-2)).subs({x:x*(1 + sqrt(2))})) assert _torational_factor_list(p, x) == (-2, [ (-x*(1 + sqrt(2))/2 + 1, 1), (-x*(1 + sqrt(2)) - 1, 1), (-x*(1 + sqrt(2)) + 1, 1)]) p = expand(((x**2-1)*(x-2)).subs({x:x*(1 + 2**Rational(1, 4))})) assert _torational_factor_list(p, x) is None def test_cancel(): assert cancel(0) == 0 assert cancel(7) == 7 assert cancel(x) == x assert cancel(oo) is oo assert cancel((2, 3)) == (1, 2, 3) assert cancel((1, 0), x) == (1, 1, 0) assert cancel((0, 1), x) == (1, 0, 1) f, g, p, q = 4*x**2 - 4, 2*x - 2, 2*x + 2, 1 F, G, P, Q = [ Poly(u, x) for u in (f, g, p, q) ] assert F.cancel(G) == (1, P, Q) assert cancel((f, g)) == (1, p, q) assert cancel((f, g), x) == (1, p, q) assert cancel((f, g), (x,)) == (1, p, q) assert cancel((F, G)) == (1, P, Q) assert cancel((f, g), polys=True) == (1, P, Q) assert cancel((F, G), polys=False) == (1, p, q) f = (x**2 - 2)/(x + sqrt(2)) assert cancel(f) == f assert cancel(f, greedy=False) == x - sqrt(2) f = (x**2 - 2)/(x - sqrt(2)) assert cancel(f) == f assert cancel(f, greedy=False) == x + sqrt(2) assert cancel((x**2/4 - 1, x/2 - 1)) == (1, x + 2, 2) # assert cancel((x**2/4 - 1, x/2 - 1)) == (S.Half, x + 2, 1) assert cancel((x**2 - y)/(x - y)) == 1/(x - y)*(x**2 - y) assert cancel((x**2 - y**2)/(x - y), x) == x + y assert cancel((x**2 - y**2)/(x - y), y) == x + y assert cancel((x**2 - y**2)/(x - y)) == x + y assert cancel((x**3 - 1)/(x**2 - 1)) == (x**2 + x + 1)/(x + 1) assert cancel((x**3/2 - S.Half)/(x**2 - 1)) == (x**2 + x + 1)/(2*x + 2) assert cancel((exp(2*x) + 2*exp(x) + 1)/(exp(x) + 1)) == exp(x) + 1 f = Poly(x**2 - a**2, x) g = Poly(x - a, x) F = Poly(x + a, x, domain='ZZ[a]') G = Poly(1, x, domain='ZZ[a]') assert cancel((f, g)) == (1, F, G) f = x**3 + (sqrt(2) - 2)*x**2 - (2*sqrt(2) + 3)*x - 3*sqrt(2) g = x**2 - 2 assert cancel((f, g), extension=True) == (1, x**2 - 2*x - 3, x - sqrt(2)) f = Poly(-2*x + 3, x) g = Poly(-x**9 + x**8 + x**6 - x**5 + 2*x**2 - 3*x + 1, x) assert cancel((f, g)) == (1, -f, -g) f = Poly(y, y, domain='ZZ(x)') g = Poly(1, y, domain='ZZ[x]') assert f.cancel( g) == (1, Poly(y, y, domain='ZZ(x)'), Poly(1, y, domain='ZZ(x)')) assert f.cancel(g, include=True) == ( Poly(y, y, domain='ZZ(x)'), Poly(1, y, domain='ZZ(x)')) f = Poly(5*x*y + x, y, domain='ZZ(x)') g = Poly(2*x**2*y, y, domain='ZZ(x)') assert f.cancel(g, include=True) == ( Poly(5*y + 1, y, domain='ZZ(x)'), Poly(2*x*y, y, domain='ZZ(x)')) f = -(-2*x - 4*y + 0.005*(z - y)**2)/((z - y)*(-z + y + 2)) assert cancel(f).is_Mul == True P = tanh(x - 3.0) Q = tanh(x + 3.0) f = ((-2*P**2 + 2)*(-P**2 + 1)*Q**2/2 + (-2*P**2 + 2)*(-2*Q**2 + 2)*P*Q - (-2*P**2 + 2)*P**2*Q**2 + (-2*Q**2 + 2)*(-Q**2 + 1)*P**2/2 - (-2*Q**2 + 2)*P**2*Q**2)/(2*sqrt(P**2*Q**2 + 0.0001)) \ + (-(-2*P**2 + 2)*P*Q**2/2 - (-2*Q**2 + 2)*P**2*Q/2)*((-2*P**2 + 2)*P*Q**2/2 + (-2*Q**2 + 2)*P**2*Q/2)/(2*(P**2*Q**2 + 0.0001)**Rational(3, 2)) assert cancel(f).is_Mul == True # issue 7022 A = Symbol('A', commutative=False) p1 = Piecewise((A*(x**2 - 1)/(x + 1), x > 1), ((x + 2)/(x**2 + 2*x), True)) p2 = Piecewise((A*(x - 1), x > 1), (1/x, True)) assert cancel(p1) == p2 assert cancel(2*p1) == 2*p2 assert cancel(1 + p1) == 1 + p2 assert cancel((x**2 - 1)/(x + 1)*p1) == (x - 1)*p2 assert cancel((x**2 - 1)/(x + 1) + p1) == (x - 1) + p2 p3 = Piecewise(((x**2 - 1)/(x + 1), x > 1), ((x + 2)/(x**2 + 2*x), True)) p4 = Piecewise(((x - 1), x > 1), (1/x, True)) assert cancel(p3) == p4 assert cancel(2*p3) == 2*p4 assert cancel(1 + p3) == 1 + p4 assert cancel((x**2 - 1)/(x + 1)*p3) == (x - 1)*p4 assert cancel((x**2 - 1)/(x + 1) + p3) == (x - 1) + p4 # issue 9363 M = MatrixSymbol('M', 5, 5) assert cancel(M[0,0] + 7) == M[0,0] + 7 expr = sin(M[1, 4] + M[2, 1] * 5 * M[4, 0]) - 5 * M[1, 2] / z assert cancel(expr) == (z*sin(M[1, 4] + M[2, 1] * 5 * M[4, 0]) - 5 * M[1, 2]) / z assert cancel((x**2 + 1)/(x - I)) == x + I def test_reduced(): f = 2*x**4 + y**2 - x**2 + y**3 G = [x**3 - x, y**3 - y] Q = [2*x, 1] r = x**2 + y**2 + y assert reduced(f, G) == (Q, r) assert reduced(f, G, x, y) == (Q, r) H = groebner(G) assert H.reduce(f) == (Q, r) Q = [Poly(2*x, x, y), Poly(1, x, y)] r = Poly(x**2 + y**2 + y, x, y) assert _strict_eq(reduced(f, G, polys=True), (Q, r)) assert _strict_eq(reduced(f, G, x, y, polys=True), (Q, r)) H = groebner(G, polys=True) assert _strict_eq(H.reduce(f), (Q, r)) f = 2*x**3 + y**3 + 3*y G = groebner([x**2 + y**2 - 1, x*y - 2]) Q = [x**2 - x*y**3/2 + x*y/2 + y**6/4 - y**4/2 + y**2/4, -y**5/4 + y**3/2 + y*Rational(3, 4)] r = 0 assert reduced(f, G) == (Q, r) assert G.reduce(f) == (Q, r) assert reduced(f, G, auto=False)[1] != 0 assert G.reduce(f, auto=False)[1] != 0 assert G.contains(f) is True assert G.contains(f + 1) is False assert reduced(1, [1], x) == ([1], 0) raises(ComputationFailed, lambda: reduced(1, [1])) def test_groebner(): assert groebner([], x, y, z) == [] assert groebner([x**2 + 1, y**4*x + x**3], x, y, order='lex') == [1 + x**2, -1 + y**4] assert groebner([x**2 + 1, y**4*x + x**3, x*y*z**3], x, y, z, order='grevlex') == [-1 + y**4, z**3, 1 + x**2] assert groebner([x**2 + 1, y**4*x + x**3], x, y, order='lex', polys=True) == \ [Poly(1 + x**2, x, y), Poly(-1 + y**4, x, y)] assert groebner([x**2 + 1, y**4*x + x**3, x*y*z**3], x, y, z, order='grevlex', polys=True) == \ [Poly(-1 + y**4, x, y, z), Poly(z**3, x, y, z), Poly(1 + x**2, x, y, z)] assert groebner([x**3 - 1, x**2 - 1]) == [x - 1] assert groebner([Eq(x**3, 1), Eq(x**2, 1)]) == [x - 1] F = [3*x**2 + y*z - 5*x - 1, 2*x + 3*x*y + y**2, x - 3*y + x*z - 2*z**2] f = z**9 - x**2*y**3 - 3*x*y**2*z + 11*y*z**2 + x**2*z**2 - 5 G = groebner(F, x, y, z, modulus=7, symmetric=False) assert G == [1 + x + y + 3*z + 2*z**2 + 2*z**3 + 6*z**4 + z**5, 1 + 3*y + y**2 + 6*z**2 + 3*z**3 + 3*z**4 + 3*z**5 + 4*z**6, 1 + 4*y + 4*z + y*z + 4*z**3 + z**4 + z**6, 6 + 6*z + z**2 + 4*z**3 + 3*z**4 + 6*z**5 + 3*z**6 + z**7] Q, r = reduced(f, G, x, y, z, modulus=7, symmetric=False, polys=True) assert sum([ q*g for q, g in zip(Q, G.polys)], r) == Poly(f, modulus=7) F = [x*y - 2*y, 2*y**2 - x**2] assert groebner(F, x, y, order='grevlex') == \ [y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y] assert groebner(F, y, x, order='grevlex') == \ [x**3 - 2*x**2, -x**2 + 2*y**2, x*y - 2*y] assert groebner(F, order='grevlex', field=True) == \ [y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y] assert groebner([1], x) == [1] assert groebner([x**2 + 2.0*y], x, y) == [1.0*x**2 + 2.0*y] raises(ComputationFailed, lambda: groebner([1])) assert groebner([x**2 - 1, x**3 + 1], method='buchberger') == [x + 1] assert groebner([x**2 - 1, x**3 + 1], method='f5b') == [x + 1] raises(ValueError, lambda: groebner([x, y], method='unknown')) def test_fglm(): F = [a + b + c + d, a*b + a*d + b*c + b*d, a*b*c + a*b*d + a*c*d + b*c*d, a*b*c*d - 1] G = groebner(F, a, b, c, d, order=grlex) B = [ 4*a + 3*d**9 - 4*d**5 - 3*d, 4*b + 4*c - 3*d**9 + 4*d**5 + 7*d, 4*c**2 + 3*d**10 - 4*d**6 - 3*d**2, 4*c*d**4 + 4*c - d**9 + 4*d**5 + 5*d, d**12 - d**8 - d**4 + 1, ] assert groebner(F, a, b, c, d, order=lex) == B assert G.fglm(lex) == B F = [9*x**8 + 36*x**7 - 32*x**6 - 252*x**5 - 78*x**4 + 468*x**3 + 288*x**2 - 108*x + 9, -72*t*x**7 - 252*t*x**6 + 192*t*x**5 + 1260*t*x**4 + 312*t*x**3 - 404*t*x**2 - 576*t*x + \ 108*t - 72*x**7 - 256*x**6 + 192*x**5 + 1280*x**4 + 312*x**3 - 576*x + 96] G = groebner(F, t, x, order=grlex) B = [ 203577793572507451707*t + 627982239411707112*x**7 - 666924143779443762*x**6 - \ 10874593056632447619*x**5 + 5119998792707079562*x**4 + 72917161949456066376*x**3 + \ 20362663855832380362*x**2 - 142079311455258371571*x + 183756699868981873194, 9*x**8 + 36*x**7 - 32*x**6 - 252*x**5 - 78*x**4 + 468*x**3 + 288*x**2 - 108*x + 9, ] assert groebner(F, t, x, order=lex) == B assert G.fglm(lex) == B F = [x**2 - x - 3*y + 1, -2*x + y**2 + y - 1] G = groebner(F, x, y, order=lex) B = [ x**2 - x - 3*y + 1, y**2 - 2*x + y - 1, ] assert groebner(F, x, y, order=grlex) == B assert G.fglm(grlex) == B def test_is_zero_dimensional(): assert is_zero_dimensional([x, y], x, y) is True assert is_zero_dimensional([x**3 + y**2], x, y) is False assert is_zero_dimensional([x, y, z], x, y, z) is True assert is_zero_dimensional([x, y, z], x, y, z, t) is False F = [x*y - z, y*z - x, x*y - y] assert is_zero_dimensional(F, x, y, z) is True F = [x**2 - 2*x*z + 5, x*y**2 + y*z**3, 3*y**2 - 8*z**2] assert is_zero_dimensional(F, x, y, z) is True def test_GroebnerBasis(): F = [x*y - 2*y, 2*y**2 - x**2] G = groebner(F, x, y, order='grevlex') H = [y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y] P = [ Poly(h, x, y) for h in H ] assert groebner(F + [0], x, y, order='grevlex') == G assert isinstance(G, GroebnerBasis) is True assert len(G) == 3 assert G[0] == H[0] and not G[0].is_Poly assert G[1] == H[1] and not G[1].is_Poly assert G[2] == H[2] and not G[2].is_Poly assert G[1:] == H[1:] and not any(g.is_Poly for g in G[1:]) assert G[:2] == H[:2] and not any(g.is_Poly for g in G[1:]) assert G.exprs == H assert G.polys == P assert G.gens == (x, y) assert G.domain == ZZ assert G.order == grevlex assert G == H assert G == tuple(H) assert G == P assert G == tuple(P) assert G != [] G = groebner(F, x, y, order='grevlex', polys=True) assert G[0] == P[0] and G[0].is_Poly assert G[1] == P[1] and G[1].is_Poly assert G[2] == P[2] and G[2].is_Poly assert G[1:] == P[1:] and all(g.is_Poly for g in G[1:]) assert G[:2] == P[:2] and all(g.is_Poly for g in G[1:]) def test_poly(): assert poly(x) == Poly(x, x) assert poly(y) == Poly(y, y) assert poly(x + y) == Poly(x + y, x, y) assert poly(x + sin(x)) == Poly(x + sin(x), x, sin(x)) assert poly(x + y, wrt=y) == Poly(x + y, y, x) assert poly(x + sin(x), wrt=sin(x)) == Poly(x + sin(x), sin(x), x) assert poly(x*y + 2*x*z**2 + 17) == Poly(x*y + 2*x*z**2 + 17, x, y, z) assert poly(2*(y + z)**2 - 1) == Poly(2*y**2 + 4*y*z + 2*z**2 - 1, y, z) assert poly( x*(y + z)**2 - 1) == Poly(x*y**2 + 2*x*y*z + x*z**2 - 1, x, y, z) assert poly(2*x*( y + z)**2 - 1) == Poly(2*x*y**2 + 4*x*y*z + 2*x*z**2 - 1, x, y, z) assert poly(2*( y + z)**2 - x - 1) == Poly(2*y**2 + 4*y*z + 2*z**2 - x - 1, x, y, z) assert poly(x*( y + z)**2 - x - 1) == Poly(x*y**2 + 2*x*y*z + x*z**2 - x - 1, x, y, z) assert poly(2*x*(y + z)**2 - x - 1) == Poly(2*x*y**2 + 4*x*y*z + 2* x*z**2 - x - 1, x, y, z) assert poly(x*y + (x + y)**2 + (x + z)**2) == \ Poly(2*x*z + 3*x*y + y**2 + z**2 + 2*x**2, x, y, z) assert poly(x*y*(x + y)*(x + z)**2) == \ Poly(x**3*y**2 + x*y**2*z**2 + y*x**2*z**2 + 2*z*x**2* y**2 + 2*y*z*x**3 + y*x**4, x, y, z) assert poly(Poly(x + y + z, y, x, z)) == Poly(x + y + z, y, x, z) assert poly((x + y)**2, x) == Poly(x**2 + 2*x*y + y**2, x, domain=ZZ[y]) assert poly((x + y)**2, y) == Poly(x**2 + 2*x*y + y**2, y, domain=ZZ[x]) assert poly(1, x) == Poly(1, x) raises(GeneratorsNeeded, lambda: poly(1)) # issue 6184 assert poly(x + y, x, y) == Poly(x + y, x, y) assert poly(x + y, y, x) == Poly(x + y, y, x) def test_keep_coeff(): u = Mul(2, x + 1, evaluate=False) assert _keep_coeff(S.One, x) == x assert _keep_coeff(S.NegativeOne, x) == -x assert _keep_coeff(S(1.0), x) == 1.0*x assert _keep_coeff(S(-1.0), x) == -1.0*x assert _keep_coeff(S.One, 2*x) == 2*x assert _keep_coeff(S(2), x/2) == x assert _keep_coeff(S(2), sin(x)) == 2*sin(x) assert _keep_coeff(S(2), x + 1) == u assert _keep_coeff(x, 1/x) == 1 assert _keep_coeff(x + 1, S(2)) == u def test_poly_matching_consistency(): # Test for this issue: # https://github.com/sympy/sympy/issues/5514 assert I * Poly(x, x) == Poly(I*x, x) assert Poly(x, x) * I == Poly(I*x, x) def test_issue_5786(): assert expand(factor(expand( (x - I*y)*(z - I*t)), extension=[I])) == -I*t*x - t*y + x*z - I*y*z def test_noncommutative(): class foo(Expr): is_commutative=False e = x/(x + x*y) c = 1/( 1 + y) assert cancel(foo(e)) == foo(c) assert cancel(e + foo(e)) == c + foo(c) assert cancel(e*foo(c)) == c*foo(c) def test_to_rational_coeffs(): assert to_rational_coeffs( Poly(x**3 + y*x**2 + sqrt(y), x, domain='EX')) is None # issue 21268 assert to_rational_coeffs( Poly(y**3 + sqrt(2)*y**2*sin(x) + 1, y)) is None assert to_rational_coeffs(Poly(x, y)) is None assert to_rational_coeffs(Poly(sqrt(2)*y)) is None def test_factor_terms(): # issue 7067 assert factor_list(x*(x + y)) == (1, [(x, 1), (x + y, 1)]) assert sqf_list(x*(x + y)) == (1, [(x**2 + x*y, 1)]) def test_as_list(): # issue 14496 assert Poly(x**3 + 2, x, domain='ZZ').as_list() == [1, 0, 0, 2] assert Poly(x**2 + y + 1, x, y, domain='ZZ').as_list() == [[1], [], [1, 1]] assert Poly(x**2 + y + 1, x, y, z, domain='ZZ').as_list() == \ [[[1]], [[]], [[1], [1]]] def test_issue_11198(): assert factor_list(sqrt(2)*x) == (sqrt(2), [(x, 1)]) assert factor_list(sqrt(2)*sin(x), sin(x)) == (sqrt(2), [(sin(x), 1)]) def test_Poly_precision(): # Make sure Poly doesn't lose precision p = Poly(pi.evalf(100)*x) assert p.as_expr() == pi.evalf(100)*x def test_issue_12400(): # Correction of check for negative exponents assert poly(1/(1+sqrt(2)), x) == \ Poly(1/(1+sqrt(2)), x , domain='EX') def test_issue_14364(): assert gcd(S(6)*(1 + sqrt(3))/5, S(3)*(1 + sqrt(3))/10) == Rational(3, 10) * (1 + sqrt(3)) assert gcd(sqrt(5)*Rational(4, 7), sqrt(5)*Rational(2, 3)) == sqrt(5)*Rational(2, 21) assert lcm(Rational(2, 3)*sqrt(3), Rational(5, 6)*sqrt(3)) == S(10)*sqrt(3)/3 assert lcm(3*sqrt(3), 4/sqrt(3)) == 12*sqrt(3) assert lcm(S(5)*(1 + 2**Rational(1, 3))/6, S(3)*(1 + 2**Rational(1, 3))/8) == Rational(15, 2) * (1 + 2**Rational(1, 3)) assert gcd(Rational(2, 3)*sqrt(3), Rational(5, 6)/sqrt(3)) == sqrt(3)/18 assert gcd(S(4)*sqrt(13)/7, S(3)*sqrt(13)/14) == sqrt(13)/14 # gcd_list and lcm_list assert gcd([S(2)*sqrt(47)/7, S(6)*sqrt(47)/5, S(8)*sqrt(47)/5]) == sqrt(47)*Rational(2, 35) assert gcd([S(6)*(1 + sqrt(7))/5, S(2)*(1 + sqrt(7))/7, S(4)*(1 + sqrt(7))/13]) == (1 + sqrt(7))*Rational(2, 455) assert lcm((Rational(7, 2)/sqrt(15), Rational(5, 6)/sqrt(15), Rational(5, 8)/sqrt(15))) == Rational(35, 2)/sqrt(15) assert lcm([S(5)*(2 + 2**Rational(5, 7))/6, S(7)*(2 + 2**Rational(5, 7))/2, S(13)*(2 + 2**Rational(5, 7))/4]) == Rational(455, 2) * (2 + 2**Rational(5, 7)) def test_issue_15669(): x = Symbol("x", positive=True) expr = (16*x**3/(-x**2 + sqrt(8*x**2 + (x**2 - 2)**2) + 2)**2 - 2*2**Rational(4, 5)*x*(-x**2 + sqrt(8*x**2 + (x**2 - 2)**2) + 2)**Rational(3, 5) + 10*x) assert factor(expr, deep=True) == x*(x**2 + 2) def test_issue_17988(): x = Symbol('x') p = poly(x - 1) M = Matrix([[poly(x + 1), poly(x + 1)]]) assert p * M == M * p == Matrix([[poly(x**2 - 1), poly(x**2 - 1)]]) def test_issue_18205(): assert cancel((2 + I)*(3 - I)) == 7 + I assert cancel((2 + I)*(2 - I)) == 5 def test_issue_8695(): p = (x**2 + 1) * (x - 1)**2 * (x - 2)**3 * (x - 3)**3 result = (1, [(x**2 + 1, 1), (x - 1, 2), (x**2 - 5*x + 6, 3)]) assert sqf_list(p) == result def test_issue_19113(): eq = sin(x)**3 - sin(x) + 1 raises(PolynomialError, lambda: refine_root(eq, 1, 2, 1e-2)) raises(PolynomialError, lambda: count_roots(eq, -1, 1)) raises(PolynomialError, lambda: real_roots(eq)) raises(PolynomialError, lambda: nroots(eq)) raises(PolynomialError, lambda: ground_roots(eq)) raises(PolynomialError, lambda: nth_power_roots_poly(eq, 2)) def test_issue_19360(): f = 2*x**2 - 2*sqrt(2)*x*y + y**2 assert factor(f, extension=sqrt(2)) == 2*(x - (sqrt(2)*y/2))**2 f = -I*t*x - t*y + x*z - I*y*z assert factor(f, extension=I) == (x - I*y)*(-I*t + z) def test_poly_copy_equals_original(): poly = Poly(x + y, x, y, z) copy = poly.copy() assert poly == copy, ( "Copied polynomial not equal to original.") assert poly.gens == copy.gens, ( "Copied polynomial has different generators than original.") def test_deserialized_poly_equals_original(): poly = Poly(x + y, x, y, z) deserialized = pickle.loads(pickle.dumps(poly)) assert poly == deserialized, ( "Deserialized polynomial not equal to original.") assert poly.gens == deserialized.gens, ( "Deserialized polynomial has different generators than original.") def test_issue_20389(): result = degree(x * (x + 1) - x ** 2 - x, x) assert result == -oo def test_issue_20985(): from sympy import symbols w, R = symbols('w R') poly = Poly(1.0 + I*w/R, w, 1/R) assert poly.degree() == S(1)
bd8325393b98bdffb5e4fd27293166fae46b85473e9c214492a60500f2f1834f
"""Tests for PythonRational type. """ from sympy.polys.domains import PythonRational as QQ from sympy.testing.pytest import raises def test_PythonRational__init__(): assert QQ(0).numerator == 0 assert QQ(0).denominator == 1 assert QQ(0, 1).numerator == 0 assert QQ(0, 1).denominator == 1 assert QQ(0, -1).numerator == 0 assert QQ(0, -1).denominator == 1 assert QQ(1).numerator == 1 assert QQ(1).denominator == 1 assert QQ(1, 1).numerator == 1 assert QQ(1, 1).denominator == 1 assert QQ(-1, -1).numerator == 1 assert QQ(-1, -1).denominator == 1 assert QQ(-1).numerator == -1 assert QQ(-1).denominator == 1 assert QQ(-1, 1).numerator == -1 assert QQ(-1, 1).denominator == 1 assert QQ( 1, -1).numerator == -1 assert QQ( 1, -1).denominator == 1 assert QQ(1, 2).numerator == 1 assert QQ(1, 2).denominator == 2 assert QQ(3, 4).numerator == 3 assert QQ(3, 4).denominator == 4 assert QQ(2, 2).numerator == 1 assert QQ(2, 2).denominator == 1 assert QQ(2, 4).numerator == 1 assert QQ(2, 4).denominator == 2 def test_PythonRational__hash__(): assert hash(QQ(0)) == hash(0) assert hash(QQ(1)) == hash(1) assert hash(QQ(117)) == hash(117) def test_PythonRational__int__(): assert int(QQ(-1, 4)) == 0 assert int(QQ( 1, 4)) == 0 assert int(QQ(-5, 4)) == -1 assert int(QQ( 5, 4)) == 1 def test_PythonRational__float__(): assert float(QQ(-1, 2)) == -0.5 assert float(QQ( 1, 2)) == 0.5 def test_PythonRational__abs__(): assert abs(QQ(-1, 2)) == QQ(1, 2) assert abs(QQ( 1, 2)) == QQ(1, 2) def test_PythonRational__pos__(): assert +QQ(-1, 2) == QQ(-1, 2) assert +QQ( 1, 2) == QQ( 1, 2) def test_PythonRational__neg__(): assert -QQ(-1, 2) == QQ( 1, 2) assert -QQ( 1, 2) == QQ(-1, 2) def test_PythonRational__add__(): assert QQ(-1, 2) + QQ( 1, 2) == QQ(0) assert QQ( 1, 2) + QQ(-1, 2) == QQ(0) assert QQ(1, 2) + QQ(1, 2) == QQ(1) assert QQ(1, 2) + QQ(3, 2) == QQ(2) assert QQ(3, 2) + QQ(1, 2) == QQ(2) assert QQ(3, 2) + QQ(3, 2) == QQ(3) assert 1 + QQ(1, 2) == QQ(3, 2) assert QQ(1, 2) + 1 == QQ(3, 2) def test_PythonRational__sub__(): assert QQ(-1, 2) - QQ( 1, 2) == QQ(-1) assert QQ( 1, 2) - QQ(-1, 2) == QQ( 1) assert QQ(1, 2) - QQ(1, 2) == QQ( 0) assert QQ(1, 2) - QQ(3, 2) == QQ(-1) assert QQ(3, 2) - QQ(1, 2) == QQ( 1) assert QQ(3, 2) - QQ(3, 2) == QQ( 0) assert 1 - QQ(1, 2) == QQ( 1, 2) assert QQ(1, 2) - 1 == QQ(-1, 2) def test_PythonRational__mul__(): assert QQ(-1, 2) * QQ( 1, 2) == QQ(-1, 4) assert QQ( 1, 2) * QQ(-1, 2) == QQ(-1, 4) assert QQ(1, 2) * QQ(1, 2) == QQ(1, 4) assert QQ(1, 2) * QQ(3, 2) == QQ(3, 4) assert QQ(3, 2) * QQ(1, 2) == QQ(3, 4) assert QQ(3, 2) * QQ(3, 2) == QQ(9, 4) assert 2 * QQ(1, 2) == QQ(1) assert QQ(1, 2) * 2 == QQ(1) def test_PythonRational__truediv__(): assert QQ(-1, 2) / QQ( 1, 2) == QQ(-1) assert QQ( 1, 2) / QQ(-1, 2) == QQ(-1) assert QQ(1, 2) / QQ(1, 2) == QQ(1) assert QQ(1, 2) / QQ(3, 2) == QQ(1, 3) assert QQ(3, 2) / QQ(1, 2) == QQ(3) assert QQ(3, 2) / QQ(3, 2) == QQ(1) assert 2 / QQ(1, 2) == QQ(4) assert QQ(1, 2) / 2 == QQ(1, 4) raises(ZeroDivisionError, lambda: QQ(1, 2) / QQ(0)) raises(ZeroDivisionError, lambda: QQ(1, 2) / 0) def test_PythonRational__pow__(): assert QQ(1)**10 == QQ(1) assert QQ(2)**10 == QQ(1024) assert QQ(1)**(-10) == QQ(1) assert QQ(2)**(-10) == QQ(1, 1024) def test_PythonRational__eq__(): assert (QQ(1, 2) == QQ(1, 2)) is True assert (QQ(1, 2) != QQ(1, 2)) is False assert (QQ(1, 2) == QQ(1, 3)) is False assert (QQ(1, 2) != QQ(1, 3)) is True def test_PythonRational__lt_le_gt_ge__(): assert (QQ(1, 2) < QQ(1, 4)) is False assert (QQ(1, 2) <= QQ(1, 4)) is False assert (QQ(1, 2) > QQ(1, 4)) is True assert (QQ(1, 2) >= QQ(1, 4)) is True assert (QQ(1, 4) < QQ(1, 2)) is True assert (QQ(1, 4) <= QQ(1, 2)) is True assert (QQ(1, 4) > QQ(1, 2)) is False assert (QQ(1, 4) >= QQ(1, 2)) is False
aa19912a11188068ebd96a71c4a018295d7c036e08a7850c1ba4772d27ee5322
"""Tests for algorithms for computing symbolic roots of polynomials. """ from sympy import (S, symbols, Symbol, Wild, Rational, sqrt, powsimp, sin, cos, pi, I, Interval, re, im, exp, ZZ, Piecewise, acos, root, conjugate) from sympy.polys import Poly, cyclotomic_poly, intervals, nroots, rootof from sympy.polys.polyroots import (root_factors, roots_linear, roots_quadratic, roots_cubic, roots_quartic, roots_cyclotomic, roots_binomial, preprocess_roots, roots) from sympy.polys.orthopolys import legendre_poly from sympy.polys.polyerrors import PolynomialError from sympy.polys.polyutils import _nsort from sympy.utilities.iterables import cartes from sympy.testing.pytest import raises, slow from sympy.testing.randtest import verify_numerically import mpmath a, b, c, d, e, q, t, x, y, z = symbols('a,b,c,d,e,q,t,x,y,z') def _check(roots): # this is the desired invariant for roots returned # by all_roots. It is trivially true for linear # polynomials. nreal = sum([1 if i.is_real else 0 for i in roots]) assert list(sorted(roots[:nreal])) == list(roots[:nreal]) for ix in range(nreal, len(roots), 2): if not ( roots[ix + 1] == roots[ix] or roots[ix + 1] == conjugate(roots[ix])): return False return True def test_roots_linear(): assert roots_linear(Poly(2*x + 1, x)) == [Rational(-1, 2)] def test_roots_quadratic(): assert roots_quadratic(Poly(2*x**2, x)) == [0, 0] assert roots_quadratic(Poly(2*x**2 + 3*x, x)) == [Rational(-3, 2), 0] assert roots_quadratic(Poly(2*x**2 + 3, x)) == [-I*sqrt(6)/2, I*sqrt(6)/2] assert roots_quadratic(Poly(2*x**2 + 4*x + 3, x)) == [-1 - I*sqrt(2)/2, -1 + I*sqrt(2)/2] _check(Poly(2*x**2 + 4*x + 3, x).all_roots()) f = x**2 + (2*a*e + 2*c*e)/(a - c)*x + (d - b + a*e**2 - c*e**2)/(a - c) assert roots_quadratic(Poly(f, x)) == \ [-e*(a + c)/(a - c) - sqrt(a*b + c*d - a*d - b*c + 4*a*c*e**2)/(a - c), -e*(a + c)/(a - c) + sqrt(a*b + c*d - a*d - b*c + 4*a*c*e**2)/(a - c)] # check for simplification f = Poly(y*x**2 - 2*x - 2*y, x) assert roots_quadratic(f) == \ [-sqrt(2*y**2 + 1)/y + 1/y, sqrt(2*y**2 + 1)/y + 1/y] f = Poly(x**2 + (-y**2 - 2)*x + y**2 + 1, x) assert roots_quadratic(f) == \ [1,y**2 + 1] f = Poly(sqrt(2)*x**2 - 1, x) r = roots_quadratic(f) assert r == _nsort(r) # issue 8255 f = Poly(-24*x**2 - 180*x + 264) assert [w.n(2) for w in f.all_roots(radicals=True)] == \ [w.n(2) for w in f.all_roots(radicals=False)] for _a, _b, _c in cartes((-2, 2), (-2, 2), (0, -1)): f = Poly(_a*x**2 + _b*x + _c) roots = roots_quadratic(f) assert roots == _nsort(roots) def test_issue_7724(): eq = Poly(x**4*I + x**2 + I, x) assert roots(eq) == { sqrt(I/2 + sqrt(5)*I/2): 1, sqrt(-sqrt(5)*I/2 + I/2): 1, -sqrt(I/2 + sqrt(5)*I/2): 1, -sqrt(-sqrt(5)*I/2 + I/2): 1} def test_issue_8438(): p = Poly([1, y, -2, -3], x).as_expr() roots = roots_cubic(Poly(p, x), x) z = Rational(-3, 2) - I*Rational(7, 2) # this will fail in code given in commit msg post = [r.subs(y, z) for r in roots] assert set(post) == \ set(roots_cubic(Poly(p.subs(y, z), x))) # /!\ if p is not made an expression, this is *very* slow assert all(p.subs({y: z, x: i}).n(2, chop=True) == 0 for i in post) def test_issue_8285(): roots = (Poly(4*x**8 - 1, x)*Poly(x**2 + 1)).all_roots() assert _check(roots) f = Poly(x**4 + 5*x**2 + 6, x) ro = [rootof(f, i) for i in range(4)] roots = Poly(x**4 + 5*x**2 + 6, x).all_roots() assert roots == ro assert _check(roots) # more than 2 complex roots from which to identify the # imaginary ones roots = Poly(2*x**8 - 1).all_roots() assert _check(roots) assert len(Poly(2*x**10 - 1).all_roots()) == 10 # doesn't fail def test_issue_8289(): roots = (Poly(x**2 + 2)*Poly(x**4 + 2)).all_roots() assert _check(roots) roots = Poly(x**6 + 3*x**3 + 2, x).all_roots() assert _check(roots) roots = Poly(x**6 - x + 1).all_roots() assert _check(roots) # all imaginary roots with multiplicity of 2 roots = Poly(x**4 + 4*x**2 + 4, x).all_roots() assert _check(roots) def test_issue_14291(): assert Poly(((x - 1)**2 + 1)*((x - 1)**2 + 2)*(x - 1) ).all_roots() == [1, 1 - I, 1 + I, 1 - sqrt(2)*I, 1 + sqrt(2)*I] p = x**4 + 10*x**2 + 1 ans = [rootof(p, i) for i in range(4)] assert Poly(p).all_roots() == ans _check(ans) def test_issue_13340(): eq = Poly(y**3 + exp(x)*y + x, y, domain='EX') roots_d = roots(eq) assert len(roots_d) == 3 def test_issue_14522(): eq = Poly(x**4 + x**3*(16 + 32*I) + x**2*(-285 + 386*I) + x*(-2824 - 448*I) - 2058 - 6053*I, x) roots_eq = roots(eq) assert all(eq(r) == 0 for r in roots_eq) def test_issue_15076(): sol = roots_quartic(Poly(t**4 - 6*t**2 + t/x - 3, t)) assert sol[0].has(x) def test_issue_16589(): eq = Poly(x**4 - 8*sqrt(2)*x**3 + 4*x**3 - 64*sqrt(2)*x**2 + 1024*x, x) roots_eq = roots(eq) assert 0 in roots_eq def test_roots_cubic(): assert roots_cubic(Poly(2*x**3, x)) == [0, 0, 0] assert roots_cubic(Poly(x**3 - 3*x**2 + 3*x - 1, x)) == [1, 1, 1] # valid for arbitrary y (issue 21263) r = root(y, 3) assert roots_cubic(Poly(x**3 - y, x)) == [r, r*(-S.Half + sqrt(3)*I/2), r*(-S.Half - sqrt(3)*I/2)] # simpler form when y is negative assert roots_cubic(Poly(x**3 - -1, x)) == \ [-1, S.Half - I*sqrt(3)/2, S.Half + I*sqrt(3)/2] assert roots_cubic(Poly(2*x**3 - 3*x**2 - 3*x - 1, x))[0] == \ S.Half + 3**Rational(1, 3)/2 + 3**Rational(2, 3)/2 eq = -x**3 + 2*x**2 + 3*x - 2 assert roots(eq, trig=True, multiple=True) == \ roots_cubic(Poly(eq, x), trig=True) == [ Rational(2, 3) + 2*sqrt(13)*cos(acos(8*sqrt(13)/169)/3)/3, -2*sqrt(13)*sin(-acos(8*sqrt(13)/169)/3 + pi/6)/3 + Rational(2, 3), -2*sqrt(13)*cos(-acos(8*sqrt(13)/169)/3 + pi/3)/3 + Rational(2, 3), ] def test_roots_quartic(): assert roots_quartic(Poly(x**4, x)) == [0, 0, 0, 0] assert roots_quartic(Poly(x**4 + x**3, x)) in [ [-1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, -1] ] assert roots_quartic(Poly(x**4 - x**3, x)) in [ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1] ] lhs = roots_quartic(Poly(x**4 + x, x)) rhs = [S.Half + I*sqrt(3)/2, S.Half - I*sqrt(3)/2, S.Zero, -S.One] assert sorted(lhs, key=hash) == sorted(rhs, key=hash) # test of all branches of roots quartic for i, (a, b, c, d) in enumerate([(1, 2, 3, 0), (3, -7, -9, 9), (1, 2, 3, 4), (1, 2, 3, 4), (-7, -3, 3, -6), (-3, 5, -6, -4), (6, -5, -10, -3)]): if i == 2: c = -a*(a**2/S(8) - b/S(2)) elif i == 3: d = a*(a*(a**2*Rational(3, 256) - b/S(16)) + c/S(4)) eq = x**4 + a*x**3 + b*x**2 + c*x + d ans = roots_quartic(Poly(eq, x)) assert all(eq.subs(x, ai).n(chop=True) == 0 for ai in ans) # not all symbolic quartics are unresolvable eq = Poly(q*x + q/4 + x**4 + x**3 + 2*x**2 - Rational(1, 3), x) sol = roots_quartic(eq) assert all(verify_numerically(eq.subs(x, i), 0) for i in sol) z = symbols('z', negative=True) eq = x**4 + 2*x**3 + 3*x**2 + x*(z + 11) + 5 zans = roots_quartic(Poly(eq, x)) assert all([verify_numerically(eq.subs(((x, i), (z, -1))), 0) for i in zans]) # but some are (see also issue 4989) # it's ok if the solution is not Piecewise, but the tests below should pass eq = Poly(y*x**4 + x**3 - x + z, x) ans = roots_quartic(eq) assert all(type(i) == Piecewise for i in ans) reps = ( dict(y=Rational(-1, 3), z=Rational(-1, 4)), # 4 real dict(y=Rational(-1, 3), z=Rational(-1, 2)), # 2 real dict(y=Rational(-1, 3), z=-2)) # 0 real for rep in reps: sol = roots_quartic(Poly(eq.subs(rep), x)) assert all([verify_numerically(w.subs(rep) - s, 0) for w, s in zip(ans, sol)]) def test_issue_21287(): assert not any(isinstance(i, Piecewise) for i in roots_quartic( Poly(x**4 - x**2*(3 + 5*I) + 2*x*(-1 + I) - 1 + 3*I, x))) def test_roots_cyclotomic(): assert roots_cyclotomic(cyclotomic_poly(1, x, polys=True)) == [1] assert roots_cyclotomic(cyclotomic_poly(2, x, polys=True)) == [-1] assert roots_cyclotomic(cyclotomic_poly( 3, x, polys=True)) == [Rational(-1, 2) - I*sqrt(3)/2, Rational(-1, 2) + I*sqrt(3)/2] assert roots_cyclotomic(cyclotomic_poly(4, x, polys=True)) == [-I, I] assert roots_cyclotomic(cyclotomic_poly( 6, x, polys=True)) == [S.Half - I*sqrt(3)/2, S.Half + I*sqrt(3)/2] assert roots_cyclotomic(cyclotomic_poly(7, x, polys=True)) == [ -cos(pi/7) - I*sin(pi/7), -cos(pi/7) + I*sin(pi/7), -cos(pi*Rational(3, 7)) - I*sin(pi*Rational(3, 7)), -cos(pi*Rational(3, 7)) + I*sin(pi*Rational(3, 7)), cos(pi*Rational(2, 7)) - I*sin(pi*Rational(2, 7)), cos(pi*Rational(2, 7)) + I*sin(pi*Rational(2, 7)), ] assert roots_cyclotomic(cyclotomic_poly(8, x, polys=True)) == [ -sqrt(2)/2 - I*sqrt(2)/2, -sqrt(2)/2 + I*sqrt(2)/2, sqrt(2)/2 - I*sqrt(2)/2, sqrt(2)/2 + I*sqrt(2)/2, ] assert roots_cyclotomic(cyclotomic_poly(12, x, polys=True)) == [ -sqrt(3)/2 - I/2, -sqrt(3)/2 + I/2, sqrt(3)/2 - I/2, sqrt(3)/2 + I/2, ] assert roots_cyclotomic( cyclotomic_poly(1, x, polys=True), factor=True) == [1] assert roots_cyclotomic( cyclotomic_poly(2, x, polys=True), factor=True) == [-1] assert roots_cyclotomic(cyclotomic_poly(3, x, polys=True), factor=True) == \ [-root(-1, 3), -1 + root(-1, 3)] assert roots_cyclotomic(cyclotomic_poly(4, x, polys=True), factor=True) == \ [-I, I] assert roots_cyclotomic(cyclotomic_poly(5, x, polys=True), factor=True) == \ [-root(-1, 5), -root(-1, 5)**3, root(-1, 5)**2, -1 - root(-1, 5)**2 + root(-1, 5) + root(-1, 5)**3] assert roots_cyclotomic(cyclotomic_poly(6, x, polys=True), factor=True) == \ [1 - root(-1, 3), root(-1, 3)] def test_roots_binomial(): assert roots_binomial(Poly(5*x, x)) == [0] assert roots_binomial(Poly(5*x**4, x)) == [0, 0, 0, 0] assert roots_binomial(Poly(5*x + 2, x)) == [Rational(-2, 5)] A = 10**Rational(3, 4)/10 assert roots_binomial(Poly(5*x**4 + 2, x)) == \ [-A - A*I, -A + A*I, A - A*I, A + A*I] _check(roots_binomial(Poly(x**8 - 2))) a1 = Symbol('a1', nonnegative=True) b1 = Symbol('b1', nonnegative=True) r0 = roots_quadratic(Poly(a1*x**2 + b1, x)) r1 = roots_binomial(Poly(a1*x**2 + b1, x)) assert powsimp(r0[0]) == powsimp(r1[0]) assert powsimp(r0[1]) == powsimp(r1[1]) for a, b, s, n in cartes((1, 2), (1, 2), (-1, 1), (2, 3, 4, 5)): if a == b and a != 1: # a == b == 1 is sufficient continue p = Poly(a*x**n + s*b) ans = roots_binomial(p) assert ans == _nsort(ans) # issue 8813 assert roots(Poly(2*x**3 - 16*y**3, x)) == { 2*y*(Rational(-1, 2) - sqrt(3)*I/2): 1, 2*y: 1, 2*y*(Rational(-1, 2) + sqrt(3)*I/2): 1} def test_roots_preprocessing(): f = a*y*x**2 + y - b coeff, poly = preprocess_roots(Poly(f, x)) assert coeff == 1 assert poly == Poly(a*y*x**2 + y - b, x) f = c**3*x**3 + c**2*x**2 + c*x + a coeff, poly = preprocess_roots(Poly(f, x)) assert coeff == 1/c assert poly == Poly(x**3 + x**2 + x + a, x) f = c**3*x**3 + c**2*x**2 + a coeff, poly = preprocess_roots(Poly(f, x)) assert coeff == 1/c assert poly == Poly(x**3 + x**2 + a, x) f = c**3*x**3 + c*x + a coeff, poly = preprocess_roots(Poly(f, x)) assert coeff == 1/c assert poly == Poly(x**3 + x + a, x) f = c**3*x**3 + a coeff, poly = preprocess_roots(Poly(f, x)) assert coeff == 1/c assert poly == Poly(x**3 + a, x) E, F, J, L = symbols("E,F,J,L") f = -21601054687500000000*E**8*J**8/L**16 + \ 508232812500000000*F*x*E**7*J**7/L**14 - \ 4269543750000000*E**6*F**2*J**6*x**2/L**12 + \ 16194716250000*E**5*F**3*J**5*x**3/L**10 - \ 27633173750*E**4*F**4*J**4*x**4/L**8 + \ 14840215*E**3*F**5*J**3*x**5/L**6 + \ 54794*E**2*F**6*J**2*x**6/(5*L**4) - \ 1153*E*J*F**7*x**7/(80*L**2) + \ 633*F**8*x**8/160000 coeff, poly = preprocess_roots(Poly(f, x)) assert coeff == 20*E*J/(F*L**2) assert poly == 633*x**8 - 115300*x**7 + 4383520*x**6 + 296804300*x**5 - 27633173750*x**4 + \ 809735812500*x**3 - 10673859375000*x**2 + 63529101562500*x - 135006591796875 f = Poly(-y**2 + x**2*exp(x), y, domain=ZZ[x, exp(x)]) g = Poly(-y**2 + exp(x), y, domain=ZZ[exp(x)]) assert preprocess_roots(f) == (x, g) def test_roots0(): assert roots(1, x) == {} assert roots(x, x) == {S.Zero: 1} assert roots(x**9, x) == {S.Zero: 9} assert roots(((x - 2)*(x + 3)*(x - 4)).expand(), x) == {-S(3): 1, S(2): 1, S(4): 1} assert roots(2*x + 1, x) == {Rational(-1, 2): 1} assert roots((2*x + 1)**2, x) == {Rational(-1, 2): 2} assert roots((2*x + 1)**5, x) == {Rational(-1, 2): 5} assert roots((2*x + 1)**10, x) == {Rational(-1, 2): 10} assert roots(x**4 - 1, x) == {I: 1, S.One: 1, -S.One: 1, -I: 1} assert roots((x**4 - 1)**2, x) == {I: 2, S.One: 2, -S.One: 2, -I: 2} assert roots(((2*x - 3)**2).expand(), x) == {Rational( 3, 2): 2} assert roots(((2*x + 3)**2).expand(), x) == {Rational(-3, 2): 2} assert roots(((2*x - 3)**3).expand(), x) == {Rational( 3, 2): 3} assert roots(((2*x + 3)**3).expand(), x) == {Rational(-3, 2): 3} assert roots(((2*x - 3)**5).expand(), x) == {Rational( 3, 2): 5} assert roots(((2*x + 3)**5).expand(), x) == {Rational(-3, 2): 5} assert roots(((a*x - b)**5).expand(), x) == { b/a: 5} assert roots(((a*x + b)**5).expand(), x) == {-b/a: 5} assert roots(x**2 + (-a - 1)*x + a, x) == {a: 1, S.One: 1} assert roots(x**4 - 2*x**2 + 1, x) == {S.One: 2, S.NegativeOne: 2} assert roots(x**6 - 4*x**4 + 4*x**3 - x**2, x) == \ {S.One: 2, -1 - sqrt(2): 1, S.Zero: 2, -1 + sqrt(2): 1} assert roots(x**8 - 1, x) == { sqrt(2)/2 + I*sqrt(2)/2: 1, sqrt(2)/2 - I*sqrt(2)/2: 1, -sqrt(2)/2 + I*sqrt(2)/2: 1, -sqrt(2)/2 - I*sqrt(2)/2: 1, S.One: 1, -S.One: 1, I: 1, -I: 1 } f = -2016*x**2 - 5616*x**3 - 2056*x**4 + 3324*x**5 + 2176*x**6 - \ 224*x**7 - 384*x**8 - 64*x**9 assert roots(f) == {S.Zero: 2, -S(2): 2, S(2): 1, Rational(-7, 2): 1, Rational(-3, 2): 1, Rational(-1, 2): 1, Rational(3, 2): 1} assert roots((a + b + c)*x - (a + b + c + d), x) == {(a + b + c + d)/(a + b + c): 1} assert roots(x**3 + x**2 - x + 1, x, cubics=False) == {} assert roots(((x - 2)*( x + 3)*(x - 4)).expand(), x, cubics=False) == {-S(3): 1, S(2): 1, S(4): 1} assert roots(((x - 2)*(x + 3)*(x - 4)*(x - 5)).expand(), x, cubics=False) == \ {-S(3): 1, S(2): 1, S(4): 1, S(5): 1} assert roots(x**3 + 2*x**2 + 4*x + 8, x) == {-S(2): 1, -2*I: 1, 2*I: 1} assert roots(x**3 + 2*x**2 + 4*x + 8, x, cubics=True) == \ {-2*I: 1, 2*I: 1, -S(2): 1} assert roots((x**2 - x)*(x**3 + 2*x**2 + 4*x + 8), x ) == \ {S.One: 1, S.Zero: 1, -S(2): 1, -2*I: 1, 2*I: 1} r1_2, r1_3 = S.Half, Rational(1, 3) x0 = (3*sqrt(33) + 19)**r1_3 x1 = 4/x0/3 x2 = x0/3 x3 = sqrt(3)*I/2 x4 = x3 - r1_2 x5 = -x3 - r1_2 assert roots(x**3 + x**2 - x + 1, x, cubics=True) == { -x1 - x2 - r1_3: 1, -x1/x4 - x2*x4 - r1_3: 1, -x1/x5 - x2*x5 - r1_3: 1, } f = (x**2 + 2*x + 3).subs(x, 2*x**2 + 3*x).subs(x, 5*x - 4) r13_20, r1_20 = [ Rational(*r) for r in ((13, 20), (1, 20)) ] s2 = sqrt(2) assert roots(f, x) == { r13_20 + r1_20*sqrt(1 - 8*I*s2): 1, r13_20 - r1_20*sqrt(1 - 8*I*s2): 1, r13_20 + r1_20*sqrt(1 + 8*I*s2): 1, r13_20 - r1_20*sqrt(1 + 8*I*s2): 1, } f = x**4 + x**3 + x**2 + x + 1 r1_4, r1_8, r5_8 = [ Rational(*r) for r in ((1, 4), (1, 8), (5, 8)) ] assert roots(f, x) == { -r1_4 + r1_4*5**r1_2 + I*(r5_8 + r1_8*5**r1_2)**r1_2: 1, -r1_4 + r1_4*5**r1_2 - I*(r5_8 + r1_8*5**r1_2)**r1_2: 1, -r1_4 - r1_4*5**r1_2 + I*(r5_8 - r1_8*5**r1_2)**r1_2: 1, -r1_4 - r1_4*5**r1_2 - I*(r5_8 - r1_8*5**r1_2)**r1_2: 1, } f = z**3 + (-2 - y)*z**2 + (1 + 2*y - 2*x**2)*z - y + 2*x**2 assert roots(f, z) == { S.One: 1, S.Half + S.Half*y + S.Half*sqrt(1 - 2*y + y**2 + 8*x**2): 1, S.Half + S.Half*y - S.Half*sqrt(1 - 2*y + y**2 + 8*x**2): 1, } assert roots(a*b*c*x**3 + 2*x**2 + 4*x + 8, x, cubics=False) == {} assert roots(a*b*c*x**3 + 2*x**2 + 4*x + 8, x, cubics=True) != {} assert roots(x**4 - 1, x, filter='Z') == {S.One: 1, -S.One: 1} assert roots(x**4 - 1, x, filter='I') == {I: 1, -I: 1} assert roots((x - 1)*(x + 1), x) == {S.One: 1, -S.One: 1} assert roots( (x - 1)*(x + 1), x, predicate=lambda r: r.is_positive) == {S.One: 1} assert roots(x**4 - 1, x, filter='Z', multiple=True) == [-S.One, S.One] assert roots(x**4 - 1, x, filter='I', multiple=True) == [I, -I] ar, br = symbols('a, b', real=True) p = x**2*(ar-br)**2 + 2*x*(br-ar) + 1 assert roots(p, x, filter='R') == {1/(ar - br): 2} assert roots(x**3, x, multiple=True) == [S.Zero, S.Zero, S.Zero] assert roots(1234, x, multiple=True) == [] f = x**6 - x**5 + x**4 - x**3 + x**2 - x + 1 assert roots(f) == { -I*sin(pi/7) + cos(pi/7): 1, -I*sin(pi*Rational(2, 7)) - cos(pi*Rational(2, 7)): 1, -I*sin(pi*Rational(3, 7)) + cos(pi*Rational(3, 7)): 1, I*sin(pi/7) + cos(pi/7): 1, I*sin(pi*Rational(2, 7)) - cos(pi*Rational(2, 7)): 1, I*sin(pi*Rational(3, 7)) + cos(pi*Rational(3, 7)): 1, } g = ((x**2 + 1)*f**2).expand() assert roots(g) == { -I*sin(pi/7) + cos(pi/7): 2, -I*sin(pi*Rational(2, 7)) - cos(pi*Rational(2, 7)): 2, -I*sin(pi*Rational(3, 7)) + cos(pi*Rational(3, 7)): 2, I*sin(pi/7) + cos(pi/7): 2, I*sin(pi*Rational(2, 7)) - cos(pi*Rational(2, 7)): 2, I*sin(pi*Rational(3, 7)) + cos(pi*Rational(3, 7)): 2, -I: 1, I: 1, } r = roots(x**3 + 40*x + 64) real_root = [rx for rx in r if rx.is_real][0] cr = 108 + 6*sqrt(1074) assert real_root == -2*root(cr, 3)/3 + 20/root(cr, 3) eq = Poly((7 + 5*sqrt(2))*x**3 + (-6 - 4*sqrt(2))*x**2 + (-sqrt(2) - 1)*x + 2, x, domain='EX') assert roots(eq) == {-1 + sqrt(2): 1, -2 + 2*sqrt(2): 1, -sqrt(2) + 1: 1} eq = Poly(41*x**5 + 29*sqrt(2)*x**5 - 153*x**4 - 108*sqrt(2)*x**4 + 175*x**3 + 125*sqrt(2)*x**3 - 45*x**2 - 30*sqrt(2)*x**2 - 26*sqrt(2)*x - 26*x + 24, x, domain='EX') assert roots(eq) == {-sqrt(2) + 1: 1, -2 + 2*sqrt(2): 1, -1 + sqrt(2): 1, -4 + 4*sqrt(2): 1, -3 + 3*sqrt(2): 1} eq = Poly(x**3 - 2*x**2 + 6*sqrt(2)*x**2 - 8*sqrt(2)*x + 23*x - 14 + 14*sqrt(2), x, domain='EX') assert roots(eq) == {-2*sqrt(2) + 2: 1, -2*sqrt(2) + 1: 1, -2*sqrt(2) - 1: 1} assert roots(Poly((x + sqrt(2))**3 - 7, x, domain='EX')) == \ {-sqrt(2) + root(7, 3)*(-S.Half - sqrt(3)*I/2): 1, -sqrt(2) + root(7, 3)*(-S.Half + sqrt(3)*I/2): 1, -sqrt(2) + root(7, 3): 1} def test_roots_slow(): """Just test that calculating these roots does not hang. """ a, b, c, d, x = symbols("a,b,c,d,x") f1 = x**2*c + (a/b) + x*c*d - a f2 = x**2*(a + b*(c - d)*a) + x*a*b*c/(b*d - d) + (a*d - c/d) assert list(roots(f1, x).values()) == [1, 1] assert list(roots(f2, x).values()) == [1, 1] (zz, yy, xx, zy, zx, yx, k) = symbols("zz,yy,xx,zy,zx,yx,k") e1 = (zz - k)*(yy - k)*(xx - k) + zy*yx*zx + zx - zy - yx e2 = (zz - k)*yx*yx + zx*(yy - k)*zx + zy*zy*(xx - k) assert list(roots(e1 - e2, k).values()) == [1, 1, 1] f = x**3 + 2*x**2 + 8 R = list(roots(f).keys()) assert not any(i for i in [f.subs(x, ri).n(chop=True) for ri in R]) def test_roots_inexact(): R1 = roots(x**2 + x + 1, x, multiple=True) R2 = roots(x**2 + x + 1.0, x, multiple=True) for r1, r2 in zip(R1, R2): assert abs(r1 - r2) < 1e-12 f = x**4 + 3.0*sqrt(2.0)*x**3 - (78.0 + 24.0*sqrt(3.0))*x**2 \ + 144.0*(2*sqrt(3.0) + 9.0) R1 = roots(f, multiple=True) R2 = (-12.7530479110482, -3.85012393732929, 4.89897948556636, 7.46155167569183) for r1, r2 in zip(R1, R2): assert abs(r1 - r2) < 1e-10 def test_roots_preprocessed(): E, F, J, L = symbols("E,F,J,L") f = -21601054687500000000*E**8*J**8/L**16 + \ 508232812500000000*F*x*E**7*J**7/L**14 - \ 4269543750000000*E**6*F**2*J**6*x**2/L**12 + \ 16194716250000*E**5*F**3*J**5*x**3/L**10 - \ 27633173750*E**4*F**4*J**4*x**4/L**8 + \ 14840215*E**3*F**5*J**3*x**5/L**6 + \ 54794*E**2*F**6*J**2*x**6/(5*L**4) - \ 1153*E*J*F**7*x**7/(80*L**2) + \ 633*F**8*x**8/160000 assert roots(f, x) == {} R1 = roots(f.evalf(), x, multiple=True) R2 = [-1304.88375606366, 97.1168816800648, 186.946430171876, 245.526792947065, 503.441004174773, 791.549343830097, 1273.16678129348, 1850.10650616851] w = Wild('w') p = w*E*J/(F*L**2) assert len(R1) == len(R2) for r1, r2 in zip(R1, R2): match = r1.match(p) assert match is not None and abs(match[w] - r2) < 1e-10 def test_roots_mixed(): f = -1936 - 5056*x - 7592*x**2 + 2704*x**3 - 49*x**4 _re, _im = intervals(f, all=True) _nroots = nroots(f) _sroots = roots(f, multiple=True) _re = [ Interval(a, b) for (a, b), _ in _re ] _im = [ Interval(re(a), re(b))*Interval(im(a), im(b)) for (a, b), _ in _im ] _intervals = _re + _im _sroots = [ r.evalf() for r in _sroots ] _nroots = sorted(_nroots, key=lambda x: x.sort_key()) _sroots = sorted(_sroots, key=lambda x: x.sort_key()) for _roots in (_nroots, _sroots): for i, r in zip(_intervals, _roots): if r.is_real: assert r in i else: assert (re(r), im(r)) in i def test_root_factors(): assert root_factors(Poly(1, x)) == [Poly(1, x)] assert root_factors(Poly(x, x)) == [Poly(x, x)] assert root_factors(x**2 - 1, x) == [x + 1, x - 1] assert root_factors(x**2 - y, x) == [x - sqrt(y), x + sqrt(y)] assert root_factors((x**4 - 1)**2) == \ [x + 1, x + 1, x - 1, x - 1, x - I, x - I, x + I, x + I] assert root_factors(Poly(x**4 - 1, x), filter='Z') == \ [Poly(x + 1, x), Poly(x - 1, x), Poly(x**2 + 1, x)] assert root_factors(8*x**2 + 12*x**4 + 6*x**6 + x**8, x, filter='Q') == \ [x, x, x**6 + 6*x**4 + 12*x**2 + 8] @slow def test_nroots1(): n = 64 p = legendre_poly(n, x, polys=True) raises(mpmath.mp.NoConvergence, lambda: p.nroots(n=3, maxsteps=5)) roots = p.nroots(n=3) # The order of roots matters. They are ordered from smallest to the # largest. assert [str(r) for r in roots] == \ ['-0.999', '-0.996', '-0.991', '-0.983', '-0.973', '-0.961', '-0.946', '-0.930', '-0.911', '-0.889', '-0.866', '-0.841', '-0.813', '-0.784', '-0.753', '-0.720', '-0.685', '-0.649', '-0.611', '-0.572', '-0.531', '-0.489', '-0.446', '-0.402', '-0.357', '-0.311', '-0.265', '-0.217', '-0.170', '-0.121', '-0.0730', '-0.0243', '0.0243', '0.0730', '0.121', '0.170', '0.217', '0.265', '0.311', '0.357', '0.402', '0.446', '0.489', '0.531', '0.572', '0.611', '0.649', '0.685', '0.720', '0.753', '0.784', '0.813', '0.841', '0.866', '0.889', '0.911', '0.930', '0.946', '0.961', '0.973', '0.983', '0.991', '0.996', '0.999'] def test_nroots2(): p = Poly(x**5 + 3*x + 1, x) roots = p.nroots(n=3) # The order of roots matters. The roots are ordered by their real # components (if they agree, then by their imaginary components), # with real roots appearing first. assert [str(r) for r in roots] == \ ['-0.332', '-0.839 - 0.944*I', '-0.839 + 0.944*I', '1.01 - 0.937*I', '1.01 + 0.937*I'] roots = p.nroots(n=5) assert [str(r) for r in roots] == \ ['-0.33199', '-0.83907 - 0.94385*I', '-0.83907 + 0.94385*I', '1.0051 - 0.93726*I', '1.0051 + 0.93726*I'] def test_roots_composite(): assert len(roots(Poly(y**3 + y**2*sqrt(x) + y + x, y, composite=True))) == 3 def test_issue_19113(): eq = cos(x)**3 - cos(x) + 1 raises(PolynomialError, lambda: roots(eq))
bf75662965d07b23eec0d1b28b37d1e9915be0691167def14441dac2e2d6aa98
"""Finite extensions of ring domains.""" from sympy.polys.domains.domain import Domain from sympy.polys.domains.domainelement import DomainElement from sympy.polys.polyerrors import (CoercionFailed, NotInvertible, GeneratorsError) from sympy.polys.polytools import Poly from sympy.printing.defaults import DefaultPrinting class ExtensionElement(DomainElement, DefaultPrinting): """ Element of a finite extension. A class of univariate polynomials modulo the ``modulus`` of the extension ``ext``. It is represented by the unique polynomial ``rep`` of lowest degree. Both ``rep`` and the representation ``mod`` of ``modulus`` are of class DMP. """ __slots__ = ('rep', 'ext') def __init__(self, rep, ext): self.rep = rep self.ext = ext def parent(f): return f.ext def __bool__(f): return bool(f.rep) def __pos__(f): return f def __neg__(f): return ExtElem(-f.rep, f.ext) def _get_rep(f, g): if isinstance(g, ExtElem): if g.ext == f.ext: return g.rep else: return None else: try: g = f.ext.convert(g) return g.rep except CoercionFailed: return None def __add__(f, g): rep = f._get_rep(g) if rep is not None: return ExtElem(f.rep + rep, f.ext) else: return NotImplemented __radd__ = __add__ def __sub__(f, g): rep = f._get_rep(g) if rep is not None: return ExtElem(f.rep - rep, f.ext) else: return NotImplemented def __rsub__(f, g): rep = f._get_rep(g) if rep is not None: return ExtElem(rep - f.rep, f.ext) else: return NotImplemented def __mul__(f, g): rep = f._get_rep(g) if rep is not None: return ExtElem((f.rep * rep) % f.ext.mod, f.ext) else: return NotImplemented __rmul__ = __mul__ def _divcheck(f): """Raise if division is not implemented for this divisor""" if not f: raise NotInvertible('Zero divisor') elif f.ext.is_Field: return True elif f.rep.is_ground and f.ext.domain.is_unit(f.rep.rep[0]): return True else: # Some cases like (2*x + 2)/2 over ZZ will fail here. It is # unclear how to implement division in general if the ground # domain is not a field so for now it was decided to restrict the # implementation to division by invertible constants. msg = (f"Can not invert {f} in {f.ext}. " "Only division by invertible constants is implemented.") raise NotImplementedError(msg) def inverse(f): """Multiplicative inverse. Raises ====== NotInvertible If the element is a zero divisor. """ f._divcheck() if f.ext.is_Field: invrep = f.rep.invert(f.ext.mod) else: R = f.ext.ring invrep = R.exquo(R.one, f.rep) return ExtElem(invrep, f.ext) def __truediv__(f, g): rep = f._get_rep(g) if rep is None: return NotImplemented g = ExtElem(rep, f.ext) try: ginv = g.inverse() except NotInvertible: raise ZeroDivisionError(f"{f} / {g}") return f * ginv __floordiv__ = __truediv__ def __rtruediv__(f, g): try: g = f.ext.convert(g) except CoercionFailed: return NotImplemented return g / f __rfloordiv__ = __rtruediv__ def __mod__(f, g): rep = f._get_rep(g) if rep is None: return NotImplemented g = ExtElem(rep, f.ext) try: g._divcheck() except NotInvertible: raise ZeroDivisionError(f"{f} % {g}") # Division where defined is always exact so there is no remainder return f.ext.zero def __rmod__(f, g): try: g = f.ext.convert(g) except CoercionFailed: return NotImplemented return g % f def __pow__(f, n): if not isinstance(n, int): raise TypeError("exponent of type 'int' expected") if n < 0: try: f, n = f.inverse(), -n except NotImplementedError: raise ValueError("negative powers are not defined") b = f.rep m = f.ext.mod r = f.ext.one.rep while n > 0: if n % 2: r = (r*b) % m b = (b*b) % m n //= 2 return ExtElem(r, f.ext) def __eq__(f, g): if isinstance(g, ExtElem): return f.rep == g.rep and f.ext == g.ext else: return NotImplemented def __ne__(f, g): return not f == g def __hash__(f): return hash((f.rep, f.ext)) def __str__(f): from sympy.printing.str import sstr return sstr(f.rep) __repr__ = __str__ @property def is_ground(f): return f.rep.is_ground def to_ground(f): [c] = f.rep.to_list() return c ExtElem = ExtensionElement class MonogenicFiniteExtension(Domain): r""" Finite extension generated by an integral element. The generator is defined by a monic univariate polynomial derived from the argument ``mod``. A shorter alias is ``FiniteExtension``. Examples ======== Quadratic integer ring $\mathbb{Z}[\sqrt2]$: >>> from sympy import Symbol, Poly >>> from sympy.polys.agca.extensions import FiniteExtension >>> x = Symbol('x') >>> R = FiniteExtension(Poly(x**2 - 2)); R ZZ[x]/(x**2 - 2) >>> R.rank 2 >>> R(1 + x)*(3 - 2*x) x - 1 Finite field $GF(5^3)$ defined by the primitive polynomial $x^3 + x^2 + 2$ (over $\mathbb{Z}_5$). >>> F = FiniteExtension(Poly(x**3 + x**2 + 2, modulus=5)); F GF(5)[x]/(x**3 + x**2 + 2) >>> F.basis (1, x, x**2) >>> F(x + 3)/(x**2 + 2) -2*x**2 + x + 2 Function field of an elliptic curve: >>> t = Symbol('t') >>> FiniteExtension(Poly(t**2 - x**3 - x + 1, t, field=True)) ZZ(x)[t]/(t**2 - x**3 - x + 1) """ is_FiniteExtension = True dtype = ExtensionElement def __init__(self, mod): if not (isinstance(mod, Poly) and mod.is_univariate): raise TypeError("modulus must be a univariate Poly") # Using auto=True (default) potentially changes the ground domain to a # field whereas auto=False raises if division is not exact. We'll let # the caller decide whether or not they want to put the ground domain # over a field. In most uses mod is already monic. mod = mod.monic(auto=False) self.rank = mod.degree() self.modulus = mod self.mod = mod.rep # DMP representation self.domain = dom = mod.domain self.ring = mod.rep.ring or dom.old_poly_ring(*mod.gens) self.zero = self.convert(self.ring.zero) self.one = self.convert(self.ring.one) gen = self.ring.gens[0] self.symbol = self.ring.symbols[0] self.generator = self.convert(gen) self.basis = tuple(self.convert(gen**i) for i in range(self.rank)) # XXX: It might be necessary to check mod.is_irreducible here self.is_Field = self.domain.is_Field def new(self, arg): rep = self.ring.convert(arg) return ExtElem(rep % self.mod, self) def __eq__(self, other): if not isinstance(other, FiniteExtension): return False return self.modulus == other.modulus def __hash__(self): return hash((self.__class__.__name__, self.modulus)) def __str__(self): return "%s/(%s)" % (self.ring, self.modulus.as_expr()) __repr__ = __str__ def convert(self, f, base=None): rep = self.ring.convert(f, base) return ExtElem(rep % self.mod, self) def convert_from(self, f, base): rep = self.ring.convert(f, base) return ExtElem(rep % self.mod, self) def to_sympy(self, f): return self.ring.to_sympy(f.rep) def from_sympy(self, f): return self.convert(f) def set_domain(self, K): mod = self.modulus.set_domain(K) return self.__class__(mod) def drop(self, *symbols): if self.symbol in symbols: raise GeneratorsError('Can not drop generator from FiniteExtension') K = self.domain.drop(*symbols) return self.set_domain(K) def quo(self, f, g): return self.exquo(f, g) def exquo(self, f, g): rep = self.ring.exquo(f.rep, g.rep) return ExtElem(rep % self.mod, self) def is_negative(self, a): return False def is_unit(self, a): if self.is_Field: return bool(a) elif a.is_ground: return self.domain.is_unit(a.to_ground()) FiniteExtension = MonogenicFiniteExtension
076724f1ec36ec8e7c15508f2511dec861a11f96c869b9f240c80755d8df5339
""" Module for the DomainMatrix class. A DomainMatrix represents a matrix with elements that are in a particular Domain. Each DomainMatrix internally wraps a DDM which is used for the lower-level operations. The idea is that the DomainMatrix class provides the convenience routines for converting between Expr and the poly domains as well as unifying matrices with different domains. """ from sympy.core.sympify import _sympify from ..constructor import construct_domain from .exceptions import (NonSquareMatrixError, ShapeError, DDMShapeError, DDMDomainError, DDMFormatError) from .ddm import DDM from .sdm import SDM from .domainscalar import DomainScalar from sympy.polys.domains import ZZ class DomainMatrix: r""" Associate Matrix with :py:class:`~.Domain` Explanation =========== DomainMatrix uses :py:class:`~.Domain` for its internal representation which makes it more faster for many common operations than current sympy Matrix class, but this advantage makes it not entirely compatible with Matrix. DomainMatrix could be found analogous to numpy arrays with "dtype". In the DomainMatrix, each matrix has a domain such as :ref:`ZZ` or :ref:`QQ(a)`. Examples ======== Creating a DomainMatrix from the existing Matrix class: >>> from sympy import Matrix >>> from sympy.polys.matrices import DomainMatrix >>> Matrix1 = Matrix([ ... [1, 2], ... [3, 4]]) >>> A = DomainMatrix.from_Matrix(Matrix1) >>> A DomainMatrix([[1, 2], [3, 4]], (2, 2), ZZ) Driectly forming a DomainMatrix: >>> from sympy import ZZ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [ZZ(1), ZZ(2)], ... [ZZ(3), ZZ(4)]], (2, 2), ZZ) >>> A DomainMatrix([[1, 2], [3, 4]], (2, 2), ZZ) See Also ======== DDM SDM Domain Poly """ def __new__(cls, rows, shape, domain, *, fmt=None): """ Creates a :py:class:`~.DomainMatrix`. Parameters ========== rows : Represents elements of DomainMatrix as list of lists shape : Represents dimension of DomainMatrix domain : Represents :py:class:`~.Domain` of DomainMatrix Raises ====== TypeError If any of rows, shape and domain are not provided """ if isinstance(rows, (DDM, SDM)): raise TypeError("Use from_rep to initialise from SDM/DDM") elif isinstance(rows, list): rep = DDM(rows, shape, domain) elif isinstance(rows, dict): rep = SDM(rows, shape, domain) else: msg = "Input should be list-of-lists or dict-of-dicts" raise TypeError(msg) if fmt is not None: if fmt == 'sparse': rep = rep.to_sdm() elif fmt == 'dense': rep = rep.to_ddm() else: raise ValueError("fmt should be 'sparse' or 'dense'") return cls.from_rep(rep) @classmethod def from_rep(cls, rep): """Create a new DomainMatrix efficiently from DDM/SDM. Examples ======== Create a :py:class:`~.DomainMatrix` with an dense internal representation as :py:class:`~.DDM`: >>> from sympy.polys.domains import ZZ >>> from sympy.polys.matrices import DomainMatrix >>> from sympy.polys.matrices.ddm import DDM >>> drep = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) >>> dM = DomainMatrix.from_rep(drep) >>> dM DomainMatrix([[1, 2], [3, 4]], (2, 2), ZZ) Create a :py:class:`~.DomainMatrix` with a sparse internal representation as :py:class:`~.SDM`: >>> from sympy.polys.matrices import DomainMatrix >>> from sympy.polys.matrices.sdm import SDM >>> from sympy import ZZ >>> drep = SDM({0:{1:ZZ(1)},1:{0:ZZ(2)}}, (2, 2), ZZ) >>> dM = DomainMatrix.from_rep(drep) >>> dM DomainMatrix({0: {1: 1}, 1: {0: 2}}, (2, 2), ZZ) Parameters ========== rep: SDM or DDM The internal sparse or dense representation of the matrix. Returns ======= DomainMatrix A :py:class:`~.DomainMatrix` wrapping *rep*. Notes ===== This takes ownership of rep as its internal representation. If rep is being mutated elsewhere then a copy should be provided to ``from_rep``. Only minimal verification or checking is done on *rep* as this is supposed to be an efficient internal routine. """ if not isinstance(rep, (DDM, SDM)): raise TypeError("rep should be of type DDM or SDM") self = super().__new__(cls) self.rep = rep self.shape = rep.shape self.domain = rep.domain return self @classmethod def from_list_sympy(cls, nrows, ncols, rows, **kwargs): r""" Convert a list of lists of Expr into a DomainMatrix using construct_domain Parameters ========== nrows: number of rows ncols: number of columns rows: list of lists Returns ======= DomainMatrix containing elements of rows Examples ======== >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix.from_list_sympy(1, 2, [[1, 0]]) >>> A DomainMatrix([[1, 0]], (1, 2), ZZ) See Also ======== sympy.polys.constructor.construct_domain """ assert len(rows) == nrows assert all(len(row) == ncols for row in rows) items_sympy = [_sympify(item) for row in rows for item in row] domain, items_domain = cls.get_domain(items_sympy, **kwargs) domain_rows = [[items_domain[ncols*r + c] for c in range(ncols)] for r in range(nrows)] return DomainMatrix(domain_rows, (nrows, ncols), domain) @classmethod def from_Matrix(cls, M, **kwargs): r""" Convert Matrix to DomainMatrix Parameters ========== M: Matrix Returns ======= Returns DomainMatrix with identical elements as M Examples ======== >>> from sympy import Matrix >>> from sympy.polys.matrices import DomainMatrix >>> M = Matrix([ ... [1.0, 3.4], ... [2.4, 1]]) >>> A = DomainMatrix.from_Matrix(M) >>> A DomainMatrix([[1.0, 3.4], [2.4, 1.0]], (2, 2), RR) See Also ======== Matrix """ return cls.from_list_sympy(*M.shape, M.tolist(), **kwargs) @classmethod def get_domain(cls, items_sympy, **kwargs): K, items_K = construct_domain(items_sympy, **kwargs) return K, items_K def convert_to(self, K): r""" Change the domain of DomainMatrix to desired domain or field Parameters ========== K : Represents the desired domain or field Returns ======= DomainMatrix DomainMatrix with the desired domain or field Examples ======== >>> from sympy import ZZ, ZZ_I >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [ZZ(1), ZZ(2)], ... [ZZ(3), ZZ(4)]], (2, 2), ZZ) >>> A.convert_to(ZZ_I) DomainMatrix([[1, 2], [3, 4]], (2, 2), ZZ_I) """ return self.from_rep(self.rep.convert_to(K)) def to_field(self): r""" Returns a DomainMatrix with the appropriate field Returns ======= DomainMatrix DomainMatrix with the appropriate field Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [ZZ(1), ZZ(2)], ... [ZZ(3), ZZ(4)]], (2, 2), ZZ) >>> A.to_field() DomainMatrix([[1, 2], [3, 4]], (2, 2), QQ) """ K = self.domain.get_field() return self.convert_to(K) def to_sparse(self): """ Return a sparse DomainMatrix representation of *self*. Examples ======== >>> from sympy.polys.matrices import DomainMatrix >>> from sympy import QQ >>> A = DomainMatrix([[1, 0],[0, 2]], (2, 2), QQ) >>> A.rep [[1, 0], [0, 2]] >>> B = A.to_sparse() >>> B.rep {0: {0: 1}, 1: {1: 2}} """ if self.rep.fmt == 'sparse': return self return self.from_rep(SDM.from_ddm(self.rep)) def to_dense(self): """ Return a dense DomainMatrix representation of *self*. Examples ======== >>> from sympy.polys.matrices import DomainMatrix >>> from sympy import QQ >>> A = DomainMatrix({0: {0: 1}, 1: {1: 2}}, (2, 2), QQ) >>> A.rep {0: {0: 1}, 1: {1: 2}} >>> B = A.to_dense() >>> B.rep [[1, 0], [0, 2]] """ if self.rep.fmt == 'dense': return self return self.from_rep(SDM.to_ddm(self.rep)) def _unify_domain(self, other): """Convert self and other to a common domain""" K1 = self.domain K2 = other.domain if K1 == K2: return self, other K = K1.unify(K2) if K1 != K: self = self.convert_to(K) if K2 != K: other = other.convert_to(K) return self, other def _unify_fmt(self, other, fmt): """Convert self and other to the same format. If both are sparse or both are dense then return both unmodified. Otherwise convert both to the preferred format given as *fmt* which should be 'dense' or 'sparse'. """ if self.rep.fmt == other.rep.fmt: return self, other elif fmt == 'sparse': return self.to_sparse(), other.to_sparse() elif fmt == 'dense': return self.to_dense(), other.to_dense() else: raise ValueError("fmt should be 'sparse' or 'dense'") def unify(self, other, *, fmt=None): """ Unifies the domains and the format of self and other matrices. Parameters ========== other : another DomainMatrix fmt: string 'dense', 'sparse' or `None` (default) The preferred format to convert to if self and other are not already in the same format. If `None` or not specified then no conversion if performed. Returns ======= (dM1, dM2) dM1, dM2 DomainMatrix matrices with unified Domain and format Examples ======== Unify the domain of DomainMatrix that have different domains: >>> from sympy import ZZ, QQ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ) >>> B = DomainMatrix([[QQ(1, 2), QQ(2)]], (1, 2), QQ) >>> Aq, Bq = A.unify(B) >>> Aq DomainMatrix([[1, 2]], (1, 2), QQ) >>> Bq DomainMatrix([[1/2, 2]], (1, 2), QQ) Unify the format (dense or sparse): >>> A = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ) >>> B = DomainMatrix({0:{0: ZZ(1)}}, (2, 2), ZZ) >>> B.rep {0: {0: 1}} >>> A2, B2 = A.unify(B, fmt='dense') >>> B2.rep [[1, 0], [0, 0]] See Also ======== convert_to, to_dense, to_sparse """ dM1, dM2 = self._unify_domain(other) if fmt is not None: dM1, dM2 = dM1._unify_fmt(dM2, fmt) return dM1, dM2 def to_Matrix(self): r""" Convert DomainMatrix to Matrix Returns ======= Matrix MutableDenseMatrix for the DomainMatrix Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [ZZ(1), ZZ(2)], ... [ZZ(3), ZZ(4)]], (2, 2), ZZ) >>> A.to_Matrix() Matrix([ [1, 2], [3, 4]]) See Also ======== from_Matrix """ from sympy.matrices.dense import MutableDenseMatrix elemlist = self.rep.to_list() rows_sympy = [[self.domain.to_sympy(e) for e in row] for row in elemlist] return MutableDenseMatrix(rows_sympy) def __repr__(self): return 'DomainMatrix(%s, %r, %r)' % (str(self.rep), self.shape, self.domain) def hstack(A, B): r""" Horizontally stacks 2 Domain Matrices. Parameters ========== A, B: DomainMatrix to stack the rows horizontally Returns ======= DomainMatrix DomainMatrix by stacking the rows horizontally Examples ======== >>> from sympy import ZZ, QQ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([[ZZ(1), ZZ(2), ZZ(3)]], (1, 3), ZZ) >>> B = DomainMatrix([[QQ(-1, 2), QQ(1, 2), QQ(1, 3)]],(1, 3), QQ) >>> A.hstack(B) DomainMatrix([[1, 2, 3, -1/2, 1/2, 1/3]], (1, 6), QQ) See Also ======== unify """ A, B = A.unify(B, fmt='dense') return A.from_rep(A.rep.hstack(B.rep)) def __add__(A, B): if not isinstance(B, DomainMatrix): return NotImplemented A, B = A.unify(B, fmt='dense') return A.add(B) def __sub__(A, B): if not isinstance(B, DomainMatrix): return NotImplemented A, B = A.unify(B, fmt='dense') return A.sub(B) def __neg__(A): return A.neg() def __mul__(A, B): """A * B""" if isinstance(B, DomainMatrix): A, B = A.unify(B, fmt='dense') return A.matmul(B) elif B in A.domain: return A.from_rep(A.rep * B) elif isinstance(B, DomainScalar): A, B = A.unify(B) return A.scalarmul(B) else: return NotImplemented def __rmul__(A, B): if B in A.domain: return A.from_rep(A.rep * B) elif isinstance(B, DomainScalar): A, B = A.unify(B) return A.scalarmul(B) else: return NotImplemented def __pow__(A, n): """A ** n""" if not isinstance(n, int): return NotImplemented return A.pow(n) def _check(a, op, b, ashape, bshape): if a.domain != b.domain: msg = "Domain mismatch: %s %s %s" % (a.domain, op, b.domain) raise DDMDomainError(msg) if ashape != bshape: msg = "Shape mismatch: %s %s %s" % (a.shape, op, b.shape) raise DDMShapeError(msg) if a.rep.fmt != b.rep.fmt: msg = "Format mismatch: %s %s %s" % (a.rep.fmt, op, b.rep.fmt) raise DDMFormatError(msg) def add(A, B): r""" Adds two DomainMatrix matrices of the same Domain Parameters ========== A, B: DomainMatrix matrices to add Returns ======= DomainMatrix DomainMatrix after Addition Raises ====== ShapeError If the dimensions of the two DomainMatrix are not equal ValueError If the domain of the two DomainMatrix are not same Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [ZZ(1), ZZ(2)], ... [ZZ(3), ZZ(4)]], (2, 2), ZZ) >>> B = DomainMatrix([ ... [ZZ(4), ZZ(3)], ... [ZZ(2), ZZ(1)]], (2, 2), ZZ) >>> A.add(B) DomainMatrix([[5, 5], [5, 5]], (2, 2), ZZ) See Also ======== sub, matmul """ A._check('+', B, A.shape, B.shape) return A.from_rep(A.rep.add(B.rep)) def sub(A, B): r""" Subtracts two DomainMatrix matrices of the same Domain Parameters ========== A, B: DomainMatrix matrices to substract Returns ======= DomainMatrix DomainMatrix after Substraction Raises ====== ShapeError If the dimensions of the two DomainMatrix are not equal ValueError If the domain of the two DomainMatrix are not same Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [ZZ(1), ZZ(2)], ... [ZZ(3), ZZ(4)]], (2, 2), ZZ) >>> B = DomainMatrix([ ... [ZZ(4), ZZ(3)], ... [ZZ(2), ZZ(1)]], (2, 2), ZZ) >>> A.sub(B) DomainMatrix([[-3, -1], [1, 3]], (2, 2), ZZ) See Also ======== add, matmul """ A._check('-', B, A.shape, B.shape) return A.from_rep(A.rep.sub(B.rep)) def neg(A): r""" Returns the negative of DomainMatrix Parameters ========== A : Represents a DomainMatrix Returns ======= DomainMatrix DomainMatrix after Negation Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [ZZ(1), ZZ(2)], ... [ZZ(3), ZZ(4)]], (2, 2), ZZ) >>> A.neg() DomainMatrix([[-1, -2], [-3, -4]], (2, 2), ZZ) """ return A.from_rep(A.rep.neg()) def mul(A, b): r""" Performs term by term multiplication for the second DomainMatrix w.r.t first DomainMatrix. Returns a DomainMatrix whose rows are list of DomainMatrix matrices created after term by term multiplication. Parameters ========== A, B: DomainMatrix matrices to multiply term-wise Returns ======= DomainMatrix DomainMatrix after term by term multiplication Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [ZZ(1), ZZ(2)], ... [ZZ(3), ZZ(4)]], (2, 2), ZZ) >>> B = DomainMatrix([ ... [ZZ(1), ZZ(1)], ... [ZZ(0), ZZ(1)]], (2, 2), ZZ) >>> A.mul(B) DomainMatrix([[DomainMatrix([[1, 1], [0, 1]], (2, 2), ZZ), DomainMatrix([[2, 2], [0, 2]], (2, 2), ZZ)], [DomainMatrix([[3, 3], [0, 3]], (2, 2), ZZ), DomainMatrix([[4, 4], [0, 4]], (2, 2), ZZ)]], (2, 2), ZZ) See Also ======== matmul """ return A.from_rep(A.rep.mul(b)) def matmul(A, B): r""" Performs matrix multiplication of two DomainMatrix matrices Parameters ========== A, B: DomainMatrix to multiply Returns ======= DomainMatrix DomainMatrix after multiplication Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [ZZ(1), ZZ(2)], ... [ZZ(3), ZZ(4)]], (2, 2), ZZ) >>> B = DomainMatrix([ ... [ZZ(1), ZZ(1)], ... [ZZ(0), ZZ(1)]], (2, 2), ZZ) >>> A.matmul(B) DomainMatrix([[1, 3], [3, 7]], (2, 2), ZZ) See Also ======== mul, pow, add, sub """ A._check('*', B, A.shape[1], B.shape[0]) return A.from_rep(A.rep.matmul(B.rep)) def scalarmul(A, lamda): if lamda.element == lamda.domain.zero: m, n = A.shape return DomainMatrix([[lamda.domain.zero]*n]*m, (m, n), A.domain) if lamda.element == lamda.domain.one: return A return A.mul(lamda.element) def __truediv__(A, lamda): """ Method for Scalar Divison""" if isinstance(lamda, int): lamda = DomainScalar(ZZ(lamda), ZZ) if not isinstance(lamda, DomainScalar): return NotImplemented A, lamda = A.to_field().unify(lamda) if lamda.element == lamda.domain.zero: raise ZeroDivisionError if lamda.element == lamda.domain.one: return A.to_field() return A.mul(1 / lamda.element) def pow(A, n): r""" Computes A**n Parameters ========== A : DomainMatrix n : exponent for A Returns ======= DomainMatrix DomainMatrix on computing A**n Raises ====== NotImplementedError if n is negative. Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [ZZ(1), ZZ(1)], ... [ZZ(0), ZZ(1)]], (2, 2), ZZ) >>> A.pow(2) DomainMatrix([[1, 2], [0, 1]], (2, 2), ZZ) See Also ======== matmul """ nrows, ncols = A.shape if nrows != ncols: raise NonSquareMatrixError('Power of a nonsquare matrix') if n < 0: raise NotImplementedError('Negative powers') elif n == 0: return A.eye(nrows, A.domain) elif n == 1: return A elif n % 2 == 1: return A * A**(n - 1) else: sqrtAn = A ** (n // 2) return sqrtAn * sqrtAn def rref(self): r""" Returns reduced-row echelon form and list of pivots for the DomainMatrix Returns ======= (DomainMatrix, list) reduced-row echelon form and list of pivots for the DomainMatrix Raises ====== ValueError If the domain of DomainMatrix not a Field Examples ======== >>> from sympy import QQ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [QQ(2), QQ(-1), QQ(0)], ... [QQ(-1), QQ(2), QQ(-1)], ... [QQ(0), QQ(0), QQ(2)]], (3, 3), QQ) >>> rref_matrix, rref_pivots = A.rref() >>> rref_matrix DomainMatrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]], (3, 3), QQ) >>> rref_pivots (0, 1, 2) See Also ======== convert_to, lu """ if not self.domain.is_Field: raise ValueError('Not a field') rref_ddm, pivots = self.rep.rref() return self.from_rep(rref_ddm), tuple(pivots) def nullspace(self): r""" Returns the Null Space for the DomainMatrix Returns ======= DomainMatrix Null Space of the DomainMatrix Examples ======== >>> from sympy import QQ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [QQ(1), QQ(-1)], ... [QQ(2), QQ(-2)]], (2, 2), QQ) >>> A.nullspace() DomainMatrix([[1, 1]], (1, 2), QQ) """ return self.from_rep(self.rep.nullspace()[0]) def inv(self): r""" Finds the inverse of the DomainMatrix if exists Returns ======= DomainMatrix DomainMatrix after inverse Raises ====== ValueError If the domain of DomainMatrix not a Field NonSquareMatrixError If the DomainMatrix is not a not Square DomainMatrix Examples ======== >>> from sympy import QQ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [QQ(2), QQ(-1), QQ(0)], ... [QQ(-1), QQ(2), QQ(-1)], ... [QQ(0), QQ(0), QQ(2)]], (3, 3), QQ) >>> A.inv() DomainMatrix([[2/3, 1/3, 1/6], [1/3, 2/3, 1/3], [0, 0, 1/2]], (3, 3), QQ) See Also ======== neg """ if not self.domain.is_Field: raise ValueError('Not a field') m, n = self.shape if m != n: raise NonSquareMatrixError inv = self.rep.inv() return self.from_rep(inv) def det(self): r""" Returns the determinant of a Square DomainMatrix Returns ======= S.Complexes determinant of Square DomainMatrix Raises ====== ValueError If the domain of DomainMatrix not a Field Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [ZZ(1), ZZ(2)], ... [ZZ(3), ZZ(4)]], (2, 2), ZZ) >>> A.det() -2 """ m, n = self.shape if m != n: raise NonSquareMatrixError return self.rep.det() def lu(self): r""" Returns Lower and Upper decomposition of the DomainMatrix Returns ======= (L, U, exchange) L, U are Lower and Upper decomposition of the DomainMatrix, exchange is the list of indices of rows exchanged in the decomposition. Raises ====== ValueError If the domain of DomainMatrix not a Field Examples ======== >>> from sympy import QQ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [QQ(1), QQ(-1)], ... [QQ(2), QQ(-2)]], (2, 2), QQ) >>> A.lu() (DomainMatrix([[1, 0], [2, 1]], (2, 2), QQ), DomainMatrix([[1, -1], [0, 0]], (2, 2), QQ), []) See Also ======== lu_solve """ if not self.domain.is_Field: raise ValueError('Not a field') L, U, swaps = self.rep.lu() return self.from_rep(L), self.from_rep(U), swaps def lu_solve(self, rhs): r""" Solver for DomainMatrix x in the A*x = B Parameters ========== rhs : DomainMatrix B Returns ======= DomainMatrix x in A*x = B Raises ====== ShapeError If the DomainMatrix A and rhs have different number of rows ValueError If the domain of DomainMatrix A not a Field Examples ======== >>> from sympy import QQ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [QQ(1), QQ(2)], ... [QQ(3), QQ(4)]], (2, 2), QQ) >>> B = DomainMatrix([ ... [QQ(1), QQ(1)], ... [QQ(0), QQ(1)]], (2, 2), QQ) >>> A.lu_solve(B) DomainMatrix([[-2, -1], [3/2, 1]], (2, 2), QQ) See Also ======== lu """ if self.shape[0] != rhs.shape[0]: raise ShapeError("Shape") if not self.domain.is_Field: raise ValueError('Not a field') sol = self.rep.lu_solve(rhs.rep) return self.from_rep(sol) def charpoly(self): r""" Returns the coefficients of the characteristic polynomial of the DomainMatrix. These elements will be domain elements. The domain of the elements will be same as domain of the DomainMatrix. Returns ======= list coefficients of the characteristic polynomial Raises ====== NonSquareMatrixError If the DomainMatrix is not a not Square DomainMatrix Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [ZZ(1), ZZ(2)], ... [ZZ(3), ZZ(4)]], (2, 2), ZZ) >>> A.charpoly() [1, -5, -2] """ m, n = self.shape if m != n: raise NonSquareMatrixError("not square") return self.rep.charpoly() @classmethod def eye(cls, n, domain): r""" Return identity matrix of size n Examples ======== >>> from sympy.polys.matrices import DomainMatrix >>> from sympy import QQ >>> DomainMatrix.eye(3, QQ) DomainMatrix({0: {0: 1}, 1: {1: 1}, 2: {2: 1}}, (3, 3), QQ) """ return cls.from_rep(SDM.eye(n, domain)) @classmethod def zeros(cls, shape, domain, *, fmt='sparse'): """Returns a zero DomainMatrix of size shape, belonging to the specified domain Examples ======== >>> from sympy.polys.matrices import DomainMatrix >>> from sympy import QQ >>> DomainMatrix.zeros((2, 3), QQ) DomainMatrix({}, (2, 3), QQ) """ return cls.from_rep(SDM.zeros(shape, domain)) @classmethod def ones(cls, shape, domain): """Returns a zero DomainMatrix of size shape, belonging to the specified domain Examples ======== >>> from sympy.polys.matrices import DomainMatrix >>> from sympy import QQ >>> DomainMatrix.ones((2,3), QQ) DomainMatrix([[1, 1, 1], [1, 1, 1]], (2, 3), QQ) """ return cls.from_rep(DDM.ones(shape, domain)) def __eq__(A, B): r""" Checks for two DomainMatrix matrices to be equal or not Parameters ========== A, B: DomainMatrix to check equality Returns ======= Boolean True for equal, else False Raises ====== NotImplementedError If B is not a DomainMatrix Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [ZZ(1), ZZ(2)], ... [ZZ(3), ZZ(4)]], (2, 2), ZZ) >>> B = DomainMatrix([ ... [ZZ(1), ZZ(1)], ... [ZZ(0), ZZ(1)]], (2, 2), ZZ) >>> A.__eq__(A) True >>> A.__eq__(B) False """ if not isinstance(B, DomainMatrix): return NotImplemented return A.rep == B.rep
298d396d5ff9d44640d9daf41cb09f76c2b74ae47690f0e3a26de72c28c5afbc
""" Module to define exceptions to be used in sympy.polys.matrices modules and classes. Ideally all exceptions raised in these modules would be defined and documented here and not e.g. imported from matrices. Also ideally generic exceptions like ValueError/TypeError would not be raised anywhere. """ from sympy.matrices.common import (NonInvertibleMatrixError, NonSquareMatrixError, ShapeError) class DDMError(Exception): """Base class for errors raised by DDM""" pass class DDMBadInputError(DDMError): """list of lists is inconsistent with shape""" pass class DDMDomainError(DDMError): """domains do not match""" pass class DDMShapeError(DDMError): """shapes are inconsistent""" pass class DDMFormatError(DDMError): """mixed dense/sparse not supported""" pass __all__ = [ 'DDMError', 'DDMShapeError', 'DDMDomainError', 'DDMFormatError', 'NonSquareMatrixError', 'NonInvertibleMatrixError', 'ShapeError', ]
2d576c0c6f0c3f59c001de18c2ea57fc26b83fbb604c7a9846178886953e0232
# # sympy.polys.matrices.linsolve module # # This module defines the _linsolve function which is the internal workhorse # used by linsolve. This computes the solution of a system of linear equations # using the SDM sparse matrix implementation in sympy.polys.matrices.sdm. This # is a replacement for solve_lin_sys in sympy.polys.solvers which is # inefficient for large sparse systems due to the use of a PolyRing with many # generators: # # https://github.com/sympy/sympy/issues/20857 # # The implementation of _linsolve here handles: # # - Extracting the coefficients from the Expr/Eq input equations. # - Constructing a domain and converting the coefficients to # that domain. # - Using the SDM.rref, SDM.nullspace etc methods to generate the full # solution working with arithmetic only in the domain of the coefficients. # # The routines here are particularly designed to be efficient for large sparse # systems of linear equations although as well as dense systems. It is # possible that for some small dense systems solve_lin_sys which uses the # dense matrix implementation DDM will be more efficient. With smaller systems # though the bulk of the time is spent just preprocessing the inputs and the # relative time spent in rref is too small to be noticeable. # from collections import defaultdict from sympy.core.add import Add from sympy.core.mul import Mul from sympy.core.singleton import S from sympy.polys.constructor import construct_domain from sympy.polys.solvers import PolyNonlinearError from .sdm import ( SDM, sdm_irref, sdm_particular_from_rref, sdm_nullspace_from_rref ) def _linsolve(eqs, syms): """Solve a linear system of equations. Examples ======== Solve a linear system with a unique solution: >>> from sympy import symbols, Eq >>> from sympy.polys.matrices.linsolve import _linsolve >>> x, y = symbols('x, y') >>> eqs = [Eq(x + y, 1), Eq(x - y, 2)] >>> _linsolve(eqs, [x, y]) {x: 3/2, y: -1/2} In the case of underdetermined systems the solution will be expressed in terms of the unknown symbols that are unconstrained: >>> _linsolve([Eq(x + y, 0)], [x, y]) {x: -y, y: y} """ # Number of unknowns (columns in the non-augmented matrix) nsyms = len(syms) # Convert to sparse augmented matrix (len(eqs) x (nsyms+1)) eqsdict, rhs = _linear_eq_to_dict(eqs, syms) Aaug = sympy_dict_to_dm(eqsdict, rhs, syms) K = Aaug.domain # Compute reduced-row echelon form (RREF) Arref, pivots, nzcols = sdm_irref(Aaug) # No solution: if pivots and pivots[-1] == nsyms: return None # Particular solution for non-homogeneous system: P = sdm_particular_from_rref(Arref, nsyms+1, pivots) # Nullspace - general solution to homogeneous system # Note: using nsyms not nsyms+1 to ignore last column V, nonpivots = sdm_nullspace_from_rref(Arref, K.one, nsyms, pivots, nzcols) # Collect together terms from particular and nullspace: sol = defaultdict(list) for i, v in P.items(): sol[syms[i]].append(K.to_sympy(v)) for npi, Vi in zip(nonpivots, V): sym = syms[npi] for i, v in Vi.items(): sol[syms[i]].append(sym * K.to_sympy(v)) # Use a single call to Add for each term: sol = {s: Add(*terms) for s, terms in sol.items()} # Fill in the zeros: zero = S.Zero for s in set(syms) - set(sol): sol[s] = zero # All done! return sol def sympy_dict_to_dm(eqs_coeffs, eqs_rhs, syms): """Convert a system of dict equations to a sparse augmented matrix""" elems = set(eqs_rhs).union(*(e.values() for e in eqs_coeffs)) K, elems_K = construct_domain(elems, field=True, extension=True) elem_map = dict(zip(elems, elems_K)) neqs = len(eqs_coeffs) nsyms = len(syms) sym2index = dict(zip(syms, range(nsyms))) eqsdict = [] for eq, rhs in zip(eqs_coeffs, eqs_rhs): eqdict = {sym2index[s]: elem_map[c] for s, c in eq.items()} if rhs: eqdict[nsyms] = - elem_map[rhs] if eqdict: eqsdict.append(eqdict) sdm_aug = SDM(enumerate(eqsdict), (neqs, nsyms+1), K) return sdm_aug def _expand_eqs_deprecated(eqs): """Use expand to cancel nonlinear terms. This approach matches previous behaviour of linsolve but should be deprecated. """ def expand_eq(eq): if eq.is_Equality: eq = eq.lhs - eq.rhs return eq.expand() return [expand_eq(eq) for eq in eqs] def _linear_eq_to_dict(eqs, syms): """Convert a system Expr/Eq equations into dict form""" try: return _linear_eq_to_dict_inner(eqs, syms) except PolyNonlinearError: # XXX: This should be deprecated: eqs = _expand_eqs_deprecated(eqs) return _linear_eq_to_dict_inner(eqs, syms) def _linear_eq_to_dict_inner(eqs, syms): """Convert a system Expr/Eq equations into dict form""" syms = set(syms) eqsdict, eqs_rhs = [], [] for eq in eqs: rhs, eqdict = _lin_eq2dict(eq, syms) eqsdict.append(eqdict) eqs_rhs.append(rhs) return eqsdict, eqs_rhs def _lin_eq2dict(a, symset): """Efficiently convert a linear equation to a dict of coefficients""" if a in symset: return S.Zero, {a: S.One} elif a.is_Add: terms_list = defaultdict(list) coeff_list = [] for ai in a.args: ci, ti = _lin_eq2dict(ai, symset) coeff_list.append(ci) for mij, cij in ti.items(): terms_list[mij].append(cij) coeff = Add(*coeff_list) terms = {sym: Add(*coeffs) for sym, coeffs in terms_list.items()} return coeff, terms elif a.is_Mul: terms = terms_coeff = None coeff_list = [] for ai in a.args: ci, ti = _lin_eq2dict(ai, symset) if not ti: coeff_list.append(ci) elif terms is None: terms = ti terms_coeff = ci else: raise PolyNonlinearError coeff = Mul(*coeff_list) if terms is None: return coeff, {} else: terms = {sym: coeff * c for sym, c in terms.items()} return coeff * terms_coeff, terms elif a.is_Equality: return _lin_eq2dict(a.lhs - a.rhs, symset) elif not a.free_symbols & symset: return a, {} else: raise PolyNonlinearError
39257f813b0ea64e90e7e503b5398494b0256e72f20ec5e47427948946cee90b
""" Module for the SDM class. """ from operator import add, neg, pos, sub from collections import defaultdict from .exceptions import DDMBadInputError, DDMDomainError, DDMShapeError from .ddm import DDM class SDM(dict): """Sparse matrix based on polys domain elements This is a dict subclass and is a wrapper for a dict of dicts that supports basic matrix arithmetic +, -, *, **. """ fmt = 'sparse' def __init__(self, elemsdict, shape, domain): super().__init__(elemsdict) self.shape = self.rows, self.cols = m, n = shape self.domain = domain if not all(0 <= r < m for r in self): raise DDMBadInputError("Row out of range") if not all(0 <= c < n for row in self.values() for c in row): raise DDMBadInputError("Column out of range") def __str__(self): rowsstr = [] for i, row in self.items(): elemsstr = ', '.join('%s: %s' % (j, elem) for j, elem in row.items()) rowsstr.append('%s: {%s}' % (i, elemsstr)) return '{%s}' % ', '.join(rowsstr) def __repr__(self): cls = type(self).__name__ rows = dict.__repr__(self) return '%s(%s, %s, %s)' % (cls, rows, self.shape, self.domain) @classmethod def new(cls, sdm, shape, domain): return cls(sdm, shape, domain) def copy(A): Ac = {i: Ai.copy() for i, Ai in A.items()} return A.new(Ac, A.shape, A.domain) @classmethod def from_list(cls, ddm, shape, domain): m, n = shape if not (len(ddm) == m and all(len(row) == n for row in ddm)): raise DDMBadInputError("Inconsistent row-list/shape") getrow = lambda i: {j:ddm[i][j] for j in range(n) if ddm[i][j]} irows = ((i, getrow(i)) for i in range(m)) sdm = {i: row for i, row in irows if row} return cls(sdm, shape, domain) @classmethod def from_ddm(cls, ddm): return cls.from_list(ddm, ddm.shape, ddm.domain) def to_list(M): m, n = M.shape zero = M.domain.zero ddm = [[zero] * n for _ in range(m)] for i, row in M.items(): for j, e in row.items(): ddm[i][j] = e return ddm def to_ddm(M): return DDM(M.to_list(), M.shape, M.domain) def to_sdm(M): return M @classmethod def zeros(cls, shape, domain): return cls({}, shape, domain) @classmethod def ones(cls, shape, domain): one = domain.one m, n = shape row = dict(zip(range(n), [one]*n)) sdm = {i: row.copy() for i in range(m)} return cls(sdm, shape, domain) @classmethod def eye(cls, size, domain): one = domain.one sdm = {i: {i: one} for i in range(size)} return cls(sdm, (size, size), domain) def transpose(M): MT = sdm_transpose(M) return M.new(MT, M.shape[::-1], M.domain) def __mul__(a, b): if b in a.domain: return a.mul(b) else: return NotImplemented def __rmul__(a, b): if b in a.domain: return a.mul(b) else: return NotImplemented def matmul(A, B): if A.domain != B.domain: raise DDMDomainError m, n = A.shape n2, o = B.shape if n != n2: raise DDMShapeError C = sdm_matmul(A, B) return A.new(C, (m, o), A.domain) def mul(A, b): Csdm = unop_dict(A, lambda aij: aij*b) return A.new(Csdm, A.shape, A.domain) def add(A, B): Csdm = binop_dict(A, B, add, pos, pos) return A.new(Csdm, A.shape, A.domain) def sub(A, B): Csdm = binop_dict(A, B, sub, pos, neg) return A.new(Csdm, A.shape, A.domain) def neg(A): Csdm = unop_dict(A, neg) return A.new(Csdm, A.shape, A.domain) def convert_to(A, K): Kold = A.domain if K == Kold: return A.copy() Ak = unop_dict(A, lambda e: K.convert_from(e, Kold)) return A.new(Ak, A.shape, K) def rref(A): B, pivots, _ = sdm_irref(A) return A.new(B, A.shape, A.domain), pivots def inv(A): return A.from_ddm(A.to_ddm().inv()) def det(A): return A.to_ddm().det() def lu(A): L, U, swaps = A.to_ddm().lu() return A.from_ddm(L), A.from_ddm(U), swaps def lu_solve(A, b): return A.from_ddm(A.to_ddm().lu_solve(b.to_ddm())) def nullspace(A): ncols = A.shape[1] one = A.domain.one B, pivots, nzcols = sdm_irref(A) K, nonpivots = sdm_nullspace_from_rref(B, one, ncols, pivots, nzcols) K = dict(enumerate(K)) shape = (len(K), ncols) return A.new(K, shape, A.domain), nonpivots def particular(A): ncols = A.shape[1] B, pivots, nzcols = sdm_irref(A) P = sdm_particular_from_rref(B, ncols, pivots) rep = {0:P} if P else {} return A.new(rep, (1, A.shape[1]), A.domain) def hstack(A, *B): Anew = dict(A.copy()) rows, cols = A.shape domain = A.domain for Bk in B: Bkrows, Bkcols = Bk.shape assert Bkrows == rows assert Bk.domain == domain for i, Bki in Bk.items(): Ai = Anew.get(i, None) if Ai is None: Anew[i] = Ai = {} for j, Bkij in Bki.items(): Ai[j + cols] = Bkij cols += Bkcols return A.new(Anew, (rows, cols), A.domain) def charpoly(A): return A.to_ddm().charpoly() def binop_dict(A, B, fab, fa, fb): Anz, Bnz = set(A), set(B) C = {} for i in Anz & Bnz: Ai, Bi = A[i], B[i] Ci = {} Anzi, Bnzi = set(Ai), set(Bi) for j in Anzi & Bnzi: elem = fab(Ai[j], Bi[j]) if elem: Ci[j] = elem for j in Anzi - Bnzi: Ci[j] = fa(Ai[j]) for j in Bnzi - Anzi: Ci[j] = fb(Bi[j]) if Ci: C[i] = Ci for i in Anz - Bnz: Ai = A[i] C[i] = {j: fa(Aij) for j, Aij in Ai.items()} for i in Bnz - Anz: Bi = B[i] C[i] = {j: fb(Bij) for j, Bij in Bi.items()} return C def unop_dict(A, f): B = {} for i, Ai in A.items(): Bi = {} for j, Aij in Ai.items(): Bij = f(Aij) if Bij: Bi[j] = Bij if Bi: B[i] = Bi return B def sdm_transpose(M): MT = {} for i, Mi in M.items(): for j, Mij in Mi.items(): try: MT[j][i] = Mij except KeyError: MT[j] = {i: Mij} return MT def sdm_matmul(A, B): # # Should be fast if A and B are very sparse. # Consider e.g. A = B = eye(1000). # # The idea here is that we compute C = A*B in terms of the rows of C and # B since the dict of dicts representation naturally stores the matrix as # rows. The ith row of C (Ci) is equal to the sum of Aik * Bk where Bk is # the kth row of B. The algorithm below loops over each nonzero element # Aik of A and if the corresponding row Bj is nonzero then we do # Ci += Aik * Bk. # To make this more efficient we don't need to loop over all elements Aik. # Instead for each row Ai we compute the intersection of the nonzero # columns in Ai with the nonzero rows in B. That gives the k such that # Aik and Bk are both nonzero. In Python the intersection of two sets # of int can be computed very efficiently. # C = {} B_knz = set(B) for i, Ai in A.items(): Ci = {} Ai_knz = set(Ai) for k in Ai_knz & B_knz: Aik = Ai[k] for j, Bkj in B[k].items(): Cij = Ci.get(j, None) if Cij is not None: Cij = Cij + Aik * Bkj if Cij: Ci[j] = Cij else: Ci.pop(j) else: Cij = Aik * Bkj if Cij: Ci[j] = Cij if Ci: C[i] = Ci return C def sdm_irref(A): """RREF and pivots of a sparse matrix *A*. Compute the reduced row echelon form (RREF) of the matrix *A* and return a list of the pivot columns. This routine does not work in place and leaves the original matrix *A* unmodified. Examples ======== This routine works with a dict of dicts sparse representation of a matrix: >>> from sympy import QQ >>> from sympy.polys.matrices.sdm import sdm_irref >>> A = {0: {0: QQ(1), 1: QQ(2)}, 1: {0: QQ(3), 1: QQ(4)}} >>> Arref, pivots, _ = sdm_irref(A) >>> Arref {0: {0: 1}, 1: {1: 1}} >>> pivots [0, 1] The analogous calculation with :py:class:`~.Matrix` would be >>> from sympy import Matrix >>> M = Matrix([[1, 2], [3, 4]]) >>> Mrref, pivots = M.rref() >>> Mrref Matrix([ [1, 0], [0, 1]]) >>> pivots (0, 1) Notes ===== The cost of this algorithm is determined purely by the nonzero elements of the matrix. No part of the cost of any step in this algorithm depends on the number of rows or columns in the matrix. No step depends even on the number of nonzero rows apart from the primary loop over those rows. The implementation is much faster than ddm_rref for sparse matrices. In fact at the time of writing it is also (slightly) faster than the dense implementation even if the input is a fully dense matrix so it seems to be faster in all cases. The elements of the matrix should support exact division with ``/``. For example elements of any domain that is a field (e.g. ``QQ``) should be fine. No attempt is made to handle inexact arithmetic. """ # # Any zeros in the matrix are not stored at all so an element is zero if # its row dict has no index at that key. A row is entirely zero if its # row index is not in the outer dict. Since rref reorders the rows and # removes zero rows we can completely discard the row indices. The first # step then copies the row dicts into a list sorted by the index of the # first nonzero column in each row. # # The algorithm then processes each row Ai one at a time. Previously seen # rows are used to cancel their pivot columns from Ai. Then a pivot from # Ai is chosen and is cancelled from all previously seen rows. At this # point Ai joins the previously seen rows. Once all rows are seen all # elimination has occurred and the rows are sorted by pivot column index. # # The previously seen rows are stored in two separate groups. The reduced # group consists of all rows that have been reduced to a single nonzero # element (the pivot). There is no need to attempt any further reduction # with these. Rows that still have other nonzeros need to be considered # when Ai is cancelled from the previously seen rows. # # A dict nonzerocolumns is used to map from a column index to a set of # previously seen rows that still have a nonzero element in that column. # This means that we can cancel the pivot from Ai into the previously seen # rows without needing to loop over each row that might have a zero in # that column. # # Row dicts sorted by index of first nonzero column # (Maybe sorting is not needed/useful.) Arows = sorted((Ai.copy() for Ai in A.values()), key=min) # Each processed row has an associated pivot column. # pivot_row_map maps from the pivot column index to the row dict. # This means that we can represent a set of rows purely as a set of their # pivot indices. pivot_row_map = {} # Set of pivot indices for rows that are fully reduced to a single nonzero. reduced_pivots = set() # Set of pivot indices for rows not fully reduced nonreduced_pivots = set() # Map from column index to a set of pivot indices representing the rows # that have a nonzero at that column. nonzero_columns = defaultdict(set) while Arows: # Select pivot element and row Ai = Arows.pop() # Nonzero columns from fully reduced pivot rows can be removed Ai = {j: Aij for j, Aij in Ai.items() if j not in reduced_pivots} # Others require full row cancellation for j in nonreduced_pivots & set(Ai): Aj = pivot_row_map[j] Aij = Ai[j] Ainz = set(Ai) Ajnz = set(Aj) for k in Ajnz - Ainz: Ai[k] = - Aij * Aj[k] for k in Ajnz & Ainz: Aik = Ai[k] - Aij * Aj[k] if Aik: Ai[k] = Aik else: Ai.pop(k) # We have now cancelled previously seen pivots from Ai. # If it is zero then discard it. if not Ai: continue # Choose a pivot from Ai: j = min(Ai) Aij = Ai[j] pivot_row_map[j] = Ai Ainz = set(Ai) # Normalise the pivot row to make the pivot 1. # # This approach is slow for some domains. Cross cancellation might be # better for e.g. QQ(x) with division delayed to the final steps. Aijinv = Aij**-1 for l in Ai: Ai[l] *= Aijinv # Use Aij to cancel column j from all previously seen rows for k in nonzero_columns.pop(j, ()): Ak = pivot_row_map[k] Akj = Ak[j] Aknz = set(Ak) for l in Ainz - Aknz: Ak[l] = - Akj * Ai[l] nonzero_columns[l].add(k) for l in Ainz & Aknz: Akl = Ak[l] - Akj * Ai[l] if Akl: Ak[l] = Akl else: # Drop nonzero elements Ak.pop(l) if l != j: nonzero_columns[l].remove(k) if len(Ak) == 1: reduced_pivots.add(k) nonreduced_pivots.remove(k) if len(Ai) == 1: reduced_pivots.add(j) else: nonreduced_pivots.add(j) for l in Ai: if l != j: nonzero_columns[l].add(j) # All done! pivots = sorted(reduced_pivots | nonreduced_pivots) pivot2row = {p: n for n, p in enumerate(pivots)} nonzero_columns = {c: set(pivot2row[p] for p in s) for c, s in nonzero_columns.items()} rows = [pivot_row_map[i] for i in pivots] rref = dict(enumerate(rows)) return rref, pivots, nonzero_columns def sdm_nullspace_from_rref(A, one, ncols, pivots, nonzero_cols): """Get nullspace from A which is in RREF""" nonpivots = sorted(set(range(ncols)) - set(pivots)) K = [] for j in nonpivots: Kj = {j:one} for i in nonzero_cols.get(j, ()): Kj[pivots[i]] = -A[i][j] K.append(Kj) return K, nonpivots def sdm_particular_from_rref(A, ncols, pivots): """Get a particular solution from A which is in RREF""" P = {} for i, j in enumerate(pivots): Ain = A[i].get(ncols-1, None) if Ain is not None: P[j] = Ain / A[i][j] return P
30411671308c12a6c96b142fa347f95d05636a57d3ba51ccca71d5176938f568
""" Module for the DomainScalar class. A DomainScalar represents an element which is in a particular Domain. The idea is that the DomainScalar class provides the convenience routines for unifying elements with different domains. It assists in Scalar Multiplication and getitem for DomainMatrix. """ from ..constructor import construct_domain from sympy.polys.domains import Domain, ZZ class DomainScalar: r""" docstring """ def __new__(cls, element, domain): if not isinstance(domain, Domain): raise TypeError("domain should be of type Domain") if not domain.of_type(element): raise TypeError("element %s should be in domain %s" % (element, domain)) return cls.new(element, domain) @classmethod def new(cls, element, domain): obj = super().__new__(cls) obj.element = element obj.domain = domain return obj def __repr__(self): return repr(self.element) @classmethod def from_sympy(cls, expr): [domain, [element]] = construct_domain([expr]) return cls.new(element, domain) def to_domain(self, domain): element = domain.convert_from(self.element, self.domain) return self.new(element, domain) def convert_to(self, domain): return self.to_domain(domain) def unify(self, other): domain = self.domain.unify(other.domain) return self.to_domain(domain), other.to_domain(domain) def __add__(self, other): if not isinstance(other, DomainScalar): return NotImplemented self, other = self.unify(other) return self.new(self.element + other.element, self.domain) def __sub__(self, other): if not isinstance(other, DomainScalar): return NotImplemented self, other = self.unify(other) return self.new(self.element - other.element, self.domain) def __mul__(self, other): if not isinstance(other, DomainScalar): if isinstance(other, int): other = DomainScalar(ZZ(other), ZZ) else: return NotImplemented self, other = self.unify(other) return self.new(self.element * other.element, self.domain) def __floordiv__(self, other): if not isinstance(other, DomainScalar): return NotImplemented self, other = self.unify(other) return self.new(self.domain.quo(self.element, other.element), self.domain) def __mod__(self, other): if not isinstance(other, DomainScalar): return NotImplemented self, other = self.unify(other) return self.new(self.domain.rem(self.element, other.element), self.domain) def __divmod__(self, other): if not isinstance(other, DomainScalar): return NotImplemented self, other = self.unify(other) q, r = self.domain.div(self.element, other.element) return (self.new(q, self.domain), self.new(r, self.domain)) def __pow__(self, n): if not isinstance(n, int): return NotImplemented return self.new(self.element**n, self.domain) def __pos__(self): return self.new(+self.element, self.domain) def __eq__(self, other): if not isinstance(other, DomainScalar): return NotImplemented return self.element == other.element and self.domain == other.domain def is_zero(self): return self.element == self.domain.zero def is_one(self): return self.element == self.domain.one
a6f202588f3faffbac6b4105aa56f3ec8f004b328c2b68f6827fbae4299348f5
""" Routines for computing eigenvectors with DomainMatrix. """ from sympy.core.symbol import Dummy from ..agca.extensions import FiniteExtension from ..factortools import dup_factor_list from ..polyroots import roots from ..polytools import Poly from ..rootoftools import CRootOf from .domainmatrix import DomainMatrix def dom_eigenvects(A, l=Dummy('lambda')): charpoly = A.charpoly() rows, cols = A.shape domain = A.domain _, factors = dup_factor_list(charpoly, domain) rational_eigenvects = [] algebraic_eigenvects = [] for base, exp in factors: if len(base) == 2: field = domain eigenval = -base[1] / base[0] EE_items = [ [eigenval if i == j else field.zero for j in range(cols)] for i in range(rows)] EE = DomainMatrix(EE_items, (rows, cols), field) basis = (A - EE).nullspace() rational_eigenvects.append((field, eigenval, exp, basis)) else: minpoly = Poly.from_list(base, l, domain=domain) field = FiniteExtension(minpoly) eigenval = field(l) AA_items = [ [Poly.from_list([item], l, domain=domain).rep for item in row] for row in A.rep.to_ddm()] AA_items = [[field(item) for item in row] for row in AA_items] AA = DomainMatrix(AA_items, (rows, cols), field) EE_items = [ [eigenval if i == j else field.zero for j in range(cols)] for i in range(rows)] EE = DomainMatrix(EE_items, (rows, cols), field) basis = (AA - EE).nullspace() algebraic_eigenvects.append((field, minpoly, exp, basis)) return rational_eigenvects, algebraic_eigenvects def dom_eigenvects_to_sympy( rational_eigenvects, algebraic_eigenvects, Matrix, **kwargs ): result = [] for field, eigenvalue, multiplicity, eigenvects in rational_eigenvects: eigenvects = eigenvects.rep.to_ddm() eigenvalue = field.to_sympy(eigenvalue) new_eigenvects = [ Matrix([field.to_sympy(x) for x in vect]) for vect in eigenvects] result.append((eigenvalue, multiplicity, new_eigenvects)) for field, minpoly, multiplicity, eigenvects in algebraic_eigenvects: eigenvects = eigenvects.rep.to_ddm() l = minpoly.gens[0] eigenvects = [[field.to_sympy(x) for x in vect] for vect in eigenvects] degree = minpoly.degree() minpoly = minpoly.as_expr() eigenvals = roots(minpoly, l, **kwargs) if len(eigenvals) != degree: eigenvals = [CRootOf(minpoly, l, idx) for idx in range(degree)] for eigenvalue in eigenvals: new_eigenvects = [ Matrix([x.subs(l, eigenvalue) for x in vect]) for vect in eigenvects] result.append((eigenvalue, multiplicity, new_eigenvects)) return result
bfcc642b7982f7e43cfaa4ea2afc886e9479ca810e9c38ee2a3ef4df0b332ccc
""" Module for the DDM class. The DDM class is an internal representation used by DomainMatrix. The letters DDM stand for Dense Domain Matrix. A DDM instance represents a matrix using elements from a polynomial Domain (e.g. ZZ, QQ, ...) in a dense-matrix representation. Basic usage: >>> from sympy import ZZ, QQ >>> from sympy.polys.matrices.ddm import DDM >>> A = DDM([[ZZ(0), ZZ(1)], [ZZ(-1), ZZ(0)]], (2, 2), ZZ) >>> A.shape (2, 2) >>> A [[0, 1], [-1, 0]] >>> type(A) <class 'sympy.polys.matrices.ddm.DDM'> >>> A @ A [[-1, 0], [0, -1]] The ddm_* functions are designed to operate on DDM as well as on an ordinary list of lists: >>> from sympy.polys.matrices.dense import ddm_idet >>> ddm_idet(A, QQ) 1 >>> ddm_idet([[0, 1], [-1, 0]], QQ) 1 >>> A [[-1, 0], [0, 1]] Note that ddm_idet modifies the input matrix in-place. It is recommended to use the DDM.det method as a friendlier interface to this instead which takes care of copying the matrix: >>> B = DDM([[ZZ(0), ZZ(1)], [ZZ(-1), ZZ(0)]], (2, 2), ZZ) >>> B.det() 1 Normally DDM would not be used directly and is just part of the internal representation of DomainMatrix which adds further functionality including e.g. unifying domains. The dense format used by DDM is a list of lists of elements e.g. the 2x2 identity matrix is like [[1, 0], [0, 1]]. The DDM class itself is a subclass of list and its list items are plain lists. Elements are accessed as e.g. ddm[i][j] where ddm[i] gives the ith row and ddm[i][j] gets the element in the jth column of that row. Subclassing list makes e.g. iteration and indexing very efficient. We do not override __getitem__ because it would lose that benefit. The core routines are implemented by the ddm_* functions defined in dense.py. Those functions are intended to be able to operate on a raw list-of-lists representation of matrices with most functions operating in-place. The DDM class takes care of copying etc and also stores a Domain object associated with its elements. This makes it possible to implement things like A + B with domain checking and also shape checking so that the list of lists representation is friendlier. """ from .exceptions import DDMBadInputError, DDMShapeError, DDMDomainError from .dense import ( ddm_iadd, ddm_isub, ddm_ineg, ddm_imul, ddm_imatmul, ddm_irref, ddm_idet, ddm_iinv, ddm_ilu_split, ddm_ilu_solve, ddm_berk, ) class DDM(list): """Dense matrix based on polys domain elements This is a list subclass and is a wrapper for a list of lists that supports basic matrix arithmetic +, -, *, **. """ fmt = 'dense' def __init__(self, rowslist, shape, domain): super().__init__(rowslist) self.shape = self.rows, self.cols = m, n = shape self.domain = domain if not (len(self) == m and all(len(row) == n for row in self)): raise DDMBadInputError("Inconsistent row-list/shape") def to_list(self): return list(self) def to_ddm(self): return self def to_sdm(self): return SDM.from_list(self, self.shape, self.domain) def convert_to(self, K): Kold = self.domain if K == Kold: return self.copy() rows = ([K.convert_from(e, Kold) for e in row] for row in self) return DDM(rows, self.shape, K) def __str__(self): rowsstr = ['[%s]' % ', '.join(map(str, row)) for row in self] return '[%s]' % ', '.join(rowsstr) def __repr__(self): cls = type(self).__name__ rows = list.__repr__(self) return '%s(%s, %s, %s)' % (cls, rows, self.shape, self.domain) def __eq__(self, other): if not isinstance(other, DDM): return False return (super().__eq__(other) and self.domain == other.domain) def __ne__(self, other): return not self.__eq__(other) @classmethod def zeros(cls, shape, domain): z = domain.zero m, n = shape rowslist = ([z] * n for _ in range(m)) return DDM(rowslist, shape, domain) @classmethod def ones(cls, shape, domain): one = domain.one m, n = shape rowlist = ([one] * n for _ in range(m)) return DDM(rowlist, shape, domain) @classmethod def eye(cls, size, domain): one = domain.one ddm = cls.zeros((size, size), domain) for i in range(size): ddm[i][i] = one return ddm def copy(self): copyrows = (row[:] for row in self) return DDM(copyrows, self.shape, self.domain) def __add__(a, b): if not isinstance(b, DDM): return NotImplemented return a.add(b) def __sub__(a, b): if not isinstance(b, DDM): return NotImplemented return a.sub(b) def __neg__(a): return a.neg() def __mul__(a, b): if b in a.domain: return a.mul(b) else: return NotImplemented def __rmul__(a, b): if b in a.domain: return a.mul(b) else: return NotImplemented def __matmul__(a, b): if isinstance(b, DDM): return a.matmul(b) else: return NotImplemented @classmethod def _check(cls, a, op, b, ashape, bshape): if a.domain != b.domain: msg = "Domain mismatch: %s %s %s" % (a.domain, op, b.domain) raise DDMDomainError(msg) if ashape != bshape: msg = "Shape mismatch: %s %s %s" % (a.shape, op, b.shape) raise DDMShapeError(msg) def add(a, b): """a + b""" a._check(a, '+', b, a.shape, b.shape) c = a.copy() ddm_iadd(c, b) return c def sub(a, b): """a - b""" a._check(a, '-', b, a.shape, b.shape) c = a.copy() ddm_isub(c, b) return c def neg(a): """-a""" b = a.copy() ddm_ineg(b) return b def mul(a, b): c = a.copy() ddm_imul(c, b) return c def matmul(a, b): """a @ b (matrix product)""" m, o = a.shape o2, n = b.shape a._check(a, '*', b, o, o2) c = a.zeros((m, n), a.domain) ddm_imatmul(c, a, b) return c def hstack(A, B): Anew = list(A.copy()) rows, cols = A.shape domain = A.domain Brows, Bcols = B.shape assert Brows == rows assert B.domain == domain cols += Bcols for i, Bi in enumerate(B): Anew[i].extend(Bi) return DDM(Anew, (rows, cols), A.domain) def rref(a): """Reduced-row echelon form of a and list of pivots""" b = a.copy() pivots = ddm_irref(b) return b, pivots def nullspace(a): rref, pivots = a.rref() rows, cols = a.shape domain = a.domain basis = [] nonpivots = [] for i in range(cols): if i in pivots: continue nonpivots.append(i) vec = [domain.one if i == j else domain.zero for j in range(cols)] for ii, jj in enumerate(pivots): vec[jj] -= rref[ii][i] basis.append(vec) return DDM(basis, (len(basis), cols), domain), nonpivots def det(a): """Determinant of a""" m, n = a.shape if m != n: raise DDMShapeError("Determinant of non-square matrix") b = a.copy() K = b.domain deta = ddm_idet(b, K) return deta def inv(a): """Inverse of a""" m, n = a.shape if m != n: raise DDMShapeError("Determinant of non-square matrix") ainv = a.copy() K = a.domain ddm_iinv(ainv, a, K) return ainv def lu(a): """L, U decomposition of a""" m, n = a.shape K = a.domain U = a.copy() L = a.eye(m, K) swaps = ddm_ilu_split(L, U, K) return L, U, swaps def lu_solve(a, b): """x where a*x = b""" m, n = a.shape m2, o = b.shape a._check(a, 'lu_solve', b, m, m2) L, U, swaps = a.lu() x = a.zeros((n, o), a.domain) ddm_ilu_solve(x, L, U, swaps, b) return x def charpoly(a): """Coefficients of characteristic polynomial of a""" K = a.domain m, n = a.shape if m != n: raise DDMShapeError("Charpoly of non-square matrix") vec = ddm_berk(a, K) coeffs = [vec[i][0] for i in range(n+1)] return coeffs from .sdm import SDM
8ebbb84b84e4fee1b24795fab8198491d1b566be34b59d91c6a86b511ac1ffd6
"""Tests for classes defining properties of ground domains, e.g. ZZ, QQ, ZZ[x] ... """ from sympy import I, S, sqrt, sin, oo, Poly, Float, Integer, Rational, pi from sympy.abc import x, y, z from sympy.core.compatibility import HAS_GMPY from sympy.polys.domains import (ZZ, QQ, RR, CC, FF, GF, EX, ZZ_gmpy, ZZ_python, QQ_gmpy, QQ_python) from sympy.polys.domains.algebraicfield import AlgebraicField from sympy.polys.domains.gaussiandomains import ZZ_I, QQ_I from sympy.polys.domains.polynomialring import PolynomialRing from sympy.polys.domains.realfield import RealField from sympy.polys.rings import ring from sympy.polys.fields import field from sympy.polys.agca.extensions import FiniteExtension from sympy.polys.polyerrors import ( UnificationFailed, GeneratorsError, CoercionFailed, NotInvertible, DomainError) from sympy.polys.polyutils import illegal from sympy.testing.pytest import raises ALG = QQ.algebraic_field(sqrt(2), sqrt(3)) def unify(K0, K1): return K0.unify(K1) def test_Domain_unify(): F3 = GF(3) assert unify(F3, F3) == F3 assert unify(F3, ZZ) == ZZ assert unify(F3, QQ) == QQ assert unify(F3, ALG) == ALG assert unify(F3, RR) == RR assert unify(F3, CC) == CC assert unify(F3, ZZ[x]) == ZZ[x] assert unify(F3, ZZ.frac_field(x)) == ZZ.frac_field(x) assert unify(F3, EX) == EX assert unify(ZZ, F3) == ZZ assert unify(ZZ, ZZ) == ZZ assert unify(ZZ, QQ) == QQ assert unify(ZZ, ALG) == ALG assert unify(ZZ, RR) == RR assert unify(ZZ, CC) == CC assert unify(ZZ, ZZ[x]) == ZZ[x] assert unify(ZZ, ZZ.frac_field(x)) == ZZ.frac_field(x) assert unify(ZZ, EX) == EX assert unify(QQ, F3) == QQ assert unify(QQ, ZZ) == QQ assert unify(QQ, QQ) == QQ assert unify(QQ, ALG) == ALG assert unify(QQ, RR) == RR assert unify(QQ, CC) == CC assert unify(QQ, ZZ[x]) == QQ[x] assert unify(QQ, ZZ.frac_field(x)) == QQ.frac_field(x) assert unify(QQ, EX) == EX assert unify(ZZ_I, F3) == ZZ_I assert unify(ZZ_I, ZZ) == ZZ_I assert unify(ZZ_I, ZZ_I) == ZZ_I assert unify(ZZ_I, QQ) == QQ_I assert unify(ZZ_I, ALG) == QQ.algebraic_field(I, sqrt(2), sqrt(3)) assert unify(ZZ_I, RR) == CC assert unify(ZZ_I, CC) == CC assert unify(ZZ_I, ZZ[x]) == ZZ_I[x] assert unify(ZZ_I, ZZ_I[x]) == ZZ_I[x] assert unify(ZZ_I, ZZ.frac_field(x)) == ZZ_I.frac_field(x) assert unify(ZZ_I, ZZ_I.frac_field(x)) == ZZ_I.frac_field(x) assert unify(ZZ_I, EX) == EX assert unify(QQ_I, F3) == QQ_I assert unify(QQ_I, ZZ) == QQ_I assert unify(QQ_I, ZZ_I) == QQ_I assert unify(QQ_I, QQ) == QQ_I assert unify(QQ_I, ALG) == QQ.algebraic_field(I, sqrt(2), sqrt(3)) assert unify(QQ_I, RR) == CC assert unify(QQ_I, CC) == CC assert unify(QQ_I, ZZ[x]) == QQ_I[x] assert unify(QQ_I, ZZ_I[x]) == QQ_I[x] assert unify(QQ_I, QQ[x]) == QQ_I[x] assert unify(QQ_I, QQ_I[x]) == QQ_I[x] assert unify(QQ_I, ZZ.frac_field(x)) == QQ_I.frac_field(x) assert unify(QQ_I, ZZ_I.frac_field(x)) == QQ_I.frac_field(x) assert unify(QQ_I, QQ.frac_field(x)) == QQ_I.frac_field(x) assert unify(QQ_I, QQ_I.frac_field(x)) == QQ_I.frac_field(x) assert unify(QQ_I, EX) == EX assert unify(RR, F3) == RR assert unify(RR, ZZ) == RR assert unify(RR, QQ) == RR assert unify(RR, ALG) == RR assert unify(RR, RR) == RR assert unify(RR, CC) == CC assert unify(RR, ZZ[x]) == RR[x] assert unify(RR, ZZ.frac_field(x)) == RR.frac_field(x) assert unify(RR, EX) == EX assert RR[x].unify(ZZ.frac_field(y)) == RR.frac_field(x, y) assert unify(CC, F3) == CC assert unify(CC, ZZ) == CC assert unify(CC, QQ) == CC assert unify(CC, ALG) == CC assert unify(CC, RR) == CC assert unify(CC, CC) == CC assert unify(CC, ZZ[x]) == CC[x] assert unify(CC, ZZ.frac_field(x)) == CC.frac_field(x) assert unify(CC, EX) == EX assert unify(ZZ[x], F3) == ZZ[x] assert unify(ZZ[x], ZZ) == ZZ[x] assert unify(ZZ[x], QQ) == QQ[x] assert unify(ZZ[x], ALG) == ALG[x] assert unify(ZZ[x], RR) == RR[x] assert unify(ZZ[x], CC) == CC[x] assert unify(ZZ[x], ZZ[x]) == ZZ[x] assert unify(ZZ[x], ZZ.frac_field(x)) == ZZ.frac_field(x) assert unify(ZZ[x], EX) == EX assert unify(ZZ.frac_field(x), F3) == ZZ.frac_field(x) assert unify(ZZ.frac_field(x), ZZ) == ZZ.frac_field(x) assert unify(ZZ.frac_field(x), QQ) == QQ.frac_field(x) assert unify(ZZ.frac_field(x), ALG) == ALG.frac_field(x) assert unify(ZZ.frac_field(x), RR) == RR.frac_field(x) assert unify(ZZ.frac_field(x), CC) == CC.frac_field(x) assert unify(ZZ.frac_field(x), ZZ[x]) == ZZ.frac_field(x) assert unify(ZZ.frac_field(x), ZZ.frac_field(x)) == ZZ.frac_field(x) assert unify(ZZ.frac_field(x), EX) == EX assert unify(EX, F3) == EX assert unify(EX, ZZ) == EX assert unify(EX, QQ) == EX assert unify(EX, ALG) == EX assert unify(EX, RR) == EX assert unify(EX, CC) == EX assert unify(EX, ZZ[x]) == EX assert unify(EX, ZZ.frac_field(x)) == EX assert unify(EX, EX) == EX def test_Domain_unify_composite(): assert unify(ZZ.poly_ring(x), ZZ) == ZZ.poly_ring(x) assert unify(ZZ.poly_ring(x), QQ) == QQ.poly_ring(x) assert unify(QQ.poly_ring(x), ZZ) == QQ.poly_ring(x) assert unify(QQ.poly_ring(x), QQ) == QQ.poly_ring(x) assert unify(ZZ, ZZ.poly_ring(x)) == ZZ.poly_ring(x) assert unify(QQ, ZZ.poly_ring(x)) == QQ.poly_ring(x) assert unify(ZZ, QQ.poly_ring(x)) == QQ.poly_ring(x) assert unify(QQ, QQ.poly_ring(x)) == QQ.poly_ring(x) assert unify(ZZ.poly_ring(x, y), ZZ) == ZZ.poly_ring(x, y) assert unify(ZZ.poly_ring(x, y), QQ) == QQ.poly_ring(x, y) assert unify(QQ.poly_ring(x, y), ZZ) == QQ.poly_ring(x, y) assert unify(QQ.poly_ring(x, y), QQ) == QQ.poly_ring(x, y) assert unify(ZZ, ZZ.poly_ring(x, y)) == ZZ.poly_ring(x, y) assert unify(QQ, ZZ.poly_ring(x, y)) == QQ.poly_ring(x, y) assert unify(ZZ, QQ.poly_ring(x, y)) == QQ.poly_ring(x, y) assert unify(QQ, QQ.poly_ring(x, y)) == QQ.poly_ring(x, y) assert unify(ZZ.frac_field(x), ZZ) == ZZ.frac_field(x) assert unify(ZZ.frac_field(x), QQ) == QQ.frac_field(x) assert unify(QQ.frac_field(x), ZZ) == QQ.frac_field(x) assert unify(QQ.frac_field(x), QQ) == QQ.frac_field(x) assert unify(ZZ, ZZ.frac_field(x)) == ZZ.frac_field(x) assert unify(QQ, ZZ.frac_field(x)) == QQ.frac_field(x) assert unify(ZZ, QQ.frac_field(x)) == QQ.frac_field(x) assert unify(QQ, QQ.frac_field(x)) == QQ.frac_field(x) assert unify(ZZ.frac_field(x, y), ZZ) == ZZ.frac_field(x, y) assert unify(ZZ.frac_field(x, y), QQ) == QQ.frac_field(x, y) assert unify(QQ.frac_field(x, y), ZZ) == QQ.frac_field(x, y) assert unify(QQ.frac_field(x, y), QQ) == QQ.frac_field(x, y) assert unify(ZZ, ZZ.frac_field(x, y)) == ZZ.frac_field(x, y) assert unify(QQ, ZZ.frac_field(x, y)) == QQ.frac_field(x, y) assert unify(ZZ, QQ.frac_field(x, y)) == QQ.frac_field(x, y) assert unify(QQ, QQ.frac_field(x, y)) == QQ.frac_field(x, y) assert unify(ZZ.poly_ring(x), ZZ.poly_ring(x)) == ZZ.poly_ring(x) assert unify(ZZ.poly_ring(x), QQ.poly_ring(x)) == QQ.poly_ring(x) assert unify(QQ.poly_ring(x), ZZ.poly_ring(x)) == QQ.poly_ring(x) assert unify(QQ.poly_ring(x), QQ.poly_ring(x)) == QQ.poly_ring(x) assert unify(ZZ.poly_ring(x, y), ZZ.poly_ring(x)) == ZZ.poly_ring(x, y) assert unify(ZZ.poly_ring(x, y), QQ.poly_ring(x)) == QQ.poly_ring(x, y) assert unify(QQ.poly_ring(x, y), ZZ.poly_ring(x)) == QQ.poly_ring(x, y) assert unify(QQ.poly_ring(x, y), QQ.poly_ring(x)) == QQ.poly_ring(x, y) assert unify(ZZ.poly_ring(x), ZZ.poly_ring(x, y)) == ZZ.poly_ring(x, y) assert unify(ZZ.poly_ring(x), QQ.poly_ring(x, y)) == QQ.poly_ring(x, y) assert unify(QQ.poly_ring(x), ZZ.poly_ring(x, y)) == QQ.poly_ring(x, y) assert unify(QQ.poly_ring(x), QQ.poly_ring(x, y)) == QQ.poly_ring(x, y) assert unify(ZZ.poly_ring(x, y), ZZ.poly_ring(x, z)) == ZZ.poly_ring(x, y, z) assert unify(ZZ.poly_ring(x, y), QQ.poly_ring(x, z)) == QQ.poly_ring(x, y, z) assert unify(QQ.poly_ring(x, y), ZZ.poly_ring(x, z)) == QQ.poly_ring(x, y, z) assert unify(QQ.poly_ring(x, y), QQ.poly_ring(x, z)) == QQ.poly_ring(x, y, z) assert unify(ZZ.frac_field(x), ZZ.frac_field(x)) == ZZ.frac_field(x) assert unify(ZZ.frac_field(x), QQ.frac_field(x)) == QQ.frac_field(x) assert unify(QQ.frac_field(x), ZZ.frac_field(x)) == QQ.frac_field(x) assert unify(QQ.frac_field(x), QQ.frac_field(x)) == QQ.frac_field(x) assert unify(ZZ.frac_field(x, y), ZZ.frac_field(x)) == ZZ.frac_field(x, y) assert unify(ZZ.frac_field(x, y), QQ.frac_field(x)) == QQ.frac_field(x, y) assert unify(QQ.frac_field(x, y), ZZ.frac_field(x)) == QQ.frac_field(x, y) assert unify(QQ.frac_field(x, y), QQ.frac_field(x)) == QQ.frac_field(x, y) assert unify(ZZ.frac_field(x), ZZ.frac_field(x, y)) == ZZ.frac_field(x, y) assert unify(ZZ.frac_field(x), QQ.frac_field(x, y)) == QQ.frac_field(x, y) assert unify(QQ.frac_field(x), ZZ.frac_field(x, y)) == QQ.frac_field(x, y) assert unify(QQ.frac_field(x), QQ.frac_field(x, y)) == QQ.frac_field(x, y) assert unify(ZZ.frac_field(x, y), ZZ.frac_field(x, z)) == ZZ.frac_field(x, y, z) assert unify(ZZ.frac_field(x, y), QQ.frac_field(x, z)) == QQ.frac_field(x, y, z) assert unify(QQ.frac_field(x, y), ZZ.frac_field(x, z)) == QQ.frac_field(x, y, z) assert unify(QQ.frac_field(x, y), QQ.frac_field(x, z)) == QQ.frac_field(x, y, z) assert unify(ZZ.poly_ring(x), ZZ.frac_field(x)) == ZZ.frac_field(x) assert unify(ZZ.poly_ring(x), QQ.frac_field(x)) == ZZ.frac_field(x) assert unify(QQ.poly_ring(x), ZZ.frac_field(x)) == ZZ.frac_field(x) assert unify(QQ.poly_ring(x), QQ.frac_field(x)) == QQ.frac_field(x) assert unify(ZZ.poly_ring(x, y), ZZ.frac_field(x)) == ZZ.frac_field(x, y) assert unify(ZZ.poly_ring(x, y), QQ.frac_field(x)) == ZZ.frac_field(x, y) assert unify(QQ.poly_ring(x, y), ZZ.frac_field(x)) == ZZ.frac_field(x, y) assert unify(QQ.poly_ring(x, y), QQ.frac_field(x)) == QQ.frac_field(x, y) assert unify(ZZ.poly_ring(x), ZZ.frac_field(x, y)) == ZZ.frac_field(x, y) assert unify(ZZ.poly_ring(x), QQ.frac_field(x, y)) == ZZ.frac_field(x, y) assert unify(QQ.poly_ring(x), ZZ.frac_field(x, y)) == ZZ.frac_field(x, y) assert unify(QQ.poly_ring(x), QQ.frac_field(x, y)) == QQ.frac_field(x, y) assert unify(ZZ.poly_ring(x, y), ZZ.frac_field(x, z)) == ZZ.frac_field(x, y, z) assert unify(ZZ.poly_ring(x, y), QQ.frac_field(x, z)) == ZZ.frac_field(x, y, z) assert unify(QQ.poly_ring(x, y), ZZ.frac_field(x, z)) == ZZ.frac_field(x, y, z) assert unify(QQ.poly_ring(x, y), QQ.frac_field(x, z)) == QQ.frac_field(x, y, z) assert unify(ZZ.frac_field(x), ZZ.poly_ring(x)) == ZZ.frac_field(x) assert unify(ZZ.frac_field(x), QQ.poly_ring(x)) == ZZ.frac_field(x) assert unify(QQ.frac_field(x), ZZ.poly_ring(x)) == ZZ.frac_field(x) assert unify(QQ.frac_field(x), QQ.poly_ring(x)) == QQ.frac_field(x) assert unify(ZZ.frac_field(x, y), ZZ.poly_ring(x)) == ZZ.frac_field(x, y) assert unify(ZZ.frac_field(x, y), QQ.poly_ring(x)) == ZZ.frac_field(x, y) assert unify(QQ.frac_field(x, y), ZZ.poly_ring(x)) == ZZ.frac_field(x, y) assert unify(QQ.frac_field(x, y), QQ.poly_ring(x)) == QQ.frac_field(x, y) assert unify(ZZ.frac_field(x), ZZ.poly_ring(x, y)) == ZZ.frac_field(x, y) assert unify(ZZ.frac_field(x), QQ.poly_ring(x, y)) == ZZ.frac_field(x, y) assert unify(QQ.frac_field(x), ZZ.poly_ring(x, y)) == ZZ.frac_field(x, y) assert unify(QQ.frac_field(x), QQ.poly_ring(x, y)) == QQ.frac_field(x, y) assert unify(ZZ.frac_field(x, y), ZZ.poly_ring(x, z)) == ZZ.frac_field(x, y, z) assert unify(ZZ.frac_field(x, y), QQ.poly_ring(x, z)) == ZZ.frac_field(x, y, z) assert unify(QQ.frac_field(x, y), ZZ.poly_ring(x, z)) == ZZ.frac_field(x, y, z) assert unify(QQ.frac_field(x, y), QQ.poly_ring(x, z)) == QQ.frac_field(x, y, z) def test_Domain_unify_algebraic(): sqrt5 = QQ.algebraic_field(sqrt(5)) sqrt7 = QQ.algebraic_field(sqrt(7)) sqrt57 = QQ.algebraic_field(sqrt(5), sqrt(7)) assert sqrt5.unify(sqrt7) == sqrt57 assert sqrt5.unify(sqrt5[x, y]) == sqrt5[x, y] assert sqrt5[x, y].unify(sqrt5) == sqrt5[x, y] assert sqrt5.unify(sqrt5.frac_field(x, y)) == sqrt5.frac_field(x, y) assert sqrt5.frac_field(x, y).unify(sqrt5) == sqrt5.frac_field(x, y) assert sqrt5.unify(sqrt7[x, y]) == sqrt57[x, y] assert sqrt5[x, y].unify(sqrt7) == sqrt57[x, y] assert sqrt5.unify(sqrt7.frac_field(x, y)) == sqrt57.frac_field(x, y) assert sqrt5.frac_field(x, y).unify(sqrt7) == sqrt57.frac_field(x, y) def test_Domain_unify_FiniteExtension(): KxZZ = FiniteExtension(Poly(x**2 - 2, x, domain=ZZ)) KxQQ = FiniteExtension(Poly(x**2 - 2, x, domain=QQ)) KxZZy = FiniteExtension(Poly(x**2 - 2, x, domain=ZZ[y])) KxQQy = FiniteExtension(Poly(x**2 - 2, x, domain=QQ[y])) assert KxZZ.unify(KxZZ) == KxZZ assert KxQQ.unify(KxQQ) == KxQQ assert KxZZy.unify(KxZZy) == KxZZy assert KxQQy.unify(KxQQy) == KxQQy assert KxZZ.unify(ZZ) == KxZZ assert KxZZ.unify(QQ) == KxQQ assert KxQQ.unify(ZZ) == KxQQ assert KxQQ.unify(QQ) == KxQQ assert KxZZ.unify(ZZ[y]) == KxZZy assert KxZZ.unify(QQ[y]) == KxQQy assert KxQQ.unify(ZZ[y]) == KxQQy assert KxQQ.unify(QQ[y]) == KxQQy assert KxZZy.unify(ZZ) == KxZZy assert KxZZy.unify(QQ) == KxQQy assert KxQQy.unify(ZZ) == KxQQy assert KxQQy.unify(QQ) == KxQQy assert KxZZy.unify(ZZ[y]) == KxZZy assert KxZZy.unify(QQ[y]) == KxQQy assert KxQQy.unify(ZZ[y]) == KxQQy assert KxQQy.unify(QQ[y]) == KxQQy K = FiniteExtension(Poly(x**2 - 2, x, domain=ZZ[y])) assert K.unify(ZZ) == K assert K.unify(ZZ[x]) == K assert K.unify(ZZ[y]) == K assert K.unify(ZZ[x, y]) == K Kz = FiniteExtension(Poly(x**2 - 2, x, domain=ZZ[y, z])) assert K.unify(ZZ[z]) == Kz assert K.unify(ZZ[x, z]) == Kz assert K.unify(ZZ[y, z]) == Kz assert K.unify(ZZ[x, y, z]) == Kz Kx = FiniteExtension(Poly(x**2 - 2, x, domain=ZZ)) Ky = FiniteExtension(Poly(y**2 - 2, y, domain=ZZ)) Kxy = FiniteExtension(Poly(y**2 - 2, y, domain=Kx)) assert Kx.unify(Kx) == Kx assert Ky.unify(Ky) == Ky assert Kx.unify(Ky) == Kxy assert Ky.unify(Kx) == Kxy def test_Domain_unify_with_symbols(): raises(UnificationFailed, lambda: ZZ[x, y].unify_with_symbols(ZZ, (y, z))) raises(UnificationFailed, lambda: ZZ.unify_with_symbols(ZZ[x, y], (y, z))) def test_Domain__contains__(): assert (0 in EX) is True assert (0 in ZZ) is True assert (0 in QQ) is True assert (0 in RR) is True assert (0 in CC) is True assert (0 in ALG) is True assert (0 in ZZ[x, y]) is True assert (0 in QQ[x, y]) is True assert (0 in RR[x, y]) is True assert (-7 in EX) is True assert (-7 in ZZ) is True assert (-7 in QQ) is True assert (-7 in RR) is True assert (-7 in CC) is True assert (-7 in ALG) is True assert (-7 in ZZ[x, y]) is True assert (-7 in QQ[x, y]) is True assert (-7 in RR[x, y]) is True assert (17 in EX) is True assert (17 in ZZ) is True assert (17 in QQ) is True assert (17 in RR) is True assert (17 in CC) is True assert (17 in ALG) is True assert (17 in ZZ[x, y]) is True assert (17 in QQ[x, y]) is True assert (17 in RR[x, y]) is True assert (Rational(-1, 7) in EX) is True assert (Rational(-1, 7) in ZZ) is False assert (Rational(-1, 7) in QQ) is True assert (Rational(-1, 7) in RR) is True assert (Rational(-1, 7) in CC) is True assert (Rational(-1, 7) in ALG) is True assert (Rational(-1, 7) in ZZ[x, y]) is False assert (Rational(-1, 7) in QQ[x, y]) is True assert (Rational(-1, 7) in RR[x, y]) is True assert (Rational(3, 5) in EX) is True assert (Rational(3, 5) in ZZ) is False assert (Rational(3, 5) in QQ) is True assert (Rational(3, 5) in RR) is True assert (Rational(3, 5) in CC) is True assert (Rational(3, 5) in ALG) is True assert (Rational(3, 5) in ZZ[x, y]) is False assert (Rational(3, 5) in QQ[x, y]) is True assert (Rational(3, 5) in RR[x, y]) is True assert (3.0 in EX) is True assert (3.0 in ZZ) is True assert (3.0 in QQ) is True assert (3.0 in RR) is True assert (3.0 in CC) is True assert (3.0 in ALG) is True assert (3.0 in ZZ[x, y]) is True assert (3.0 in QQ[x, y]) is True assert (3.0 in RR[x, y]) is True assert (3.14 in EX) is True assert (3.14 in ZZ) is False assert (3.14 in QQ) is True assert (3.14 in RR) is True assert (3.14 in CC) is True assert (3.14 in ALG) is True assert (3.14 in ZZ[x, y]) is False assert (3.14 in QQ[x, y]) is True assert (3.14 in RR[x, y]) is True assert (oo in ALG) is False assert (oo in ZZ[x, y]) is False assert (oo in QQ[x, y]) is False assert (-oo in ZZ) is False assert (-oo in QQ) is False assert (-oo in ALG) is False assert (-oo in ZZ[x, y]) is False assert (-oo in QQ[x, y]) is False assert (sqrt(7) in EX) is True assert (sqrt(7) in ZZ) is False assert (sqrt(7) in QQ) is False assert (sqrt(7) in RR) is True assert (sqrt(7) in CC) is True assert (sqrt(7) in ALG) is False assert (sqrt(7) in ZZ[x, y]) is False assert (sqrt(7) in QQ[x, y]) is False assert (sqrt(7) in RR[x, y]) is True assert (2*sqrt(3) + 1 in EX) is True assert (2*sqrt(3) + 1 in ZZ) is False assert (2*sqrt(3) + 1 in QQ) is False assert (2*sqrt(3) + 1 in RR) is True assert (2*sqrt(3) + 1 in CC) is True assert (2*sqrt(3) + 1 in ALG) is True assert (2*sqrt(3) + 1 in ZZ[x, y]) is False assert (2*sqrt(3) + 1 in QQ[x, y]) is False assert (2*sqrt(3) + 1 in RR[x, y]) is True assert (sin(1) in EX) is True assert (sin(1) in ZZ) is False assert (sin(1) in QQ) is False assert (sin(1) in RR) is True assert (sin(1) in CC) is True assert (sin(1) in ALG) is False assert (sin(1) in ZZ[x, y]) is False assert (sin(1) in QQ[x, y]) is False assert (sin(1) in RR[x, y]) is True assert (x**2 + 1 in EX) is True assert (x**2 + 1 in ZZ) is False assert (x**2 + 1 in QQ) is False assert (x**2 + 1 in RR) is False assert (x**2 + 1 in CC) is False assert (x**2 + 1 in ALG) is False assert (x**2 + 1 in ZZ[x]) is True assert (x**2 + 1 in QQ[x]) is True assert (x**2 + 1 in RR[x]) is True assert (x**2 + 1 in ZZ[x, y]) is True assert (x**2 + 1 in QQ[x, y]) is True assert (x**2 + 1 in RR[x, y]) is True assert (x**2 + y**2 in EX) is True assert (x**2 + y**2 in ZZ) is False assert (x**2 + y**2 in QQ) is False assert (x**2 + y**2 in RR) is False assert (x**2 + y**2 in CC) is False assert (x**2 + y**2 in ALG) is False assert (x**2 + y**2 in ZZ[x]) is False assert (x**2 + y**2 in QQ[x]) is False assert (x**2 + y**2 in RR[x]) is False assert (x**2 + y**2 in ZZ[x, y]) is True assert (x**2 + y**2 in QQ[x, y]) is True assert (x**2 + y**2 in RR[x, y]) is True assert (Rational(3, 2)*x/(y + 1) - z in QQ[x, y, z]) is False def test_Domain_get_ring(): assert ZZ.has_assoc_Ring is True assert QQ.has_assoc_Ring is True assert ZZ[x].has_assoc_Ring is True assert QQ[x].has_assoc_Ring is True assert ZZ[x, y].has_assoc_Ring is True assert QQ[x, y].has_assoc_Ring is True assert ZZ.frac_field(x).has_assoc_Ring is True assert QQ.frac_field(x).has_assoc_Ring is True assert ZZ.frac_field(x, y).has_assoc_Ring is True assert QQ.frac_field(x, y).has_assoc_Ring is True assert EX.has_assoc_Ring is False assert RR.has_assoc_Ring is False assert ALG.has_assoc_Ring is False assert ZZ.get_ring() == ZZ assert QQ.get_ring() == ZZ assert ZZ[x].get_ring() == ZZ[x] assert QQ[x].get_ring() == QQ[x] assert ZZ[x, y].get_ring() == ZZ[x, y] assert QQ[x, y].get_ring() == QQ[x, y] assert ZZ.frac_field(x).get_ring() == ZZ[x] assert QQ.frac_field(x).get_ring() == QQ[x] assert ZZ.frac_field(x, y).get_ring() == ZZ[x, y] assert QQ.frac_field(x, y).get_ring() == QQ[x, y] assert EX.get_ring() == EX assert RR.get_ring() == RR # XXX: This should also be like RR raises(DomainError, lambda: ALG.get_ring()) def test_Domain_get_field(): assert EX.has_assoc_Field is True assert ZZ.has_assoc_Field is True assert QQ.has_assoc_Field is True assert RR.has_assoc_Field is True assert ALG.has_assoc_Field is True assert ZZ[x].has_assoc_Field is True assert QQ[x].has_assoc_Field is True assert ZZ[x, y].has_assoc_Field is True assert QQ[x, y].has_assoc_Field is True assert EX.get_field() == EX assert ZZ.get_field() == QQ assert QQ.get_field() == QQ assert RR.get_field() == RR assert ALG.get_field() == ALG assert ZZ[x].get_field() == ZZ.frac_field(x) assert QQ[x].get_field() == QQ.frac_field(x) assert ZZ[x, y].get_field() == ZZ.frac_field(x, y) assert QQ[x, y].get_field() == QQ.frac_field(x, y) def test_Domain_get_exact(): assert EX.get_exact() == EX assert ZZ.get_exact() == ZZ assert QQ.get_exact() == QQ assert RR.get_exact() == QQ assert ALG.get_exact() == ALG assert ZZ[x].get_exact() == ZZ[x] assert QQ[x].get_exact() == QQ[x] assert ZZ[x, y].get_exact() == ZZ[x, y] assert QQ[x, y].get_exact() == QQ[x, y] assert ZZ.frac_field(x).get_exact() == ZZ.frac_field(x) assert QQ.frac_field(x).get_exact() == QQ.frac_field(x) assert ZZ.frac_field(x, y).get_exact() == ZZ.frac_field(x, y) assert QQ.frac_field(x, y).get_exact() == QQ.frac_field(x, y) def test_Domain_is_unit(): nums = [-2, -1, 0, 1, 2] invring = [False, True, False, True, False] invfield = [True, True, False, True, True] ZZx, QQx, QQxf = ZZ[x], QQ[x], QQ.frac_field(x) assert [ZZ.is_unit(ZZ(n)) for n in nums] == invring assert [QQ.is_unit(QQ(n)) for n in nums] == invfield assert [ZZx.is_unit(ZZx(n)) for n in nums] == invring assert [QQx.is_unit(QQx(n)) for n in nums] == invfield assert [QQxf.is_unit(QQxf(n)) for n in nums] == invfield assert ZZx.is_unit(ZZx(x)) is False assert QQx.is_unit(QQx(x)) is False assert QQxf.is_unit(QQxf(x)) is True def test_Domain_convert(): def check_element(e1, e2, K1, K2, K3): assert type(e1) is type(e2), '%s, %s: %s %s -> %s' % (e1, e2, K1, K2, K3) assert e1 == e2, '%s, %s: %s %s -> %s' % (e1, e2, K1, K2, K3) def check_domains(K1, K2): K3 = K1.unify(K2) check_element(K3.convert_from(K1.one, K1), K3.one , K1, K2, K3) check_element(K3.convert_from(K2.one, K2), K3.one , K1, K2, K3) check_element(K3.convert_from(K1.zero, K1), K3.zero, K1, K2, K3) check_element(K3.convert_from(K2.zero, K2), K3.zero, K1, K2, K3) def composite_domains(K): return [K, K[y], K[z], K[y, z], K.frac_field(y), K.frac_field(z), K.frac_field(y, z)] QQ2 = QQ.algebraic_field(sqrt(2)) QQ3 = QQ.algebraic_field(sqrt(3)) doms = [ZZ, QQ, QQ2, QQ3, QQ_I, ZZ_I, RR, CC] for i, K1 in enumerate(doms): for K2 in doms[i:]: for K3 in composite_domains(K1): for K4 in composite_domains(K2): check_domains(K3, K4) assert QQ.convert(10e-52) == QQ(1684996666696915, 1684996666696914987166688442938726917102321526408785780068975640576) R, x = ring("x", ZZ) assert ZZ.convert(x - x) == 0 assert ZZ.convert(x - x, R.to_domain()) == 0 assert CC.convert(ZZ_I(1, 2)) == CC(1, 2) assert CC.convert(QQ_I(1, 2)) == CC(1, 2) def test_GlobalPolynomialRing_convert(): K1 = QQ.old_poly_ring(x) K2 = QQ[x] assert K1.convert(x) == K1.convert(K2.convert(x), K2) assert K2.convert(x) == K2.convert(K1.convert(x), K1) K1 = QQ.old_poly_ring(x, y) K2 = QQ[x] assert K1.convert(x) == K1.convert(K2.convert(x), K2) #assert K2.convert(x) == K2.convert(K1.convert(x), K1) K1 = ZZ.old_poly_ring(x, y) K2 = QQ[x] assert K1.convert(x) == K1.convert(K2.convert(x), K2) #assert K2.convert(x) == K2.convert(K1.convert(x), K1) def test_PolynomialRing__init(): R, = ring("", ZZ) assert ZZ.poly_ring() == R.to_domain() def test_FractionField__init(): F, = field("", ZZ) assert ZZ.frac_field() == F.to_domain() def test_FractionField_convert(): K = QQ.frac_field(x) assert K.convert(QQ(2, 3), QQ) == K.from_sympy(Rational(2, 3)) K = QQ.frac_field(x) assert K.convert(ZZ(2), ZZ) == K.from_sympy(Integer(2)) def test_inject(): assert ZZ.inject(x, y, z) == ZZ[x, y, z] assert ZZ[x].inject(y, z) == ZZ[x, y, z] assert ZZ.frac_field(x).inject(y, z) == ZZ.frac_field(x, y, z) raises(GeneratorsError, lambda: ZZ[x].inject(x)) def test_drop(): assert ZZ.drop(x) == ZZ assert ZZ[x].drop(x) == ZZ assert ZZ[x, y].drop(x) == ZZ[y] assert ZZ.frac_field(x).drop(x) == ZZ assert ZZ.frac_field(x, y).drop(x) == ZZ.frac_field(y) assert ZZ[x][y].drop(y) == ZZ[x] assert ZZ[x][y].drop(x) == ZZ[y] assert ZZ.frac_field(x)[y].drop(x) == ZZ[y] assert ZZ.frac_field(x)[y].drop(y) == ZZ.frac_field(x) Ky = FiniteExtension(Poly(x**2-1, x, domain=ZZ[y])) K = FiniteExtension(Poly(x**2-1, x, domain=ZZ)) assert Ky.drop(y) == K raises(GeneratorsError, lambda: Ky.drop(x)) def test_Domain_map(): seq = ZZ.map([1, 2, 3, 4]) assert all(ZZ.of_type(elt) for elt in seq) seq = ZZ.map([[1, 2, 3, 4]]) assert all(ZZ.of_type(elt) for elt in seq[0]) and len(seq) == 1 def test_Domain___eq__(): assert (ZZ[x, y] == ZZ[x, y]) is True assert (QQ[x, y] == QQ[x, y]) is True assert (ZZ[x, y] == QQ[x, y]) is False assert (QQ[x, y] == ZZ[x, y]) is False assert (ZZ.frac_field(x, y) == ZZ.frac_field(x, y)) is True assert (QQ.frac_field(x, y) == QQ.frac_field(x, y)) is True assert (ZZ.frac_field(x, y) == QQ.frac_field(x, y)) is False assert (QQ.frac_field(x, y) == ZZ.frac_field(x, y)) is False assert RealField()[x] == RR[x] def test_Domain__algebraic_field(): alg = ZZ.algebraic_field(sqrt(2)) assert alg.ext.minpoly == Poly(x**2 - 2) assert alg.dom == QQ alg = QQ.algebraic_field(sqrt(2)) assert alg.ext.minpoly == Poly(x**2 - 2) assert alg.dom == QQ alg = alg.algebraic_field(sqrt(3)) assert alg.ext.minpoly == Poly(x**4 - 10*x**2 + 1) assert alg.dom == QQ def test_PolynomialRing_from_FractionField(): F, x,y = field("x,y", ZZ) R, X,Y = ring("x,y", ZZ) f = (x**2 + y**2)/(x + 1) g = (x**2 + y**2)/4 h = x**2 + y**2 assert R.to_domain().from_FractionField(f, F.to_domain()) is None assert R.to_domain().from_FractionField(g, F.to_domain()) == X**2/4 + Y**2/4 assert R.to_domain().from_FractionField(h, F.to_domain()) == X**2 + Y**2 F, x,y = field("x,y", QQ) R, X,Y = ring("x,y", QQ) f = (x**2 + y**2)/(x + 1) g = (x**2 + y**2)/4 h = x**2 + y**2 assert R.to_domain().from_FractionField(f, F.to_domain()) is None assert R.to_domain().from_FractionField(g, F.to_domain()) == X**2/4 + Y**2/4 assert R.to_domain().from_FractionField(h, F.to_domain()) == X**2 + Y**2 def test_FractionField_from_PolynomialRing(): R, x,y = ring("x,y", QQ) F, X,Y = field("x,y", ZZ) f = 3*x**2 + 5*y**2 g = x**2/3 + y**2/5 assert F.to_domain().from_PolynomialRing(f, R.to_domain()) == 3*X**2 + 5*Y**2 assert F.to_domain().from_PolynomialRing(g, R.to_domain()) == (5*X**2 + 3*Y**2)/15 def test_FF_of_type(): assert FF(3).of_type(FF(3)(1)) is True assert FF(5).of_type(FF(5)(3)) is True assert FF(5).of_type(FF(7)(3)) is False def test___eq__(): assert not QQ[x] == ZZ[x] assert not QQ.frac_field(x) == ZZ.frac_field(x) def test_RealField_from_sympy(): assert RR.convert(S.Zero) == RR.dtype(0) assert RR.convert(S(0.0)) == RR.dtype(0.0) assert RR.convert(S.One) == RR.dtype(1) assert RR.convert(S(1.0)) == RR.dtype(1.0) assert RR.convert(sin(1)) == RR.dtype(sin(1).evalf()) def test_not_in_any_domain(): check = illegal + [x] + [ float(i) for i in illegal if i != S.ComplexInfinity] for dom in (ZZ, QQ, RR, CC, EX): for i in check: if i == x and dom == EX: continue assert i not in dom, (i, dom) raises(CoercionFailed, lambda: dom.convert(i)) def test_ModularInteger(): F3 = FF(3) a = F3(0) assert isinstance(a, F3.dtype) and a == 0 a = F3(1) assert isinstance(a, F3.dtype) and a == 1 a = F3(2) assert isinstance(a, F3.dtype) and a == 2 a = F3(3) assert isinstance(a, F3.dtype) and a == 0 a = F3(4) assert isinstance(a, F3.dtype) and a == 1 a = F3(F3(0)) assert isinstance(a, F3.dtype) and a == 0 a = F3(F3(1)) assert isinstance(a, F3.dtype) and a == 1 a = F3(F3(2)) assert isinstance(a, F3.dtype) and a == 2 a = F3(F3(3)) assert isinstance(a, F3.dtype) and a == 0 a = F3(F3(4)) assert isinstance(a, F3.dtype) and a == 1 a = -F3(1) assert isinstance(a, F3.dtype) and a == 2 a = -F3(2) assert isinstance(a, F3.dtype) and a == 1 a = 2 + F3(2) assert isinstance(a, F3.dtype) and a == 1 a = F3(2) + 2 assert isinstance(a, F3.dtype) and a == 1 a = F3(2) + F3(2) assert isinstance(a, F3.dtype) and a == 1 a = F3(2) + F3(2) assert isinstance(a, F3.dtype) and a == 1 a = 3 - F3(2) assert isinstance(a, F3.dtype) and a == 1 a = F3(3) - 2 assert isinstance(a, F3.dtype) and a == 1 a = F3(3) - F3(2) assert isinstance(a, F3.dtype) and a == 1 a = F3(3) - F3(2) assert isinstance(a, F3.dtype) and a == 1 a = 2*F3(2) assert isinstance(a, F3.dtype) and a == 1 a = F3(2)*2 assert isinstance(a, F3.dtype) and a == 1 a = F3(2)*F3(2) assert isinstance(a, F3.dtype) and a == 1 a = F3(2)*F3(2) assert isinstance(a, F3.dtype) and a == 1 a = 2/F3(2) assert isinstance(a, F3.dtype) and a == 1 a = F3(2)/2 assert isinstance(a, F3.dtype) and a == 1 a = F3(2)/F3(2) assert isinstance(a, F3.dtype) and a == 1 a = F3(2)/F3(2) assert isinstance(a, F3.dtype) and a == 1 a = 1 % F3(2) assert isinstance(a, F3.dtype) and a == 1 a = F3(1) % 2 assert isinstance(a, F3.dtype) and a == 1 a = F3(1) % F3(2) assert isinstance(a, F3.dtype) and a == 1 a = F3(1) % F3(2) assert isinstance(a, F3.dtype) and a == 1 a = F3(2)**0 assert isinstance(a, F3.dtype) and a == 1 a = F3(2)**1 assert isinstance(a, F3.dtype) and a == 2 a = F3(2)**2 assert isinstance(a, F3.dtype) and a == 1 F7 = FF(7) a = F7(3)**100000000000 assert isinstance(a, F7.dtype) and a == 4 a = F7(3)**-100000000000 assert isinstance(a, F7.dtype) and a == 2 a = F7(3)**S(2) assert isinstance(a, F7.dtype) and a == 2 assert bool(F3(3)) is False assert bool(F3(4)) is True F5 = FF(5) a = F5(1)**(-1) assert isinstance(a, F5.dtype) and a == 1 a = F5(2)**(-1) assert isinstance(a, F5.dtype) and a == 3 a = F5(3)**(-1) assert isinstance(a, F5.dtype) and a == 2 a = F5(4)**(-1) assert isinstance(a, F5.dtype) and a == 4 assert (F5(1) < F5(2)) is True assert (F5(1) <= F5(2)) is True assert (F5(1) > F5(2)) is False assert (F5(1) >= F5(2)) is False assert (F5(3) < F5(2)) is False assert (F5(3) <= F5(2)) is False assert (F5(3) > F5(2)) is True assert (F5(3) >= F5(2)) is True assert (F5(1) < F5(7)) is True assert (F5(1) <= F5(7)) is True assert (F5(1) > F5(7)) is False assert (F5(1) >= F5(7)) is False assert (F5(3) < F5(7)) is False assert (F5(3) <= F5(7)) is False assert (F5(3) > F5(7)) is True assert (F5(3) >= F5(7)) is True assert (F5(1) < 2) is True assert (F5(1) <= 2) is True assert (F5(1) > 2) is False assert (F5(1) >= 2) is False assert (F5(3) < 2) is False assert (F5(3) <= 2) is False assert (F5(3) > 2) is True assert (F5(3) >= 2) is True assert (F5(1) < 7) is True assert (F5(1) <= 7) is True assert (F5(1) > 7) is False assert (F5(1) >= 7) is False assert (F5(3) < 7) is False assert (F5(3) <= 7) is False assert (F5(3) > 7) is True assert (F5(3) >= 7) is True raises(NotInvertible, lambda: F5(0)**(-1)) raises(NotInvertible, lambda: F5(5)**(-1)) raises(ValueError, lambda: FF(0)) raises(ValueError, lambda: FF(2.1)) def test_QQ_int(): assert int(QQ(2**2000, 3**1250)) == 455431 assert int(QQ(2**100, 3)) == 422550200076076467165567735125 def test_RR_double(): assert RR(3.14) > 1e-50 assert RR(1e-13) > 1e-50 assert RR(1e-14) > 1e-50 assert RR(1e-15) > 1e-50 assert RR(1e-20) > 1e-50 assert RR(1e-40) > 1e-50 def test_RR_Float(): f1 = Float("1.01") f2 = Float("1.0000000000000000000001") assert f1._prec == 53 assert f2._prec == 80 assert RR(f1)-1 > 1e-50 assert RR(f2)-1 < 1e-50 # RR's precision is lower than f2's RR2 = RealField(prec=f2._prec) assert RR2(f1)-1 > 1e-50 assert RR2(f2)-1 > 1e-50 # RR's precision is equal to f2's def test_CC_double(): assert CC(3.14).real > 1e-50 assert CC(1e-13).real > 1e-50 assert CC(1e-14).real > 1e-50 assert CC(1e-15).real > 1e-50 assert CC(1e-20).real > 1e-50 assert CC(1e-40).real > 1e-50 assert CC(3.14j).imag > 1e-50 assert CC(1e-13j).imag > 1e-50 assert CC(1e-14j).imag > 1e-50 assert CC(1e-15j).imag > 1e-50 assert CC(1e-20j).imag > 1e-50 assert CC(1e-40j).imag > 1e-50 def test_gaussian_domains(): I = S.ImaginaryUnit a, b, c, d = [ZZ_I.convert(x) for x in (5, 2 + I, 3 - I, 5 - 5)] ZZ_I.gcd(a, b) == b ZZ_I.gcd(a, c) == b ZZ_I.lcm(a, b) == a ZZ_I.lcm(a, c) == d assert ZZ_I(3, 4) != QQ_I(3, 4) # XXX is this right or should QQ->ZZ if possible? assert ZZ_I(3, 0) != 3 # and should this go to Integer? assert QQ_I(S(3)/4, 0) != S(3)/4 # and this to Rational? assert ZZ_I(0, 0).quadrant() == 0 assert ZZ_I(-1, 0).quadrant() == 2 assert QQ_I.convert(QQ(3, 2)) == QQ_I(QQ(3, 2), QQ(0)) assert QQ_I.convert(QQ(3, 2), QQ) == QQ_I(QQ(3, 2), QQ(0)) for G in (QQ_I, ZZ_I): q = G(3, 4) assert str(q) == '3 + 4*I' assert q.parent() == G assert q._get_xy(pi) == (None, None) assert q._get_xy(2) == (2, 0) assert q._get_xy(2*I) == (0, 2) assert hash(q) == hash((3, 4)) assert G(1, 2) == G(1, 2) assert G(1, 2) != G(1, 3) assert G(3, 0) == G(3) assert q + q == G(6, 8) assert q - q == G(0, 0) assert 3 - q == -q + 3 == G(0, -4) assert 3 + q == q + 3 == G(6, 4) assert q * q == G(-7, 24) assert 3 * q == q * 3 == G(9, 12) assert q ** 0 == G(1, 0) assert q ** 1 == q assert q ** 2 == q * q == G(-7, 24) assert q ** 3 == q * q * q == G(-117, 44) assert 1 / q == q ** -1 == QQ_I(S(3)/25, - S(4)/25) assert q / 1 == QQ_I(3, 4) assert q / 2 == QQ_I(S(3)/2, 2) assert q/3 == QQ_I(1, S(4)/3) assert 3/q == QQ_I(S(9)/25, -S(12)/25) i, r = divmod(q, 2) assert 2*i + r == q i, r = divmod(2, q) assert q*i + r == G(2, 0) raises(ZeroDivisionError, lambda: q % 0) raises(ZeroDivisionError, lambda: q / 0) raises(ZeroDivisionError, lambda: q // 0) raises(ZeroDivisionError, lambda: divmod(q, 0)) raises(ZeroDivisionError, lambda: divmod(q, 0)) raises(TypeError, lambda: q + x) raises(TypeError, lambda: q - x) raises(TypeError, lambda: x + q) raises(TypeError, lambda: x - q) raises(TypeError, lambda: q * x) raises(TypeError, lambda: x * q) raises(TypeError, lambda: q / x) raises(TypeError, lambda: x / q) raises(TypeError, lambda: q // x) raises(TypeError, lambda: x // q) assert G.from_sympy(S(2)) == G(2, 0) assert G.to_sympy(G(2, 0)) == S(2) raises(CoercionFailed, lambda: G.from_sympy(pi)) PR = G.inject(x) assert isinstance(PR, PolynomialRing) assert PR.domain == G assert len(PR.gens) == 1 and PR.gens[0].as_expr() == x if G is QQ_I: AF = G.as_AlgebraicField() assert isinstance(AF, AlgebraicField) assert AF.domain == QQ assert AF.ext.args[0] == I for qi in [G(-1, 0), G(1, 0), G(0, -1), G(0, 1)]: assert G.is_negative(qi) is False assert G.is_positive(qi) is False assert G.is_nonnegative(qi) is False assert G.is_nonpositive(qi) is False domains = [ZZ_python(), QQ_python(), AlgebraicField(QQ, I)] if HAS_GMPY: domains += [ZZ_gmpy(), QQ_gmpy()] for K in domains: assert G.convert(K(2)) == G(2, 0) assert G.convert(K(2), K) == G(2, 0) for K in ZZ_I, QQ_I: assert G.convert(K(1, 1)) == G(1, 1) assert G.convert(K(1, 1), K) == G(1, 1) if G == ZZ_I: assert repr(q) == 'ZZ_I(3, 4)' assert q//3 == G(1, 1) assert 12//q == G(1, -2) assert 12 % q == G(1, 2) assert q % 2 == G(-1, 0) assert i == G(0, 0) assert r == G(2, 0) assert G.get_ring() == G assert G.get_field() == QQ_I else: assert repr(q) == 'QQ_I(3, 4)' assert G.get_ring() == ZZ_I assert G.get_field() == G assert q//3 == G(1, S(4)/3) assert 12//q == G(S(36)/25, -S(48)/25) assert 12 % q == G(0, 0) assert q % 2 == G(0, 0) assert i == G(S(6)/25, -S(8)/25), (G,i) assert r == G(0, 0) q2 = G(S(3)/2, S(5)/3) assert G.numer(q2) == ZZ_I(9, 10) assert G.denom(q2) == ZZ_I(6) def test_canonical_unit(): for K in [ZZ, QQ, RR]: # CC? assert K.canonical_unit(K(2)) == K(1) assert K.canonical_unit(K(-2)) == K(-1) for K in [ZZ_I, QQ_I]: i = K.from_sympy(I) assert K.canonical_unit(K(2)) == K(1) assert K.canonical_unit(K(2)*i) == -i assert K.canonical_unit(-K(2)) == K(-1) assert K.canonical_unit(-K(2)*i) == i K = ZZ[x] assert K.canonical_unit(K(x + 1)) == K(1) assert K.canonical_unit(K(-x + 1)) == K(-1) K = ZZ_I[x] assert K.canonical_unit(K.from_sympy(I*x)) == ZZ_I(0, -1) K = ZZ_I.frac_field(x, y) i = K.from_sympy(I) assert i / i == K.one assert (K.one + i)/(i - K.one) == -i def test_issue_18278(): assert str(RR(2).parent()) == 'RR' assert str(CC(2).parent()) == 'CC' def test_Domain_is_negative(): I = S.ImaginaryUnit a, b = [CC.convert(x) for x in (2 + I, 5)] assert CC.is_negative(a) == False assert CC.is_negative(b) == False def test_Domain_is_positive(): I = S.ImaginaryUnit a, b = [CC.convert(x) for x in (2 + I, 5)] assert CC.is_positive(a) == False assert CC.is_positive(b) == False def test_Domain_is_nonnegative(): I = S.ImaginaryUnit a, b = [CC.convert(x) for x in (2 + I, 5)] assert CC.is_nonnegative(a) == False assert CC.is_nonnegative(b) == False def test_Domain_is_nonpositive(): I = S.ImaginaryUnit a, b = [CC.convert(x) for x in (2 + I, 5)] assert CC.is_nonpositive(a) == False assert CC.is_nonpositive(b) == False
283b84b55bb47012b17b2fb0b4fc590e92d82c34b8e10375f11a922f07546711
""" Tests for the sympy.polys.matrices.eigen module """ from sympy import S, Matrix, sqrt from sympy.polys.agca.extensions import FiniteExtension from sympy.polys.domains import QQ from sympy.polys.polytools import Poly from sympy.polys.rootoftools import CRootOf from sympy.polys.matrices.domainmatrix import DomainMatrix from sympy.polys.matrices.eigen import dom_eigenvects, dom_eigenvects_to_sympy def test_dom_eigenvects_rational(): # Rational eigenvalues A = DomainMatrix([[QQ(1), QQ(2)], [QQ(1), QQ(2)]], (2, 2), QQ) rational_eigenvects = [ (QQ, QQ(3), 1, DomainMatrix([[QQ(1), QQ(1)]], (1, 2), QQ)), (QQ, QQ(0), 1, DomainMatrix([[QQ(-2), QQ(1)]], (1, 2), QQ)), ] assert dom_eigenvects(A) == (rational_eigenvects, []) # Test converting to Expr: sympy_eigenvects = [ (S(3), 1, [Matrix([1, 1])]), (S(0), 1, [Matrix([-2, 1])]), ] assert dom_eigenvects_to_sympy(rational_eigenvects, [], Matrix) == sympy_eigenvects def test_dom_eigenvects_algebraic(): # Algebraic eigenvalues A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) Avects = dom_eigenvects(A) # Extract the dummy to build the expected result: lamda = Avects[1][0][1].gens[0] irreducible = Poly(lamda**2 - 5*lamda - 2, lamda, domain=QQ) K = FiniteExtension(irreducible) KK = K.from_sympy algebraic_eigenvects = [ (K, irreducible, 1, DomainMatrix([[KK((lamda-4)/3), KK(1)]], (1, 2), K)), ] assert Avects == ([], algebraic_eigenvects) # Test converting to Expr: sympy_eigenvects = [ (S(5)/2 - sqrt(33)/2, 1, [Matrix([[-sqrt(33)/6 - S(1)/2], [1]])]), (S(5)/2 + sqrt(33)/2, 1, [Matrix([[-S(1)/2 + sqrt(33)/6], [1]])]), ] assert dom_eigenvects_to_sympy([], algebraic_eigenvects, Matrix) == sympy_eigenvects def test_dom_eigenvects_rootof(): # Algebraic eigenvalues A = DomainMatrix([ [0, 0, 0, 0, -1], [1, 0, 0, 0, 1], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0]], (5, 5), QQ) Avects = dom_eigenvects(A) # Extract the dummy to build the expected result: lamda = Avects[1][0][1].gens[0] irreducible = Poly(lamda**5 - lamda + 1, lamda, domain=QQ) K = FiniteExtension(irreducible) KK = K.from_sympy algebraic_eigenvects = [ (K, irreducible, 1, DomainMatrix([ [KK(lamda**4-1), KK(lamda**3), KK(lamda**2), KK(lamda), KK(1)] ], (1, 5), K)), ] assert Avects == ([], algebraic_eigenvects) # Test converting to Expr (slow): l0, l1, l2, l3, l4 = [CRootOf(lamda**5 - lamda + 1, i) for i in range(5)] sympy_eigenvects = [ (l0, 1, [Matrix([-1 + l0**4, l0**3, l0**2, l0, 1])]), (l1, 1, [Matrix([-1 + l1**4, l1**3, l1**2, l1, 1])]), (l2, 1, [Matrix([-1 + l2**4, l2**3, l2**2, l2, 1])]), (l3, 1, [Matrix([-1 + l3**4, l3**3, l3**2, l3, 1])]), (l4, 1, [Matrix([-1 + l4**4, l4**3, l4**2, l4, 1])]), ] assert dom_eigenvects_to_sympy([], algebraic_eigenvects, Matrix) == sympy_eigenvects
05e5b55e50d9168d646768470bb66bbd47c0c4c34a953125e50f48a9ce9b7b01
from sympy.testing.pytest import raises from sympy.core.compatibility import HAS_GMPY from sympy.polys import ZZ, QQ from sympy.polys.matrices.ddm import DDM from sympy.polys.matrices.exceptions import ( DDMShapeError, NonInvertibleMatrixError, DDMDomainError, DDMBadInputError) def test_DDM_init(): items = [[ZZ(0), ZZ(1), ZZ(2)], [ZZ(3), ZZ(4), ZZ(5)]] shape = (2, 3) ddm = DDM(items, shape, ZZ) assert ddm.shape == shape assert ddm.rows == 2 assert ddm.cols == 3 assert ddm.domain == ZZ raises(DDMBadInputError, lambda: DDM([[ZZ(2), ZZ(3)]], (2, 2), ZZ)) raises(DDMBadInputError, lambda: DDM([[ZZ(1)], [ZZ(2), ZZ(3)]], (2, 2), ZZ)) def test_DDM_getsetitem(): ddm = DDM([[ZZ(2), ZZ(3)], [ZZ(4), ZZ(5)]], (2, 2), ZZ) assert ddm[0][0] == ZZ(2) assert ddm[0][1] == ZZ(3) assert ddm[1][0] == ZZ(4) assert ddm[1][1] == ZZ(5) raises(IndexError, lambda: ddm[2][0]) raises(IndexError, lambda: ddm[0][2]) ddm[0][0] = ZZ(-1) assert ddm[0][0] == ZZ(-1) def test_DDM_str(): ddm = DDM([[ZZ(0), ZZ(1)], [ZZ(2), ZZ(3)]], (2, 2), ZZ) if HAS_GMPY: # pragma: no cover assert str(ddm) == '[[0, 1], [2, 3]]' assert repr(ddm) == 'DDM([[mpz(0), mpz(1)], [mpz(2), mpz(3)]], (2, 2), ZZ)' else: # pragma: no cover assert repr(ddm) == 'DDM([[0, 1], [2, 3]], (2, 2), ZZ)' assert str(ddm) == '[[0, 1], [2, 3]]' def test_DDM_eq(): items = [[ZZ(0), ZZ(1)], [ZZ(2), ZZ(3)]] ddm1 = DDM(items, (2, 2), ZZ) ddm2 = DDM(items, (2, 2), ZZ) assert (ddm1 == ddm1) is True assert (ddm1 == items) is False assert (items == ddm1) is False assert (ddm1 == ddm2) is True assert (ddm2 == ddm1) is True assert (ddm1 != ddm1) is False assert (ddm1 != items) is True assert (items != ddm1) is True assert (ddm1 != ddm2) is False assert (ddm2 != ddm1) is False ddm3 = DDM([[ZZ(0), ZZ(1)], [ZZ(3), ZZ(3)]], (2, 2), ZZ) ddm3 = DDM(items, (2, 2), QQ) assert (ddm1 == ddm3) is False assert (ddm3 == ddm1) is False assert (ddm1 != ddm3) is True assert (ddm3 != ddm1) is True def test_DDM_convert_to(): ddm = DDM([[ZZ(1), ZZ(2)]], (1, 2), ZZ) assert ddm.convert_to(ZZ) == ddm ddmq = ddm.convert_to(QQ) assert ddmq.domain == QQ def test_DDM_zeros(): ddmz = DDM.zeros((3, 4), QQ) assert list(ddmz) == [[QQ(0)] * 4] * 3 assert ddmz.shape == (3, 4) assert ddmz.domain == QQ def test_DDM_ones(): ddmone = DDM.ones((2, 3), QQ) assert list(ddmone) == [[QQ(1)] * 3] * 2 assert ddmone.shape == (2, 3) assert ddmone.domain == QQ def test_DDM_eye(): ddmz = DDM.eye(3, QQ) f = lambda i, j: QQ(1) if i == j else QQ(0) assert list(ddmz) == [[f(i, j) for i in range(3)] for j in range(3)] assert ddmz.shape == (3, 3) assert ddmz.domain == QQ def test_DDM_copy(): ddm1 = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ) ddm2 = ddm1.copy() assert (ddm1 == ddm2) is True ddm1[0][0] = QQ(-1) assert (ddm1 == ddm2) is False ddm2[0][0] = QQ(-1) assert (ddm1 == ddm2) is True def test_DDM_add(): A = DDM([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ) B = DDM([[ZZ(3)], [ZZ(4)]], (2, 1), ZZ) C = DDM([[ZZ(4)], [ZZ(6)]], (2, 1), ZZ) AQ = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ) assert A + B == A.add(B) == C raises(DDMShapeError, lambda: A + DDM([[ZZ(5)]], (1, 1), ZZ)) raises(TypeError, lambda: A + ZZ(1)) raises(TypeError, lambda: ZZ(1) + A) raises(DDMDomainError, lambda: A + AQ) raises(DDMDomainError, lambda: AQ + A) def test_DDM_sub(): A = DDM([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ) B = DDM([[ZZ(3)], [ZZ(4)]], (2, 1), ZZ) C = DDM([[ZZ(-2)], [ZZ(-2)]], (2, 1), ZZ) AQ = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ) D = DDM([[ZZ(5)]], (1, 1), ZZ) assert A - B == A.sub(B) == C raises(TypeError, lambda: A - ZZ(1)) raises(TypeError, lambda: ZZ(1) - A) raises(DDMShapeError, lambda: A - D) raises(DDMShapeError, lambda: D - A) raises(DDMShapeError, lambda: A.sub(D)) raises(DDMShapeError, lambda: D.sub(A)) raises(DDMDomainError, lambda: A - AQ) raises(DDMDomainError, lambda: AQ - A) raises(DDMDomainError, lambda: A.sub(AQ)) raises(DDMDomainError, lambda: AQ.sub(A)) def test_DDM_neg(): A = DDM([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ) An = DDM([[ZZ(-1)], [ZZ(-2)]], (2, 1), ZZ) assert -A == A.neg() == An assert -An == An.neg() == A def test_DDM_mul(): A = DDM([[ZZ(1)]], (1, 1), ZZ) A2 = DDM([[ZZ(2)]], (1, 1), ZZ) assert A * ZZ(2) == A2 assert ZZ(2) * A == A2 raises(TypeError, lambda: [[1]] * A) raises(TypeError, lambda: A * [[1]]) def test_DDM_matmul(): A = DDM([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ) B = DDM([[ZZ(3), ZZ(4)]], (1, 2), ZZ) AB = DDM([[ZZ(3), ZZ(4)], [ZZ(6), ZZ(8)]], (2, 2), ZZ) BA = DDM([[ZZ(11)]], (1, 1), ZZ) assert A @ B == A.matmul(B) == AB assert B @ A == B.matmul(A) == BA raises(TypeError, lambda: A @ 1) raises(TypeError, lambda: A @ [[3, 4]]) Bq = DDM([[QQ(3), QQ(4)]], (1, 2), QQ) raises(DDMDomainError, lambda: A @ Bq) raises(DDMDomainError, lambda: Bq @ A) C = DDM([[ZZ(1)]], (1, 1), ZZ) assert A @ C == A.matmul(C) == A raises(DDMShapeError, lambda: C @ A) raises(DDMShapeError, lambda: C.matmul(A)) Z04 = DDM([], (0, 4), ZZ) Z40 = DDM([[]]*4, (4, 0), ZZ) Z50 = DDM([[]]*5, (5, 0), ZZ) Z05 = DDM([], (0, 5), ZZ) Z45 = DDM([[0] * 5] * 4, (4, 5), ZZ) Z54 = DDM([[0] * 4] * 5, (5, 4), ZZ) Z00 = DDM([], (0, 0), ZZ) assert Z04 @ Z45 == Z04.matmul(Z45) == Z05 assert Z45 @ Z50 == Z45.matmul(Z50) == Z40 assert Z00 @ Z04 == Z00.matmul(Z04) == Z04 assert Z50 @ Z00 == Z50.matmul(Z00) == Z50 assert Z00 @ Z00 == Z00.matmul(Z00) == Z00 assert Z50 @ Z04 == Z50.matmul(Z04) == Z54 raises(DDMShapeError, lambda: Z05 @ Z40) raises(DDMShapeError, lambda: Z05.matmul(Z40)) def test_DDM_hstack(): A = DDM([[ZZ(1), ZZ(2), ZZ(3)]], (1, 3), ZZ) B = DDM([[ZZ(4), ZZ(5)]], (1, 2), ZZ) Ah = A.hstack(B) assert Ah.shape == (1, 5) assert Ah.domain == ZZ assert Ah == DDM([[ZZ(1), ZZ(2), ZZ(3), ZZ(4), ZZ(5)]], (1, 5), ZZ) def test_DDM_rref(): A = DDM([], (0, 4), QQ) assert A.rref() == (A, []) A = DDM([[QQ(0), QQ(1)], [QQ(1), QQ(1)]], (2, 2), QQ) Ar = DDM([[QQ(1), QQ(0)], [QQ(0), QQ(1)]], (2, 2), QQ) pivots = [0, 1] assert A.rref() == (Ar, pivots) A = DDM([[QQ(1), QQ(2), QQ(1)], [QQ(3), QQ(4), QQ(1)]], (2, 3), QQ) Ar = DDM([[QQ(1), QQ(0), QQ(-1)], [QQ(0), QQ(1), QQ(1)]], (2, 3), QQ) pivots = [0, 1] assert A.rref() == (Ar, pivots) A = DDM([[QQ(3), QQ(4), QQ(1)], [QQ(1), QQ(2), QQ(1)]], (2, 3), QQ) Ar = DDM([[QQ(1), QQ(0), QQ(-1)], [QQ(0), QQ(1), QQ(1)]], (2, 3), QQ) pivots = [0, 1] assert A.rref() == (Ar, pivots) A = DDM([[QQ(1), QQ(0)], [QQ(1), QQ(3)], [QQ(0), QQ(1)]], (3, 2), QQ) Ar = DDM([[QQ(1), QQ(0)], [QQ(0), QQ(1)], [QQ(0), QQ(0)]], (3, 2), QQ) pivots = [0, 1] assert A.rref() == (Ar, pivots) A = DDM([[QQ(1), QQ(0), QQ(1)], [QQ(3), QQ(0), QQ(1)]], (2, 3), QQ) Ar = DDM([[QQ(1), QQ(0), QQ(0)], [QQ(0), QQ(0), QQ(1)]], (2, 3), QQ) pivots = [0, 2] assert A.rref() == (Ar, pivots) def test_DDM_nullspace(): A = DDM([[QQ(1), QQ(1)], [QQ(1), QQ(1)]], (2, 2), QQ) Anull = DDM([[QQ(-1), QQ(1)]], (1, 2), QQ) nonpivots = [1] assert A.nullspace() == (Anull, nonpivots) def test_DDM_det(): # 0x0 case A = DDM([], (0, 0), ZZ) assert A.det() == ZZ(1) # 1x1 case A = DDM([[ZZ(2)]], (1, 1), ZZ) assert A.det() == ZZ(2) # 2x2 case A = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) assert A.det() == ZZ(-2) # 3x3 with swap A = DDM([[ZZ(1), ZZ(2), ZZ(3)], [ZZ(1), ZZ(2), ZZ(4)], [ZZ(1), ZZ(2), ZZ(5)]], (3, 3), ZZ) assert A.det() == ZZ(0) # 2x2 QQ case A = DDM([[QQ(1, 2), QQ(1, 2)], [QQ(1, 3), QQ(1, 4)]], (2, 2), QQ) assert A.det() == QQ(-1, 24) # Nonsquare error A = DDM([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ) raises(DDMShapeError, lambda: A.det()) # Nonsquare error with empty matrix A = DDM([], (0, 1), ZZ) raises(DDMShapeError, lambda: A.det()) def test_DDM_inv(): A = DDM([[QQ(1, 1), QQ(2, 1)], [QQ(3, 1), QQ(4, 1)]], (2, 2), QQ) Ainv = DDM([[QQ(-2, 1), QQ(1, 1)], [QQ(3, 2), QQ(-1, 2)]], (2, 2), QQ) assert A.inv() == Ainv A = DDM([[QQ(1), QQ(2)]], (1, 2), QQ) raises(DDMShapeError, lambda: A.inv()) A = DDM([[ZZ(2)]], (1, 1), ZZ) raises(ValueError, lambda: A.inv()) A = DDM([], (0, 0), QQ) assert A.inv() == A A = DDM([[QQ(1), QQ(2)], [QQ(2), QQ(4)]], (2, 2), QQ) raises(NonInvertibleMatrixError, lambda: A.inv()) def test_DDM_lu(): A = DDM([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) L, U, swaps = A.lu() assert L == DDM([[QQ(1), QQ(0)], [QQ(3), QQ(1)]], (2, 2), QQ) assert U == DDM([[QQ(1), QQ(2)], [QQ(0), QQ(-2)]], (2, 2), QQ) assert swaps == [] A = [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 1], [0, 0, 1, 2]] Lexp = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 1, 1]] Uexp = [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 1], [0, 0, 0, 1]] to_dom = lambda rows, dom: [[dom(e) for e in row] for row in rows] A = DDM(to_dom(A, QQ), (4, 4), QQ) Lexp = DDM(to_dom(Lexp, QQ), (4, 4), QQ) Uexp = DDM(to_dom(Uexp, QQ), (4, 4), QQ) L, U, swaps = A.lu() assert L == Lexp assert U == Uexp assert swaps == [] def test_DDM_lu_solve(): # Basic example A = DDM([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) b = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ) x = DDM([[QQ(0)], [QQ(1, 2)]], (2, 1), QQ) assert A.lu_solve(b) == x # Example with swaps A = DDM([[QQ(0), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) assert A.lu_solve(b) == x # Overdetermined, consistent A = DDM([[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(5), QQ(6)]], (3, 2), QQ) b = DDM([[QQ(1)], [QQ(2)], [QQ(3)]], (3, 1), QQ) assert A.lu_solve(b) == x # Overdetermined, inconsistent b = DDM([[QQ(1)], [QQ(2)], [QQ(4)]], (3, 1), QQ) raises(NonInvertibleMatrixError, lambda: A.lu_solve(b)) # Square, noninvertible A = DDM([[QQ(1), QQ(2)], [QQ(1), QQ(2)]], (2, 2), QQ) b = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ) raises(NonInvertibleMatrixError, lambda: A.lu_solve(b)) # Underdetermined A = DDM([[QQ(1), QQ(2)]], (1, 2), QQ) b = DDM([[QQ(3)]], (1, 1), QQ) raises(NotImplementedError, lambda: A.lu_solve(b)) # Domain mismatch bz = DDM([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ) raises(DDMDomainError, lambda: A.lu_solve(bz)) # Shape mismatch b3 = DDM([[QQ(1)], [QQ(2)], [QQ(3)]], (3, 1), QQ) raises(DDMShapeError, lambda: A.lu_solve(b3)) def test_DDM_charpoly(): A = DDM([], (0, 0), ZZ) assert A.charpoly() == [ZZ(1)] A = DDM([ [ZZ(1), ZZ(2), ZZ(3)], [ZZ(4), ZZ(5), ZZ(6)], [ZZ(7), ZZ(8), ZZ(9)]], (3, 3), ZZ) Avec = [ZZ(1), ZZ(-15), ZZ(-18), ZZ(0)] assert A.charpoly() == Avec A = DDM([[ZZ(1), ZZ(2)]], (1, 2), ZZ) raises(DDMShapeError, lambda: A.charpoly())
8f77f42cfb6f618ba5bfc5b5956a97bdd3771c915c43b9a91965a12773754da5
from sympy.testing.pytest import raises from sympy.core.symbol import S from sympy.polys import ZZ, QQ from sympy.polys.matrices.domainscalar import DomainScalar from sympy.polys.matrices.domainmatrix import DomainMatrix def test_DomainScalar___new__(): raises(TypeError, lambda: DomainScalar(ZZ(1), QQ)) raises(TypeError, lambda: DomainScalar(ZZ(1), 1)) def test_DomainScalar_new(): A = DomainScalar(ZZ(1), ZZ) B = A.new(ZZ(4), ZZ) assert B == DomainScalar(ZZ(4), ZZ) def test_DomainScalar_repr(): A = DomainScalar(ZZ(1), ZZ) assert repr(A) in {'1', 'mpz(1)'} def test_DomainScalar_from_sympy(): expr = S(1) B = DomainScalar.from_sympy(expr) assert B == DomainScalar(ZZ(1), ZZ) def test_DomainScalar_to_domain(): A = DomainScalar(ZZ(1), ZZ) B = A.to_domain(QQ) assert B == DomainScalar(QQ(1), QQ) def test_DomainScalar_convert_to(): A = DomainScalar(ZZ(1), ZZ) B = A.convert_to(QQ) assert B == DomainScalar(QQ(1), QQ) def test_DomainScalar_unify(): A = DomainScalar(ZZ(1), ZZ) B = DomainScalar(QQ(2), QQ) A, B = A.unify(B) assert A.domain == B.domain == QQ def test_DomainScalar_add(): A = DomainScalar(ZZ(1), ZZ) B = DomainScalar(QQ(2), QQ) assert A + B == DomainScalar(QQ(3), QQ) raises(TypeError, lambda: A + 1.5) def test_DomainScalar_sub(): A = DomainScalar(ZZ(1), ZZ) B = DomainScalar(QQ(2), QQ) assert A - B == DomainScalar(QQ(-1), QQ) raises(TypeError, lambda: A - 1.5) def test_DomainScalar_mul(): A = DomainScalar(ZZ(1), ZZ) B = DomainScalar(QQ(2), QQ) dm = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) assert A * B == DomainScalar(QQ(2), QQ) assert A * dm == dm assert B * 2 == DomainScalar(QQ(4), QQ) raises(TypeError, lambda: A * 1.5) def test_DomainScalar_floordiv(): A = DomainScalar(ZZ(-5), ZZ) B = DomainScalar(QQ(2), QQ) assert A // B == DomainScalar(QQ(-5, 2), QQ) C = DomainScalar(ZZ(2), ZZ) assert A // C == DomainScalar(ZZ(-3), ZZ) raises(TypeError, lambda: A // 1.5) def test_DomainScalar_mod(): A = DomainScalar(ZZ(5), ZZ) B = DomainScalar(QQ(2), QQ) assert A % B == DomainScalar(QQ(0), QQ) C = DomainScalar(ZZ(2), ZZ) assert A % C == DomainScalar(ZZ(1), ZZ) raises(TypeError, lambda: A % 1.5) def test_DomainScalar_divmod(): A = DomainScalar(ZZ(5), ZZ) B = DomainScalar(QQ(2), QQ) assert divmod(A, B) == (DomainScalar(QQ(5, 2), QQ), DomainScalar(QQ(0), QQ)) C = DomainScalar(ZZ(2), ZZ) assert divmod(A, C) == (DomainScalar(ZZ(2), ZZ), DomainScalar(ZZ(1), ZZ)) raises(TypeError, lambda: divmod(A, 1.5)) def test_DomainScalar_pow(): A = DomainScalar(ZZ(-5), ZZ) B = A**(2) assert B == DomainScalar(ZZ(25), ZZ) raises(TypeError, lambda: A**(1.5)) def test_DomainScalar_pos(): A = DomainScalar(QQ(2), QQ) B = DomainScalar(QQ(2), QQ) assert +A == B def test_DomainScalar_eq(): A = DomainScalar(QQ(2), QQ) assert A == A B = DomainScalar(ZZ(-5), ZZ) assert A != B C = DomainScalar(ZZ(2), ZZ) assert A != C D = [1] assert A != D def test_DomainScalar_isZero(): A = DomainScalar(ZZ(0), ZZ) assert A.is_zero() == True B = DomainScalar(ZZ(1), ZZ) assert B.is_zero() == False def test_DomainScalar_isOne(): A = DomainScalar(ZZ(1), ZZ) assert A.is_one() == True B = DomainScalar(ZZ(0), ZZ) assert B.is_one() == False
646473dd030415d86398ef3f39b9dc2d02aa9b071bea10bbe459fae2478e2462
from sympy.testing.pytest import raises from sympy.core.numbers import Rational from sympy.functions import sqrt from sympy.matrices.common import (NonInvertibleMatrixError, NonSquareMatrixError, ShapeError) from sympy.matrices.dense import Matrix from sympy.polys import ZZ, QQ from sympy.polys.matrices.domainmatrix import DomainMatrix from sympy.polys.matrices.exceptions import (DDMBadInputError, DDMDomainError, DDMShapeError, DDMFormatError) from sympy.polys.matrices.ddm import DDM from sympy.polys.matrices.sdm import SDM from sympy.polys.matrices.domainscalar import DomainScalar def test_DomainMatrix_init(): lol = [[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]] dod = {0: {0: ZZ(1), 1:ZZ(2)}, 1: {0:ZZ(3), 1:ZZ(4)}} ddm = DDM(lol, (2, 2), ZZ) sdm = SDM(dod, (2, 2), ZZ) A = DomainMatrix(lol, (2, 2), ZZ) assert A.rep == ddm assert A.shape == (2, 2) assert A.domain == ZZ A = DomainMatrix(dod, (2, 2), ZZ) assert A.rep == sdm assert A.shape == (2, 2) assert A.domain == ZZ raises(TypeError, lambda: DomainMatrix(ddm, (2, 2), ZZ)) raises(TypeError, lambda: DomainMatrix(sdm, (2, 2), ZZ)) raises(TypeError, lambda: DomainMatrix(Matrix([[1]]), (1, 1), ZZ)) for fmt, rep in [('sparse', sdm), ('dense', ddm)]: A = DomainMatrix(lol, (2, 2), ZZ, fmt=fmt) assert A.rep == rep A = DomainMatrix(dod, (2, 2), ZZ, fmt=fmt) assert A.rep == rep raises(ValueError, lambda: DomainMatrix(lol, (2, 2), ZZ, fmt='invalid')) raises(DDMBadInputError, lambda: DomainMatrix([[ZZ(1), ZZ(2)]], (2, 2), ZZ)) def test_DomainMatrix_from_rep(): ddm = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) A = DomainMatrix.from_rep(ddm) assert A.rep == ddm assert A.shape == (2, 2) assert A.domain == ZZ sdm = SDM({0: {0: ZZ(1), 1:ZZ(2)}, 1: {0:ZZ(3), 1:ZZ(4)}}, (2, 2), ZZ) A = DomainMatrix.from_rep(sdm) assert A.rep == sdm assert A.shape == (2, 2) assert A.domain == ZZ A = DomainMatrix([[ZZ(1)]], (1, 1), ZZ) raises(TypeError, lambda: DomainMatrix.from_rep(A)) def test_DomainMatrix_from_list_sympy(): ddm = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) A = DomainMatrix.from_list_sympy(2, 2, [[1, 2], [3, 4]]) assert A.rep == ddm assert A.shape == (2, 2) assert A.domain == ZZ K = QQ.algebraic_field(sqrt(2)) ddm = DDM( [[K.convert(1 + sqrt(2)), K.convert(2 + sqrt(2))], [K.convert(3 + sqrt(2)), K.convert(4 + sqrt(2))]], (2, 2), K ) A = DomainMatrix.from_list_sympy( 2, 2, [[1 + sqrt(2), 2 + sqrt(2)], [3 + sqrt(2), 4 + sqrt(2)]], extension=True) assert A.rep == ddm assert A.shape == (2, 2) assert A.domain == K def test_DomainMatrix_from_Matrix(): ddm = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) A = DomainMatrix.from_Matrix(Matrix([[1, 2], [3, 4]])) assert A.rep == ddm assert A.shape == (2, 2) assert A.domain == ZZ K = QQ.algebraic_field(sqrt(2)) ddm = DDM( [[K.convert(1 + sqrt(2)), K.convert(2 + sqrt(2))], [K.convert(3 + sqrt(2)), K.convert(4 + sqrt(2))]], (2, 2), K ) A = DomainMatrix.from_Matrix( Matrix([[1 + sqrt(2), 2 + sqrt(2)], [3 + sqrt(2), 4 + sqrt(2)]]), extension=True) assert A.rep == ddm assert A.shape == (2, 2) assert A.domain == K def test_DomainMatrix_eq(): A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) assert A == A B = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(1)]], (2, 2), ZZ) assert A != B C = [[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]] assert A != C def test_DomainMatrix_get_domain(): K, items = DomainMatrix.get_domain([1, 2, 3, 4]) assert items == [ZZ(1), ZZ(2), ZZ(3), ZZ(4)] assert K == ZZ K, items = DomainMatrix.get_domain([1, 2, 3, Rational(1, 2)]) assert items == [QQ(1), QQ(2), QQ(3), QQ(1, 2)] assert K == QQ def test_DomainMatrix_convert_to(): A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) Aq = A.convert_to(QQ) assert Aq == DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) def test_DomainMatrix_to_field(): A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) Aq = A.to_field() assert Aq == DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) def test_DomainMatrix_to_sparse(): A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) A_sparse = A.to_sparse() assert A_sparse.rep == {0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}} def test_DomainMatrix_to_dense(): A = DomainMatrix({0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}}, (2, 2), ZZ) A_dense = A.to_dense() assert A_dense.rep == DDM([[1, 2], [3, 4]], (2, 2), ZZ) def test_DomainMatrix_unify(): Az = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) Aq = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) assert Az.unify(Az) == (Az, Az) assert Az.unify(Aq) == (Aq, Aq) assert Aq.unify(Az) == (Aq, Aq) assert Aq.unify(Aq) == (Aq, Aq) As = DomainMatrix({0: {1: ZZ(1)}, 1:{0:ZZ(2)}}, (2, 2), ZZ) Ad = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) assert As.unify(As) == (As, As) assert Ad.unify(Ad) == (Ad, Ad) Bs, Bd = As.unify(Ad, fmt='dense') assert Bs.rep == DDM([[0, 1], [2, 0]], (2, 2), ZZ) assert Bd.rep == DDM([[1, 2],[3, 4]], (2, 2), ZZ) Bs, Bd = As.unify(Ad, fmt='sparse') assert Bs.rep == SDM({0: {1: 1}, 1: {0: 2}}, (2, 2), ZZ) assert Bd.rep == SDM({0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}}, (2, 2), ZZ) raises(ValueError, lambda: As.unify(Ad, fmt='invalid')) def test_DomainMatrix_to_Matrix(): A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) assert A.to_Matrix() == Matrix([[1, 2], [3, 4]]) def test_DomainMatrix_repr(): A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) assert repr(A) == 'DomainMatrix([[1, 2], [3, 4]], (2, 2), ZZ)' def test_DomainMatrix_add(): A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) B = DomainMatrix([[ZZ(2), ZZ(4)], [ZZ(6), ZZ(8)]], (2, 2), ZZ) assert A + A == A.add(A) == B A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) L = [[2, 3], [3, 4]] raises(TypeError, lambda: A + L) raises(TypeError, lambda: L + A) A1 = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) A2 = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ) raises(DDMShapeError, lambda: A1 + A2) raises(DDMShapeError, lambda: A2 + A1) raises(DDMShapeError, lambda: A1.add(A2)) raises(DDMShapeError, lambda: A2.add(A1)) Az = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) Aq = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) Asum = DomainMatrix([[QQ(2), QQ(4)], [QQ(6), QQ(8)]], (2, 2), QQ) assert Az + Aq == Asum assert Aq + Az == Asum raises(DDMDomainError, lambda: Az.add(Aq)) raises(DDMDomainError, lambda: Aq.add(Az)) As = DomainMatrix({0: {1: ZZ(1)}, 1: {0: ZZ(2)}}, (2, 2), ZZ) Ad = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) Asd = As + Ad Ads = Ad + As assert Asd == DomainMatrix([[1, 3], [5, 4]], (2, 2), ZZ) assert Asd.rep == DDM([[1, 3], [5, 4]], (2, 2), ZZ) assert Ads == DomainMatrix([[1, 3], [5, 4]], (2, 2), ZZ) assert Ads.rep == DDM([[1, 3], [5, 4]], (2, 2), ZZ) raises(DDMFormatError, lambda: As.add(Ad)) def test_DomainMatrix_sub(): A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) B = DomainMatrix([[ZZ(0), ZZ(0)], [ZZ(0), ZZ(0)]], (2, 2), ZZ) assert A - A == A.sub(A) == B A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) L = [[2, 3], [3, 4]] raises(TypeError, lambda: A - L) raises(TypeError, lambda: L - A) A1 = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) A2 = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ) raises(DDMShapeError, lambda: A1 - A2) raises(DDMShapeError, lambda: A2 - A1) raises(DDMShapeError, lambda: A1.sub(A2)) raises(DDMShapeError, lambda: A2.sub(A1)) Az = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) Aq = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) Adiff = DomainMatrix([[QQ(0), QQ(0)], [QQ(0), QQ(0)]], (2, 2), QQ) assert Az - Aq == Adiff assert Aq - Az == Adiff raises(DDMDomainError, lambda: Az.sub(Aq)) raises(DDMDomainError, lambda: Aq.sub(Az)) As = DomainMatrix({0: {1: ZZ(1)}, 1: {0: ZZ(2)}}, (2, 2), ZZ) Ad = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) Asd = As - Ad Ads = Ad - As assert Asd == DomainMatrix([[-1, -1], [-1, -4]], (2, 2), ZZ) assert Asd.rep == DDM([[-1, -1], [-1, -4]], (2, 2), ZZ) assert Asd == -Ads assert Asd.rep == -Ads.rep def test_DomainMatrix_neg(): A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) Aneg = DomainMatrix([[ZZ(-1), ZZ(-2)], [ZZ(-3), ZZ(-4)]], (2, 2), ZZ) assert -A == A.neg() == Aneg def test_DomainMatrix_mul(): A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) A2 = DomainMatrix([[ZZ(7), ZZ(10)], [ZZ(15), ZZ(22)]], (2, 2), ZZ) assert A*A == A.matmul(A) == A2 A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) L = [[1, 2], [3, 4]] raises(TypeError, lambda: A * L) raises(TypeError, lambda: L * A) Az = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) Aq = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) Aprod = DomainMatrix([[QQ(7), QQ(10)], [QQ(15), QQ(22)]], (2, 2), QQ) assert Az * Aq == Aprod assert Aq * Az == Aprod raises(DDMDomainError, lambda: Az.matmul(Aq)) raises(DDMDomainError, lambda: Aq.matmul(Az)) A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) AA = DomainMatrix([[ZZ(2), ZZ(4)], [ZZ(6), ZZ(8)]], (2, 2), ZZ) x = ZZ(2) assert A * x == x * A == A.mul(x) == AA A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) AA = DomainMatrix([[ZZ(0), ZZ(0)], [ZZ(0), ZZ(0)]], (2, 2), ZZ) x = ZZ(0) assert A * x == x * A == A.mul(x) == AA As = DomainMatrix({0: {1: ZZ(1)}, 1: {0: ZZ(2)}}, (2, 2), ZZ) Ad = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) Asd = As * Ad Ads = Ad * As assert Asd == DomainMatrix([[3, 4], [2, 4]], (2, 2), ZZ) assert Asd.rep == DDM([[3, 4], [2, 4]], (2, 2), ZZ) assert Ads == DomainMatrix([[4, 1], [8, 3]], (2, 2), ZZ) assert Ads.rep == DDM([[4, 1], [8, 3]], (2, 2), ZZ) def test_DomainMatrix_pow(): eye = DomainMatrix.eye(2, ZZ) A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) A2 = DomainMatrix([[ZZ(7), ZZ(10)], [ZZ(15), ZZ(22)]], (2, 2), ZZ) A3 = DomainMatrix([[ZZ(37), ZZ(54)], [ZZ(81), ZZ(118)]], (2, 2), ZZ) assert A**0 == A.pow(0) == eye assert A**1 == A.pow(1) == A assert A**2 == A.pow(2) == A2 assert A**3 == A.pow(3) == A3 raises(TypeError, lambda: A ** Rational(1, 2)) raises(NotImplementedError, lambda: A ** -1) raises(NotImplementedError, lambda: A.pow(-1)) A = DomainMatrix.zeros((2, 1), ZZ) raises(NonSquareMatrixError, lambda: A ** 1) def test_DomainMatrix_rref(): A = DomainMatrix([], (0, 1), QQ) assert A.rref() == (A, ()) A = DomainMatrix([[QQ(1)]], (1, 1), QQ) assert A.rref() == (A, (0,)) A = DomainMatrix([[QQ(0)]], (1, 1), QQ) assert A.rref() == (A, ()) A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) Ar, pivots = A.rref() assert Ar == DomainMatrix([[QQ(1), QQ(0)], [QQ(0), QQ(1)]], (2, 2), QQ) assert pivots == (0, 1) A = DomainMatrix([[QQ(0), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) Ar, pivots = A.rref() assert Ar == DomainMatrix([[QQ(1), QQ(0)], [QQ(0), QQ(1)]], (2, 2), QQ) assert pivots == (0, 1) A = DomainMatrix([[QQ(0), QQ(2)], [QQ(0), QQ(4)]], (2, 2), QQ) Ar, pivots = A.rref() assert Ar == DomainMatrix([[QQ(0), QQ(1)], [QQ(0), QQ(0)]], (2, 2), QQ) assert pivots == (1,) Az = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) raises(ValueError, lambda: Az.rref()) def test_DomainMatrix_nullspace(): A = DomainMatrix([[QQ(1), QQ(1)], [QQ(1), QQ(1)]], (2, 2), ZZ) Anull = DomainMatrix([[QQ(-1), QQ(1)]], (1, 2), ZZ) assert A.nullspace() == Anull def test_DomainMatrix_inv(): A = DomainMatrix([], (0, 0), QQ) assert A.inv() == A A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) Ainv = DomainMatrix([[QQ(-2), QQ(1)], [QQ(3, 2), QQ(-1, 2)]], (2, 2), QQ) assert A.inv() == Ainv Az = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) raises(ValueError, lambda: Az.inv()) Ans = DomainMatrix([[QQ(1), QQ(2)]], (1, 2), QQ) raises(NonSquareMatrixError, lambda: Ans.inv()) Aninv = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(6)]], (2, 2), QQ) raises(NonInvertibleMatrixError, lambda: Aninv.inv()) def test_DomainMatrix_det(): A = DomainMatrix([], (0, 0), ZZ) assert A.det() == 1 A = DomainMatrix([[1]], (1, 1), ZZ) assert A.det() == 1 A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) assert A.det() == ZZ(-2) A = DomainMatrix([[ZZ(1), ZZ(2), ZZ(3)], [ZZ(1), ZZ(2), ZZ(4)], [ZZ(1), ZZ(3), ZZ(5)]], (3, 3), ZZ) assert A.det() == ZZ(-1) A = DomainMatrix([[ZZ(1), ZZ(2), ZZ(3)], [ZZ(1), ZZ(2), ZZ(4)], [ZZ(1), ZZ(2), ZZ(5)]], (3, 3), ZZ) assert A.det() == ZZ(0) Ans = DomainMatrix([[QQ(1), QQ(2)]], (1, 2), QQ) raises(NonSquareMatrixError, lambda: Ans.det()) A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) assert A.det() == QQ(-2) def test_DomainMatrix_lu(): A = DomainMatrix([], (0, 0), QQ) assert A.lu() == (A, A, []) A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) L = DomainMatrix([[QQ(1), QQ(0)], [QQ(3), QQ(1)]], (2, 2), QQ) U = DomainMatrix([[QQ(1), QQ(2)], [QQ(0), QQ(-2)]], (2, 2), QQ) swaps = [] assert A.lu() == (L, U, swaps) A = DomainMatrix([[QQ(0), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) L = DomainMatrix([[QQ(1), QQ(0)], [QQ(0), QQ(1)]], (2, 2), QQ) U = DomainMatrix([[QQ(3), QQ(4)], [QQ(0), QQ(2)]], (2, 2), QQ) swaps = [(0, 1)] assert A.lu() == (L, U, swaps) A = DomainMatrix([[QQ(1), QQ(2)], [QQ(2), QQ(4)]], (2, 2), QQ) L = DomainMatrix([[QQ(1), QQ(0)], [QQ(2), QQ(1)]], (2, 2), QQ) U = DomainMatrix([[QQ(1), QQ(2)], [QQ(0), QQ(0)]], (2, 2), QQ) swaps = [] assert A.lu() == (L, U, swaps) A = DomainMatrix([[QQ(0), QQ(2)], [QQ(0), QQ(4)]], (2, 2), QQ) L = DomainMatrix([[QQ(1), QQ(0)], [QQ(0), QQ(1)]], (2, 2), QQ) U = DomainMatrix([[QQ(0), QQ(2)], [QQ(0), QQ(4)]], (2, 2), QQ) swaps = [] assert A.lu() == (L, U, swaps) A = DomainMatrix([[QQ(1), QQ(2), QQ(3)], [QQ(4), QQ(5), QQ(6)]], (2, 3), QQ) L = DomainMatrix([[QQ(1), QQ(0)], [QQ(4), QQ(1)]], (2, 2), QQ) U = DomainMatrix([[QQ(1), QQ(2), QQ(3)], [QQ(0), QQ(-3), QQ(-6)]], (2, 3), QQ) swaps = [] assert A.lu() == (L, U, swaps) A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(5), QQ(6)]], (3, 2), QQ) L = DomainMatrix([ [QQ(1), QQ(0), QQ(0)], [QQ(3), QQ(1), QQ(0)], [QQ(5), QQ(2), QQ(1)]], (3, 3), QQ) U = DomainMatrix([[QQ(1), QQ(2)], [QQ(0), QQ(-2)], [QQ(0), QQ(0)]], (3, 2), QQ) swaps = [] assert A.lu() == (L, U, swaps) A = [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 1], [0, 0, 1, 2]] L = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 1, 1]] U = [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 1], [0, 0, 0, 1]] to_dom = lambda rows, dom: [[dom(e) for e in row] for row in rows] A = DomainMatrix(to_dom(A, QQ), (4, 4), QQ) L = DomainMatrix(to_dom(L, QQ), (4, 4), QQ) U = DomainMatrix(to_dom(U, QQ), (4, 4), QQ) assert A.lu() == (L, U, []) A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) raises(ValueError, lambda: A.lu()) def test_DomainMatrix_lu_solve(): # Base case A = b = x = DomainMatrix([], (0, 0), QQ) assert A.lu_solve(b) == x # Basic example A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) b = DomainMatrix([[QQ(1)], [QQ(2)]], (2, 1), QQ) x = DomainMatrix([[QQ(0)], [QQ(1, 2)]], (2, 1), QQ) assert A.lu_solve(b) == x # Example with swaps A = DomainMatrix([[QQ(0), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) b = DomainMatrix([[QQ(1)], [QQ(2)]], (2, 1), QQ) x = DomainMatrix([[QQ(0)], [QQ(1, 2)]], (2, 1), QQ) assert A.lu_solve(b) == x # Non-invertible A = DomainMatrix([[QQ(1), QQ(2)], [QQ(2), QQ(4)]], (2, 2), QQ) b = DomainMatrix([[QQ(1)], [QQ(2)]], (2, 1), QQ) raises(NonInvertibleMatrixError, lambda: A.lu_solve(b)) # Overdetermined, consistent A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(5), QQ(6)]], (3, 2), QQ) b = DomainMatrix([[QQ(1)], [QQ(2)], [QQ(3)]], (3, 1), QQ) x = DomainMatrix([[QQ(0)], [QQ(1, 2)]], (2, 1), QQ) assert A.lu_solve(b) == x # Overdetermined, inconsistent A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(5), QQ(6)]], (3, 2), QQ) b = DomainMatrix([[QQ(1)], [QQ(2)], [QQ(4)]], (3, 1), QQ) raises(NonInvertibleMatrixError, lambda: A.lu_solve(b)) # Underdetermined A = DomainMatrix([[QQ(1), QQ(2)]], (1, 2), QQ) b = DomainMatrix([[QQ(1)]], (1, 1), QQ) raises(NotImplementedError, lambda: A.lu_solve(b)) # Non-field A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) b = DomainMatrix([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ) raises(ValueError, lambda: A.lu_solve(b)) # Shape mismatch A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) b = DomainMatrix([[QQ(1), QQ(2)]], (1, 2), QQ) raises(ShapeError, lambda: A.lu_solve(b)) def test_DomainMatrix_charpoly(): A = DomainMatrix([], (0, 0), ZZ) assert A.charpoly() == [ZZ(1)] A = DomainMatrix([[1]], (1, 1), ZZ) assert A.charpoly() == [ZZ(1), ZZ(-1)] A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) assert A.charpoly() == [ZZ(1), ZZ(-5), ZZ(-2)] A = DomainMatrix([[ZZ(1), ZZ(2), ZZ(3)], [ZZ(4), ZZ(5), ZZ(6)], [ZZ(7), ZZ(8), ZZ(9)]], (3, 3), ZZ) assert A.charpoly() == [ZZ(1), ZZ(-15), ZZ(-18), ZZ(0)] Ans = DomainMatrix([[QQ(1), QQ(2)]], (1, 2), QQ) raises(NonSquareMatrixError, lambda: Ans.charpoly()) def test_DomainMatrix_eye(): A = DomainMatrix.eye(3, QQ) assert A.rep == SDM.eye(3, QQ) assert A.shape == (3, 3) assert A.domain == QQ def test_DomainMatrix_zeros(): A = DomainMatrix.zeros((1, 2), QQ) assert A.rep == SDM.zeros((1, 2), QQ) assert A.shape == (1, 2) assert A.domain == QQ def test_DomainMatrix_ones(): A = DomainMatrix.ones((2, 3), QQ) assert A.rep == DDM.ones((2, 3), QQ) assert A.shape == (2, 3) assert A.domain == QQ def test_DomainMatrix_hstack(): A = DomainMatrix([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ) B = DomainMatrix([[QQ(3), QQ(4)], [QQ(5), QQ(6)]], (2, 2), QQ) AB = DomainMatrix([[QQ(1), QQ(3), QQ(4)], [QQ(2), QQ(5), QQ(6)]], (2, 3), QQ) assert A.hstack(B) == AB def test_DomainMatrix_scalarmul(): A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) lamda = DomainScalar(QQ(3)/QQ(2), QQ) assert A * lamda == DomainMatrix([[QQ(3, 2), QQ(3)], [QQ(9, 2), QQ(6)]], (2, 2), QQ) assert A * 2 == DomainMatrix([[ZZ(2), ZZ(4)], [ZZ(6), ZZ(8)]], (2, 2), ZZ) assert A * DomainScalar(ZZ(0), ZZ) == DomainMatrix([[ZZ(0)]*2]*2, (2, 2), ZZ) assert A * DomainScalar(ZZ(1), ZZ) == A raises(TypeError, lambda: A * 1.5) def test_DomainMatrix_truediv(): A = DomainMatrix.from_Matrix(Matrix([[1, 2], [3, 4]])) lamda = DomainScalar(QQ(3)/QQ(2), QQ) assert A / lamda == DomainMatrix([[QQ(2, 3), QQ(4, 3)], [QQ(2), QQ(8, 3)]], (2, 2), QQ) b = DomainScalar(ZZ(1), ZZ) assert A / b == DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) assert A / 1 == DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) assert A / 2 == DomainMatrix([[QQ(1, 2), QQ(1)], [QQ(3, 2), QQ(2)]], (2, 2), QQ) raises(ZeroDivisionError, lambda: A / 0) raises(TypeError, lambda: A / 1.5) raises(ZeroDivisionError, lambda: A / DomainScalar(ZZ(0), ZZ))
ad62603a61c44c793c938020814c11eaf3387bcff91310c22a05430af1d93a07
# # test_linsolve.py # # Test the internal implementation of linsolve. # from sympy import S from sympy.abc import x from sympy.polys.matrices.linsolve import _linsolve def test__linsolve(): assert _linsolve([], [x]) == {x:x} assert _linsolve([S.Zero], [x]) == {x:x}
4af3be6557fae3a948f8cc5344c1b00d1c9722c9478a75adf4a27cbf47495e67
""" Tests for the basic functionality of the SDM class. """ from sympy.core.compatibility import HAS_GMPY from sympy.testing.pytest import raises from sympy import QQ, ZZ from sympy.polys.matrices.sdm import SDM from sympy.polys.matrices.ddm import DDM from sympy.polys.matrices.exceptions import (DDMBadInputError, DDMDomainError, DDMShapeError) def test_SDM(): A = SDM({0:{0:ZZ(1)}}, (2, 2), ZZ) assert A.domain == ZZ assert A.shape == (2, 2) assert dict(A) == {0:{0:ZZ(1)}} raises(DDMBadInputError, lambda: SDM({5:{1:ZZ(0)}}, (2, 2), ZZ)) raises(DDMBadInputError, lambda: SDM({0:{5:ZZ(0)}}, (2, 2), ZZ)) def test_DDM_str(): sdm = SDM({0:{0:ZZ(1)}, 1:{1:ZZ(1)}}, (2, 2), ZZ) assert str(sdm) == '{0: {0: 1}, 1: {1: 1}}' if HAS_GMPY: # pragma: no cover assert repr(sdm) == 'SDM({0: {0: mpz(1)}, 1: {1: mpz(1)}}, (2, 2), ZZ)' else: # pragma: no cover assert repr(sdm) == 'SDM({0: {0: 1}, 1: {1: 1}}, (2, 2), ZZ)' def test_SDM_new(): A = SDM({0:{0:ZZ(1)}}, (2, 2), ZZ) B = A.new({}, (2, 2), ZZ) assert B == SDM({}, (2, 2), ZZ) def test_SDM_copy(): A = SDM({0:{0:ZZ(1)}}, (2, 2), ZZ) B = A.copy() assert A == B A[0][0] = ZZ(2) assert A != B def test_SDM_from_list(): A = SDM.from_list([[ZZ(0), ZZ(1)], [ZZ(1), ZZ(0)]], (2, 2), ZZ) assert A == SDM({0:{1:ZZ(1)}, 1:{0:ZZ(1)}}, (2, 2), ZZ) raises(DDMBadInputError, lambda: SDM.from_list([[ZZ(0)], [ZZ(0), ZZ(1)]], (2, 2), ZZ)) raises(DDMBadInputError, lambda: SDM.from_list([[ZZ(0), ZZ(1)]], (2, 2), ZZ)) def test_SDM_to_list(): A = SDM({0:{1: ZZ(1)}}, (2, 2), ZZ) assert A.to_list() == [[ZZ(0), ZZ(1)], [ZZ(0), ZZ(0)]] A = SDM({}, (0, 2), ZZ) assert A.to_list() == [] A = SDM({}, (2, 0), ZZ) assert A.to_list() == [[], []] def test_SDM_from_ddm(): A = DDM([[ZZ(1), ZZ(0)], [ZZ(1), ZZ(0)]], (2, 2), ZZ) B = SDM.from_ddm(A) assert B.domain == ZZ assert B.shape == (2, 2) assert dict(B) == {0:{0:ZZ(1)}, 1:{0:ZZ(1)}} def test_SDM_to_ddm(): A = SDM({0:{1: ZZ(1)}}, (2, 2), ZZ) B = DDM([[ZZ(0), ZZ(1)], [ZZ(0), ZZ(0)]], (2, 2), ZZ) assert A.to_ddm() == B def test_SDM_zeros(): A = SDM.zeros((2, 2), ZZ) assert A.domain == ZZ assert A.shape == (2, 2) assert dict(A) == {} def test_SDM_ones(): A = SDM.ones((1, 2), QQ) assert A.domain == QQ assert A.shape == (1, 2) assert dict(A) == {0:{0:QQ(1), 1:QQ(1)}} def test_SDM_eye(): A = SDM.eye(2, ZZ) assert A.domain == ZZ assert A.shape == (2, 2) assert dict(A) == {0:{0:ZZ(1)}, 1:{1:ZZ(1)}} def test_SDM_transpose(): A = SDM({0:{0:ZZ(1), 1:ZZ(2)}, 1:{0:ZZ(3), 1:ZZ(4)}}, (2, 2), ZZ) B = SDM({0:{0:ZZ(1), 1:ZZ(3)}, 1:{0:ZZ(2), 1:ZZ(4)}}, (2, 2), ZZ) assert A.transpose() == B A = SDM({0:{1:ZZ(2)}}, (2, 2), ZZ) B = SDM({1:{0:ZZ(2)}}, (2, 2), ZZ) assert A.transpose() == B A = SDM({0:{1:ZZ(2)}}, (1, 2), ZZ) B = SDM({1:{0:ZZ(2)}}, (2, 1), ZZ) assert A.transpose() == B def test_SDM_mul(): A = SDM({0:{0:ZZ(2)}}, (2, 2), ZZ) B = SDM({0:{0:ZZ(4)}}, (2, 2), ZZ) assert A*ZZ(2) == B assert ZZ(2)*A == B raises(TypeError, lambda: A*QQ(1, 2)) raises(TypeError, lambda: QQ(1, 2)*A) def test_SDM_matmul(): A = SDM({0:{0:ZZ(2)}}, (2, 2), ZZ) B = SDM({0:{0:ZZ(4)}}, (2, 2), ZZ) assert A.matmul(A) == B C = SDM({0:{0:ZZ(2)}}, (2, 2), QQ) raises(DDMDomainError, lambda: A.matmul(C)) A = SDM({0:{0:ZZ(1), 1:ZZ(2)}, 1:{0:ZZ(3), 1:ZZ(4)}}, (2, 2), ZZ) B = SDM({0:{0:ZZ(7), 1:ZZ(10)}, 1:{0:ZZ(15), 1:ZZ(22)}}, (2, 2), ZZ) assert A.matmul(A) == B A22 = SDM({0:{0:ZZ(4)}}, (2, 2), ZZ) A32 = SDM({0:{0:ZZ(2)}}, (3, 2), ZZ) A23 = SDM({0:{0:ZZ(4)}}, (2, 3), ZZ) A33 = SDM({0:{0:ZZ(8)}}, (3, 3), ZZ) A22 = SDM({0:{0:ZZ(8)}}, (2, 2), ZZ) assert A32.matmul(A23) == A33 assert A23.matmul(A32) == A22 # XXX: @ not supported by SDM... #assert A32.matmul(A23) == A32 @ A23 == A33 #assert A23.matmul(A32) == A23 @ A32 == A22 #raises(DDMShapeError, lambda: A23 @ A22) raises(DDMShapeError, lambda: A23.matmul(A22)) def test_SDM_add(): A = SDM({0:{1:ZZ(1)}, 1:{0:ZZ(2), 1:ZZ(3)}}, (2, 2), ZZ) B = SDM({0:{0:ZZ(1)}, 1:{0:ZZ(-2), 1:ZZ(3)}}, (2, 2), ZZ) C = SDM({0:{0:ZZ(1), 1:ZZ(1)}, 1:{1:ZZ(6)}}, (2, 2), ZZ) assert A.add(B) == C A = SDM({0:{1:ZZ(1)}}, (2, 2), ZZ) B = SDM({0:{0:ZZ(1)}, 1:{0:ZZ(-2), 1:ZZ(3)}}, (2, 2), ZZ) C = SDM({0:{0:ZZ(1), 1:ZZ(1)}, 1:{0:ZZ(-2), 1:ZZ(3)}}, (2, 2), ZZ) assert A.add(B) == C assert B.add(A) == C def test_SDM_sub(): A = SDM({0:{1:ZZ(1)}, 1:{0:ZZ(2), 1:ZZ(3)}}, (2, 2), ZZ) B = SDM({0:{0:ZZ(1)}, 1:{0:ZZ(-2), 1:ZZ(3)}}, (2, 2), ZZ) C = SDM({0:{0:ZZ(-1), 1:ZZ(1)}, 1:{0:ZZ(4)}}, (2, 2), ZZ) assert A.sub(B) == C def test_SDM_neg(): A = SDM({0:{1:ZZ(1)}, 1:{0:ZZ(2), 1:ZZ(3)}}, (2, 2), ZZ) B = SDM({0:{1:ZZ(-1)}, 1:{0:ZZ(-2), 1:ZZ(-3)}}, (2, 2), ZZ) assert A.neg() == B def test_SDM_convert_to(): A = SDM({0:{1:ZZ(1)}, 1:{0:ZZ(2), 1:ZZ(3)}}, (2, 2), ZZ) B = SDM({0:{1:QQ(1)}, 1:{0:QQ(2), 1:QQ(3)}}, (2, 2), QQ) C = A.convert_to(QQ) assert C == B assert C.domain == QQ D = A.convert_to(ZZ) assert D == A assert D.domain == ZZ def test_SDM_hstack(): A = SDM({0:{1:ZZ(1)}}, (2, 2), ZZ) B = SDM({1:{1:ZZ(1)}}, (2, 2), ZZ) AA = SDM({0:{1:ZZ(1), 3:ZZ(1)}}, (2, 4), ZZ) AB = SDM({0:{1:ZZ(1)}, 1:{3:ZZ(1)}}, (2, 4), ZZ) assert SDM.hstack(A) == A assert SDM.hstack(A, A) == AA assert SDM.hstack(A, B) == AB def test_SDM_inv(): A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ) B = SDM({0:{0:QQ(-2), 1:QQ(1)}, 1:{0:QQ(3, 2), 1:QQ(-1, 2)}}, (2, 2), QQ) assert A.inv() == B def test_SDM_det(): A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ) assert A.det() == QQ(-2) def test_SDM_lu(): A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ) L = SDM({0:{0:QQ(1)}, 1:{0:QQ(3), 1:QQ(1)}}, (2, 2), QQ) #U = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(-2)}}, (2, 2), QQ) #swaps = [] # This doesn't quite work. U has some nonzero elements in the lower part. #assert A.lu() == (L, U, swaps) assert A.lu()[0] == L def test_SDM_lu_solve(): A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ) b = SDM({0:{0:QQ(1)}, 1:{0:QQ(2)}}, (2, 1), QQ) x = SDM({1:{0:QQ(1, 2)}}, (2, 1), QQ) assert A.matmul(x) == b assert A.lu_solve(b) == x def test_SDM_charpoly(): A = SDM({0:{0:ZZ(1), 1:ZZ(2)}, 1:{0:ZZ(3), 1:ZZ(4)}}, (2, 2), ZZ) assert A.charpoly() == [ZZ(1), ZZ(-5), ZZ(-2)] def test_SDM_nullspace(): A = SDM({0:{0:QQ(1), 1:QQ(1)}}, (2, 2), QQ) assert A.nullspace()[0] == SDM({0:{0:QQ(-1), 1:QQ(1)}}, (1, 2), QQ) def test_SDM_rref(): eye2 = SDM({0:{0:QQ(1)}, 1:{1:QQ(1)}}, (2, 2), QQ) A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ) assert A.rref() == (eye2, [0, 1]) A = SDM({0:{0:QQ(1)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ) assert A.rref() == (eye2, [0, 1]) A = SDM({0:{1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ) assert A.rref() == (eye2, [0, 1]) A = SDM({0:{0:QQ(1), 1:QQ(2), 2:QQ(3)}, 1:{0:QQ(4), 1:QQ(5), 2:QQ(6)}, 2:{0:QQ(7), 1:QQ(8), 2:QQ(9)} }, (3, 3), QQ) Arref = SDM({0:{0:QQ(1), 2:QQ(-1)}, 1:{1:QQ(1), 2:QQ(2)}}, (3, 3), QQ) assert A.rref() == (Arref, [0, 1]) A = SDM({0:{0:QQ(1), 1:QQ(2), 3:QQ(1)}, 1:{0:QQ(1), 1:QQ(1), 2:QQ(9)}}, (2, 4), QQ) Arref = SDM({0:{0:QQ(1), 2:QQ(18), 3:QQ(-1)}, 1:{1:QQ(1), 2:QQ(-9), 3:QQ(1)}}, (2, 4), QQ) assert A.rref() == (Arref, [0, 1]) A = SDM({0:{0:QQ(1), 1:QQ(1), 2:QQ(1)}, 1:{0:QQ(1), 1:QQ(2), 2:QQ(2)}}, (2, 3), QQ) Arref = SDM( {0: {0: QQ(1,1)}, 1: {1: QQ(1,1), 2: QQ(1,1)}}, (2, 3), QQ) assert A.rref() == (Arref, [0, 1])
df2432ae4f417eea0d22ded314695e2ee54ba0be65bc433e302ccc456cf8b054
from sympy import Add, Basic, symbols, Symbol, And, S from sympy.core.symbol import Str from sympy.unify.core import Compound, Variable from sympy.unify.usympy import (deconstruct, construct, unify, is_associative, is_commutative) from sympy.abc import x, y, z, n def test_deconstruct(): expr = Basic(1, 2, 3) expected = Compound(Basic, (1, 2, 3)) assert deconstruct(expr) == expected assert deconstruct(1) == 1 assert deconstruct(x) == x assert deconstruct(x, variables=(x,)) == Variable(x) assert deconstruct(Add(1, x, evaluate=False)) == Compound(Add, (1, x)) assert deconstruct(Add(1, x, evaluate=False), variables=(x,)) == \ Compound(Add, (1, Variable(x))) def test_construct(): expr = Compound(Basic, (1, 2, 3)) expected = Basic(1, 2, 3) assert construct(expr) == expected def test_nested(): expr = Basic(1, Basic(2), 3) cmpd = Compound(Basic, (1, Compound(Basic, (2,)), 3)) assert deconstruct(expr) == cmpd assert construct(cmpd) == expr def test_unify(): expr = Basic(1, 2, 3) a, b, c = map(Symbol, 'abc') pattern = Basic(a, b, c) assert list(unify(expr, pattern, {}, (a, b, c))) == [{a: 1, b: 2, c: 3}] assert list(unify(expr, pattern, variables=(a, b, c))) == \ [{a: 1, b: 2, c: 3}] def test_unify_variables(): assert list(unify(Basic(1, 2), Basic(1, x), {}, variables=(x,))) == [{x: 2}] def test_s_input(): expr = Basic(1, 2) a, b = map(Symbol, 'ab') pattern = Basic(a, b) assert list(unify(expr, pattern, {}, (a, b))) == [{a: 1, b: 2}] assert list(unify(expr, pattern, {a: 5}, (a, b))) == [] def iterdicteq(a, b): a = tuple(a) b = tuple(b) return len(a) == len(b) and all(x in b for x in a) def test_unify_commutative(): expr = Add(1, 2, 3, evaluate=False) a, b, c = map(Symbol, 'abc') pattern = Add(a, b, c, evaluate=False) result = tuple(unify(expr, pattern, {}, (a, b, c))) expected = ({a: 1, b: 2, c: 3}, {a: 1, b: 3, c: 2}, {a: 2, b: 1, c: 3}, {a: 2, b: 3, c: 1}, {a: 3, b: 1, c: 2}, {a: 3, b: 2, c: 1}) assert iterdicteq(result, expected) def test_unify_iter(): expr = Add(1, 2, 3, evaluate=False) a, b, c = map(Symbol, 'abc') pattern = Add(a, c, evaluate=False) assert is_associative(deconstruct(pattern)) assert is_commutative(deconstruct(pattern)) result = list(unify(expr, pattern, {}, (a, c))) expected = [{a: 1, c: Add(2, 3, evaluate=False)}, {a: 1, c: Add(3, 2, evaluate=False)}, {a: 2, c: Add(1, 3, evaluate=False)}, {a: 2, c: Add(3, 1, evaluate=False)}, {a: 3, c: Add(1, 2, evaluate=False)}, {a: 3, c: Add(2, 1, evaluate=False)}, {a: Add(1, 2, evaluate=False), c: 3}, {a: Add(2, 1, evaluate=False), c: 3}, {a: Add(1, 3, evaluate=False), c: 2}, {a: Add(3, 1, evaluate=False), c: 2}, {a: Add(2, 3, evaluate=False), c: 1}, {a: Add(3, 2, evaluate=False), c: 1}] assert iterdicteq(result, expected) def test_hard_match(): from sympy import sin, cos expr = sin(x) + cos(x)**2 p, q = map(Symbol, 'pq') pattern = sin(p) + cos(p)**2 assert list(unify(expr, pattern, {}, (p, q))) == [{p: x}] def test_matrix(): from sympy import MatrixSymbol X = MatrixSymbol('X', n, n) Y = MatrixSymbol('Y', 2, 2) Z = MatrixSymbol('Z', 2, 3) assert list(unify(X, Y, {}, variables=[n, Str('X')])) == [{Str('X'): Str('Y'), n: 2}] assert list(unify(X, Z, {}, variables=[n, Str('X')])) == [] def test_non_frankenAdds(): # the is_commutative property used to fail because of Basic.__new__ # This caused is_commutative and str calls to fail expr = x+y*2 rebuilt = construct(deconstruct(expr)) # Ensure that we can run these commands without causing an error str(rebuilt) rebuilt.is_commutative def test_FiniteSet_commutivity(): from sympy import FiniteSet a, b, c, x, y = symbols('a,b,c,x,y') s = FiniteSet(a, b, c) t = FiniteSet(x, y) variables = (x, y) assert {x: FiniteSet(a, c), y: b} in tuple(unify(s, t, variables=variables)) def test_FiniteSet_complex(): from sympy import FiniteSet a, b, c, x, y, z = symbols('a,b,c,x,y,z') expr = FiniteSet(Basic(S(1), x), y, Basic(x, z)) pattern = FiniteSet(a, Basic(x, b)) variables = a, b expected = tuple([{b: 1, a: FiniteSet(y, Basic(x, z))}, {b: z, a: FiniteSet(y, Basic(S(1), x))}]) assert iterdicteq(unify(expr, pattern, variables=variables), expected) def test_and(): variables = x, y expected = tuple([{x: z > 0, y: n < 3}]) assert iterdicteq(unify((z>0) & (n<3), And(x, y), variables=variables), expected) def test_Union(): from sympy import Interval assert list(unify(Interval(0, 1) + Interval(10, 11), Interval(0, 1) + Interval(12, 13), variables=(Interval(12, 13),))) def test_is_commutative(): assert is_commutative(deconstruct(x+y)) assert is_commutative(deconstruct(x*y)) assert not is_commutative(deconstruct(x**y)) def test_commutative_in_commutative(): from sympy.abc import a,b,c,d from sympy import sin, cos eq = sin(3)*sin(4)*sin(5) + 4*cos(3)*cos(4) pat = a*cos(b)*cos(c) + d*sin(b)*sin(c) assert next(unify(eq, pat, variables=(a,b,c,d)))
180d43ec78ee00c3137508dfcdf7dd3a853809e4455d5d0881d942bb89939901
from sympy import sin, cos, pi, S, sqrt from sympy.testing.pytest import raises from sympy.vector.coordsysrect import CoordSys3D from sympy.vector.integrals import ParametricIntegral, vector_integrate from sympy.vector.parametricregion import ParametricRegion from sympy.vector.implicitregion import ImplicitRegion from sympy.abc import x, y, z, u, v, r, t, theta, phi from sympy.geometry import Point, Segment, Curve, Circle, Polygon, Plane C = CoordSys3D('C') def test_parametric_lineintegrals(): halfcircle = ParametricRegion((4*cos(theta), 4*sin(theta)), (theta, -pi/2, pi/2)) assert ParametricIntegral(C.x*C.y**4, halfcircle) == S(8192)/5 curve = ParametricRegion((t, t**2, t**3), (t, 0, 1)) field1 = 8*C.x**2*C.y*C.z*C.i + 5*C.z*C.j - 4*C.x*C.y*C.k assert ParametricIntegral(field1, curve) == 1 line = ParametricRegion((4*t - 1, 2 - 2*t, t), (t, 0, 1)) assert ParametricIntegral(C.x*C.z*C.i - C.y*C.z*C.k, line) == 3 assert ParametricIntegral(4*C.x**3, ParametricRegion((1, t), (t, 0, 2))) == 8 helix = ParametricRegion((cos(t), sin(t), 3*t), (t, 0, 4*pi)) assert ParametricIntegral(C.x*C.y*C.z, helix) == -3*sqrt(10)*pi field2 = C.y*C.i + C.z*C.j + C.z*C.k assert ParametricIntegral(field2, ParametricRegion((cos(t), sin(t), t**2), (t, 0, pi))) == -5*pi/2 + pi**4/2 def test_parametric_surfaceintegrals(): semisphere = ParametricRegion((2*sin(phi)*cos(theta), 2*sin(phi)*sin(theta), 2*cos(phi)),\ (theta, 0, 2*pi), (phi, 0, pi/2)) assert ParametricIntegral(C.z, semisphere) == 8*pi cylinder = ParametricRegion((sqrt(3)*cos(theta), sqrt(3)*sin(theta), z), (z, 0, 6), (theta, 0, 2*pi)) assert ParametricIntegral(C.y, cylinder) == 0 cone = ParametricRegion((v*cos(u), v*sin(u), v), (u, 0, 2*pi), (v, 0, 1)) assert ParametricIntegral(C.x*C.i + C.y*C.j + C.z**4*C.k, cone) == pi/3 triangle1 = ParametricRegion((x, y), (x, 0, 2), (y, 0, 10 - 5*x)) triangle2 = ParametricRegion((x, y), (y, 0, 10 - 5*x), (x, 0, 2)) assert ParametricIntegral(-15.6*C.y*C.k, triangle1) == ParametricIntegral(-15.6*C.y*C.k, triangle2) assert ParametricIntegral(C.z, triangle1) == 10*C.z def test_parametric_volumeintegrals(): cube = ParametricRegion((x, y, z), (x, 0, 1), (y, 0, 1), (z, 0, 1)) assert ParametricIntegral(1, cube) == 1 solidsphere1 = ParametricRegion((r*sin(phi)*cos(theta), r*sin(phi)*sin(theta), r*cos(phi)),\ (r, 0, 2), (theta, 0, 2*pi), (phi, 0, pi)) solidsphere2 = ParametricRegion((r*sin(phi)*cos(theta), r*sin(phi)*sin(theta), r*cos(phi)),\ (r, 0, 2), (phi, 0, pi), (theta, 0, 2*pi)) assert ParametricIntegral(C.x**2 + C.y**2, solidsphere1) == -256*pi/15 assert ParametricIntegral(C.x**2 + C.y**2, solidsphere2) == 256*pi/15 region_under_plane1 = ParametricRegion((x, y, z), (x, 0, 3), (y, 0, -2*x/3 + 2),\ (z, 0, 6 - 2*x - 3*y)) region_under_plane2 = ParametricRegion((x, y, z), (x, 0, 3), (z, 0, 6 - 2*x - 3*y),\ (y, 0, -2*x/3 + 2)) assert ParametricIntegral(C.x*C.i + C.j - 100*C.k, region_under_plane1) == \ ParametricIntegral(C.x*C.i + C.j - 100*C.k, region_under_plane2) assert ParametricIntegral(2*C.x, region_under_plane2) == -9 def test_vector_integrate(): halfdisc = ParametricRegion((r*cos(theta), r* sin(theta)), (r, -2, 2), (theta, 0, pi)) assert vector_integrate(C.x**2, halfdisc) == 4*pi vector_integrate(C.x, ParametricRegion((t, t**2), (t, 2, 3))) == -17*sqrt(17)/12 + 37*sqrt(37)/12 assert vector_integrate(C.y**3*C.z, (C.x, 0, 3), (C.y, -1, 4)) == 765*C.z/4 s1 = Segment(Point(0, 0), Point(0, 1)) assert vector_integrate(-15*C.y, s1) == S(-15)/2 s2 = Segment(Point(4, 3, 9), Point(1, 1, 7)) assert vector_integrate(C.y*C.i, s2) == -6 curve = Curve((sin(t), cos(t)), (t, 0, 2)) assert vector_integrate(5*C.z, curve) == 10*C.z c1 = Circle(Point(2, 3), 6) assert vector_integrate(C.x*C.y, c1) == 72*pi c2 = Circle(Point(0, 0), Point(1, 1), Point(1, 0)) assert vector_integrate(1, c2) == c2.circumference triangle = Polygon((0, 0), (1, 0), (1, 1)) assert vector_integrate(C.x*C.i - 14*C.y*C.j, triangle) == 0 p1, p2, p3, p4 = [(0, 0), (1, 0), (5, 1), (0, 1)] poly = Polygon(p1, p2, p3, p4) assert vector_integrate(-23*C.z, poly) == -161*C.z - 23*sqrt(17)*C.z point = Point(2, 3) assert vector_integrate(C.i*C.y - C.z, point) == ParametricIntegral(C.y*C.i, ParametricRegion((2, 3))) c3 = ImplicitRegion((x, y), x**2 + y**2 - 4) assert vector_integrate(45, c3) == 180*pi c4 = ImplicitRegion((x, y), (x - 3)**2 + (y - 4)**2 - 9) assert vector_integrate(1, c4) == 6*pi pl = Plane(Point(1, 1, 1), Point(2, 3, 4), Point(2, 2, 2)) raises(ValueError, lambda: vector_integrate(C.x*C.z*C.i + C.k, pl))
d338aab6aa5fce70f1a5cf31ed79a6a88da2732a8f973678aba5e4fcedf47df1
from sympy import Eq, Rational, S, Symbol, symbols, pi, sqrt, oo, Point2D, Segment2D, Abs, sec from sympy.geometry import (Circle, Ellipse, GeometryError, Line, Point, Polygon, Ray, RegularPolygon, Segment, Triangle, intersection) from sympy.testing.pytest import raises, slow from sympy import integrate from sympy.functions.special.elliptic_integrals import elliptic_e from sympy.functions.elementary.miscellaneous import Max def test_ellipse_equation_using_slope(): from sympy.abc import x, y e1 = Ellipse(Point(1, 0), 3, 2) assert str(e1.equation(_slope=1)) == str((-x + y + 1)**2/8 + (x + y - 1)**2/18 - 1) e2 = Ellipse(Point(0, 0), 4, 1) assert str(e2.equation(_slope=1)) == str((-x + y)**2/2 + (x + y)**2/32 - 1) e3 = Ellipse(Point(1, 5), 6, 2) assert str(e3.equation(_slope=2)) == str((-2*x + y - 3)**2/20 + (x + 2*y - 11)**2/180 - 1) def test_object_from_equation(): from sympy.abc import x, y, a, b assert Circle(x**2 + y**2 + 3*x + 4*y - 8) == Circle(Point2D(S(-3) / 2, -2), sqrt(57) / 2) assert Circle(x**2 + y**2 + 6*x + 8*y + 25) == Circle(Point2D(-3, -4), 0) assert Circle(a**2 + b**2 + 6*a + 8*b + 25, x='a', y='b') == Circle(Point2D(-3, -4), 0) assert Circle(x**2 + y**2 - 25) == Circle(Point2D(0, 0), 5) assert Circle(x**2 + y**2) == Circle(Point2D(0, 0), 0) assert Circle(a**2 + b**2, x='a', y='b') == Circle(Point2D(0, 0), 0) assert Circle(x**2 + y**2 + 6*x + 8) == Circle(Point2D(-3, 0), 1) assert Circle(x**2 + y**2 + 6*y + 8) == Circle(Point2D(0, -3), 1) assert Circle(6*(x**2) + 6*(y**2) + 6*x + 8*y - 25) == Circle(Point2D(Rational(-1, 2), Rational(-2, 3)), 5*sqrt(37)/6) assert Circle(Eq(a**2 + b**2, 25), x='a', y=b) == Circle(Point2D(0, 0), 5) raises(GeometryError, lambda: Circle(x**2 + y**2 + 3*x + 4*y + 26)) raises(GeometryError, lambda: Circle(x**2 + y**2 + 25)) raises(GeometryError, lambda: Circle(a**2 + b**2 + 25, x='a', y='b')) raises(GeometryError, lambda: Circle(x**2 + 6*y + 8)) raises(GeometryError, lambda: Circle(6*(x ** 2) + 4*(y**2) + 6*x + 8*y + 25)) raises(ValueError, lambda: Circle(a**2 + b**2 + 3*a + 4*b - 8)) @slow def test_ellipse_geom(): x = Symbol('x', real=True) y = Symbol('y', real=True) t = Symbol('t', real=True) y1 = Symbol('y1', real=True) half = S.Half p1 = Point(0, 0) p2 = Point(1, 1) p4 = Point(0, 1) e1 = Ellipse(p1, 1, 1) e2 = Ellipse(p2, half, 1) e3 = Ellipse(p1, y1, y1) c1 = Circle(p1, 1) c2 = Circle(p2, 1) c3 = Circle(Point(sqrt(2), sqrt(2)), 1) l1 = Line(p1, p2) # Test creation with three points cen, rad = Point(3*half, 2), 5*half assert Circle(Point(0, 0), Point(3, 0), Point(0, 4)) == Circle(cen, rad) assert Circle(Point(0, 0), Point(1, 1), Point(2, 2)) == Segment2D(Point2D(0, 0), Point2D(2, 2)) raises(ValueError, lambda: Ellipse(None, None, None, 1)) raises(ValueError, lambda: Ellipse()) raises(GeometryError, lambda: Circle(Point(0, 0))) raises(GeometryError, lambda: Circle(Symbol('x')*Symbol('y'))) # Basic Stuff assert Ellipse(None, 1, 1).center == Point(0, 0) assert e1 == c1 assert e1 != e2 assert e1 != l1 assert p4 in e1 assert e1 in e1 assert e2 in e2 assert 1 not in e2 assert p2 not in e2 assert e1.area == pi assert e2.area == pi/2 assert e3.area == pi*y1*abs(y1) assert c1.area == e1.area assert c1.circumference == e1.circumference assert e3.circumference == 2*pi*y1 assert e1.plot_interval() == e2.plot_interval() == [t, -pi, pi] assert e1.plot_interval(x) == e2.plot_interval(x) == [x, -pi, pi] assert c1.minor == 1 assert c1.major == 1 assert c1.hradius == 1 assert c1.vradius == 1 assert Ellipse((1, 1), 0, 0) == Point(1, 1) assert Ellipse((1, 1), 1, 0) == Segment(Point(0, 1), Point(2, 1)) assert Ellipse((1, 1), 0, 1) == Segment(Point(1, 0), Point(1, 2)) # Private Functions assert hash(c1) == hash(Circle(Point(1, 0), Point(0, 1), Point(0, -1))) assert c1 in e1 assert (Line(p1, p2) in e1) is False assert e1.__cmp__(e1) == 0 assert e1.__cmp__(Point(0, 0)) > 0 # Encloses assert e1.encloses(Segment(Point(-0.5, -0.5), Point(0.5, 0.5))) is True assert e1.encloses(Line(p1, p2)) is False assert e1.encloses(Ray(p1, p2)) is False assert e1.encloses(e1) is False assert e1.encloses( Polygon(Point(-0.5, -0.5), Point(-0.5, 0.5), Point(0.5, 0.5))) is True assert e1.encloses(RegularPolygon(p1, 0.5, 3)) is True assert e1.encloses(RegularPolygon(p1, 5, 3)) is False assert e1.encloses(RegularPolygon(p2, 5, 3)) is False assert e2.arbitrary_point() in e2 raises(ValueError, lambda: Ellipse(Point(x, y), 1, 1).arbitrary_point(parameter='x')) # Foci f1, f2 = Point(sqrt(12), 0), Point(-sqrt(12), 0) ef = Ellipse(Point(0, 0), 4, 2) assert ef.foci in [(f1, f2), (f2, f1)] # Tangents v = sqrt(2) / 2 p1_1 = Point(v, v) p1_2 = p2 + Point(half, 0) p1_3 = p2 + Point(0, 1) assert e1.tangent_lines(p4) == c1.tangent_lines(p4) assert e2.tangent_lines(p1_2) == [Line(Point(Rational(3, 2), 1), Point(Rational(3, 2), S.Half))] assert e2.tangent_lines(p1_3) == [Line(Point(1, 2), Point(Rational(5, 4), 2))] assert c1.tangent_lines(p1_1) != [Line(p1_1, Point(0, sqrt(2)))] assert c1.tangent_lines(p1) == [] assert e2.is_tangent(Line(p1_2, p2 + Point(half, 1))) assert e2.is_tangent(Line(p1_3, p2 + Point(half, 1))) assert c1.is_tangent(Line(p1_1, Point(0, sqrt(2)))) assert e1.is_tangent(Line(Point(0, 0), Point(1, 1))) is False assert c1.is_tangent(e1) is True assert c1.is_tangent(Ellipse(Point(2, 0), 1, 1)) is True assert c1.is_tangent( Polygon(Point(1, 1), Point(1, -1), Point(2, 0))) is True assert c1.is_tangent( Polygon(Point(1, 1), Point(1, 0), Point(2, 0))) is False assert Circle(Point(5, 5), 3).is_tangent(Circle(Point(0, 5), 1)) is False assert Ellipse(Point(5, 5), 2, 1).tangent_lines(Point(0, 0)) == \ [Line(Point(0, 0), Point(Rational(77, 25), Rational(132, 25))), Line(Point(0, 0), Point(Rational(33, 5), Rational(22, 5)))] assert Ellipse(Point(5, 5), 2, 1).tangent_lines(Point(3, 4)) == \ [Line(Point(3, 4), Point(4, 4)), Line(Point(3, 4), Point(3, 5))] assert Circle(Point(5, 5), 2).tangent_lines(Point(3, 3)) == \ [Line(Point(3, 3), Point(4, 3)), Line(Point(3, 3), Point(3, 4))] assert Circle(Point(5, 5), 2).tangent_lines(Point(5 - 2*sqrt(2), 5)) == \ [Line(Point(5 - 2*sqrt(2), 5), Point(5 - sqrt(2), 5 - sqrt(2))), Line(Point(5 - 2*sqrt(2), 5), Point(5 - sqrt(2), 5 + sqrt(2))), ] assert Circle(Point(5, 5), 5).tangent_lines(Point(4, 0)) == \ [Line(Point(4, 0), Point(Rational(40, 13), Rational(5, 13))), Line(Point(4, 0), Point(5, 0))] assert Circle(Point(5, 5), 5).tangent_lines(Point(0, 6)) == \ [Line(Point(0, 6), Point(0, 7)), Line(Point(0, 6), Point(Rational(5, 13), Rational(90, 13)))] # for numerical calculations, we shouldn't demand exact equality, # so only test up to the desired precision def lines_close(l1, l2, prec): """ tests whether l1 and 12 are within 10**(-prec) of each other """ return abs(l1.p1 - l2.p1) < 10**(-prec) and abs(l1.p2 - l2.p2) < 10**(-prec) def line_list_close(ll1, ll2, prec): return all(lines_close(l1, l2, prec) for l1, l2 in zip(ll1, ll2)) e = Ellipse(Point(0, 0), 2, 1) assert e.normal_lines(Point(0, 0)) == \ [Line(Point(0, 0), Point(0, 1)), Line(Point(0, 0), Point(1, 0))] assert e.normal_lines(Point(1, 0)) == \ [Line(Point(0, 0), Point(1, 0))] assert e.normal_lines((0, 1)) == \ [Line(Point(0, 0), Point(0, 1))] assert line_list_close(e.normal_lines(Point(1, 1), 2), [ Line(Point(Rational(-51, 26), Rational(-1, 5)), Point(Rational(-25, 26), Rational(17, 83))), Line(Point(Rational(28, 29), Rational(-7, 8)), Point(Rational(57, 29), Rational(-9, 2)))], 2) # test the failure of Poly.intervals and checks a point on the boundary p = Point(sqrt(3), S.Half) assert p in e assert line_list_close(e.normal_lines(p, 2), [ Line(Point(Rational(-341, 171), Rational(-1, 13)), Point(Rational(-170, 171), Rational(5, 64))), Line(Point(Rational(26, 15), Rational(-1, 2)), Point(Rational(41, 15), Rational(-43, 26)))], 2) # be sure to use the slope that isn't undefined on boundary e = Ellipse((0, 0), 2, 2*sqrt(3)/3) assert line_list_close(e.normal_lines((1, 1), 2), [ Line(Point(Rational(-64, 33), Rational(-20, 71)), Point(Rational(-31, 33), Rational(2, 13))), Line(Point(1, -1), Point(2, -4))], 2) # general ellipse fails except under certain conditions e = Ellipse((0, 0), x, 1) assert e.normal_lines((x + 1, 0)) == [Line(Point(0, 0), Point(1, 0))] raises(NotImplementedError, lambda: e.normal_lines((x + 1, 1))) # Properties major = 3 minor = 1 e4 = Ellipse(p2, minor, major) assert e4.focus_distance == sqrt(major**2 - minor**2) ecc = e4.focus_distance / major assert e4.eccentricity == ecc assert e4.periapsis == major*(1 - ecc) assert e4.apoapsis == major*(1 + ecc) assert e4.semilatus_rectum == major*(1 - ecc ** 2) # independent of orientation e4 = Ellipse(p2, major, minor) assert e4.focus_distance == sqrt(major**2 - minor**2) ecc = e4.focus_distance / major assert e4.eccentricity == ecc assert e4.periapsis == major*(1 - ecc) assert e4.apoapsis == major*(1 + ecc) # Intersection l1 = Line(Point(1, -5), Point(1, 5)) l2 = Line(Point(-5, -1), Point(5, -1)) l3 = Line(Point(-1, -1), Point(1, 1)) l4 = Line(Point(-10, 0), Point(0, 10)) pts_c1_l3 = [Point(sqrt(2)/2, sqrt(2)/2), Point(-sqrt(2)/2, -sqrt(2)/2)] assert intersection(e2, l4) == [] assert intersection(c1, Point(1, 0)) == [Point(1, 0)] assert intersection(c1, l1) == [Point(1, 0)] assert intersection(c1, l2) == [Point(0, -1)] assert intersection(c1, l3) in [pts_c1_l3, [pts_c1_l3[1], pts_c1_l3[0]]] assert intersection(c1, c2) == [Point(0, 1), Point(1, 0)] assert intersection(c1, c3) == [Point(sqrt(2)/2, sqrt(2)/2)] assert e1.intersection(l1) == [Point(1, 0)] assert e2.intersection(l4) == [] assert e1.intersection(Circle(Point(0, 2), 1)) == [Point(0, 1)] assert e1.intersection(Circle(Point(5, 0), 1)) == [] assert e1.intersection(Ellipse(Point(2, 0), 1, 1)) == [Point(1, 0)] assert e1.intersection(Ellipse(Point(5, 0), 1, 1)) == [] assert e1.intersection(Point(2, 0)) == [] assert e1.intersection(e1) == e1 assert intersection(Ellipse(Point(0, 0), 2, 1), Ellipse(Point(3, 0), 1, 2)) == [Point(2, 0)] assert intersection(Circle(Point(0, 0), 2), Circle(Point(3, 0), 1)) == [Point(2, 0)] assert intersection(Circle(Point(0, 0), 2), Circle(Point(7, 0), 1)) == [] assert intersection(Ellipse(Point(0, 0), 5, 17), Ellipse(Point(4, 0), 1, 0.2)) == [Point(5, 0)] assert intersection(Ellipse(Point(0, 0), 5, 17), Ellipse(Point(4, 0), 0.999, 0.2)) == [] assert Circle((0, 0), S.Half).intersection( Triangle((-1, 0), (1, 0), (0, 1))) == [ Point(Rational(-1, 2), 0), Point(S.Half, 0)] raises(TypeError, lambda: intersection(e2, Line((0, 0, 0), (0, 0, 1)))) raises(TypeError, lambda: intersection(e2, Rational(12))) raises(TypeError, lambda: Ellipse.intersection(e2, 1)) # some special case intersections csmall = Circle(p1, 3) cbig = Circle(p1, 5) cout = Circle(Point(5, 5), 1) # one circle inside of another assert csmall.intersection(cbig) == [] # separate circles assert csmall.intersection(cout) == [] # coincident circles assert csmall.intersection(csmall) == csmall v = sqrt(2) t1 = Triangle(Point(0, v), Point(0, -v), Point(v, 0)) points = intersection(t1, c1) assert len(points) == 4 assert Point(0, 1) in points assert Point(0, -1) in points assert Point(v/2, v/2) in points assert Point(v/2, -v/2) in points circ = Circle(Point(0, 0), 5) elip = Ellipse(Point(0, 0), 5, 20) assert intersection(circ, elip) in \ [[Point(5, 0), Point(-5, 0)], [Point(-5, 0), Point(5, 0)]] assert elip.tangent_lines(Point(0, 0)) == [] elip = Ellipse(Point(0, 0), 3, 2) assert elip.tangent_lines(Point(3, 0)) == \ [Line(Point(3, 0), Point(3, -12))] e1 = Ellipse(Point(0, 0), 5, 10) e2 = Ellipse(Point(2, 1), 4, 8) a = Rational(53, 17) c = 2*sqrt(3991)/17 ans = [Point(a - c/8, a/2 + c), Point(a + c/8, a/2 - c)] assert e1.intersection(e2) == ans e2 = Ellipse(Point(x, y), 4, 8) c = sqrt(3991) ans = [Point(-c/68 + a, c*Rational(2, 17) + a/2), Point(c/68 + a, c*Rational(-2, 17) + a/2)] assert [p.subs({x: 2, y:1}) for p in e1.intersection(e2)] == ans # Combinations of above assert e3.is_tangent(e3.tangent_lines(p1 + Point(y1, 0))[0]) e = Ellipse((1, 2), 3, 2) assert e.tangent_lines(Point(10, 0)) == \ [Line(Point(10, 0), Point(1, 0)), Line(Point(10, 0), Point(Rational(14, 5), Rational(18, 5)))] # encloses_point e = Ellipse((0, 0), 1, 2) assert e.encloses_point(e.center) assert e.encloses_point(e.center + Point(0, e.vradius - Rational(1, 10))) assert e.encloses_point(e.center + Point(e.hradius - Rational(1, 10), 0)) assert e.encloses_point(e.center + Point(e.hradius, 0)) is False assert e.encloses_point( e.center + Point(e.hradius + Rational(1, 10), 0)) is False e = Ellipse((0, 0), 2, 1) assert e.encloses_point(e.center) assert e.encloses_point(e.center + Point(0, e.vradius - Rational(1, 10))) assert e.encloses_point(e.center + Point(e.hradius - Rational(1, 10), 0)) assert e.encloses_point(e.center + Point(e.hradius, 0)) is False assert e.encloses_point( e.center + Point(e.hradius + Rational(1, 10), 0)) is False assert c1.encloses_point(Point(1, 0)) is False assert c1.encloses_point(Point(0.3, 0.4)) is True assert e.scale(2, 3) == Ellipse((0, 0), 4, 3) assert e.scale(3, 6) == Ellipse((0, 0), 6, 6) assert e.rotate(pi) == e assert e.rotate(pi, (1, 2)) == Ellipse(Point(2, 4), 2, 1) raises(NotImplementedError, lambda: e.rotate(pi/3)) # Circle rotation tests (Issue #11743) # Link - https://github.com/sympy/sympy/issues/11743 cir = Circle(Point(1, 0), 1) assert cir.rotate(pi/2) == Circle(Point(0, 1), 1) assert cir.rotate(pi/3) == Circle(Point(S.Half, sqrt(3)/2), 1) assert cir.rotate(pi/3, Point(1, 0)) == Circle(Point(1, 0), 1) assert cir.rotate(pi/3, Point(0, 1)) == Circle(Point(S.Half + sqrt(3)/2, S.Half + sqrt(3)/2), 1) def test_construction(): e1 = Ellipse(hradius=2, vradius=1, eccentricity=None) assert e1.eccentricity == sqrt(3)/2 e2 = Ellipse(hradius=2, vradius=None, eccentricity=sqrt(3)/2) assert e2.vradius == 1 e3 = Ellipse(hradius=None, vradius=1, eccentricity=sqrt(3)/2) assert e3.hradius == 2 # filter(None, iterator) filters out anything falsey, including 0 # eccentricity would be filtered out in this case and the constructor would throw an error e4 = Ellipse(Point(0, 0), hradius=1, eccentricity=0) assert e4.vradius == 1 #tests for eccentricity > 1 raises(GeometryError, lambda: Ellipse(Point(3, 1), hradius=3, eccentricity = S(3)/2)) raises(GeometryError, lambda: Ellipse(Point(3, 1), hradius=3, eccentricity=sec(5))) raises(GeometryError, lambda: Ellipse(Point(3, 1), hradius=3, eccentricity=S.Pi-S(2))) #tests for eccentricity = 1 #if vradius is not defined assert Ellipse(None, 1, None, 1).length == 2 #if hradius is not defined raises(GeometryError, lambda: Ellipse(None, None, 1, eccentricity = 1)) #tests for eccentricity < 0 raises(GeometryError, lambda: Ellipse(Point(3, 1), hradius=3, eccentricity = -3)) raises(GeometryError, lambda: Ellipse(Point(3, 1), hradius=3, eccentricity = -0.5)) def test_ellipse_random_point(): y1 = Symbol('y1', real=True) e3 = Ellipse(Point(0, 0), y1, y1) rx, ry = Symbol('rx'), Symbol('ry') for ind in range(0, 5): r = e3.random_point() # substitution should give zero*y1**2 assert e3.equation(rx, ry).subs(zip((rx, ry), r.args)).equals(0) # test for the case with seed r = e3.random_point(seed=1) assert e3.equation(rx, ry).subs(zip((rx, ry), r.args)).equals(0) def test_repr(): assert repr(Circle((0, 1), 2)) == 'Circle(Point2D(0, 1), 2)' def test_transform(): c = Circle((1, 1), 2) assert c.scale(-1) == Circle((-1, 1), 2) assert c.scale(y=-1) == Circle((1, -1), 2) assert c.scale(2) == Ellipse((2, 1), 4, 2) assert Ellipse((0, 0), 2, 3).scale(2, 3, (4, 5)) == \ Ellipse(Point(-4, -10), 4, 9) assert Circle((0, 0), 2).scale(2, 3, (4, 5)) == \ Ellipse(Point(-4, -10), 4, 6) assert Ellipse((0, 0), 2, 3).scale(3, 3, (4, 5)) == \ Ellipse(Point(-8, -10), 6, 9) assert Circle((0, 0), 2).scale(3, 3, (4, 5)) == \ Circle(Point(-8, -10), 6) assert Circle(Point(-8, -10), 6).scale(Rational(1, 3), Rational(1, 3), (4, 5)) == \ Circle((0, 0), 2) assert Circle((0, 0), 2).translate(4, 5) == \ Circle((4, 5), 2) assert Circle((0, 0), 2).scale(3, 3) == \ Circle((0, 0), 6) def test_bounds(): e1 = Ellipse(Point(0, 0), 3, 5) e2 = Ellipse(Point(2, -2), 7, 7) c1 = Circle(Point(2, -2), 7) c2 = Circle(Point(-2, 0), Point(0, 2), Point(2, 0)) assert e1.bounds == (-3, -5, 3, 5) assert e2.bounds == (-5, -9, 9, 5) assert c1.bounds == (-5, -9, 9, 5) assert c2.bounds == (-2, -2, 2, 2) def test_reflect(): b = Symbol('b') m = Symbol('m') l = Line((0, b), slope=m) t1 = Triangle((0, 0), (1, 0), (2, 3)) assert t1.area == -t1.reflect(l).area e = Ellipse((1, 0), 1, 2) assert e.area == -e.reflect(Line((1, 0), slope=0)).area assert e.area == -e.reflect(Line((1, 0), slope=oo)).area raises(NotImplementedError, lambda: e.reflect(Line((1, 0), slope=m))) assert Circle((0, 1), 1).reflect(Line((0, 0), (1, 1))) == Circle(Point2D(1, 0), -1) def test_is_tangent(): e1 = Ellipse(Point(0, 0), 3, 5) c1 = Circle(Point(2, -2), 7) assert e1.is_tangent(Point(0, 0)) is False assert e1.is_tangent(Point(3, 0)) is False assert e1.is_tangent(e1) is True assert e1.is_tangent(Ellipse((0, 0), 1, 2)) is False assert e1.is_tangent(Ellipse((0, 0), 3, 2)) is True assert c1.is_tangent(Ellipse((2, -2), 7, 1)) is True assert c1.is_tangent(Circle((11, -2), 2)) is True assert c1.is_tangent(Circle((7, -2), 2)) is True assert c1.is_tangent(Ray((-5, -2), (-15, -20))) is False assert c1.is_tangent(Ray((-3, -2), (-15, -20))) is False assert c1.is_tangent(Ray((-3, -22), (15, 20))) is False assert c1.is_tangent(Ray((9, 20), (9, -20))) is True assert e1.is_tangent(Segment((2, 2), (-7, 7))) is False assert e1.is_tangent(Segment((0, 0), (1, 2))) is False assert c1.is_tangent(Segment((0, 0), (-5, -2))) is False assert e1.is_tangent(Segment((3, 0), (12, 12))) is False assert e1.is_tangent(Segment((12, 12), (3, 0))) is False assert e1.is_tangent(Segment((-3, 0), (3, 0))) is False assert e1.is_tangent(Segment((-3, 5), (3, 5))) is True assert e1.is_tangent(Line((10, 0), (10, 10))) is False assert e1.is_tangent(Line((0, 0), (1, 1))) is False assert e1.is_tangent(Line((-3, 0), (-2.99, -0.001))) is False assert e1.is_tangent(Line((-3, 0), (-3, 1))) is True assert e1.is_tangent(Polygon((0, 0), (5, 5), (5, -5))) is False assert e1.is_tangent(Polygon((-100, -50), (-40, -334), (-70, -52))) is False assert e1.is_tangent(Polygon((-3, 0), (3, 0), (0, 1))) is False assert e1.is_tangent(Polygon((-3, 0), (3, 0), (0, 5))) is False assert e1.is_tangent(Polygon((-3, 0), (0, -5), (3, 0), (0, 5))) is False assert e1.is_tangent(Polygon((-3, -5), (-3, 5), (3, 5), (3, -5))) is True assert c1.is_tangent(Polygon((-3, -5), (-3, 5), (3, 5), (3, -5))) is False assert e1.is_tangent(Polygon((0, 0), (3, 0), (7, 7), (0, 5))) is False assert e1.is_tangent(Polygon((3, 12), (3, -12), (6, 5))) is True assert e1.is_tangent(Polygon((3, 12), (3, -12), (0, -5), (0, 5))) is False assert e1.is_tangent(Polygon((3, 0), (5, 7), (6, -5))) is False raises(TypeError, lambda: e1.is_tangent(Point(0, 0, 0))) raises(TypeError, lambda: e1.is_tangent(Rational(5))) def test_parameter_value(): t = Symbol('t') e = Ellipse(Point(0, 0), 3, 5) assert e.parameter_value((3, 0), t) == {t: 0} raises(ValueError, lambda: e.parameter_value((4, 0), t)) @slow def test_second_moment_of_area(): x, y = symbols('x, y') e = Ellipse(Point(0, 0), 5, 4) I_yy = 2*4*integrate(sqrt(25 - x**2)*x**2, (x, -5, 5))/5 I_xx = 2*5*integrate(sqrt(16 - y**2)*y**2, (y, -4, 4))/4 Y = 3*sqrt(1 - x**2/5**2) I_xy = integrate(integrate(y, (y, -Y, Y))*x, (x, -5, 5)) assert I_yy == e.second_moment_of_area()[1] assert I_xx == e.second_moment_of_area()[0] assert I_xy == e.second_moment_of_area()[2] #checking for other point t1 = e.second_moment_of_area(Point(6,5)) t2 = (580*pi, 845*pi, 600*pi) assert t1==t2 def test_section_modulus_and_polar_second_moment_of_area(): d = Symbol('d', positive=True) c = Circle((3, 7), 8) assert c.polar_second_moment_of_area() == 2048*pi assert c.section_modulus() == (128*pi, 128*pi) c = Circle((2, 9), d/2) assert c.polar_second_moment_of_area() == pi*d**3*Abs(d)/64 + pi*d*Abs(d)**3/64 assert c.section_modulus() == (pi*d**3/S(32), pi*d**3/S(32)) a, b = symbols('a, b', positive=True) e = Ellipse((4, 6), a, b) assert e.section_modulus() == (pi*a*b**2/S(4), pi*a**2*b/S(4)) assert e.polar_second_moment_of_area() == pi*a**3*b/S(4) + pi*a*b**3/S(4) e = e.rotate(pi/2) # no change in polar and section modulus assert e.section_modulus() == (pi*a**2*b/S(4), pi*a*b**2/S(4)) assert e.polar_second_moment_of_area() == pi*a**3*b/S(4) + pi*a*b**3/S(4) e = Ellipse((a, b), 2, 6) assert e.section_modulus() == (18*pi, 6*pi) assert e.polar_second_moment_of_area() == 120*pi e = Ellipse(Point(0, 0), 2, 2) assert e.section_modulus() == (2*pi, 2*pi) assert e.section_modulus(Point(2, 2)) == (2*pi, 2*pi) assert e.section_modulus((2, 2)) == (2*pi, 2*pi) def test_circumference(): M = Symbol('M') m = Symbol('m') assert Ellipse(Point(0, 0), M, m).circumference == 4 * M * elliptic_e((M ** 2 - m ** 2) / M**2) assert Ellipse(Point(0, 0), 5, 4).circumference == 20 * elliptic_e(S(9) / 25) # circle assert Ellipse(None, 1, None, 0).circumference == 2*pi # test numerically assert abs(Ellipse(None, hradius=5, vradius=3).circumference.evalf(16) - 25.52699886339813) < 1e-10 def test_issue_15259(): assert Circle((1, 2), 0) == Point(1, 2) def test_issue_15797_equals(): Ri = 0.024127189424130748 Ci = (0.0864931002830291, 0.0819863295239654) A = Point(0, 0.0578591400998346) c = Circle(Ci, Ri) # evaluated assert c.is_tangent(c.tangent_lines(A)[0]) == True assert c.center.x.is_Rational assert c.center.y.is_Rational assert c.radius.is_Rational u = Circle(Ci, Ri, evaluate=False) # unevaluated assert u.center.x.is_Float assert u.center.y.is_Float assert u.radius.is_Float def test_auxiliary_circle(): x, y, a, b = symbols('x y a b') e = Ellipse((x, y), a, b) # the general result assert e.auxiliary_circle() == Circle((x, y), Max(a, b)) # a special case where Ellipse is a Circle assert Circle((3, 4), 8).auxiliary_circle() == Circle((3, 4), 8) def test_director_circle(): x, y, a, b = symbols('x y a b') e = Ellipse((x, y), a, b) # the general result assert e.director_circle() == Circle((x, y), sqrt(a**2 + b**2)) # a special case where Ellipse is a Circle assert Circle((3, 4), 8).director_circle() == Circle((3, 4), 8*sqrt(2)) def test_evolute(): #ellipse centered at h,k x, y, h, k = symbols('x y h k',real = True) a, b = symbols('a b') e = Ellipse(Point(h, k), a, b) t1 = (e.hradius*(x - e.center.x))**Rational(2, 3) t2 = (e.vradius*(y - e.center.y))**Rational(2, 3) E = t1 + t2 - (e.hradius**2 - e.vradius**2)**Rational(2, 3) assert e.evolute() == E #Numerical Example e = Ellipse(Point(1, 1), 6, 3) t1 = (6*(x - 1))**Rational(2, 3) t2 = (3*(y - 1))**Rational(2, 3) E = t1 + t2 - (27)**Rational(2, 3) assert e.evolute() == E def test_svg(): e1 = Ellipse(Point(1, 0), 3, 2) assert e1._svg(2, "#FFAAFF") == '<ellipse fill="#FFAAFF" stroke="#555555" stroke-width="4.0" opacity="0.6" cx="1.00000000000000" cy="0" rx="3.00000000000000" ry="2.00000000000000"/>'
dd4e38acea08620865aebea176369f0577859ff08f2fca81d315aad90ee644bc
import sympy from sympy.parsing.sympy_parser import ( parse_expr, standard_transformations, convert_xor, implicit_multiplication_application, implicit_multiplication, implicit_application, function_exponentiation, split_symbols, split_symbols_custom, _token_splittable ) from sympy.testing.pytest import raises def test_implicit_multiplication(): cases = { '5x': '5*x', 'abc': 'a*b*c', '3sin(x)': '3*sin(x)', '(x+1)(x+2)': '(x+1)*(x+2)', '(5 x**2)sin(x)': '(5*x**2)*sin(x)', '2 sin(x) cos(x)': '2*sin(x)*cos(x)', 'pi x': 'pi*x', 'x pi': 'x*pi', 'E x': 'E*x', 'EulerGamma y': 'EulerGamma*y', 'E pi': 'E*pi', 'pi (x + 2)': 'pi*(x+2)', '(x + 2) pi': '(x+2)*pi', 'pi sin(x)': 'pi*sin(x)', } transformations = standard_transformations + (convert_xor,) transformations2 = transformations + (split_symbols, implicit_multiplication) for case in cases: implicit = parse_expr(case, transformations=transformations2) normal = parse_expr(cases[case], transformations=transformations) assert(implicit == normal) application = ['sin x', 'cos 2*x', 'sin cos x'] for case in application: raises(SyntaxError, lambda: parse_expr(case, transformations=transformations2)) raises(TypeError, lambda: parse_expr('sin**2(x)', transformations=transformations2)) def test_implicit_application(): cases = { 'factorial': 'factorial', 'sin x': 'sin(x)', 'tan y**3': 'tan(y**3)', 'cos 2*x': 'cos(2*x)', '(cot)': 'cot', 'sin cos tan x': 'sin(cos(tan(x)))' } transformations = standard_transformations + (convert_xor,) transformations2 = transformations + (implicit_application,) for case in cases: implicit = parse_expr(case, transformations=transformations2) normal = parse_expr(cases[case], transformations=transformations) assert(implicit == normal), (implicit, normal) multiplication = ['x y', 'x sin x', '2x'] for case in multiplication: raises(SyntaxError, lambda: parse_expr(case, transformations=transformations2)) raises(TypeError, lambda: parse_expr('sin**2(x)', transformations=transformations2)) def test_function_exponentiation(): cases = { 'sin**2(x)': 'sin(x)**2', 'exp^y(z)': 'exp(z)^y', 'sin**2(E^(x))': 'sin(E^(x))**2' } transformations = standard_transformations + (convert_xor,) transformations2 = transformations + (function_exponentiation,) for case in cases: implicit = parse_expr(case, transformations=transformations2) normal = parse_expr(cases[case], transformations=transformations) assert(implicit == normal) other_implicit = ['x y', 'x sin x', '2x', 'sin x', 'cos 2*x', 'sin cos x'] for case in other_implicit: raises(SyntaxError, lambda: parse_expr(case, transformations=transformations2)) assert parse_expr('x**2', local_dict={ 'x': sympy.Symbol('x') }, transformations=transformations2) == parse_expr('x**2') def test_symbol_splitting(): # By default Greek letter names should not be split (lambda is a keyword # so skip it) transformations = standard_transformations + (split_symbols,) greek_letters = ('alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', 'eta', 'theta', 'iota', 'kappa', 'mu', 'nu', 'xi', 'omicron', 'pi', 'rho', 'sigma', 'tau', 'upsilon', 'phi', 'chi', 'psi', 'omega') for letter in greek_letters: assert(parse_expr(letter, transformations=transformations) == parse_expr(letter)) # Make sure symbol splitting resolves names transformations += (implicit_multiplication,) local_dict = { 'e': sympy.E } cases = { 'xe': 'E*x', 'Iy': 'I*y', 'ee': 'E*E', } for case, expected in cases.items(): assert(parse_expr(case, local_dict=local_dict, transformations=transformations) == parse_expr(expected)) # Make sure custom splitting works def can_split(symbol): if symbol not in ('unsplittable', 'names'): return _token_splittable(symbol) return False transformations = standard_transformations transformations += (split_symbols_custom(can_split), implicit_multiplication) assert(parse_expr('unsplittable', transformations=transformations) == parse_expr('unsplittable')) assert(parse_expr('names', transformations=transformations) == parse_expr('names')) assert(parse_expr('xy', transformations=transformations) == parse_expr('x*y')) for letter in greek_letters: assert(parse_expr(letter, transformations=transformations) == parse_expr(letter)) def test_all_implicit_steps(): cases = { '2x': '2*x', # implicit multiplication 'x y': 'x*y', 'xy': 'x*y', 'sin x': 'sin(x)', # add parentheses '2sin x': '2*sin(x)', 'x y z': 'x*y*z', 'sin(2 * 3x)': 'sin(2 * 3 * x)', 'sin(x) (1 + cos(x))': 'sin(x) * (1 + cos(x))', '(x + 2) sin(x)': '(x + 2) * sin(x)', '(x + 2) sin x': '(x + 2) * sin(x)', 'sin(sin x)': 'sin(sin(x))', 'sin x!': 'sin(factorial(x))', 'sin x!!': 'sin(factorial2(x))', 'factorial': 'factorial', # don't apply a bare function 'x sin x': 'x * sin(x)', # both application and multiplication 'xy sin x': 'x * y * sin(x)', '(x+2)(x+3)': '(x + 2) * (x+3)', 'x**2 + 2xy + y**2': 'x**2 + 2 * x * y + y**2', # split the xy 'pi': 'pi', # don't mess with constants 'None': 'None', 'ln sin x': 'ln(sin(x))', # multiple implicit function applications 'factorial': 'factorial', # don't add parentheses 'sin x**2': 'sin(x**2)', # implicit application to an exponential 'alpha': 'Symbol("alpha")', # don't split Greek letters/subscripts 'x_2': 'Symbol("x_2")', 'sin^2 x**2': 'sin(x**2)**2', # function raised to a power 'sin**3(x)': 'sin(x)**3', '(factorial)': 'factorial', 'tan 3x': 'tan(3*x)', 'sin^2(3*E^(x))': 'sin(3*E**(x))**2', 'sin**2(E^(3x))': 'sin(E**(3*x))**2', 'sin^2 (3x*E^(x))': 'sin(3*x*E^x)**2', 'pi sin x': 'pi*sin(x)', } transformations = standard_transformations + (convert_xor,) transformations2 = transformations + (implicit_multiplication_application,) for case in cases: implicit = parse_expr(case, transformations=transformations2) normal = parse_expr(cases[case], transformations=transformations) assert(implicit == normal) def test_no_methods_implicit_multiplication(): # Issue 21020 u = sympy.Symbol('u') transformations = standard_transformations + \ (implicit_multiplication,) expr = parse_expr('x.is_polynomial(x)', transformations=transformations) assert expr == True expr = parse_expr('(exp(x) / (1 + exp(2x))).subs(exp(x), u)', transformations=transformations) assert expr == u/(u**2 + 1)
5ec745f0191c5337aca7c123e2b1802075a3132ad9f91bb3f3f6f60b1b90caef
# -*- coding: utf-8 -*- import sys 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 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, implicit_multiplication_application, ) 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) # XXX: bit odd, but would be error if parser left the Symbol d = {'foo': Symbol('baz')} assert parse_expr('foo(x)', local_dict=d) == Function('baz')(x) 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_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_issue_10560(): inputs = { '4*-3' : '(-3)*4', '-4*3' : '(-4)*3', } for text, result in inputs.items(): assert parse_expr(text, evaluate=False) == parse_expr(result, evaluate=False) 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, 6): skip("test_python3_features requires Python 3.6 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)
b41f15d579b2669bac0aef45a8b71ab19d520eb14c3c6501f6b3dd7934e6e5eb
from sympy.testing.pytest import raises, XFAIL from sympy.external import import_module from sympy import ( Symbol, Mul, Add, Abs, sin, asin, cos, Pow, csc, sec, Limit, oo, Derivative, Integral, factorial, sqrt, root, conjugate, StrictLessThan, LessThan, StrictGreaterThan, GreaterThan, Sum, Product, E, log, tan, Function, binomial, exp, floor, ceiling, Unequality ) from sympy.core.relational import Eq, Ne, Lt, Le, Gt, Ge from sympy.physics.quantum.state import Bra, Ket from sympy.abc import x, y, z, a, b, c, t, k, n antlr4 = import_module("antlr4") # disable tests if antlr4-python*-runtime is not present if not antlr4: disabled = True theta = Symbol('theta') f = Function('f') # shorthand definitions def _Add(a, b): return Add(a, b, evaluate=False) def _Mul(a, b): return Mul(a, b, evaluate=False) def _Pow(a, b): return Pow(a, b, evaluate=False) def _Sqrt(a): return sqrt(a, evaluate=False) def _Conjugate(a): return conjugate(a, evaluate=False) def _Abs(a): return Abs(a, evaluate=False) def _factorial(a): return factorial(a, evaluate=False) def _exp(a): return exp(a, evaluate=False) def _log(a, b): return log(a, b, evaluate=False) def _binomial(n, k): return binomial(n, k, evaluate=False) def test_import(): from sympy.parsing.latex._build_latex_antlr import ( build_parser, check_antlr_version, dir_latex_antlr ) # XXX: It would be better to come up with a test for these... del build_parser, check_antlr_version, dir_latex_antlr # These LaTeX strings should parse to the corresponding SymPy expression GOOD_PAIRS = [ (r"0", 0), (r"1", 1), (r"-3.14", _Mul(-1, 3.14)), (r"(-7.13)(1.5)", _Mul(_Mul(-1, 7.13), 1.5)), (r"x", x), (r"2x", 2*x), (r"x^2", x**2), (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"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"\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_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"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)), ] 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 # 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)
3f95d3a365239320f2c7877d929996226e81a025f23a2103f6cf13af7c37026e
import collections import warnings from sympy.external import import_module autolevparser = import_module('sympy.parsing.autolev._antlr.autolevparser', import_kwargs={'fromlist': ['AutolevParser']}) autolevlexer = import_module('sympy.parsing.autolev._antlr.autolevlexer', import_kwargs={'fromlist': ['AutolevLexer']}) autolevlistener = import_module('sympy.parsing.autolev._antlr.autolevlistener', import_kwargs={'fromlist': ['AutolevListener']}) AutolevParser = getattr(autolevparser, 'AutolevParser', None) AutolevLexer = getattr(autolevlexer, 'AutolevLexer', None) AutolevListener = getattr(autolevlistener, 'AutolevListener', None) def strfunc(z): if z == 0: return "" elif z == 1: return "_d" else: return "_" + "d" * z def declare_phy_entities(self, ctx, phy_type, i, j=None): if phy_type in ("frame", "newtonian"): declare_frames(self, ctx, i, j) elif phy_type == "particle": declare_particles(self, ctx, i, j) elif phy_type == "point": declare_points(self, ctx, i, j) elif phy_type == "bodies": declare_bodies(self, ctx, i, j) def declare_frames(self, ctx, i, j=None): if "{" in ctx.getText(): if j: name1 = ctx.ID().getText().lower() + str(i) + str(j) else: name1 = ctx.ID().getText().lower() + str(i) else: name1 = ctx.ID().getText().lower() name2 = "frame_" + name1 if self.getValue(ctx.parentCtx.varType()) == "newtonian": self.newtonian = name2 self.symbol_table2.update({name1: name2}) self.symbol_table.update({name1 + "1>": name2 + ".x"}) self.symbol_table.update({name1 + "2>": name2 + ".y"}) self.symbol_table.update({name1 + "3>": name2 + ".z"}) self.type2.update({name1: "frame"}) self.write(name2 + " = " + "_me.ReferenceFrame('" + name1 + "')\n") def declare_points(self, ctx, i, j=None): if "{" in ctx.getText(): if j: name1 = ctx.ID().getText().lower() + str(i) + str(j) else: name1 = ctx.ID().getText().lower() + str(i) else: name1 = ctx.ID().getText().lower() name2 = "point_" + name1 self.symbol_table2.update({name1: name2}) self.type2.update({name1: "point"}) self.write(name2 + " = " + "_me.Point('" + name1 + "')\n") def declare_particles(self, ctx, i, j=None): if "{" in ctx.getText(): if j: name1 = ctx.ID().getText().lower() + str(i) + str(j) else: name1 = ctx.ID().getText().lower() + str(i) else: name1 = ctx.ID().getText().lower() name2 = "particle_" + name1 self.symbol_table2.update({name1: name2}) self.type2.update({name1: "particle"}) self.bodies.update({name1: name2}) self.write(name2 + " = " + "_me.Particle('" + name1 + "', " + "_me.Point('" + name1 + "_pt" + "'), " + "_sm.Symbol('m'))\n") def declare_bodies(self, ctx, i, j=None): if "{" in ctx.getText(): if j: name1 = ctx.ID().getText().lower() + str(i) + str(j) else: name1 = ctx.ID().getText().lower() + str(i) else: name1 = ctx.ID().getText().lower() name2 = "body_" + name1 self.bodies.update({name1: name2}) masscenter = name2 + "_cm" refFrame = name2 + "_f" self.symbol_table2.update({name1: name2}) self.symbol_table2.update({name1 + "o": masscenter}) self.symbol_table.update({name1 + "1>": refFrame+".x"}) self.symbol_table.update({name1 + "2>": refFrame+".y"}) self.symbol_table.update({name1 + "3>": refFrame+".z"}) self.type2.update({name1: "bodies"}) self.type2.update({name1+"o": "point"}) self.write(masscenter + " = " + "_me.Point('" + name1 + "_cm" + "')\n") if self.newtonian: self.write(masscenter + ".set_vel(" + self.newtonian + ", " + "0)\n") self.write(refFrame + " = " + "_me.ReferenceFrame('" + name1 + "_f" + "')\n") # We set a dummy mass and inertia here. # They will be reset using the setters later in the code anyway. self.write(name2 + " = " + "_me.RigidBody('" + name1 + "', " + masscenter + ", " + refFrame + ", " + "_sm.symbols('m'), (_me.outer(" + refFrame + ".x," + refFrame + ".x)," + masscenter + "))\n") def inertia_func(self, v1, v2, l, frame): if self.type2[v1] == "particle": l.append("_me.inertia_of_point_mass(" + self.bodies[v1] + ".mass, " + self.bodies[v1] + ".point.pos_from(" + self.symbol_table2[v2] + "), " + frame + ")") elif self.type2[v1] == "bodies": # Inertia has been defined about center of mass. if self.inertia_point[v1] == v1 + "o": # Asking point is cm as well if v2 == self.inertia_point[v1]: l.append(self.symbol_table2[v1] + ".inertia[0]") # Asking point is not cm else: l.append(self.bodies[v1] + ".inertia[0]" + " + " + "_me.inertia_of_point_mass(" + self.bodies[v1] + ".mass, " + self.bodies[v1] + ".masscenter" + ".pos_from(" + self.symbol_table2[v2] + "), " + frame + ")") # Inertia has been defined about another point else: # Asking point is the defined point if v2 == self.inertia_point[v1]: l.append(self.symbol_table2[v1] + ".inertia[0]") # Asking point is cm elif v2 == v1 + "o": l.append(self.bodies[v1] + ".inertia[0]" + " - " + "_me.inertia_of_point_mass(" + self.bodies[v1] + ".mass, " + self.bodies[v1] + ".masscenter" + ".pos_from(" + self.symbol_table2[self.inertia_point[v1]] + "), " + frame + ")") # Asking point is some other point else: l.append(self.bodies[v1] + ".inertia[0]" + " - " + "_me.inertia_of_point_mass(" + self.bodies[v1] + ".mass, " + self.bodies[v1] + ".masscenter" + ".pos_from(" + self.symbol_table2[self.inertia_point[v1]] + "), " + frame + ")" + " + " + "_me.inertia_of_point_mass(" + self.bodies[v1] + ".mass, " + self.bodies[v1] + ".masscenter" + ".pos_from(" + self.symbol_table2[v2] + "), " + frame + ")") def processConstants(self, ctx): # Process constant declarations of the type: Constants F = 3, g = 9.81 name = ctx.ID().getText().lower() if "=" in ctx.getText(): self.symbol_table.update({name: name}) # self.inputs.update({self.symbol_table[name]: self.getValue(ctx.getChild(2))}) self.write(self.symbol_table[name] + " = " + "_sm.S(" + self.getValue(ctx.getChild(2)) + ")\n") self.type.update({name: "constants"}) return # Constants declarations of the type: Constants A, B else: if "{" not in ctx.getText(): self.symbol_table[name] = name self.type[name] = "constants" # Process constant declarations of the type: Constants C+, D- if ctx.getChildCount() == 2: # This is set for declaring nonpositive=True and nonnegative=True if ctx.getChild(1).getText() == "+": self.sign[name] = "+" elif ctx.getChild(1).getText() == "-": self.sign[name] = "-" else: if "{" not in ctx.getText(): self.sign[name] = "o" # Process constant declarations of the type: Constants K{4}, a{1:2, 1:2}, b{1:2} if "{" in ctx.getText(): if ":" in ctx.getText(): num1 = int(ctx.INT(0).getText()) num2 = int(ctx.INT(1).getText()) + 1 else: num1 = 1 num2 = int(ctx.INT(0).getText()) + 1 if ":" in ctx.getText(): if "," in ctx.getText(): num3 = int(ctx.INT(2).getText()) num4 = int(ctx.INT(3).getText()) + 1 for i in range(num1, num2): for j in range(num3, num4): self.symbol_table[name + str(i) + str(j)] = name + str(i) + str(j) self.type[name + str(i) + str(j)] = "constants" self.var_list.append(name + str(i) + str(j)) self.sign[name + str(i) + str(j)] = "o" else: for i in range(num1, num2): self.symbol_table[name + str(i)] = name + str(i) self.type[name + str(i)] = "constants" self.var_list.append(name + str(i)) self.sign[name + str(i)] = "o" elif "," in ctx.getText(): for i in range(1, int(ctx.INT(0).getText()) + 1): for j in range(1, int(ctx.INT(1).getText()) + 1): self.symbol_table[name] = name + str(i) + str(j) self.type[name + str(i) + str(j)] = "constants" self.var_list.append(name + str(i) + str(j)) self.sign[name + str(i) + str(j)] = "o" else: for i in range(num1, num2): self.symbol_table[name + str(i)] = name + str(i) self.type[name + str(i)] = "constants" self.var_list.append(name + str(i)) self.sign[name + str(i)] = "o" if "{" not in ctx.getText(): self.var_list.append(name) def writeConstants(self, ctx): l1 = list(filter(lambda x: self.sign[x] == "o", self.var_list)) l2 = list(filter(lambda x: self.sign[x] == "+", self.var_list)) l3 = list(filter(lambda x: self.sign[x] == "-", self.var_list)) try: if self.settings["complex"] == "on": real = ", real=True" elif self.settings["complex"] == "off": real = "" except Exception: real = ", real=True" if l1: a = ", ".join(l1) + " = " + "_sm.symbols(" + "'" +\ " ".join(l1) + "'" + real + ")\n" self.write(a) if l2: a = ", ".join(l2) + " = " + "_sm.symbols(" + "'" +\ " ".join(l2) + "'" + real + ", nonnegative=True)\n" self.write(a) if l3: a = ", ".join(l3) + " = " + "_sm.symbols(" + "'" + \ " ".join(l3) + "'" + real + ", nonpositive=True)\n" self.write(a) self.var_list = [] def processVariables(self, ctx): # Specified F = x*N1> + y*N2> name = ctx.ID().getText().lower() if "=" in ctx.getText(): text = name + "'"*(ctx.getChildCount()-3) self.write(text + " = " + self.getValue(ctx.expr()) + "\n") return # Process variables of the type: Variables qA, qB if ctx.getChildCount() == 1: self.symbol_table[name] = name if self.getValue(ctx.parentCtx.getChild(0)) in ("variable", "specified", "motionvariable", "motionvariable'"): self.type.update({name: self.getValue(ctx.parentCtx.getChild(0))}) self.var_list.append(name) self.sign[name] = 0 # Process variables of the type: Variables x', y'' elif "'" in ctx.getText() and "{" not in ctx.getText(): if ctx.getText().count("'") > self.maxDegree: self.maxDegree = ctx.getText().count("'") for i in range(ctx.getChildCount()): self.sign[name + strfunc(i)] = i self.symbol_table[name + "'"*i] = name + strfunc(i) if self.getValue(ctx.parentCtx.getChild(0)) in ("variable", "specified", "motionvariable", "motionvariable'"): self.type.update({name + "'"*i: self.getValue(ctx.parentCtx.getChild(0))}) self.var_list.append(name + strfunc(i)) elif "{" in ctx.getText(): # Process variables of the type: Variales x{3}, y{2} if "'" in ctx.getText(): dash_count = ctx.getText().count("'") if dash_count > self.maxDegree: self.maxDegree = dash_count if ":" in ctx.getText(): # Variables C{1:2, 1:2} if "," in ctx.getText(): num1 = int(ctx.INT(0).getText()) num2 = int(ctx.INT(1).getText()) + 1 num3 = int(ctx.INT(2).getText()) num4 = int(ctx.INT(3).getText()) + 1 # Variables C{1:2} else: num1 = int(ctx.INT(0).getText()) num2 = int(ctx.INT(1).getText()) + 1 # Variables C{1,3} elif "," in ctx.getText(): num1 = 1 num2 = int(ctx.INT(0).getText()) + 1 num3 = 1 num4 = int(ctx.INT(1).getText()) + 1 else: num1 = 1 num2 = int(ctx.INT(0).getText()) + 1 for i in range(num1, num2): try: for j in range(num3, num4): try: for z in range(dash_count+1): self.symbol_table.update({name + str(i) + str(j) + "'"*z: name + str(i) + str(j) + strfunc(z)}) if self.getValue(ctx.parentCtx.getChild(0)) in ("variable", "specified", "motionvariable", "motionvariable'"): self.type.update({name + str(i) + str(j) + "'"*z: self.getValue(ctx.parentCtx.getChild(0))}) self.var_list.append(name + str(i) + str(j) + strfunc(z)) self.sign.update({name + str(i) + str(j) + strfunc(z): z}) if dash_count > self.maxDegree: self.maxDegree = dash_count except Exception: self.symbol_table.update({name + str(i) + str(j): name + str(i) + str(j)}) if self.getValue(ctx.parentCtx.getChild(0)) in ("variable", "specified", "motionvariable", "motionvariable'"): self.type.update({name + str(i) + str(j): self.getValue(ctx.parentCtx.getChild(0))}) self.var_list.append(name + str(i) + str(j)) self.sign.update({name + str(i) + str(j): 0}) except Exception: try: for z in range(dash_count+1): self.symbol_table.update({name + str(i) + "'"*z: name + str(i) + strfunc(z)}) if self.getValue(ctx.parentCtx.getChild(0)) in ("variable", "specified", "motionvariable", "motionvariable'"): self.type.update({name + str(i) + "'"*z: self.getValue(ctx.parentCtx.getChild(0))}) self.var_list.append(name + str(i) + strfunc(z)) self.sign.update({name + str(i) + strfunc(z): z}) if dash_count > self.maxDegree: self.maxDegree = dash_count except Exception: self.symbol_table.update({name + str(i): name + str(i)}) if self.getValue(ctx.parentCtx.getChild(0)) in ("variable", "specified", "motionvariable", "motionvariable'"): self.type.update({name + str(i): self.getValue(ctx.parentCtx.getChild(0))}) self.var_list.append(name + str(i)) self.sign.update({name + str(i): 0}) def writeVariables(self, ctx): #print(self.sign) #print(self.symbol_table) if self.var_list: for i in range(self.maxDegree+1): if i == 0: j = "" t = "" else: j = str(i) t = ", " l = [] for k in list(filter(lambda x: self.sign[x] == i, self.var_list)): if i == 0: l.append(k) if i == 1: l.append(k[:-1]) if i > 1: l.append(k[:-2]) a = ", ".join(list(filter(lambda x: self.sign[x] == i, self.var_list))) + " = " +\ "_me.dynamicsymbols(" + "'" + " ".join(l) + "'" + t + j + ")\n" l = [] self.write(a) self.maxDegree = 0 self.var_list = [] def processImaginary(self, ctx): name = ctx.ID().getText().lower() self.symbol_table[name] = name self.type[name] = "imaginary" self.var_list.append(name) def writeImaginary(self, ctx): a = ", ".join(self.var_list) + " = " + "_sm.symbols(" + "'" + \ " ".join(self.var_list) + "')\n" b = ", ".join(self.var_list) + " = " + "_sm.I\n" self.write(a) self.write(b) self.var_list = [] if AutolevListener: class MyListener(AutolevListener): # type: ignore def __init__(self, include_numeric=False): # Stores data in tree nodes(tree annotation). Especially useful for expr reconstruction. self.tree_property = {} # Stores the declared variables, constants etc as they are declared in Autolev and SymPy # {"<Autolev symbol>": "<SymPy symbol>"}. self.symbol_table = collections.OrderedDict() # Similar to symbol_table. Used for storing Physical entities like Frames, Points, # Particles, Bodies etc self.symbol_table2 = collections.OrderedDict() # Used to store nonpositive, nonnegative etc for constants and number of "'"s (order of diff) # in variables. self.sign = {} # Simple list used as a store to pass around variables between the 'process' and 'write' # methods. self.var_list = [] # Stores the type of a declared variable (constants, variables, specifieds etc) self.type = collections.OrderedDict() # Similar to self.type. Used for storing the type of Physical entities like Frames, Points, # Particles, Bodies etc self.type2 = collections.OrderedDict() # These lists are used to distinguish matrix, numeric and vector expressions. self.matrix_expr = [] self.numeric_expr = [] self.vector_expr = [] self.fr_expr = [] self.output_code = [] # Stores the variables and their rhs for substituting upon the Autolev command EXPLICIT. self.explicit = collections.OrderedDict() # Write code to import common dependencies. self.output_code.append("import sympy.physics.mechanics as _me\n") self.output_code.append("import sympy as _sm\n") self.output_code.append("import math as m\n") self.output_code.append("import numpy as _np\n") self.output_code.append("\n") # Just a store for the max degree variable in a line. self.maxDegree = 0 # Stores the input parameters which are then used for codegen and numerical analysis. self.inputs = collections.OrderedDict() # Stores the variables which appear in Output Autolev commands. self.outputs = [] # Stores the settings specified by the user. Ex: Complex on/off, Degrees on/off self.settings = {} # Boolean which changes the behaviour of some expression reconstruction # when parsing Input Autolev commands. self.in_inputs = False self.in_outputs = False # Stores for the physical entities. self.newtonian = None self.bodies = collections.OrderedDict() self.constants = [] self.forces = collections.OrderedDict() self.q_ind = [] self.q_dep = [] self.u_ind = [] self.u_dep = [] self.kd_eqs = [] self.dependent_variables = [] self.kd_equivalents = collections.OrderedDict() self.kd_equivalents2 = collections.OrderedDict() self.kd_eqs_supplied = None self.kane_type = "no_args" self.inertia_point = collections.OrderedDict() self.kane_parsed = False self.t = False # PyDy ode code will be included only if this flag is set to True. self.include_numeric = include_numeric def write(self, string): self.output_code.append(string) def getValue(self, node): return self.tree_property[node] def setValue(self, node, value): self.tree_property[node] = value def getSymbolTable(self): return self.symbol_table def getType(self): return self.type def exitVarDecl(self, ctx): # This event method handles variable declarations. The parse tree node varDecl contains # one or more varDecl2 nodes. Eg varDecl for 'Constants a{1:2, 1:2}, b{1:2}' has two varDecl2 # nodes(one for a{1:2, 1:2} and one for b{1:2}). # Variable declarations are processed and stored in the event method exitVarDecl2. # This stored information is used to write the final SymPy output code in the exitVarDecl event method. # determine the type of declaration if self.getValue(ctx.varType()) == "constant": writeConstants(self, ctx) elif self.getValue(ctx.varType()) in\ ("variable", "motionvariable", "motionvariable'", "specified"): writeVariables(self, ctx) elif self.getValue(ctx.varType()) == "imaginary": writeImaginary(self, ctx) def exitVarType(self, ctx): # Annotate the varType tree node with the type of the variable declaration. name = ctx.getChild(0).getText().lower() if name[-1] == "s" and name != "bodies": self.setValue(ctx, name[:-1]) else: self.setValue(ctx, name) def exitVarDecl2(self, ctx): # Variable declarations are processed and stored in the event method exitVarDecl2. # This stored information is used to write the final SymPy output code in the exitVarDecl event method. # This is the case for constants, variables, specifieds etc. # This isn't the case for all types of declarations though. For instance # Frames A, B, C, N cannot be defined on one line in SymPy. So we do not append A, B, C, N # to a var_list or use exitVarDecl. exitVarDecl2 directly writes out to the file. # determine the type of declaration if self.getValue(ctx.parentCtx.varType()) == "constant": processConstants(self, ctx) elif self.getValue(ctx.parentCtx.varType()) in \ ("variable", "motionvariable", "motionvariable'", "specified"): processVariables(self, ctx) elif self.getValue(ctx.parentCtx.varType()) == "imaginary": processImaginary(self, ctx) elif self.getValue(ctx.parentCtx.varType()) in ("frame", "newtonian", "point", "particle", "bodies"): if "{" in ctx.getText(): if ":" in ctx.getText() and "," not in ctx.getText(): num1 = int(ctx.INT(0).getText()) num2 = int(ctx.INT(1).getText()) + 1 elif ":" not in ctx.getText() and "," in ctx.getText(): num1 = 1 num2 = int(ctx.INT(0).getText()) + 1 num3 = 1 num4 = int(ctx.INT(1).getText()) + 1 elif ":" in ctx.getText() and "," in ctx.getText(): num1 = int(ctx.INT(0).getText()) num2 = int(ctx.INT(1).getText()) + 1 num3 = int(ctx.INT(2).getText()) num4 = int(ctx.INT(3).getText()) + 1 else: num1 = 1 num2 = int(ctx.INT(0).getText()) + 1 else: num1 = 1 num2 = 2 for i in range(num1, num2): try: for j in range(num3, num4): declare_phy_entities(self, ctx, self.getValue(ctx.parentCtx.varType()), i, j) except Exception: declare_phy_entities(self, ctx, self.getValue(ctx.parentCtx.varType()), i) # ================== Subrules of parser rule expr (Start) ====================== # def exitId(self, ctx): # Tree annotation for ID which is a labeled subrule of the parser rule expr. # A_C python_keywords = ["and", "as", "assert", "break", "class", "continue", "def", "del", "elif", "else", "except",\ "exec", "finally", "for", "from", "global", "if", "import", "in", "is", "lambda", "not", "or", "pass", "print",\ "raise", "return", "try", "while", "with", "yield"] if ctx.ID().getText().lower() in python_keywords: warnings.warn("Python keywords must not be used as identifiers. Please refer to the list of keywords at https://docs.python.org/2.5/ref/keywords.html", SyntaxWarning) if "_" in ctx.ID().getText() and ctx.ID().getText().count('_') == 1: e1, e2 = ctx.ID().getText().lower().split('_') try: if self.type2[e1] == "frame": e1 = self.symbol_table2[e1] elif self.type2[e1] == "bodies": e1 = self.symbol_table2[e1] + "_f" if self.type2[e2] == "frame": e2 = self.symbol_table2[e2] elif self.type2[e2] == "bodies": e2 = self.symbol_table2[e2] + "_f" self.setValue(ctx, e1 + ".dcm(" + e2 + ")") except Exception: self.setValue(ctx, ctx.ID().getText().lower()) else: # Reserved constant Pi if ctx.ID().getText().lower() == "pi": self.setValue(ctx, "_sm.pi") self.numeric_expr.append(ctx) # Reserved variable T (for time) elif ctx.ID().getText().lower() == "t": self.setValue(ctx, "_me.dynamicsymbols._t") if not self.in_inputs and not self.in_outputs: self.t = True else: idText = ctx.ID().getText().lower() + "'"*(ctx.getChildCount() - 1) if idText in self.type.keys() and self.type[idText] == "matrix": self.matrix_expr.append(ctx) if self.in_inputs: try: self.setValue(ctx, self.symbol_table[idText]) except Exception: self.setValue(ctx, idText.lower()) else: try: self.setValue(ctx, self.symbol_table[idText]) except Exception: pass def exitInt(self, ctx): # Tree annotation for int which is a labeled subrule of the parser rule expr. int_text = ctx.INT().getText() self.setValue(ctx, int_text) self.numeric_expr.append(ctx) def exitFloat(self, ctx): # Tree annotation for float which is a labeled subrule of the parser rule expr. floatText = ctx.FLOAT().getText() self.setValue(ctx, floatText) self.numeric_expr.append(ctx) def exitAddSub(self, ctx): # Tree annotation for AddSub which is a labeled subrule of the parser rule expr. # The subrule is expr = expr (+|-) expr if ctx.expr(0) in self.matrix_expr or ctx.expr(1) in self.matrix_expr: self.matrix_expr.append(ctx) if ctx.expr(0) in self.vector_expr or ctx.expr(1) in self.vector_expr: self.vector_expr.append(ctx) if ctx.expr(0) in self.numeric_expr and ctx.expr(1) in self.numeric_expr: self.numeric_expr.append(ctx) self.setValue(ctx, self.getValue(ctx.expr(0)) + ctx.getChild(1).getText() + self.getValue(ctx.expr(1))) def exitMulDiv(self, ctx): # Tree annotation for MulDiv which is a labeled subrule of the parser rule expr. # The subrule is expr = expr (*|/) expr try: if ctx.expr(0) in self.vector_expr and ctx.expr(1) in self.vector_expr: self.setValue(ctx, "_me.outer(" + self.getValue(ctx.expr(0)) + ", " + self.getValue(ctx.expr(1)) + ")") else: if ctx.expr(0) in self.matrix_expr or ctx.expr(1) in self.matrix_expr: self.matrix_expr.append(ctx) if ctx.expr(0) in self.vector_expr or ctx.expr(1) in self.vector_expr: self.vector_expr.append(ctx) if ctx.expr(0) in self.numeric_expr and ctx.expr(1) in self.numeric_expr: self.numeric_expr.append(ctx) self.setValue(ctx, self.getValue(ctx.expr(0)) + ctx.getChild(1).getText() + self.getValue(ctx.expr(1))) except Exception: pass def exitNegativeOne(self, ctx): # Tree annotation for negativeOne which is a labeled subrule of the parser rule expr. self.setValue(ctx, "-1*" + self.getValue(ctx.getChild(1))) if ctx.getChild(1) in self.matrix_expr: self.matrix_expr.append(ctx) if ctx.getChild(1) in self.numeric_expr: self.numeric_expr.append(ctx) def exitParens(self, ctx): # Tree annotation for parens which is a labeled subrule of the parser rule expr. # The subrule is expr = '(' expr ')' if ctx.expr() in self.matrix_expr: self.matrix_expr.append(ctx) if ctx.expr() in self.vector_expr: self.vector_expr.append(ctx) if ctx.expr() in self.numeric_expr: self.numeric_expr.append(ctx) self.setValue(ctx, "(" + self.getValue(ctx.expr()) + ")") def exitExponent(self, ctx): # Tree annotation for Exponent which is a labeled subrule of the parser rule expr. # The subrule is expr = expr ^ expr if ctx.expr(0) in self.matrix_expr or ctx.expr(1) in self.matrix_expr: self.matrix_expr.append(ctx) if ctx.expr(0) in self.vector_expr or ctx.expr(1) in self.vector_expr: self.vector_expr.append(ctx) if ctx.expr(0) in self.numeric_expr and ctx.expr(1) in self.numeric_expr: self.numeric_expr.append(ctx) self.setValue(ctx, self.getValue(ctx.expr(0)) + "**" + self.getValue(ctx.expr(1))) def exitExp(self, ctx): s = ctx.EXP().getText()[ctx.EXP().getText().index('E')+1:] if "-" in s: s = s[0] + s[1:].lstrip("0") else: s = s.lstrip("0") self.setValue(ctx, ctx.EXP().getText()[:ctx.EXP().getText().index('E')] + "*10**(" + s + ")") def exitFunction(self, ctx): # Tree annotation for function which is a labeled subrule of the parser rule expr. # The difference between this and FunctionCall is that this is used for non standalone functions # appearing in expressions and assignments. # Eg: # When we come across a standalone function say Expand(E, n:m) then it is categorized as FunctionCall # which is a parser rule in itself under rule stat. exitFunctionCall() takes care of it and writes to the file. # # On the other hand, while we come across E_diff = D(E, y), we annotate the tree node # of the function D(E, y) with the SymPy equivalent in exitFunction(). # In this case it is the method exitAssignment() that writes the code to the file and not exitFunction(). ch = ctx.getChild(0) func_name = ch.getChild(0).getText().lower() # Expand(y, n:m) * if func_name == "expand": expr = self.getValue(ch.expr(0)) if ch.expr(0) in self.matrix_expr or (expr in self.type.keys() and self.type[expr] == "matrix"): self.matrix_expr.append(ctx) # _sm.Matrix([i.expand() for i in z]).reshape(z.shape[0], z.shape[1]) self.setValue(ctx, "_sm.Matrix([i.expand() for i in " + expr + "])" + ".reshape((" + expr + ").shape[0], " + "(" + expr + ").shape[1])") else: self.setValue(ctx, "(" + expr + ")" + "." + "expand()") # Factor(y, x) * elif func_name == "factor": expr = self.getValue(ch.expr(0)) if ch.expr(0) in self.matrix_expr or (expr in self.type.keys() and self.type[expr] == "matrix"): self.matrix_expr.append(ctx) self.setValue(ctx, "_sm.Matrix([_sm.factor(i, " + self.getValue(ch.expr(1)) + ") for i in " + expr + "])" + ".reshape((" + expr + ").shape[0], " + "(" + expr + ").shape[1])") else: self.setValue(ctx, "_sm.factor(" + "(" + expr + ")" + ", " + self.getValue(ch.expr(1)) + ")") # D(y, x) elif func_name == "d": expr = self.getValue(ch.expr(0)) if ch.expr(0) in self.matrix_expr or (expr in self.type.keys() and self.type[expr] == "matrix"): self.matrix_expr.append(ctx) self.setValue(ctx, "_sm.Matrix([i.diff(" + self.getValue(ch.expr(1)) + ") for i in " + expr + "])" + ".reshape((" + expr + ").shape[0], " + "(" + expr + ").shape[1])") else: if ch.getChildCount() == 8: frame = self.symbol_table2[ch.expr(2).getText().lower()] self.setValue(ctx, "(" + expr + ")" + "." + "diff(" + self.getValue(ch.expr(1)) + ", " + frame + ")") else: self.setValue(ctx, "(" + expr + ")" + "." + "diff(" + self.getValue(ch.expr(1)) + ")") # Dt(y) elif func_name == "dt": expr = self.getValue(ch.expr(0)) if ch.expr(0) in self.vector_expr: text = "dt(" else: text = "diff(_sm.Symbol('t')" if ch.expr(0) in self.matrix_expr or (expr in self.type.keys() and self.type[expr] == "matrix"): self.matrix_expr.append(ctx) self.setValue(ctx, "_sm.Matrix([i." + text + ") for i in " + expr + "])" + ".reshape((" + expr + ").shape[0], " + "(" + expr + ").shape[1])") else: if ch.getChildCount() == 6: frame = self.symbol_table2[ch.expr(1).getText().lower()] self.setValue(ctx, "(" + expr + ")" + "." + "dt(" + frame + ")") else: self.setValue(ctx, "(" + expr + ")" + "." + text + ")") # Explicit(EXPRESS(IMPLICIT>,C)) elif func_name == "explicit": if ch.expr(0) in self.vector_expr: self.vector_expr.append(ctx) expr = self.getValue(ch.expr(0)) if self.explicit.keys(): explicit_list = [] for i in self.explicit.keys(): explicit_list.append(i + ":" + self.explicit[i]) self.setValue(ctx, "(" + expr + ")" + ".subs({" + ", ".join(explicit_list) + "})") else: self.setValue(ctx, expr) # Taylor(y, 0:2, w=a, x=0) # TODO: Currently only works with symbols. Make it work for dynamicsymbols. elif func_name == "taylor": exp = self.getValue(ch.expr(0)) order = self.getValue(ch.expr(1).expr(1)) x = (ch.getChildCount()-6)//2 l = [] for i in range(x): index = 2 + i child = ch.expr(index) l.append(".series(" + self.getValue(child.getChild(0)) + ", " + self.getValue(child.getChild(2)) + ", " + order + ").removeO()") self.setValue(ctx, "(" + exp + ")" + "".join(l)) # Evaluate(y, a=x, b=2) elif func_name == "evaluate": expr = self.getValue(ch.expr(0)) l = [] x = (ch.getChildCount()-4)//2 for i in range(x): index = 1 + i child = ch.expr(index) l.append(self.getValue(child.getChild(0)) + ":" + self.getValue(child.getChild(2))) if ch.expr(0) in self.matrix_expr or (expr in self.type.keys() and self.type[expr] == "matrix"): self.matrix_expr.append(ctx) self.setValue(ctx, "_sm.Matrix([i.subs({" + ",".join(l) + "}) for i in " + expr + "])" + ".reshape((" + expr + ").shape[0], " + "(" + expr + ").shape[1])") else: if self.explicit: explicit_list = [] for i in self.explicit.keys(): explicit_list.append(i + ":" + self.explicit[i]) self.setValue(ctx, "(" + expr + ")" + ".subs({" + ",".join(explicit_list) + "}).subs({" + ",".join(l) + "})") else: self.setValue(ctx, "(" + expr + ")" + ".subs({" + ",".join(l) + "})") # Polynomial([a, b, c], x) elif func_name == "polynomial": self.setValue(ctx, "_sm.Poly(" + self.getValue(ch.expr(0)) + ", " + self.getValue(ch.expr(1)) + ")") # Roots(Poly, x, 2) # Roots([1; 2; 3; 4]) elif func_name == "roots": self.matrix_expr.append(ctx) expr = self.getValue(ch.expr(0)) if ch.expr(0) in self.matrix_expr or (expr in self.type.keys() and self.type[expr] == "matrix"): self.setValue(ctx, "[i.evalf() for i in " + "_sm.solve(" + "_sm.Poly(" + expr + ", " + "x),x)]") else: self.setValue(ctx, "[i.evalf() for i in " + "_sm.solve(" + expr + ", " + self.getValue(ch.expr(1)) + ")]") # Transpose(A), Inv(A) elif func_name in ("transpose", "inv", "inverse"): self.matrix_expr.append(ctx) if func_name == "transpose": e = ".T" elif func_name in ("inv", "inverse"): e = "**(-1)" self.setValue(ctx, "(" + self.getValue(ch.expr(0)) + ")" + e) # Eig(A) elif func_name == "eig": # "_sm.Matrix([i.evalf() for i in " + self.setValue(ctx, "_sm.Matrix([i.evalf() for i in (" + self.getValue(ch.expr(0)) + ").eigenvals().keys()])") # Diagmat(n, m, x) # Diagmat(3, 1) elif func_name == "diagmat": self.matrix_expr.append(ctx) if ch.getChildCount() == 6: l = [] for i in range(int(self.getValue(ch.expr(0)))): l.append(self.getValue(ch.expr(1)) + ",") self.setValue(ctx, "_sm.diag(" + ("".join(l))[:-1] + ")") elif ch.getChildCount() == 8: # _sm.Matrix([x if i==j else 0 for i in range(n) for j in range(m)]).reshape(n, m) n = self.getValue(ch.expr(0)) m = self.getValue(ch.expr(1)) x = self.getValue(ch.expr(2)) self.setValue(ctx, "_sm.Matrix([" + x + " if i==j else 0 for i in range(" + n + ") for j in range(" + m + ")]).reshape(" + n + ", " + m + ")") # Cols(A) # Cols(A, 1) # Cols(A, 1, 2:4, 3) elif func_name in ("cols", "rows"): self.matrix_expr.append(ctx) if func_name == "cols": e1 = ".cols" e2 = ".T." else: e1 = ".rows" e2 = "." if ch.getChildCount() == 4: self.setValue(ctx, "(" + self.getValue(ch.expr(0)) + ")" + e1) elif ch.getChildCount() == 6: self.setValue(ctx, "(" + self.getValue(ch.expr(0)) + ")" + e1[:-1] + "(" + str(int(self.getValue(ch.expr(1))) - 1) + ")") else: l = [] for i in range(4, ch.getChildCount()): try: if ch.getChild(i).getChildCount() > 1 and ch.getChild(i).getChild(1).getText() == ":": for j in range(int(ch.getChild(i).getChild(0).getText()), int(ch.getChild(i).getChild(2).getText())+1): l.append("(" + self.getValue(ch.getChild(2)) + ")" + e2 + "row(" + str(j-1) + ")") else: l.append("(" + self.getValue(ch.getChild(2)) + ")" + e2 + "row(" + str(int(ch.getChild(i).getText())-1) + ")") except Exception: pass self.setValue(ctx, "_sm.Matrix([" + ",".join(l) + "])") # Det(A) Trace(A) elif func_name in ["det", "trace"]: self.setValue(ctx, "(" + self.getValue(ch.expr(0)) + ")" + "." + func_name + "()") # Element(A, 2, 3) elif func_name == "element": self.setValue(ctx, "(" + self.getValue(ch.expr(0)) + ")" + "[" + str(int(self.getValue(ch.expr(1)))-1) + "," + str(int(self.getValue(ch.expr(2)))-1) + "]") elif func_name in \ ["cos", "sin", "tan", "cosh", "sinh", "tanh", "acos", "asin", "atan", "log", "exp", "sqrt", "factorial", "floor", "sign"]: self.setValue(ctx, "_sm." + func_name + "(" + self.getValue(ch.expr(0)) + ")") elif func_name == "ceil": self.setValue(ctx, "_sm.ceiling" + "(" + self.getValue(ch.expr(0)) + ")") elif func_name == "sqr": self.setValue(ctx, "(" + self.getValue(ch.expr(0)) + ")" + "**2") elif func_name == "log10": self.setValue(ctx, "_sm.log" + "(" + self.getValue(ch.expr(0)) + ", 10)") elif func_name == "atan2": self.setValue(ctx, "_sm.atan2" + "(" + self.getValue(ch.expr(0)) + ", " + self.getValue(ch.expr(1)) + ")") elif func_name in ["int", "round"]: self.setValue(ctx, func_name + "(" + self.getValue(ch.expr(0)) + ")") elif func_name == "abs": self.setValue(ctx, "_sm.Abs(" + self.getValue(ch.expr(0)) + ")") elif func_name in ["max", "min"]: # max(x, y, z) l = [] for i in range(1, ch.getChildCount()): if ch.getChild(i) in self.tree_property.keys(): l.append(self.getValue(ch.getChild(i))) elif ch.getChild(i).getText() in [",", "(", ")"]: l.append(ch.getChild(i).getText()) self.setValue(ctx, "_sm." + ch.getChild(0).getText().capitalize() + "".join(l)) # Coef(y, x) elif func_name == "coef": #A41_A53=COEF([RHS(U4);RHS(U5)],[U1,U2,U3]) if ch.expr(0) in self.matrix_expr and ch.expr(1) in self.matrix_expr: icount = jcount = 0 for i in range(ch.expr(0).getChild(0).getChildCount()): try: ch.expr(0).getChild(0).getChild(i).getRuleIndex() icount+=1 except Exception: pass for j in range(ch.expr(1).getChild(0).getChildCount()): try: ch.expr(1).getChild(0).getChild(j).getRuleIndex() jcount+=1 except Exception: pass l = [] for i in range(icount): for j in range(jcount): # a41_a53[i,j] = u4.expand().coeff(u1) l.append(self.getValue(ch.expr(0).getChild(0).expr(i)) + ".expand().coeff(" + self.getValue(ch.expr(1).getChild(0).expr(j)) + ")") self.setValue(ctx, "_sm.Matrix([" + ", ".join(l) + "]).reshape(" + str(icount) + ", " + str(jcount) + ")") else: self.setValue(ctx, "(" + self.getValue(ch.expr(0)) + ")" + ".expand().coeff(" + self.getValue(ch.expr(1)) + ")") # Exclude(y, x) Include(y, x) elif func_name in ("exclude", "include"): if func_name == "exclude": e = "0" else: e = "1" expr = self.getValue(ch.expr(0)) if ch.expr(0) in self.matrix_expr or (expr in self.type.keys() and self.type[expr] == "matrix"): self.matrix_expr.append(ctx) self.setValue(ctx, "_sm.Matrix([i.collect(" + self.getValue(ch.expr(1)) + "])" + ".coeff(" + self.getValue(ch.expr(1)) + "," + e + ")" + "for i in " + expr + ")" + ".reshape((" + expr + ").shape[0], " + "(" + expr + ").shape[1])") else: self.setValue(ctx, "(" + expr + ")" + ".collect(" + self.getValue(ch.expr(1)) + ")" + ".coeff(" + self.getValue(ch.expr(1)) + "," + e + ")") # RHS(y) elif func_name == "rhs": self.setValue(ctx, self.explicit[self.getValue(ch.expr(0))]) # Arrange(y, n, x) * elif func_name == "arrange": expr = self.getValue(ch.expr(0)) if ch.expr(0) in self.matrix_expr or (expr in self.type.keys() and self.type[expr] == "matrix"): self.matrix_expr.append(ctx) self.setValue(ctx, "_sm.Matrix([i.collect(" + self.getValue(ch.expr(2)) + ")" + "for i in " + expr + "])"+ ".reshape((" + expr + ").shape[0], " + "(" + expr + ").shape[1])") else: self.setValue(ctx, "(" + expr + ")" + ".collect(" + self.getValue(ch.expr(2)) + ")") # Replace(y, sin(x)=3) elif func_name == "replace": l = [] for i in range(1, ch.getChildCount()): try: if ch.getChild(i).getChild(1).getText() == "=": l.append(self.getValue(ch.getChild(i).getChild(0)) + ":" + self.getValue(ch.getChild(i).getChild(2))) except Exception: pass expr = self.getValue(ch.expr(0)) if ch.expr(0) in self.matrix_expr or (expr in self.type.keys() and self.type[expr] == "matrix"): self.matrix_expr.append(ctx) self.setValue(ctx, "_sm.Matrix([i.subs({" + ",".join(l) + "}) for i in " + expr + "])" + ".reshape((" + expr + ").shape[0], " + "(" + expr + ").shape[1])") else: self.setValue(ctx, "(" + self.getValue(ch.expr(0)) + ")" + ".subs({" + ",".join(l) + "})") # Dot(Loop>, N1>) elif func_name == "dot": l = [] num = (ch.expr(1).getChild(0).getChildCount()-1)//2 if ch.expr(1) in self.matrix_expr: for i in range(num): l.append("_me.dot(" + self.getValue(ch.expr(0)) + ", " + self.getValue(ch.expr(1).getChild(0).expr(i)) + ")") self.setValue(ctx, "_sm.Matrix([" + ",".join(l) + "]).reshape(" + str(num) + ", " + "1)") else: self.setValue(ctx, "_me.dot(" + self.getValue(ch.expr(0)) + ", " + self.getValue(ch.expr(1)) + ")") # Cross(w_A_N>, P_NA_AB>) elif func_name == "cross": self.vector_expr.append(ctx) self.setValue(ctx, "_me.cross(" + self.getValue(ch.expr(0)) + ", " + self.getValue(ch.expr(1)) + ")") # Mag(P_O_Q>) elif func_name == "mag": self.setValue(ctx, self.getValue(ch.expr(0)) + "." + "magnitude()") # MATRIX(A, I_R>>) elif func_name == "matrix": if self.type2[ch.expr(0).getText().lower()] == "frame": text = "" elif self.type2[ch.expr(0).getText().lower()] == "bodies": text = "_f" self.setValue(ctx, "(" + self.getValue(ch.expr(1)) + ")" + ".to_matrix(" + self.symbol_table2[ch.expr(0).getText().lower()] + text + ")") # VECTOR(A, ROWS(EIGVECS,1)) elif func_name == "vector": if self.type2[ch.expr(0).getText().lower()] == "frame": text = "" elif self.type2[ch.expr(0).getText().lower()] == "bodies": text = "_f" v = self.getValue(ch.expr(1)) f = self.symbol_table2[ch.expr(0).getText().lower()] + text self.setValue(ctx, v + "[0]*" + f + ".x +" + v + "[1]*" + f + ".y +" + v + "[2]*" + f + ".z") # Express(A2>, B) # Here I am dealing with all the Inertia commands as I expect the users to use Inertia # commands only with Express because SymPy needs the Reference frame to be specified unlike Autolev. elif func_name == "express": self.vector_expr.append(ctx) if self.type2[ch.expr(1).getText().lower()] == "frame": frame = self.symbol_table2[ch.expr(1).getText().lower()] else: frame = self.symbol_table2[ch.expr(1).getText().lower()] + "_f" if ch.expr(0).getText().lower() == "1>>": self.setValue(ctx, "_me.inertia(" + frame + ", 1, 1, 1)") elif '_' in ch.expr(0).getText().lower() and ch.expr(0).getText().lower().count('_') == 2\ and ch.expr(0).getText().lower()[0] == "i" and ch.expr(0).getText().lower()[-2:] == ">>": v1 = ch.expr(0).getText().lower()[:-2].split('_')[1] v2 = ch.expr(0).getText().lower()[:-2].split('_')[2] l = [] inertia_func(self, v1, v2, l, frame) self.setValue(ctx, " + ".join(l)) elif ch.expr(0).getChild(0).getChild(0).getText().lower() == "inertia": if ch.expr(0).getChild(0).getChildCount() == 4: l = [] v2 = ch.expr(0).getChild(0).ID(0).getText().lower() for v1 in self.bodies: inertia_func(self, v1, v2, l, frame) self.setValue(ctx, " + ".join(l)) else: l = [] l2 = [] v2 = ch.expr(0).getChild(0).ID(0).getText().lower() for i in range(1, (ch.expr(0).getChild(0).getChildCount()-2)//2): l2.append(ch.expr(0).getChild(0).ID(i).getText().lower()) for v1 in l2: inertia_func(self, v1, v2, l, frame) self.setValue(ctx, " + ".join(l)) else: self.setValue(ctx, "(" + self.getValue(ch.expr(0)) + ")" + ".express(" + self.symbol_table2[ch.expr(1).getText().lower()] + ")") # CM(P) elif func_name == "cm": if self.type2[ch.expr(0).getText().lower()] == "point": text = "" else: text = ".point" if ch.getChildCount() == 4: self.setValue(ctx, "_me.functions.center_of_mass(" + self.symbol_table2[ch.expr(0).getText().lower()] + text + "," + ", ".join(self.bodies.values()) + ")") else: bodies = [] for i in range(1, (ch.getChildCount()-1)//2): bodies.append(self.symbol_table2[ch.expr(i).getText().lower()]) self.setValue(ctx, "_me.functions.center_of_mass(" + self.symbol_table2[ch.expr(0).getText().lower()] + text + "," + ", ".join(bodies) + ")") # PARTIALS(V_P1_E>,U1) elif func_name == "partials": speeds = [] for i in range(1, (ch.getChildCount()-1)//2): if self.kd_equivalents2: speeds.append(self.kd_equivalents2[self.symbol_table[ch.expr(i).getText().lower()]]) else: speeds.append(self.symbol_table[ch.expr(i).getText().lower()]) v1, v2, v3 = ch.expr(0).getText().lower().replace(">","").split('_') if self.type2[v2] == "point": point = self.symbol_table2[v2] elif self.type2[v2] == "particle": point = self.symbol_table2[v2] + ".point" frame = self.symbol_table2[v3] self.setValue(ctx, point + ".partial_velocity(" + frame + ", " + ",".join(speeds) + ")") # UnitVec(A1>+A2>+A3>) elif func_name == "unitvec": self.setValue(ctx, "(" + self.getValue(ch.expr(0)) + ")" + ".normalize()") # Units(deg, rad) elif func_name == "units": if ch.expr(0).getText().lower() == "deg" and ch.expr(1).getText().lower() == "rad": factor = 0.0174533 elif ch.expr(0).getText().lower() == "rad" and ch.expr(1).getText().lower() == "deg": factor = 57.2958 self.setValue(ctx, str(factor)) # Mass(A) elif func_name == "mass": l = [] try: ch.ID(0).getText().lower() for i in range((ch.getChildCount()-1)//2): l.append(self.symbol_table2[ch.ID(i).getText().lower()] + ".mass") self.setValue(ctx, "+".join(l)) except Exception: for i in self.bodies.keys(): l.append(self.bodies[i] + ".mass") self.setValue(ctx, "+".join(l)) # Fr() FrStar() # _me.KanesMethod(n, q_ind, u_ind, kd, velocity_constraints).kanes_equations(pl, fl)[0] elif func_name in ["fr", "frstar"]: if not self.kane_parsed: if self.kd_eqs: for i in self.kd_eqs: self.q_ind.append(self.symbol_table[i.strip().split('-')[0].replace("'","")]) self.u_ind.append(self.symbol_table[i.strip().split('-')[1].replace("'","")]) for i in range(len(self.kd_eqs)): self.kd_eqs[i] = self.symbol_table[self.kd_eqs[i].strip().split('-')[0]] + " - " +\ self.symbol_table[self.kd_eqs[i].strip().split('-')[1]] # Do all of this if kd_eqs are not specified if not self.kd_eqs: self.kd_eqs_supplied = False self.matrix_expr.append(ctx) for i in self.type.keys(): if self.type[i] == "motionvariable": if self.sign[self.symbol_table[i.lower()]] == 0: self.q_ind.append(self.symbol_table[i.lower()]) elif self.sign[self.symbol_table[i.lower()]] == 1: name = "u_" + self.symbol_table[i.lower()] self.symbol_table.update({name: name}) self.write(name + " = " + "_me.dynamicsymbols('" + name + "')\n") if self.symbol_table[i.lower()] not in self.dependent_variables: self.u_ind.append(name) self.kd_equivalents.update({name: self.symbol_table[i.lower()]}) else: self.u_dep.append(name) self.kd_equivalents.update({name: self.symbol_table[i.lower()]}) for i in self.kd_equivalents.keys(): self.kd_eqs.append(self.kd_equivalents[i] + "-" + i) if not self.u_ind and not self.kd_eqs: self.u_ind = self.q_ind.copy() self.q_ind = [] # deal with velocity constraints if self.dependent_variables: for i in self.dependent_variables: self.u_dep.append(i) if i in self.u_ind: self.u_ind.remove(i) self.u_dep[:] = [i for i in self.u_dep if i not in self.kd_equivalents.values()] force_list = [] for i in self.forces.keys(): force_list.append("(" + i + "," + self.forces[i] + ")") if self.u_dep: u_dep_text = ", u_dependent=[" + ", ".join(self.u_dep) + "]" else: u_dep_text = "" if self.dependent_variables: velocity_constraints_text = ", velocity_constraints = velocity_constraints" else: velocity_constraints_text = "" if ctx.parentCtx not in self.fr_expr: self.write("kd_eqs = [" + ", ".join(self.kd_eqs) + "]\n") self.write("forceList = " + "[" + ", ".join(force_list) + "]\n") self.write("kane = _me.KanesMethod(" + self.newtonian + ", " + "q_ind=[" + ",".join(self.q_ind) + "], " + "u_ind=[" + ", ".join(self.u_ind) + "]" + u_dep_text + ", " + "kd_eqs = kd_eqs" + velocity_constraints_text + ")\n") self.write("fr, frstar = kane." + "kanes_equations([" + ", ".join(self.bodies.values()) + "], forceList)\n") self.fr_expr.append(ctx.parentCtx) self.kane_parsed = True self.setValue(ctx, func_name) def exitMatrices(self, ctx): # Tree annotation for Matrices which is a labeled subrule of the parser rule expr. # MO = [a, b; c, d] # we generate _sm.Matrix([a, b, c, d]).reshape(2, 2) # The reshape values are determined by counting the "," and ";" in the Autolev matrix # Eg: # [1, 2, 3; 4, 5, 6; 7, 8, 9; 10, 11, 12] # semicolon_count = 3 and rows = 3+1 = 4 # comma_count = 8 and cols = 8/rows + 1 = 8/4 + 1 = 3 # TODO** Parse block matrices self.matrix_expr.append(ctx) l = [] semicolon_count = 0 comma_count = 0 for i in range(ctx.matrix().getChildCount()): child = ctx.matrix().getChild(i) if child == AutolevParser.ExprContext: l.append(self.getValue(child)) elif child.getText() == ";": semicolon_count += 1 l.append(",") elif child.getText() == ",": comma_count += 1 l.append(",") else: try: try: l.append(self.getValue(child)) except Exception: l.append(self.symbol_table[child.getText().lower()]) except Exception: l.append(child.getText().lower()) num_of_rows = semicolon_count + 1 num_of_cols = (comma_count//num_of_rows) + 1 self.setValue(ctx, "_sm.Matrix(" + "".join(l) + ")" + ".reshape(" + str(num_of_rows) + ", " + str(num_of_cols) + ")") def exitVectorOrDyadic(self, ctx): self.vector_expr.append(ctx) ch = ctx.vec() if ch.getChild(0).getText() == "0>": self.setValue(ctx, "0") elif ch.getChild(0).getText() == "1>>": self.setValue(ctx, "1>>") elif "_" in ch.ID().getText() and ch.ID().getText().count('_') == 2: vec_text = ch.getText().lower() v1, v2, v3 = ch.ID().getText().lower().split('_') if v1 == "p": if self.type2[v2] == "point": e2 = self.symbol_table2[v2] elif self.type2[v2] == "particle": e2 = self.symbol_table2[v2] + ".point" if self.type2[v3] == "point": e3 = self.symbol_table2[v3] elif self.type2[v3] == "particle": e3 = self.symbol_table2[v3] + ".point" get_vec = e3 + ".pos_from(" + e2 + ")" self.setValue(ctx, get_vec) elif v1 in ("w", "alf"): if v1 == "w": text = ".ang_vel_in(" elif v1 == "alf": text = ".ang_acc_in(" if self.type2[v2] == "bodies": e2 = self.symbol_table2[v2] + "_f" elif self.type2[v2] == "frame": e2 = self.symbol_table2[v2] if self.type2[v3] == "bodies": e3 = self.symbol_table2[v3] + "_f" elif self.type2[v3] == "frame": e3 = self.symbol_table2[v3] get_vec = e2 + text + e3 + ")" self.setValue(ctx, get_vec) elif v1 in ("v", "a"): if v1 == "v": text = ".vel(" elif v1 == "a": text = ".acc(" if self.type2[v2] == "point": e2 = self.symbol_table2[v2] elif self.type2[v2] == "particle": e2 = self.symbol_table2[v2] + ".point" get_vec = e2 + text + self.symbol_table2[v3] + ")" self.setValue(ctx, get_vec) else: self.setValue(ctx, vec_text.replace(">", "")) else: vec_text = ch.getText().lower() name = self.symbol_table[vec_text] self.setValue(ctx, name) def exitIndexing(self, ctx): if ctx.getChildCount() == 4: try: int_text = str(int(self.getValue(ctx.getChild(2))) - 1) except Exception: int_text = self.getValue(ctx.getChild(2)) + " - 1" self.setValue(ctx, ctx.ID().getText().lower() + "[" + int_text + "]") elif ctx.getChildCount() == 6: try: int_text1 = str(int(self.getValue(ctx.getChild(2))) - 1) except Exception: int_text1 = self.getValue(ctx.getChild(2)) + " - 1" try: int_text2 = str(int(self.getValue(ctx.getChild(4))) - 1) except Exception: int_text2 = self.getValue(ctx.getChild(2)) + " - 1" self.setValue(ctx, ctx.ID().getText().lower() + "[" + int_text1 + ", " + int_text2 + "]") # ================== Subrules of parser rule expr (End) ====================== # def exitRegularAssign(self, ctx): # Handle assignments of type ID = expr if ctx.equals().getText() in ["=", "+=", "-=", "*=", "/="]: equals = ctx.equals().getText() elif ctx.equals().getText() == ":=": equals = " = " elif ctx.equals().getText() == "^=": equals = "**=" try: a = ctx.ID().getText().lower() + "'"*ctx.diff().getText().count("'") except Exception: a = ctx.ID().getText().lower() if a in self.type.keys() and self.type[a] in ("motionvariable", "motionvariable'") and\ self.type[ctx.expr().getText().lower()] in ("motionvariable", "motionvariable'"): b = ctx.expr().getText().lower() if "'" in b and "'" not in a: a, b = b, a if not self.kane_parsed: self.kd_eqs.append(a + "-" + b) self.kd_equivalents.update({self.symbol_table[a]: self.symbol_table[b]}) self.kd_equivalents2.update({self.symbol_table[b]: self.symbol_table[a]}) if a in self.symbol_table.keys() and a in self.type.keys() and self.type[a] in ("variable", "motionvariable"): self.explicit.update({self.symbol_table[a]: self.getValue(ctx.expr())}) else: if ctx.expr() in self.matrix_expr: self.type.update({a: "matrix"}) try: b = self.symbol_table[a] except KeyError: self.symbol_table[a] = a if "_" in a and a.count("_") == 1: e1, e2 = a.split('_') if e1 in self.type2.keys() and self.type2[e1] in ("frame", "bodies")\ and e2 in self.type2.keys() and self.type2[e2] in ("frame", "bodies"): if self.type2[e1] == "bodies": t1 = "_f" else: t1 = "" if self.type2[e2] == "bodies": t2 = "_f" else: t2 = "" self.write(self.symbol_table2[e2] + t2 + ".orient(" + self.symbol_table2[e1] + t1 + ", 'DCM', " + self.getValue(ctx.expr()) + ")\n") else: self.write(self.symbol_table[a] + " " + equals + " " + self.getValue(ctx.expr()) + "\n") else: self.write(self.symbol_table[a] + " " + equals + " " + self.getValue(ctx.expr()) + "\n") def exitIndexAssign(self, ctx): # Handle assignments of type ID[index] = expr if ctx.equals().getText() in ["=", "+=", "-=", "*=", "/="]: equals = ctx.equals().getText() elif ctx.equals().getText() == ":=": equals = " = " elif ctx.equals().getText() == "^=": equals = "**=" text = ctx.ID().getText().lower() self.type.update({text: "matrix"}) # Handle assignments of type ID[2] = expr if ctx.index().getChildCount() == 1: if ctx.index().getChild(0).getText() == "1": self.type.update({text: "matrix"}) self.symbol_table.update({text: text}) self.write(text + " = " + "_sm.Matrix([[0]])\n") self.write(text + "[0] = " + self.getValue(ctx.expr()) + "\n") else: # m = m.row_insert(m.shape[0], _sm.Matrix([[0]])) self.write(text + " = " + text + ".row_insert(" + text + ".shape[0]" + ", " + "_sm.Matrix([[0]])" + ")\n") self.write(text + "[" + text + ".shape[0]-1" + "] = " + self.getValue(ctx.expr()) + "\n") # Handle assignments of type ID[2, 2] = expr elif ctx.index().getChildCount() == 3: l = [] try: l.append(str(int(self.getValue(ctx.index().getChild(0)))-1)) except Exception: l.append(self.getValue(ctx.index().getChild(0)) + "-1") l.append(",") try: l.append(str(int(self.getValue(ctx.index().getChild(2)))-1)) except Exception: l.append(self.getValue(ctx.index().getChild(2)) + "-1") self.write(self.symbol_table[ctx.ID().getText().lower()] + "[" + "".join(l) + "]" + " " + equals + " " + self.getValue(ctx.expr()) + "\n") def exitVecAssign(self, ctx): # Handle assignments of the type vec = expr ch = ctx.vec() vec_text = ch.getText().lower() if "_" in ch.ID().getText(): num = ch.ID().getText().count('_') if num == 2: v1, v2, v3 = ch.ID().getText().lower().split('_') if v1 == "p": if self.type2[v2] == "point": e2 = self.symbol_table2[v2] elif self.type2[v2] == "particle": e2 = self.symbol_table2[v2] + ".point" if self.type2[v3] == "point": e3 = self.symbol_table2[v3] elif self.type2[v3] == "particle": e3 = self.symbol_table2[v3] + ".point" # ab.set_pos(na, la*a.x) self.write(e3 + ".set_pos(" + e2 + ", " + self.getValue(ctx.expr()) + ")\n") elif v1 in ("w", "alf"): if v1 == "w": text = ".set_ang_vel(" elif v1 == "alf": text = ".set_ang_acc(" # a.set_ang_vel(n, qad*a.z) if self.type2[v2] == "bodies": e2 = self.symbol_table2[v2] + "_f" else: e2 = self.symbol_table2[v2] if self.type2[v3] == "bodies": e3 = self.symbol_table2[v3] + "_f" else: e3 = self.symbol_table2[v3] self.write(e2 + text + e3 + ", " + self.getValue(ctx.expr()) + ")\n") elif v1 in ("v", "a"): if v1 == "v": text = ".set_vel(" elif v1 == "a": text = ".set_acc(" if self.type2[v2] == "point": e2 = self.symbol_table2[v2] elif self.type2[v2] == "particle": e2 = self.symbol_table2[v2] + ".point" self.write(e2 + text + self.symbol_table2[v3] + ", " + self.getValue(ctx.expr()) + ")\n") elif v1 == "i": if v2 in self.type2.keys() and self.type2[v2] == "bodies": self.write(self.symbol_table2[v2] + ".inertia = (" + self.getValue(ctx.expr()) + ", " + self.symbol_table2[v3] + ")\n") self.inertia_point.update({v2: v3}) elif v2 in self.type2.keys() and self.type2[v2] == "particle": self.write(ch.ID().getText().lower() + " = " + self.getValue(ctx.expr()) + "\n") else: self.write(ch.ID().getText().lower() + " = " + self.getValue(ctx.expr()) + "\n") else: self.write(ch.ID().getText().lower() + " = " + self.getValue(ctx.expr()) + "\n") elif num == 1: v1, v2 = ch.ID().getText().lower().split('_') if v1 in ("force", "torque"): if self.type2[v2] in ("point", "frame"): e2 = self.symbol_table2[v2] elif self.type2[v2] == "particle": e2 = self.symbol_table2[v2] + ".point" self.symbol_table.update({vec_text: ch.ID().getText().lower()}) if e2 in self.forces.keys(): self.forces[e2] = self.forces[e2] + " + " + self.getValue(ctx.expr()) else: self.forces.update({e2: self.getValue(ctx.expr())}) self.write(ch.ID().getText().lower() + " = " + self.forces[e2] + "\n") else: name = ch.ID().getText().lower() self.symbol_table.update({vec_text: name}) self.write(ch.ID().getText().lower() + " = " + self.getValue(ctx.expr()) + "\n") else: name = ch.ID().getText().lower() self.symbol_table.update({vec_text: name}) self.write(name + " " + ctx.getChild(1).getText() + " " + self.getValue(ctx.expr()) + "\n") else: name = ch.ID().getText().lower() self.symbol_table.update({vec_text: name}) self.write(name + " " + ctx.getChild(1).getText() + " " + self.getValue(ctx.expr()) + "\n") def enterInputs2(self, ctx): self.in_inputs = True # Inputs def exitInputs2(self, ctx): # Stores numerical values given by the input command which # are used for codegen and numerical analysis. if ctx.getChildCount() == 3: try: self.inputs.update({self.symbol_table[ctx.id_diff().getText().lower()]: self.getValue(ctx.expr(0))}) except Exception: self.inputs.update({ctx.id_diff().getText().lower(): self.getValue(ctx.expr(0))}) elif ctx.getChildCount() == 4: try: self.inputs.update({self.symbol_table[ctx.id_diff().getText().lower()]: (self.getValue(ctx.expr(0)), self.getValue(ctx.expr(1)))}) except Exception: self.inputs.update({ctx.id_diff().getText().lower(): (self.getValue(ctx.expr(0)), self.getValue(ctx.expr(1)))}) self.in_inputs = False def enterOutputs(self, ctx): self.in_outputs = True def exitOutputs(self, ctx): self.in_outputs = False def exitOutputs2(self, ctx): try: if "[" in ctx.expr(1).getText(): self.outputs.append(self.symbol_table[ctx.expr(0).getText().lower()] + ctx.expr(1).getText().lower()) else: self.outputs.append(self.symbol_table[ctx.expr(0).getText().lower()]) except Exception: pass # Code commands def exitCodegen(self, ctx): # Handles the CODE() command ie the solvers and the codgen part. # Uses linsolve for the algebraic solvers and nsolve for non linear solvers. if ctx.functionCall().getChild(0).getText().lower() == "algebraic": matrix_name = self.getValue(ctx.functionCall().expr(0)) e = [] d = [] for i in range(1, (ctx.functionCall().getChildCount()-2)//2): a = self.getValue(ctx.functionCall().expr(i)) e.append(a) for i in self.inputs.keys(): d.append(i + ":" + self.inputs[i]) self.write(matrix_name + "_list" + " = " + "[]\n") self.write("for i in " + matrix_name + ": " + matrix_name + "_list" + ".append(i.subs({" + ", ".join(d) + "}))\n") self.write("print(_sm.linsolve(" + matrix_name + "_list" + ", " + ",".join(e) + "))\n") elif ctx.functionCall().getChild(0).getText().lower() == "nonlinear": e = [] d = [] guess = [] for i in range(1, (ctx.functionCall().getChildCount()-2)//2): a = self.getValue(ctx.functionCall().expr(i)) e.append(a) #print(self.inputs) for i in self.inputs.keys(): if i in self.symbol_table.keys(): if type(self.inputs[i]) is tuple: j, z = self.inputs[i] else: j = self.inputs[i] z = "" if i not in e: if z == "deg": d.append(i + ":" + "_np.deg2rad(" + j + ")") else: d.append(i + ":" + j) else: if z == "deg": guess.append("_np.deg2rad(" + j + ")") else: guess.append(j) self.write("matrix_list" + " = " + "[]\n") self.write("for i in " + self.getValue(ctx.functionCall().expr(0)) + ":") self.write("matrix_list" + ".append(i.subs({" + ", ".join(d) + "}))\n") self.write("print(_sm.nsolve(matrix_list," + "(" + ",".join(e) + ")" + ",(" + ",".join(guess) + ")" + "))\n") elif ctx.functionCall().getChild(0).getText().lower() in ["ode", "dynamics"] and self.include_numeric: if self.kane_type == "no_args": for i in self.symbol_table.keys(): try: if self.type[i] == "constants" or self.type[self.symbol_table[i]] == "constants": self.constants.append(self.symbol_table[i]) except Exception: pass q_add_u = self.q_ind + self.q_dep + self.u_ind + self.u_dep x0 = [] for i in q_add_u: try: if i in self.inputs.keys(): if type(self.inputs[i]) is tuple: if self.inputs[i][1] == "deg": x0.append(i + ":" + "_np.deg2rad(" + self.inputs[i][0] + ")") else: x0.append(i + ":" + self.inputs[i][0]) else: x0.append(i + ":" + self.inputs[i]) elif self.kd_equivalents[i] in self.inputs.keys(): if type(self.inputs[self.kd_equivalents[i]]) is tuple: x0.append(i + ":" + self.inputs[self.kd_equivalents[i]][0]) else: x0.append(i + ":" + self.inputs[self.kd_equivalents[i]]) except Exception: pass # numerical constants numerical_constants = [] for i in self.constants: if i in self.inputs.keys(): if type(self.inputs[i]) is tuple: numerical_constants.append(self.inputs[i][0]) else: numerical_constants.append(self.inputs[i]) # t = linspace t_final = self.inputs["tfinal"] integ_stp = self.inputs["integstp"] self.write("from pydy.system import System\n") const_list = [] if numerical_constants: for i in range(len(self.constants)): const_list.append(self.constants[i] + ":" + numerical_constants[i]) specifieds = [] if self.t: specifieds.append("_me.dynamicsymbols('t')" + ":" + "lambda x, t: t") for i in self.inputs: if i in self.symbol_table.keys() and self.symbol_table[i] not in\ self.constants + self.q_ind + self.q_dep + self.u_ind + self.u_dep: specifieds.append(self.symbol_table[i] + ":" + self.inputs[i]) self.write("sys = System(kane, constants = {" + ", ".join(const_list) + "},\n" + "specifieds={" + ", ".join(specifieds) + "},\n" + "initial_conditions={" + ", ".join(x0) + "},\n" + "times = _np.linspace(0.0, " + str(t_final) + ", " + str(t_final) + "/" + str(integ_stp) + "))\n\ny=sys.integrate()\n") # For outputs other than qs and us. other_outputs = [] for i in self.outputs: if i not in q_add_u: if "[" in i: other_outputs.append((i[:-3] + i[-2], i[:-3] + "[" + str(int(i[-2])-1) + "]")) else: other_outputs.append((i, i)) for i in other_outputs: self.write(i[0] + "_out" + " = " + "[]\n") if other_outputs: self.write("for i in y:\n") self.write(" q_u_dict = dict(zip(sys.coordinates+sys.speeds, i))\n") for i in other_outputs: self.write(" "*4 + i[0] + "_out" + ".append(" + i[1] + ".subs(q_u_dict)" + ".subs(sys.constants).evalf())\n") # Standalone function calls (used for dual functions) def exitFunctionCall(self, ctx): # Basically deals with standalone function calls ie functions which are not a part of # expressions and assignments. Autolev Dual functions can both appear in standalone # function calls and also on the right hand side as part of expr or assignment. # Dual functions are indicated by a * in the comments below # Checks if the function is a statement on its own if ctx.parentCtx.getRuleIndex() == AutolevParser.RULE_stat: func_name = ctx.getChild(0).getText().lower() # Expand(E, n:m) * if func_name == "expand": # If the first argument is a pre declared variable. expr = self.getValue(ctx.expr(0)) symbol = self.symbol_table[ctx.expr(0).getText().lower()] if ctx.expr(0) in self.matrix_expr or (expr in self.type.keys() and self.type[expr] == "matrix"): self.write(symbol + " = " + "_sm.Matrix([i.expand() for i in " + expr + "])" + ".reshape((" + expr + ").shape[0], " + "(" + expr + ").shape[1])\n") else: self.write(symbol + " = " + symbol + "." + "expand()\n") # Factor(E, x) * elif func_name == "factor": expr = self.getValue(ctx.expr(0)) symbol = self.symbol_table[ctx.expr(0).getText().lower()] if ctx.expr(0) in self.matrix_expr or (expr in self.type.keys() and self.type[expr] == "matrix"): self.write(symbol + " = " + "_sm.Matrix([_sm.factor(i," + self.getValue(ctx.expr(1)) + ") for i in " + expr + "])" + ".reshape((" + expr + ").shape[0], " + "(" + expr + ").shape[1])\n") else: self.write(expr + " = " + "_sm.factor(" + expr + ", " + self.getValue(ctx.expr(1)) + ")\n") # Solve(Zero, x, y) elif func_name == "solve": l = [] l2 = [] num = 0 for i in range(1, ctx.getChildCount()): if ctx.getChild(i).getText() == ",": num+=1 try: l.append(self.getValue(ctx.getChild(i))) except Exception: l.append(ctx.getChild(i).getText()) if i != 2: try: l2.append(self.getValue(ctx.getChild(i))) except Exception: pass for i in l2: self.explicit.update({i: "_sm.solve" + "".join(l) + "[" + i + "]"}) self.write("print(_sm.solve" + "".join(l) + ")\n") # Arrange(y, n, x) * elif func_name == "arrange": expr = self.getValue(ctx.expr(0)) symbol = self.symbol_table[ctx.expr(0).getText().lower()] if ctx.expr(0) in self.matrix_expr or (expr in self.type.keys() and self.type[expr] == "matrix"): self.write(symbol + " = " + "_sm.Matrix([i.collect(" + self.getValue(ctx.expr(2)) + ")" + "for i in " + expr + "])" + ".reshape((" + expr + ").shape[0], " + "(" + expr + ").shape[1])\n") else: self.write(self.getValue(ctx.expr(0)) + ".collect(" + self.getValue(ctx.expr(2)) + ")\n") # Eig(M, EigenValue, EigenVec) elif func_name == "eig": self.symbol_table.update({ctx.expr(1).getText().lower(): ctx.expr(1).getText().lower()}) self.symbol_table.update({ctx.expr(2).getText().lower(): ctx.expr(2).getText().lower()}) # _sm.Matrix([i.evalf() for i in (i_s_so).eigenvals().keys()]) self.write(ctx.expr(1).getText().lower() + " = " + "_sm.Matrix([i.evalf() for i in " + "(" + self.getValue(ctx.expr(0)) + ")" + ".eigenvals().keys()])\n") # _sm.Matrix([i[2][0].evalf() for i in (i_s_o).eigenvects()]).reshape(i_s_o.shape[0], i_s_o.shape[1]) self.write(ctx.expr(2).getText().lower() + " = " + "_sm.Matrix([i[2][0].evalf() for i in " + "(" + self.getValue(ctx.expr(0)) + ")" + ".eigenvects()]).reshape(" + self.getValue(ctx.expr(0)) + ".shape[0], " + self.getValue(ctx.expr(0)) + ".shape[1])\n") # Simprot(N, A, 3, qA) elif func_name == "simprot": # A.orient(N, 'Axis', qA, N.z) if self.type2[ctx.expr(0).getText().lower()] == "frame": frame1 = self.symbol_table2[ctx.expr(0).getText().lower()] elif self.type2[ctx.expr(0).getText().lower()] == "bodies": frame1 = self.symbol_table2[ctx.expr(0).getText().lower()] + "_f" if self.type2[ctx.expr(1).getText().lower()] == "frame": frame2 = self.symbol_table2[ctx.expr(1).getText().lower()] elif self.type2[ctx.expr(1).getText().lower()] == "bodies": frame2 = self.symbol_table2[ctx.expr(1).getText().lower()] + "_f" e2 = "" if ctx.expr(2).getText()[0] == "-": e2 = "-1*" if ctx.expr(2).getText() in ("1", "-1"): e = frame1 + ".x" elif ctx.expr(2).getText() in ("2", "-2"): e = frame1 + ".y" elif ctx.expr(2).getText() in ("3", "-3"): e = frame1 + ".z" else: e = self.getValue(ctx.expr(2)) e2 = "" if "degrees" in self.settings.keys() and self.settings["degrees"] == "off": value = self.getValue(ctx.expr(3)) else: if ctx.expr(3) in self.numeric_expr: value = "_np.deg2rad(" + self.getValue(ctx.expr(3)) + ")" else: value = self.getValue(ctx.expr(3)) self.write(frame2 + ".orient(" + frame1 + ", " + "'Axis'" + ", " + "[" + value + ", " + e2 + e + "]" + ")\n") # Express(A2>, B) * elif func_name == "express": if self.type2[ctx.expr(1).getText().lower()] == "bodies": f = "_f" else: f = "" if '_' in ctx.expr(0).getText().lower() and ctx.expr(0).getText().count('_') == 2: vec = ctx.expr(0).getText().lower().replace(">", "").split('_') v1 = self.symbol_table2[vec[1]] v2 = self.symbol_table2[vec[2]] if vec[0] == "p": self.write(v2 + ".set_pos(" + v1 + ", " + "(" + self.getValue(ctx.expr(0)) + ")" + ".express(" + self.symbol_table2[ctx.expr(1).getText().lower()] + f + "))\n") elif vec[0] == "v": self.write(v1 + ".set_vel(" + v2 + ", " + "(" + self.getValue(ctx.expr(0)) + ")" + ".express(" + self.symbol_table2[ctx.expr(1).getText().lower()] + f + "))\n") elif vec[0] == "a": self.write(v1 + ".set_acc(" + v2 + ", " + "(" + self.getValue(ctx.expr(0)) + ")" + ".express(" + self.symbol_table2[ctx.expr(1).getText().lower()] + f + "))\n") else: self.write(self.getValue(ctx.expr(0)) + " = " + "(" + self.getValue(ctx.expr(0)) + ")" + ".express(" + self.symbol_table2[ctx.expr(1).getText().lower()] + f + ")\n") else: self.write(self.getValue(ctx.expr(0)) + " = " + "(" + self.getValue(ctx.expr(0)) + ")" + ".express(" + self.symbol_table2[ctx.expr(1).getText().lower()] + f + ")\n") # Angvel(A, B) elif func_name == "angvel": self.write("print(" + self.symbol_table2[ctx.expr(1).getText().lower()] + ".ang_vel_in(" + self.symbol_table2[ctx.expr(0).getText().lower()] + "))\n") # v2pts(N, A, O, P) elif func_name in ("v2pts", "a2pts", "v2pt", "a1pt"): if func_name == "v2pts": text = ".v2pt_theory(" elif func_name == "a2pts": text = ".a2pt_theory(" elif func_name == "v1pt": text = ".v1pt_theory(" elif func_name == "a1pt": text = ".a1pt_theory(" if self.type2[ctx.expr(1).getText().lower()] == "frame": frame = self.symbol_table2[ctx.expr(1).getText().lower()] elif self.type2[ctx.expr(1).getText().lower()] == "bodies": frame = self.symbol_table2[ctx.expr(1).getText().lower()] + "_f" expr_list = [] for i in range(2, 4): if self.type2[ctx.expr(i).getText().lower()] == "point": expr_list.append(self.symbol_table2[ctx.expr(i).getText().lower()]) elif self.type2[ctx.expr(i).getText().lower()] == "particle": expr_list.append(self.symbol_table2[ctx.expr(i).getText().lower()] + ".point") self.write(expr_list[1] + text + expr_list[0] + "," + self.symbol_table2[ctx.expr(0).getText().lower()] + "," + frame + ")\n") # Gravity(g*N1>) elif func_name == "gravity": for i in self.bodies.keys(): if self.type2[i] == "bodies": e = self.symbol_table2[i] + ".masscenter" elif self.type2[i] == "particle": e = self.symbol_table2[i] + ".point" if e in self.forces.keys(): self.forces[e] = self.forces[e] + self.symbol_table2[i] +\ ".mass*(" + self.getValue(ctx.expr(0)) + ")" else: self.forces.update({e: self.symbol_table2[i] + ".mass*(" + self.getValue(ctx.expr(0)) + ")"}) self.write("force_" + i + " = " + self.forces[e] + "\n") # Explicit(EXPRESS(IMPLICIT>,C)) elif func_name == "explicit": if ctx.expr(0) in self.vector_expr: self.vector_expr.append(ctx) expr = self.getValue(ctx.expr(0)) if self.explicit.keys(): explicit_list = [] for i in self.explicit.keys(): explicit_list.append(i + ":" + self.explicit[i]) if '_' in ctx.expr(0).getText().lower() and ctx.expr(0).getText().count('_') == 2: vec = ctx.expr(0).getText().lower().replace(">", "").split('_') v1 = self.symbol_table2[vec[1]] v2 = self.symbol_table2[vec[2]] if vec[0] == "p": self.write(v2 + ".set_pos(" + v1 + ", " + "(" + expr + ")" + ".subs({" + ", ".join(explicit_list) + "}))\n") elif vec[0] == "v": self.write(v2 + ".set_vel(" + v1 + ", " + "(" + expr + ")" + ".subs({" + ", ".join(explicit_list) + "}))\n") elif vec[0] == "a": self.write(v2 + ".set_acc(" + v1 + ", " + "(" + expr + ")" + ".subs({" + ", ".join(explicit_list) + "}))\n") else: self.write(expr + " = " + "(" + expr + ")" + ".subs({" + ", ".join(explicit_list) + "})\n") else: self.write(expr + " = " + "(" + expr + ")" + ".subs({" + ", ".join(explicit_list) + "})\n") # Force(O/Q, -k*Stretch*Uvec>) elif func_name in ("force", "torque"): if "/" in ctx.expr(0).getText().lower(): p1 = ctx.expr(0).getText().lower().split('/')[0] p2 = ctx.expr(0).getText().lower().split('/')[1] if self.type2[p1] in ("point", "frame"): pt1 = self.symbol_table2[p1] elif self.type2[p1] == "particle": pt1 = self.symbol_table2[p1] + ".point" if self.type2[p2] in ("point", "frame"): pt2 = self.symbol_table2[p2] elif self.type2[p2] == "particle": pt2 = self.symbol_table2[p2] + ".point" if pt1 in self.forces.keys(): self.forces[pt1] = self.forces[pt1] + " + -1*("+self.getValue(ctx.expr(1)) + ")" self.write("force_" + p1 + " = " + self.forces[pt1] + "\n") else: self.forces.update({pt1: "-1*("+self.getValue(ctx.expr(1)) + ")"}) self.write("force_" + p1 + " = " + self.forces[pt1] + "\n") if pt2 in self.forces.keys(): self.forces[pt2] = self.forces[pt2] + "+ " + self.getValue(ctx.expr(1)) self.write("force_" + p2 + " = " + self.forces[pt2] + "\n") else: self.forces.update({pt2: self.getValue(ctx.expr(1))}) self.write("force_" + p2 + " = " + self.forces[pt2] + "\n") elif ctx.expr(0).getChildCount() == 1: p1 = ctx.expr(0).getText().lower() if self.type2[p1] in ("point", "frame"): pt1 = self.symbol_table2[p1] elif self.type2[p1] == "particle": pt1 = self.symbol_table2[p1] + ".point" if pt1 in self.forces.keys(): self.forces[pt1] = self.forces[pt1] + "+ -1*(" + self.getValue(ctx.expr(1)) + ")" else: self.forces.update({pt1: "-1*(" + self.getValue(ctx.expr(1)) + ")"}) # Constrain(Dependent[qB]) elif func_name == "constrain": if ctx.getChild(2).getChild(0).getText().lower() == "dependent": self.write("velocity_constraints = [i for i in dependent]\n") x = (ctx.expr(0).getChildCount()-2)//2 for i in range(x): self.dependent_variables.append(self.getValue(ctx.expr(0).expr(i))) # Kane() elif func_name == "kane": if ctx.getChildCount() == 3: self.kane_type = "no_args" # Settings def exitSettings(self, ctx): # Stores settings like Complex on/off, Degrees on/off etc in self.settings. try: self.settings.update({ctx.getChild(0).getText().lower(): ctx.getChild(1).getText().lower()}) except Exception: pass def exitMassDecl2(self, ctx): # Used for declaring the masses of particles and rigidbodies. particle = self.symbol_table2[ctx.getChild(0).getText().lower()] if ctx.getText().count("=") == 2: if ctx.expr().expr(1) in self.numeric_expr: e = "_sm.S(" + self.getValue(ctx.expr().expr(1)) + ")" else: e = self.getValue(ctx.expr().expr(1)) self.symbol_table.update({ctx.expr().expr(0).getText().lower(): ctx.expr().expr(0).getText().lower()}) self.write(ctx.expr().expr(0).getText().lower() + " = " + e + "\n") mass = ctx.expr().expr(0).getText().lower() else: try: if ctx.expr() in self.numeric_expr: mass = "_sm.S(" + self.getValue(ctx.expr()) + ")" else: mass = self.getValue(ctx.expr()) except Exception: a_text = ctx.expr().getText().lower() self.symbol_table.update({a_text: a_text}) self.type.update({a_text: "constants"}) self.write(a_text + " = " + "_sm.symbols('" + a_text + "')\n") mass = a_text self.write(particle + ".mass = " + mass + "\n") def exitInertiaDecl(self, ctx): inertia_list = [] try: ctx.ID(1).getText() num = 5 except Exception: num = 2 for i in range((ctx.getChildCount()-num)//2): try: if ctx.expr(i) in self.numeric_expr: inertia_list.append("_sm.S(" + self.getValue(ctx.expr(i)) + ")") else: inertia_list.append(self.getValue(ctx.expr(i))) except Exception: a_text = ctx.expr(i).getText().lower() self.symbol_table.update({a_text: a_text}) self.type.update({a_text: "constants"}) self.write(a_text + " = " + "_sm.symbols('" + a_text + "')\n") inertia_list.append(a_text) if len(inertia_list) < 6: for i in range(6-len(inertia_list)): inertia_list.append("0") # body_a.inertia = (_me.inertia(body_a, I1, I2, I3, 0, 0, 0), body_a_cm) try: frame = self.symbol_table2[ctx.ID(1).getText().lower()] point = self.symbol_table2[ctx.ID(0).getText().lower().split('_')[1]] body = self.symbol_table2[ctx.ID(0).getText().lower().split('_')[0]] self.inertia_point.update({ctx.ID(0).getText().lower().split('_')[0] : ctx.ID(0).getText().lower().split('_')[1]}) self.write(body + ".inertia" + " = " + "(_me.inertia(" + frame + ", " + ", ".join(inertia_list) + "), " + point + ")\n") except Exception: body_name = self.symbol_table2[ctx.ID(0).getText().lower()] body_name_cm = body_name + "_cm" self.inertia_point.update({ctx.ID(0).getText().lower(): ctx.ID(0).getText().lower() + "o"}) self.write(body_name + ".inertia" + " = " + "(_me.inertia(" + body_name + "_f" + ", " + ", ".join(inertia_list) + "), " + body_name_cm + ")\n")
27353aa5c529c6f31b1aa66ac506c9a63140dcea76a4d7f983de801b18304710
from sympy.external import import_module from sympy.utilities.decorator import doctest_depends_on @doctest_depends_on(modules=('antlr4',)) def parse_autolev(autolev_code, include_numeric=False): """Parses Autolev code (version 4.1) to SymPy code. Parameters ========= autolev_code : Can be an str or any object with a readlines() method (such as a file handle or StringIO). include_numeric : boolean, optional If True NumPy, PyDy, or other numeric code is included for numeric evaluation lines in the Autolev code. Returns ======= sympy_code : str Equivalent sympy and/or numpy/pydy code as the input code. Example (Double Pendulum) ========================= >>> my_al_text = ("MOTIONVARIABLES' Q{2}', U{2}'", ... "CONSTANTS L,M,G", ... "NEWTONIAN N", ... "FRAMES A,B", ... "SIMPROT(N, A, 3, Q1)", ... "SIMPROT(N, B, 3, Q2)", ... "W_A_N>=U1*N3>", ... "W_B_N>=U2*N3>", ... "POINT O", ... "PARTICLES P,R", ... "P_O_P> = L*A1>", ... "P_P_R> = L*B1>", ... "V_O_N> = 0>", ... "V2PTS(N, A, O, P)", ... "V2PTS(N, B, P, R)", ... "MASS P=M, R=M", ... "Q1' = U1", ... "Q2' = U2", ... "GRAVITY(G*N1>)", ... "ZERO = FR() + FRSTAR()", ... "KANE()", ... "INPUT M=1,G=9.81,L=1", ... "INPUT Q1=.1,Q2=.2,U1=0,U2=0", ... "INPUT TFINAL=10, INTEGSTP=.01", ... "CODE DYNAMICS() some_filename.c") >>> my_al_text = '\\n'.join(my_al_text) >>> from sympy.parsing.autolev import parse_autolev >>> print(parse_autolev(my_al_text, include_numeric=True)) import sympy.physics.mechanics as _me import sympy as _sm import math as m import numpy as _np <BLANKLINE> q1, q2, u1, u2 = _me.dynamicsymbols('q1 q2 u1 u2') q1_d, q2_d, u1_d, u2_d = _me.dynamicsymbols('q1_ q2_ u1_ u2_', 1) l, m, g = _sm.symbols('l m g', real=True) frame_n = _me.ReferenceFrame('n') frame_a = _me.ReferenceFrame('a') frame_b = _me.ReferenceFrame('b') frame_a.orient(frame_n, 'Axis', [q1, frame_n.z]) frame_b.orient(frame_n, 'Axis', [q2, frame_n.z]) frame_a.set_ang_vel(frame_n, u1*frame_n.z) frame_b.set_ang_vel(frame_n, u2*frame_n.z) point_o = _me.Point('o') particle_p = _me.Particle('p', _me.Point('p_pt'), _sm.Symbol('m')) particle_r = _me.Particle('r', _me.Point('r_pt'), _sm.Symbol('m')) particle_p.point.set_pos(point_o, l*frame_a.x) particle_r.point.set_pos(particle_p.point, l*frame_b.x) point_o.set_vel(frame_n, 0) particle_p.point.v2pt_theory(point_o,frame_n,frame_a) particle_r.point.v2pt_theory(particle_p.point,frame_n,frame_b) particle_p.mass = m particle_r.mass = m force_p = particle_p.mass*(g*frame_n.x) force_r = particle_r.mass*(g*frame_n.x) kd_eqs = [q1_d - u1, q2_d - u2] forceList = [(particle_p.point,particle_p.mass*(g*frame_n.x)), (particle_r.point,particle_r.mass*(g*frame_n.x))] kane = _me.KanesMethod(frame_n, q_ind=[q1,q2], u_ind=[u1, u2], kd_eqs = kd_eqs) fr, frstar = kane.kanes_equations([particle_p, particle_r], forceList) zero = fr+frstar from pydy.system import System sys = System(kane, constants = {l:1, m:1, g:9.81}, specifieds={}, initial_conditions={q1:.1, q2:.2, u1:0, u2:0}, times = _np.linspace(0.0, 10, 10/.01)) <BLANKLINE> y=sys.integrate() <BLANKLINE> """ _autolev = import_module( 'sympy.parsing.autolev._parse_autolev_antlr', import_kwargs={'fromlist': ['X']}) if _autolev is not None: return _autolev.parse_autolev(autolev_code, include_numeric)
f76dc4aaa21de29b811ba56c1f6cf7177e51d3ea318a5bf72fba5dc13ee3ffb7
# Ported from latex2sympy by @augustt198 # https://github.com/augustt198/latex2sympy # See license in LICENSE.txt import sympy from sympy.external import import_module from sympy.printing.str import StrPrinter from sympy.physics.quantum.state import Bra, Ket from .errors import LaTeXParsingError LaTeXParser = LaTeXLexer = MathErrorListener = None try: LaTeXParser = import_module('sympy.parsing.latex._antlr.latexparser', import_kwargs={'fromlist': ['LaTeXParser']}).LaTeXParser LaTeXLexer = import_module('sympy.parsing.latex._antlr.latexlexer', import_kwargs={'fromlist': ['LaTeXLexer']}).LaTeXLexer except Exception: pass ErrorListener = import_module('antlr4.error.ErrorListener', warn_not_installed=True, import_kwargs={'fromlist': ['ErrorListener']} ) if ErrorListener: class MathErrorListener(ErrorListener.ErrorListener): # type: ignore def __init__(self, src): super(ErrorListener.ErrorListener, self).__init__() self.src = src def syntaxError(self, recog, symbol, line, col, msg, e): fmt = "%s\n%s\n%s" marker = "~" * col + "^" if msg.startswith("missing"): err = fmt % (msg, self.src, marker) elif msg.startswith("no viable"): err = fmt % ("I expected something else here", self.src, marker) elif msg.startswith("mismatched"): names = LaTeXParser.literalNames expected = [ names[i] for i in e.getExpectedTokens() if i < len(names) ] if len(expected) < 10: expected = " ".join(expected) err = (fmt % ("I expected one of these: " + expected, self.src, marker)) else: err = (fmt % ("I expected something else here", self.src, marker)) else: err = fmt % ("I don't understand this", self.src, marker) raise LaTeXParsingError(err) def parse_latex(sympy): antlr4 = import_module('antlr4', warn_not_installed=True) if None in [antlr4, MathErrorListener]: raise ImportError("LaTeX parsing requires the antlr4 python package," " provided by pip (antlr4-python2-runtime or" " antlr4-python3-runtime) or" " conda (antlr-python-runtime)") matherror = MathErrorListener(sympy) stream = antlr4.InputStream(sympy) lex = LaTeXLexer(stream) lex.removeErrorListeners() lex.addErrorListener(matherror) tokens = antlr4.CommonTokenStream(lex) parser = LaTeXParser(tokens) # remove default console error listener parser.removeErrorListeners() parser.addErrorListener(matherror) relation = parser.math().relation() expr = convert_relation(relation) return expr def convert_relation(rel): if rel.expr(): return convert_expr(rel.expr()) lh = convert_relation(rel.relation(0)) rh = convert_relation(rel.relation(1)) if rel.LT(): return sympy.StrictLessThan(lh, rh) elif rel.LTE(): return sympy.LessThan(lh, rh) elif rel.GT(): return sympy.StrictGreaterThan(lh, rh) elif rel.GTE(): return sympy.GreaterThan(lh, rh) elif rel.EQUAL(): return sympy.Eq(lh, rh) elif rel.NEQ(): return sympy.Ne(lh, rh) def convert_expr(expr): return convert_add(expr.additive()) def convert_add(add): if add.ADD(): lh = convert_add(add.additive(0)) rh = convert_add(add.additive(1)) return sympy.Add(lh, rh, evaluate=False) elif add.SUB(): lh = convert_add(add.additive(0)) rh = convert_add(add.additive(1)) return sympy.Add(lh, -1 * rh, evaluate=False) else: return convert_mp(add.mp()) def convert_mp(mp): if hasattr(mp, 'mp'): mp_left = mp.mp(0) mp_right = mp.mp(1) else: mp_left = mp.mp_nofunc(0) mp_right = mp.mp_nofunc(1) if mp.MUL() or mp.CMD_TIMES() or mp.CMD_CDOT(): lh = convert_mp(mp_left) rh = convert_mp(mp_right) return sympy.Mul(lh, rh, evaluate=False) elif mp.DIV() or mp.CMD_DIV() or mp.COLON(): lh = convert_mp(mp_left) rh = convert_mp(mp_right) return sympy.Mul(lh, sympy.Pow(rh, -1, evaluate=False), evaluate=False) else: if hasattr(mp, 'unary'): return convert_unary(mp.unary()) else: return convert_unary(mp.unary_nofunc()) def convert_unary(unary): if hasattr(unary, 'unary'): nested_unary = unary.unary() else: nested_unary = unary.unary_nofunc() if hasattr(unary, 'postfix_nofunc'): first = unary.postfix() tail = unary.postfix_nofunc() postfix = [first] + tail else: postfix = unary.postfix() if unary.ADD(): return convert_unary(nested_unary) elif unary.SUB(): numabs = convert_unary(nested_unary) if numabs == 1: # Use Integer(-1) instead of Mul(-1, 1) return -numabs else: return sympy.Mul(-1, convert_unary(nested_unary), evaluate=False) elif postfix: return convert_postfix_list(postfix) def convert_postfix_list(arr, i=0): if i >= len(arr): raise LaTeXParsingError("Index out of bounds") res = convert_postfix(arr[i]) if isinstance(res, sympy.Expr): if i == len(arr) - 1: return res # nothing to multiply by else: if i > 0: left = convert_postfix(arr[i - 1]) right = convert_postfix(arr[i + 1]) if isinstance(left, sympy.Expr) and isinstance( right, sympy.Expr): left_syms = convert_postfix(arr[i - 1]).atoms(sympy.Symbol) right_syms = convert_postfix(arr[i + 1]).atoms( sympy.Symbol) # if the left and right sides contain no variables and the # symbol in between is 'x', treat as multiplication. if len(left_syms) == 0 and len(right_syms) == 0 and str( res) == "x": return convert_postfix_list(arr, i + 1) # multiply by next return sympy.Mul( res, convert_postfix_list(arr, i + 1), evaluate=False) else: # must be derivative wrt = res[0] if i == len(arr) - 1: raise LaTeXParsingError("Expected expression for derivative") else: expr = convert_postfix_list(arr, i + 1) return sympy.Derivative(expr, wrt) def do_subs(expr, at): if at.expr(): at_expr = convert_expr(at.expr()) syms = at_expr.atoms(sympy.Symbol) if len(syms) == 0: return expr elif len(syms) > 0: sym = next(iter(syms)) return expr.subs(sym, at_expr) elif at.equality(): lh = convert_expr(at.equality().expr(0)) rh = convert_expr(at.equality().expr(1)) return expr.subs(lh, rh) def convert_postfix(postfix): if hasattr(postfix, 'exp'): exp_nested = postfix.exp() else: exp_nested = postfix.exp_nofunc() exp = convert_exp(exp_nested) for op in postfix.postfix_op(): if op.BANG(): if isinstance(exp, list): raise LaTeXParsingError("Cannot apply postfix to derivative") exp = sympy.factorial(exp, evaluate=False) elif op.eval_at(): ev = op.eval_at() at_b = None at_a = None if ev.eval_at_sup(): at_b = do_subs(exp, ev.eval_at_sup()) if ev.eval_at_sub(): at_a = do_subs(exp, ev.eval_at_sub()) if at_b is not None and at_a is not None: exp = sympy.Add(at_b, -1 * at_a, evaluate=False) elif at_b is not None: exp = at_b elif at_a is not None: exp = at_a return exp def convert_exp(exp): if hasattr(exp, 'exp'): exp_nested = exp.exp() else: exp_nested = exp.exp_nofunc() if exp_nested: base = convert_exp(exp_nested) if isinstance(base, list): raise LaTeXParsingError("Cannot raise derivative to power") if exp.atom(): exponent = convert_atom(exp.atom()) elif exp.expr(): exponent = convert_expr(exp.expr()) return sympy.Pow(base, exponent, evaluate=False) else: if hasattr(exp, 'comp'): return convert_comp(exp.comp()) else: return convert_comp(exp.comp_nofunc()) def convert_comp(comp): if comp.group(): return convert_expr(comp.group().expr()) elif comp.abs_group(): return sympy.Abs(convert_expr(comp.abs_group().expr()), evaluate=False) elif comp.atom(): return convert_atom(comp.atom()) elif comp.frac(): return convert_frac(comp.frac()) elif comp.binom(): return convert_binom(comp.binom()) elif comp.floor(): return convert_floor(comp.floor()) elif comp.ceil(): return convert_ceil(comp.ceil()) elif comp.func(): return convert_func(comp.func()) def convert_atom(atom): if atom.LETTER(): subscriptName = '' if atom.subexpr(): subscript = None if atom.subexpr().expr(): # subscript is expr subscript = convert_expr(atom.subexpr().expr()) else: # subscript is atom subscript = convert_atom(atom.subexpr().atom()) subscriptName = '_{' + StrPrinter().doprint(subscript) + '}' return sympy.Symbol(atom.LETTER().getText() + subscriptName) elif atom.SYMBOL(): s = atom.SYMBOL().getText()[1:] if s == "infty": return sympy.oo else: if atom.subexpr(): subscript = None if atom.subexpr().expr(): # subscript is expr subscript = convert_expr(atom.subexpr().expr()) else: # subscript is atom subscript = convert_atom(atom.subexpr().atom()) subscriptName = StrPrinter().doprint(subscript) s += '_{' + subscriptName + '}' return sympy.Symbol(s) elif atom.NUMBER(): s = atom.NUMBER().getText().replace(",", "") return sympy.Number(s) elif atom.DIFFERENTIAL(): var = get_differential_var(atom.DIFFERENTIAL()) return sympy.Symbol('d' + var.name) elif atom.mathit(): text = rule2text(atom.mathit().mathit_text()) return sympy.Symbol(text) elif atom.bra(): val = convert_expr(atom.bra().expr()) return Bra(val) elif atom.ket(): val = convert_expr(atom.ket().expr()) return Ket(val) def rule2text(ctx): stream = ctx.start.getInputStream() # starting index of starting token startIdx = ctx.start.start # stopping index of stopping token stopIdx = ctx.stop.stop return stream.getText(startIdx, stopIdx) def convert_frac(frac): diff_op = False partial_op = False lower_itv = frac.lower.getSourceInterval() lower_itv_len = lower_itv[1] - lower_itv[0] + 1 if (frac.lower.start == frac.lower.stop and frac.lower.start.type == LaTeXLexer.DIFFERENTIAL): wrt = get_differential_var_str(frac.lower.start.text) diff_op = True elif (lower_itv_len == 2 and frac.lower.start.type == LaTeXLexer.SYMBOL and frac.lower.start.text == '\\partial' and (frac.lower.stop.type == LaTeXLexer.LETTER or frac.lower.stop.type == LaTeXLexer.SYMBOL)): partial_op = True wrt = frac.lower.stop.text if frac.lower.stop.type == LaTeXLexer.SYMBOL: wrt = wrt[1:] if diff_op or partial_op: wrt = sympy.Symbol(wrt) if (diff_op and frac.upper.start == frac.upper.stop and frac.upper.start.type == LaTeXLexer.LETTER and frac.upper.start.text == 'd'): return [wrt] elif (partial_op and frac.upper.start == frac.upper.stop and frac.upper.start.type == LaTeXLexer.SYMBOL and frac.upper.start.text == '\\partial'): return [wrt] upper_text = rule2text(frac.upper) expr_top = None if diff_op and upper_text.startswith('d'): expr_top = parse_latex(upper_text[1:]) elif partial_op and frac.upper.start.text == '\\partial': expr_top = parse_latex(upper_text[len('\\partial'):]) if expr_top: return sympy.Derivative(expr_top, wrt) expr_top = convert_expr(frac.upper) expr_bot = convert_expr(frac.lower) inverse_denom = sympy.Pow(expr_bot, -1, evaluate=False) if expr_top == 1: return inverse_denom else: return sympy.Mul(expr_top, inverse_denom, evaluate=False) def convert_binom(binom): expr_n = convert_expr(binom.n) expr_k = convert_expr(binom.k) return sympy.binomial(expr_n, expr_k, evaluate=False) def convert_floor(floor): val = convert_expr(floor.val) return sympy.floor(val, evaluate=False) def convert_ceil(ceil): val = convert_expr(ceil.val) return sympy.ceiling(val, evaluate=False) def convert_func(func): if func.func_normal(): if func.L_PAREN(): # function called with parenthesis arg = convert_func_arg(func.func_arg()) else: arg = convert_func_arg(func.func_arg_noparens()) name = func.func_normal().start.text[1:] # change arc<trig> -> a<trig> if name in [ "arcsin", "arccos", "arctan", "arccsc", "arcsec", "arccot" ]: name = "a" + name[3:] expr = getattr(sympy.functions, name)(arg, evaluate=False) if name in ["arsinh", "arcosh", "artanh"]: name = "a" + name[2:] expr = getattr(sympy.functions, name)(arg, evaluate=False) if name == "exp": expr = sympy.exp(arg, evaluate=False) if (name == "log" or name == "ln"): if func.subexpr(): 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
7882841731309021613c5d064e67fa48bbb15d3dfce06a9d0899e188bd94d014
import sympy.physics.mechanics as _me import sympy as _sm import math as m import numpy as _np f = _sm.S(3) g = _sm.S(9.81) a, b = _sm.symbols('a b', real=True) s, s1 = _sm.symbols('s s1', real=True) s2, s3 = _sm.symbols('s2 s3', real=True, nonnegative=True) s4 = _sm.symbols('s4', real=True, nonpositive=True) k1, k2, k3, k4, l1, l2, l3, p11, p12, p13, p21, p22, p23 = _sm.symbols('k1 k2 k3 k4 l1 l2 l3 p11 p12 p13 p21 p22 p23', real=True) c11, c12, c13, c21, c22, c23 = _sm.symbols('c11 c12 c13 c21 c22 c23', real=True) e1 = a*f+s2-g e2 = f**2+k3*k2*g
235b6c41c4805bac2a220b85fbb970963f43e1867c90266a3ea4ca3d41d1f682
import sympy.physics.mechanics as _me import sympy as _sm import math as m import numpy as _np x, y = _me.dynamicsymbols('x y') a, b = _sm.symbols('a b', real=True) e = a*(b*x+y)**2 m = _sm.Matrix([e,e]).reshape(2, 1) e = e.expand() m = _sm.Matrix([i.expand() for i in m]).reshape((m).shape[0], (m).shape[1]) e = _sm.factor(e, x) m = _sm.Matrix([_sm.factor(i,x) for i in m]).reshape((m).shape[0], (m).shape[1]) eqn = _sm.Matrix([[0]]) eqn[0] = a*x+b*y eqn = eqn.row_insert(eqn.shape[0], _sm.Matrix([[0]])) eqn[eqn.shape[0]-1] = 2*a*x-3*b*y print(_sm.solve(eqn,x,y)) rhs_y = _sm.solve(eqn,x,y)[y] e = (x+y)**2+2*x**2 e.collect(x) a, b, c = _sm.symbols('a b c', real=True) m = _sm.Matrix([a,b,c,0]).reshape(2, 2) m2 = _sm.Matrix([i.subs({a:1,b:2,c:3}) for i in m]).reshape((m).shape[0], (m).shape[1]) eigvalue = _sm.Matrix([i.evalf() for i in (m2).eigenvals().keys()]) eigvec = _sm.Matrix([i[2][0].evalf() for i in (m2).eigenvects()]).reshape(m2.shape[0], m2.shape[1]) frame_n = _me.ReferenceFrame('n') frame_a = _me.ReferenceFrame('a') frame_a.orient(frame_n, 'Axis', [x, frame_n.x]) frame_a.orient(frame_n, 'Axis', [_sm.pi/2, frame_n.x]) c1, c2, c3 = _sm.symbols('c1 c2 c3', real=True) v = c1*frame_a.x+c2*frame_a.y+c3*frame_a.z point_o = _me.Point('o') point_p = _me.Point('p') point_o.set_pos(point_p, c1*frame_a.x) v = (v).express(frame_n) point_o.set_pos(point_p, (point_o.pos_from(point_p)).express(frame_n)) frame_a.set_ang_vel(frame_n, c3*frame_a.z) print(frame_n.ang_vel_in(frame_a)) point_p.v2pt_theory(point_o,frame_n,frame_a) particle_p1 = _me.Particle('p1', _me.Point('p1_pt'), _sm.Symbol('m')) particle_p2 = _me.Particle('p2', _me.Point('p2_pt'), _sm.Symbol('m')) particle_p2.point.v2pt_theory(particle_p1.point,frame_n,frame_a) point_p.a2pt_theory(particle_p1.point,frame_n,frame_a) body_b1_cm = _me.Point('b1_cm') body_b1_cm.set_vel(frame_n, 0) body_b1_f = _me.ReferenceFrame('b1_f') body_b1 = _me.RigidBody('b1', body_b1_cm, body_b1_f, _sm.symbols('m'), (_me.outer(body_b1_f.x,body_b1_f.x),body_b1_cm)) body_b2_cm = _me.Point('b2_cm') body_b2_cm.set_vel(frame_n, 0) body_b2_f = _me.ReferenceFrame('b2_f') body_b2 = _me.RigidBody('b2', body_b2_cm, body_b2_f, _sm.symbols('m'), (_me.outer(body_b2_f.x,body_b2_f.x),body_b2_cm)) g = _sm.symbols('g', real=True) force_p1 = particle_p1.mass*(g*frame_n.x) force_p2 = particle_p2.mass*(g*frame_n.x) force_b1 = body_b1.mass*(g*frame_n.x) force_b2 = body_b2.mass*(g*frame_n.x) z = _me.dynamicsymbols('z') v = x*frame_a.x+y*frame_a.z point_o.set_pos(point_p, x*frame_a.x+y*frame_a.y) v = (v).subs({x:2*z, y:z}) point_o.set_pos(point_p, (point_o.pos_from(point_p)).subs({x:2*z, y:z})) force_o = -1*(x*y*frame_a.x) force_p1 = particle_p1.mass*(g*frame_n.x)+ x*y*frame_a.x
3b72b7210a3e1c28c020e4a47f3ddb0e5b2dedd554891c21399d2aff78dbe4b5
import sympy.physics.mechanics as _me import sympy as _sm import math as m import numpy as _np frame_a = _me.ReferenceFrame('a') frame_b = _me.ReferenceFrame('b') frame_n = _me.ReferenceFrame('n') x1, x2, x3 = _me.dynamicsymbols('x1 x2 x3') l = _sm.symbols('l', real=True) v1 = x1*frame_a.x+x2*frame_a.y+x3*frame_a.z v2 = x1*frame_b.x+x2*frame_b.y+x3*frame_b.z v3 = x1*frame_n.x+x2*frame_n.y+x3*frame_n.z v = v1+v2+v3 point_c = _me.Point('c') point_d = _me.Point('d') point_po1 = _me.Point('po1') point_po2 = _me.Point('po2') point_po3 = _me.Point('po3') particle_l = _me.Particle('l', _me.Point('l_pt'), _sm.Symbol('m')) particle_p1 = _me.Particle('p1', _me.Point('p1_pt'), _sm.Symbol('m')) particle_p2 = _me.Particle('p2', _me.Point('p2_pt'), _sm.Symbol('m')) particle_p3 = _me.Particle('p3', _me.Point('p3_pt'), _sm.Symbol('m')) body_s_cm = _me.Point('s_cm') body_s_cm.set_vel(frame_n, 0) body_s_f = _me.ReferenceFrame('s_f') body_s = _me.RigidBody('s', body_s_cm, body_s_f, _sm.symbols('m'), (_me.outer(body_s_f.x,body_s_f.x),body_s_cm)) body_r1_cm = _me.Point('r1_cm') body_r1_cm.set_vel(frame_n, 0) body_r1_f = _me.ReferenceFrame('r1_f') body_r1 = _me.RigidBody('r1', body_r1_cm, body_r1_f, _sm.symbols('m'), (_me.outer(body_r1_f.x,body_r1_f.x),body_r1_cm)) body_r2_cm = _me.Point('r2_cm') body_r2_cm.set_vel(frame_n, 0) body_r2_f = _me.ReferenceFrame('r2_f') body_r2 = _me.RigidBody('r2', body_r2_cm, body_r2_f, _sm.symbols('m'), (_me.outer(body_r2_f.x,body_r2_f.x),body_r2_cm)) v4 = x1*body_s_f.x+x2*body_s_f.y+x3*body_s_f.z body_s_cm.set_pos(point_c, l*frame_n.x)
bc43b48cc383f8a21ebc07157b19a9bda7343068cdecefdd362a4e04924dcc5d
import sympy.physics.mechanics as _me import sympy as _sm import math as m import numpy as _np q1, q2 = _me.dynamicsymbols('q1 q2') x, y, z = _me.dynamicsymbols('x y z') e = q1+q2 a = (e).subs({q1:x**2+y**2, q2:x-y}) e2 = _sm.cos(x) e3 = _sm.cos(x*y) a = (e2).series(x, 0, 2).removeO() b = (e3).series(x, 0, 2).removeO().series(y, 0, 2).removeO() e = ((x+y)**2).expand() a = (e).subs({q1:x**2+y**2,q2:x-y}).subs({x:1,y:z}) bm = _sm.Matrix([i.subs({x:1,y:z}) for i in _sm.Matrix([e,2*e]).reshape(2, 1)]).reshape((_sm.Matrix([e,2*e]).reshape(2, 1)).shape[0], (_sm.Matrix([e,2*e]).reshape(2, 1)).shape[1]) e = q1+q2 a = (e).subs({q1:x**2+y**2,q2:x-y}).subs({x:2,y:z**2}) j, k, l = _sm.symbols('j k l', real=True) p1 = _sm.Poly(_sm.Matrix([j,k,l]).reshape(1, 3), x) p2 = _sm.Poly(j*x+k, x) root1 = [i.evalf() for i in _sm.solve(p1, x)] root2 = [i.evalf() for i in _sm.solve(_sm.Poly(_sm.Matrix([1,2,3]).reshape(3, 1), x),x)] m = _sm.Matrix([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]).reshape(4, 4) am = (m).T+m bm = _sm.Matrix([i.evalf() for i in (m).eigenvals().keys()]) c1 = _sm.diag(1,1,1,1) c2 = _sm.Matrix([2 if i==j else 0 for i in range(3) for j in range(4)]).reshape(3, 4) dm = (m+c1)**(-1) e = (m+c1).det()+(_sm.Matrix([1,0,0,1]).reshape(2, 2)).trace() f = (m)[1,2] a = (m).cols bm = (m).col(0) cm = _sm.Matrix([(m).T.row(0),(m).T.row(1),(m).T.row(2),(m).T.row(3),(m).T.row(2)]) dm = (m).row(0) em = _sm.Matrix([(m).row(0),(m).row(1),(m).row(2),(m).row(3),(m).row(2)])
f2d81bc09fa2af4c22382b20205080bb8b83f1289e611acba0bcc47da7b96106
import sympy.physics.mechanics as _me import sympy as _sm import math as m import numpy as _np frame_a = _me.ReferenceFrame('a') c1, c2, c3 = _sm.symbols('c1 c2 c3', real=True) a = _me.inertia(frame_a, 1, 1, 1) particle_p1 = _me.Particle('p1', _me.Point('p1_pt'), _sm.Symbol('m')) particle_p2 = _me.Particle('p2', _me.Point('p2_pt'), _sm.Symbol('m')) body_r_cm = _me.Point('r_cm') body_r_f = _me.ReferenceFrame('r_f') body_r = _me.RigidBody('r', body_r_cm, body_r_f, _sm.symbols('m'), (_me.outer(body_r_f.x,body_r_f.x),body_r_cm)) frame_a.orient(body_r_f, 'DCM', _sm.Matrix([1,1,1,1,1,0,0,0,1]).reshape(3, 3)) point_o = _me.Point('o') m1 = _sm.symbols('m1') particle_p1.mass = m1 m2 = _sm.symbols('m2') particle_p2.mass = m2 mr = _sm.symbols('mr') body_r.mass = mr i1 = _sm.symbols('i1') i2 = _sm.symbols('i2') i3 = _sm.symbols('i3') body_r.inertia = (_me.inertia(body_r_f, i1, i2, i3, 0, 0, 0), body_r_cm) point_o.set_pos(particle_p1.point, c1*frame_a.x) point_o.set_pos(particle_p2.point, c2*frame_a.y) point_o.set_pos(body_r_cm, c3*frame_a.z) a = _me.inertia_of_point_mass(particle_p1.mass, particle_p1.point.pos_from(point_o), frame_a) a = _me.inertia_of_point_mass(particle_p2.mass, particle_p2.point.pos_from(point_o), frame_a) a = body_r.inertia[0] + _me.inertia_of_point_mass(body_r.mass, body_r.masscenter.pos_from(point_o), frame_a) a = _me.inertia_of_point_mass(particle_p1.mass, particle_p1.point.pos_from(point_o), frame_a) + _me.inertia_of_point_mass(particle_p2.mass, particle_p2.point.pos_from(point_o), frame_a) + body_r.inertia[0] + _me.inertia_of_point_mass(body_r.mass, body_r.masscenter.pos_from(point_o), frame_a) a = _me.inertia_of_point_mass(particle_p1.mass, particle_p1.point.pos_from(point_o), frame_a) + body_r.inertia[0] + _me.inertia_of_point_mass(body_r.mass, body_r.masscenter.pos_from(point_o), frame_a) a = body_r.inertia[0] + _me.inertia_of_point_mass(body_r.mass, body_r.masscenter.pos_from(point_o), frame_a) a = body_r.inertia[0] particle_p2.point.set_pos(particle_p1.point, c1*frame_a.x+c2*frame_a.y) body_r_cm.set_pos(particle_p1.point, c3*frame_a.x) body_r_cm.set_pos(particle_p2.point, c3*frame_a.y) b = _me.functions.center_of_mass(point_o,particle_p1, particle_p2, body_r) b = _me.functions.center_of_mass(point_o,particle_p1, body_r) b = _me.functions.center_of_mass(particle_p1.point,particle_p1, particle_p2, body_r) u1, u2, u3 = _me.dynamicsymbols('u1 u2 u3') v = u1*frame_a.x+u2*frame_a.y+u3*frame_a.z u = (v+c1*frame_a.x).normalize() particle_p1.point.set_vel(frame_a, u1*frame_a.x) a = particle_p1.point.partial_velocity(frame_a, u1) m = particle_p1.mass+body_r.mass m = particle_p2.mass m = particle_p1.mass+particle_p2.mass+body_r.mass
1ada95f96ab61862737db94cb1c033f8a5c2cecd0fff85eabc0dc521d94f7b4e
import sympy.physics.mechanics as _me import sympy as _sm import math as m import numpy as _np frame_n = _me.ReferenceFrame('n') frame_a = _me.ReferenceFrame('a') a = 0 d = _me.inertia(frame_a, 1, 1, 1) point_po1 = _me.Point('po1') point_po2 = _me.Point('po2') particle_p1 = _me.Particle('p1', _me.Point('p1_pt'), _sm.Symbol('m')) particle_p2 = _me.Particle('p2', _me.Point('p2_pt'), _sm.Symbol('m')) c1, c2, c3 = _me.dynamicsymbols('c1 c2 c3') c1_d, c2_d, c3_d = _me.dynamicsymbols('c1_ c2_ c3_', 1) body_r_cm = _me.Point('r_cm') body_r_cm.set_vel(frame_n, 0) body_r_f = _me.ReferenceFrame('r_f') body_r = _me.RigidBody('r', body_r_cm, body_r_f, _sm.symbols('m'), (_me.outer(body_r_f.x,body_r_f.x),body_r_cm)) point_po2.set_pos(particle_p1.point, c1*frame_a.x) v = 2*point_po2.pos_from(particle_p1.point)+c2*frame_a.y frame_a.set_ang_vel(frame_n, c3*frame_a.z) v = 2*frame_a.ang_vel_in(frame_n)+c2*frame_a.y body_r_f.set_ang_vel(frame_n, c3*frame_a.z) v = 2*body_r_f.ang_vel_in(frame_n)+c2*frame_a.y frame_a.set_ang_acc(frame_n, (frame_a.ang_vel_in(frame_n)).dt(frame_a)) v = 2*frame_a.ang_acc_in(frame_n)+c2*frame_a.y particle_p1.point.set_vel(frame_a, c1*frame_a.x+c3*frame_a.y) body_r_cm.set_acc(frame_n, c2*frame_a.y) v_a = _me.cross(body_r_cm.acc(frame_n), particle_p1.point.vel(frame_a)) x_b_c = v_a x_b_d = 2*x_b_c a_b_c_d_e = x_b_d*2 a_b_c = 2*c1*c2*c3 a_b_c += 2*c1 a_b_c = 3*c1 q1, q2, u1, u2 = _me.dynamicsymbols('q1 q2 u1 u2') q1_d, q2_d, u1_d, u2_d = _me.dynamicsymbols('q1_ q2_ u1_ u2_', 1) x, y = _me.dynamicsymbols('x y') x_d, y_d = _me.dynamicsymbols('x_ y_', 1) x_dd, y_dd = _me.dynamicsymbols('x_ y_', 2) yy = _me.dynamicsymbols('yy') yy = x*x_d**2+1 m = _sm.Matrix([[0]]) m[0] = 2*x m = m.row_insert(m.shape[0], _sm.Matrix([[0]])) m[m.shape[0]-1] = 2*y a = 2*m[0] m = _sm.Matrix([1,2,3,4,5,6,7,8,9]).reshape(3, 3) m[0,1] = 5 a = m[0, 1]*2 force_ro = q1*frame_n.x torque_a = q2*frame_n.z force_ro = q1*frame_n.x + q2*frame_n.y f = force_ro*2
fd7bccacc7b9afd44ba294eb22a3062e1698bc72f5aa3b5e5b3f4229ca2d08bf
import sympy.physics.mechanics as _me import sympy as _sm import math as m import numpy as _np x, y = _me.dynamicsymbols('x y') x_d, y_d = _me.dynamicsymbols('x_ y_', 1) e = _sm.cos(x)+_sm.sin(x)+_sm.tan(x)+_sm.cosh(x)+_sm.sinh(x)+_sm.tanh(x)+_sm.acos(x)+_sm.asin(x)+_sm.atan(x)+_sm.log(x)+_sm.exp(x)+_sm.sqrt(x)+_sm.factorial(x)+_sm.ceiling(x)+_sm.floor(x)+_sm.sign(x) e = (x)**2+_sm.log(x, 10) a = _sm.Abs(-1*1)+int(1.5)+round(1.9) e1 = 2*x+3*y e2 = x+y am = _sm.Matrix([e1.expand().coeff(x), e1.expand().coeff(y), e2.expand().coeff(x), e2.expand().coeff(y)]).reshape(2, 2) b = (e1).expand().coeff(x) c = (e2).expand().coeff(y) d1 = (e1).collect(x).coeff(x,0) d2 = (e1).collect(x).coeff(x,1) fm = _sm.Matrix([i.collect(x)for i in _sm.Matrix([e1,e2]).reshape(1, 2)]).reshape((_sm.Matrix([e1,e2]).reshape(1, 2)).shape[0], (_sm.Matrix([e1,e2]).reshape(1, 2)).shape[1]) f = (e1).collect(y) g = (e1).subs({x:2*x}) gm = _sm.Matrix([i.subs({x:3}) for i in _sm.Matrix([e1,e2]).reshape(2, 1)]).reshape((_sm.Matrix([e1,e2]).reshape(2, 1)).shape[0], (_sm.Matrix([e1,e2]).reshape(2, 1)).shape[1]) frame_a = _me.ReferenceFrame('a') frame_b = _me.ReferenceFrame('b') theta = _me.dynamicsymbols('theta') frame_b.orient(frame_a, 'Axis', [theta, frame_a.z]) v1 = 2*frame_a.x-3*frame_a.y+frame_a.z v2 = frame_b.x+frame_b.y+frame_b.z a = _me.dot(v1, v2) bm = _sm.Matrix([_me.dot(v1, v2),_me.dot(v1, 2*v2)]).reshape(2, 1) c = _me.cross(v1, v2) d = 2*v1.magnitude()+3*v1.magnitude() dyadic = _me.outer(3*frame_a.x, frame_a.x)+_me.outer(frame_a.y, frame_a.y)+_me.outer(2*frame_a.z, frame_a.z) am = (dyadic).to_matrix(frame_b) m = _sm.Matrix([1,2,3]).reshape(3, 1) v = m[0]*frame_a.x +m[1]*frame_a.y +m[2]*frame_a.z
646dfab373e7913d1a28133d371e87d2c749aeda0bc1a79b53ddfce98494aa5f
import sympy.physics.mechanics as _me import sympy as _sm import math as m import numpy as _np x, y = _me.dynamicsymbols('x y') a, b, r = _sm.symbols('a b r', real=True) eqn = _sm.Matrix([[0]]) eqn[0] = a*x**3+b*y**2-r eqn = eqn.row_insert(eqn.shape[0], _sm.Matrix([[0]])) eqn[eqn.shape[0]-1] = a*_sm.sin(x)**2+b*_sm.cos(2*y)-r**2 matrix_list = [] for i in eqn:matrix_list.append(i.subs({a:2.0, b:3.0, r:1.0})) print(_sm.nsolve(matrix_list,(x,y),(_np.deg2rad(30),3.14)))
5af52d9e8d43dc1ae614d3d860804a47f80e03e3da1e8c4b9524cd0d7ebb75c4
import sympy.physics.mechanics as _me import sympy as _sm import math as m import numpy as _np x, y = _me.dynamicsymbols('x y') x_d, y_d = _me.dynamicsymbols('x_ y_', 1) e1 = (x+y)**2+(x-y)**3 e2 = (x-y)**2 e3 = x**2+y**2+2*x*y m1 = _sm.Matrix([e1,e2]).reshape(2, 1) m2 = _sm.Matrix([(x+y)**2,(x-y)**2]).reshape(1, 2) m3 = m1+_sm.Matrix([x,y]).reshape(2, 1) am = _sm.Matrix([i.expand() for i in m1]).reshape((m1).shape[0], (m1).shape[1]) cm = _sm.Matrix([i.expand() for i in _sm.Matrix([(x+y)**2,(x-y)**2]).reshape(1, 2)]).reshape((_sm.Matrix([(x+y)**2,(x-y)**2]).reshape(1, 2)).shape[0], (_sm.Matrix([(x+y)**2,(x-y)**2]).reshape(1, 2)).shape[1]) em = _sm.Matrix([i.expand() for i in m1+_sm.Matrix([x,y]).reshape(2, 1)]).reshape((m1+_sm.Matrix([x,y]).reshape(2, 1)).shape[0], (m1+_sm.Matrix([x,y]).reshape(2, 1)).shape[1]) f = (e1).expand() g = (e2).expand() a = _sm.factor((e3), x) bm = _sm.Matrix([_sm.factor(i, x) for i in m1]).reshape((m1).shape[0], (m1).shape[1]) cm = _sm.Matrix([_sm.factor(i, x) for i in m1+_sm.Matrix([x,y]).reshape(2, 1)]).reshape((m1+_sm.Matrix([x,y]).reshape(2, 1)).shape[0], (m1+_sm.Matrix([x,y]).reshape(2, 1)).shape[1]) a = (e3).diff(x) b = (e3).diff(y) cm = _sm.Matrix([i.diff(x) for i in m2]).reshape((m2).shape[0], (m2).shape[1]) dm = _sm.Matrix([i.diff(x) for i in m1+_sm.Matrix([x,y]).reshape(2, 1)]).reshape((m1+_sm.Matrix([x,y]).reshape(2, 1)).shape[0], (m1+_sm.Matrix([x,y]).reshape(2, 1)).shape[1]) frame_a = _me.ReferenceFrame('a') frame_b = _me.ReferenceFrame('b') frame_b.orient(frame_a, 'DCM', _sm.Matrix([1,0,0,1,0,0,1,0,0]).reshape(3, 3)) v1 = x*frame_a.x+y*frame_a.y+x*y*frame_a.z e = (v1).diff(x, frame_b) fm = _sm.Matrix([i.diff(_sm.Symbol('t')) for i in m1]).reshape((m1).shape[0], (m1).shape[1]) gm = _sm.Matrix([i.diff(_sm.Symbol('t')) for i in _sm.Matrix([(x+y)**2,(x-y)**2]).reshape(1, 2)]).reshape((_sm.Matrix([(x+y)**2,(x-y)**2]).reshape(1, 2)).shape[0], (_sm.Matrix([(x+y)**2,(x-y)**2]).reshape(1, 2)).shape[1]) h = (v1).dt(frame_b)
587a1de72cca1784cd6c47f861fc66c7d5a78a603b34e5eab538d95d1f05b0fd
import sympy.physics.mechanics as _me import sympy as _sm import math as m import numpy as _np frame_a = _me.ReferenceFrame('a') frame_b = _me.ReferenceFrame('b') q1, q2, q3 = _me.dynamicsymbols('q1 q2 q3') frame_b.orient(frame_a, 'Axis', [q3, frame_a.x]) dcm = frame_a.dcm(frame_b) m = dcm*3-frame_a.dcm(frame_b) r = _me.dynamicsymbols('r') circle_area = _sm.pi*r**2 u, a = _me.dynamicsymbols('u a') x, y = _me.dynamicsymbols('x y') s = u*_me.dynamicsymbols._t-1/2*a*_me.dynamicsymbols._t**2 expr1 = 2*a*0.5-1.25+0.25 expr2 = -1*x**2+y**2+0.25*(x+y)**2 expr3 = 0.5*10**(-10) dyadic = _me.outer(frame_a.x, frame_a.x)+_me.outer(frame_a.y, frame_a.y)+_me.outer(frame_a.z, frame_a.z)
7584d1b57bcc0d71e22b35c70f64a1d1f704ba4a1bdf0aff19b49ea9a66bacef
import sympy.physics.mechanics as _me import sympy as _sm import math as m import numpy as _np x, y = _me.dynamicsymbols('x y') a11, a12, a21, a22, b1, b2 = _sm.symbols('a11 a12 a21 a22 b1 b2', real=True) eqn = _sm.Matrix([[0]]) eqn[0] = a11*x+a12*y-b1 eqn = eqn.row_insert(eqn.shape[0], _sm.Matrix([[0]])) eqn[eqn.shape[0]-1] = a21*x+a22*y-b2 eqn_list = [] for i in eqn: eqn_list.append(i.subs({a11:2, a12:5, a21:3, a22:4, b1:7, b2:6})) print(_sm.linsolve(eqn_list, x,y))
8eb25f6f4264d853f8192e690dad14079a61d228c455dd57f2678a799ad35678
import sympy.physics.mechanics as _me import sympy as _sm import math as m import numpy as _np x1, x2 = _me.dynamicsymbols('x1 x2') f1 = x1*x2+3*x1**2 f2 = x1*_me.dynamicsymbols._t+x2*_me.dynamicsymbols._t**2 x, y = _me.dynamicsymbols('x y') x_d, y_d = _me.dynamicsymbols('x_ y_', 1) y_dd = _me.dynamicsymbols('y_', 2) q1, q2, q3, u1, u2 = _me.dynamicsymbols('q1 q2 q3 u1 u2') p1, p2 = _me.dynamicsymbols('p1 p2') p1_d, p2_d = _me.dynamicsymbols('p1_ p2_', 1) w1, w2, w3, r1, r2 = _me.dynamicsymbols('w1 w2 w3 r1 r2') w1_d, w2_d, w3_d, r1_d, r2_d = _me.dynamicsymbols('w1_ w2_ w3_ r1_ r2_', 1) r1_dd, r2_dd = _me.dynamicsymbols('r1_ r2_', 2) c11, c12, c21, c22 = _me.dynamicsymbols('c11 c12 c21 c22') d11, d12, d13 = _me.dynamicsymbols('d11 d12 d13') j1, j2 = _me.dynamicsymbols('j1 j2') n = _sm.symbols('n') n = _sm.I
152bb84cfd810d3423cd884c91ca518576dbde4003dbb5c2c8efc4a0be7901c9
import sympy.physics.mechanics as _me import sympy as _sm import math as m import numpy as _np g, lb, w, h = _sm.symbols('g lb w h', real=True) theta, phi, omega, alpha = _me.dynamicsymbols('theta phi omega alpha') theta_d, phi_d, omega_d, alpha_d = _me.dynamicsymbols('theta_ phi_ omega_ alpha_', 1) theta_dd, phi_dd = _me.dynamicsymbols('theta_ phi_', 2) frame_n = _me.ReferenceFrame('n') body_a_cm = _me.Point('a_cm') body_a_cm.set_vel(frame_n, 0) body_a_f = _me.ReferenceFrame('a_f') body_a = _me.RigidBody('a', body_a_cm, body_a_f, _sm.symbols('m'), (_me.outer(body_a_f.x,body_a_f.x),body_a_cm)) body_b_cm = _me.Point('b_cm') body_b_cm.set_vel(frame_n, 0) body_b_f = _me.ReferenceFrame('b_f') body_b = _me.RigidBody('b', body_b_cm, body_b_f, _sm.symbols('m'), (_me.outer(body_b_f.x,body_b_f.x),body_b_cm)) body_a_f.orient(frame_n, 'Axis', [theta, frame_n.y]) body_b_f.orient(body_a_f, 'Axis', [phi, body_a_f.z]) point_o = _me.Point('o') la = (lb-h/2)/2 body_a_cm.set_pos(point_o, la*body_a_f.z) body_b_cm.set_pos(point_o, lb*body_a_f.z) body_a_f.set_ang_vel(frame_n, omega*frame_n.y) body_b_f.set_ang_vel(body_a_f, alpha*body_a_f.z) point_o.set_vel(frame_n, 0) body_a_cm.v2pt_theory(point_o,frame_n,body_a_f) body_b_cm.v2pt_theory(point_o,frame_n,body_a_f) ma = _sm.symbols('ma') body_a.mass = ma mb = _sm.symbols('mb') body_b.mass = mb iaxx = 1/12*ma*(2*la)**2 iayy = iaxx iazz = 0 ibxx = 1/12*mb*h**2 ibyy = 1/12*mb*(w**2+h**2) ibzz = 1/12*mb*w**2 body_a.inertia = (_me.inertia(body_a_f, iaxx, iayy, iazz, 0, 0, 0), body_a_cm) body_b.inertia = (_me.inertia(body_b_f, ibxx, ibyy, ibzz, 0, 0, 0), body_b_cm) force_a = body_a.mass*(g*frame_n.z) force_b = body_b.mass*(g*frame_n.z) kd_eqs = [theta_d - omega, phi_d - alpha] forceList = [(body_a.masscenter,body_a.mass*(g*frame_n.z)), (body_b.masscenter,body_b.mass*(g*frame_n.z))] kane = _me.KanesMethod(frame_n, q_ind=[theta,phi], u_ind=[omega, alpha], kd_eqs = kd_eqs) fr, frstar = kane.kanes_equations([body_a, body_b], forceList) zero = fr+frstar from pydy.system import System sys = System(kane, constants = {g:9.81, lb:0.2, w:0.2, h:0.1, ma:0.01, mb:0.1}, specifieds={}, initial_conditions={theta:_np.deg2rad(90), phi:_np.deg2rad(0.5), omega:0, alpha:0}, times = _np.linspace(0.0, 10, 10/0.02)) y=sys.integrate()
0ddc5c5ab9b71cc42ecb26373e4eac2876f845785010cfc4298dc761908ff1e7
import sympy.physics.mechanics as _me import sympy as _sm import math as m import numpy as _np q1, q2 = _me.dynamicsymbols('q1 q2') q1_d, q2_d = _me.dynamicsymbols('q1_ q2_', 1) q1_dd, q2_dd = _me.dynamicsymbols('q1_ q2_', 2) l, m, g = _sm.symbols('l m g', real=True) frame_n = _me.ReferenceFrame('n') point_pn = _me.Point('pn') point_pn.set_vel(frame_n, 0) theta1 = _sm.atan(q2/q1) frame_a = _me.ReferenceFrame('a') frame_a.orient(frame_n, 'Axis', [theta1, frame_n.z]) particle_p = _me.Particle('p', _me.Point('p_pt'), _sm.Symbol('m')) particle_p.point.set_pos(point_pn, q1*frame_n.x+q2*frame_n.y) particle_p.mass = m particle_p.point.set_vel(frame_n, (point_pn.pos_from(particle_p.point)).dt(frame_n)) f_v = _me.dot((particle_p.point.vel(frame_n)).express(frame_a), frame_a.x) force_p = particle_p.mass*(g*frame_n.x) dependent = _sm.Matrix([[0]]) dependent[0] = f_v velocity_constraints = [i for i in dependent] u_q1_d = _me.dynamicsymbols('u_q1_d') u_q2_d = _me.dynamicsymbols('u_q2_d') kd_eqs = [q1_d-u_q1_d, q2_d-u_q2_d] forceList = [(particle_p.point,particle_p.mass*(g*frame_n.x))] kane = _me.KanesMethod(frame_n, q_ind=[q1,q2], u_ind=[u_q2_d], u_dependent=[u_q1_d], kd_eqs = kd_eqs, velocity_constraints = velocity_constraints) fr, frstar = kane.kanes_equations([particle_p], forceList) zero = fr+frstar f_c = point_pn.pos_from(particle_p.point).magnitude()-l config = _sm.Matrix([[0]]) config[0] = f_c zero = zero.row_insert(zero.shape[0], _sm.Matrix([[0]])) zero[zero.shape[0]-1] = config[0]
b94f5acd3506ad8d790520edc394ff57eee09a3ca11db5ec973926c01bc58c69
import sympy.physics.mechanics as _me import sympy as _sm import math as m import numpy as _np q1, q2, u1, u2 = _me.dynamicsymbols('q1 q2 u1 u2') q1_d, q2_d, u1_d, u2_d = _me.dynamicsymbols('q1_ q2_ u1_ u2_', 1) l, m, g = _sm.symbols('l m g', real=True) frame_n = _me.ReferenceFrame('n') frame_a = _me.ReferenceFrame('a') frame_b = _me.ReferenceFrame('b') frame_a.orient(frame_n, 'Axis', [q1, frame_n.z]) frame_b.orient(frame_n, 'Axis', [q2, frame_n.z]) frame_a.set_ang_vel(frame_n, u1*frame_n.z) frame_b.set_ang_vel(frame_n, u2*frame_n.z) point_o = _me.Point('o') particle_p = _me.Particle('p', _me.Point('p_pt'), _sm.Symbol('m')) particle_r = _me.Particle('r', _me.Point('r_pt'), _sm.Symbol('m')) particle_p.point.set_pos(point_o, l*frame_a.x) particle_r.point.set_pos(particle_p.point, l*frame_b.x) point_o.set_vel(frame_n, 0) particle_p.point.v2pt_theory(point_o,frame_n,frame_a) particle_r.point.v2pt_theory(particle_p.point,frame_n,frame_b) particle_p.mass = m particle_r.mass = m force_p = particle_p.mass*(g*frame_n.x) force_r = particle_r.mass*(g*frame_n.x) kd_eqs = [q1_d - u1, q2_d - u2] forceList = [(particle_p.point,particle_p.mass*(g*frame_n.x)), (particle_r.point,particle_r.mass*(g*frame_n.x))] kane = _me.KanesMethod(frame_n, q_ind=[q1,q2], u_ind=[u1, u2], kd_eqs = kd_eqs) fr, frstar = kane.kanes_equations([particle_p, particle_r], forceList) zero = fr+frstar from pydy.system import System sys = System(kane, constants = {l:1, m:1, g:9.81}, specifieds={}, initial_conditions={q1:.1, q2:.2, u1:0, u2:0}, times = _np.linspace(0.0, 10, 10/.01)) y=sys.integrate()
f5178202a7141f91d80601e6a29f61e59c79e267d271664de4be45eab087938c
import sympy.physics.mechanics as _me import sympy as _sm import math as m import numpy as _np m, k, b, g = _sm.symbols('m k b g', real=True) position, speed = _me.dynamicsymbols('position speed') position_d, speed_d = _me.dynamicsymbols('position_ speed_', 1) o = _me.dynamicsymbols('o') force = o*_sm.sin(_me.dynamicsymbols._t) frame_ceiling = _me.ReferenceFrame('ceiling') point_origin = _me.Point('origin') point_origin.set_vel(frame_ceiling, 0) particle_block = _me.Particle('block', _me.Point('block_pt'), _sm.Symbol('m')) particle_block.point.set_pos(point_origin, position*frame_ceiling.x) particle_block.mass = m particle_block.point.set_vel(frame_ceiling, speed*frame_ceiling.x) force_magnitude = m*g-k*position-b*speed+force force_block = (force_magnitude*frame_ceiling.x).subs({position_d:speed}) kd_eqs = [position_d - speed] forceList = [(particle_block.point,(force_magnitude*frame_ceiling.x).subs({position_d:speed}))] kane = _me.KanesMethod(frame_ceiling, q_ind=[position], u_ind=[speed], kd_eqs = kd_eqs) fr, frstar = kane.kanes_equations([particle_block], forceList) zero = fr+frstar from pydy.system import System sys = System(kane, constants = {m:1.0, k:1.0, b:0.2, g:9.8}, specifieds={_me.dynamicsymbols('t'):lambda x, t: t, o:2}, initial_conditions={position:0.1, speed:-1*1.0}, times = _np.linspace(0.0, 10.0, 10.0/0.01)) y=sys.integrate()
e1fbafbfbe870792072d3d45b65f55008fb748b943d3a9ff3c7e619e17ac96ea
from collections import deque from random import randint from sympy.external import import_module from sympy import Mul, Basic, Number, Pow, Integer from sympy.physics.quantum.represent import represent from sympy.physics.quantum.dagger import Dagger __all__ = [ # Public interfaces 'generate_gate_rules', 'generate_equivalent_ids', 'GateIdentity', 'bfs_identity_search', 'random_identity_search', # "Private" functions 'is_scalar_sparse_matrix', 'is_scalar_nonsparse_matrix', 'is_degenerate', 'is_reducible', ] np = import_module('numpy') scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']}) def is_scalar_sparse_matrix(circuit, nqubits, identity_only, eps=1e-11): """Checks if a given scipy.sparse matrix is a scalar matrix. A scalar matrix is such that B = bI, where B is the scalar matrix, b is some scalar multiple, and I is the identity matrix. A scalar matrix would have only the element b along it's main diagonal and zeroes elsewhere. Parameters ========== circuit : Gate tuple Sequence of quantum gates representing a quantum circuit nqubits : int Number of qubits in the circuit identity_only : bool Check for only identity matrices eps : number The tolerance value for zeroing out elements in the matrix. Values in the range [-eps, +eps] will be changed to a zero. """ if not np or not scipy: pass matrix = represent(Mul(*circuit), nqubits=nqubits, format='scipy.sparse') # In some cases, represent returns a 1D scalar value in place # of a multi-dimensional scalar matrix if (isinstance(matrix, int)): return matrix == 1 if identity_only else True # If represent returns a matrix, check if the matrix is diagonal # and if every item along the diagonal is the same else: # Due to floating pointing operations, must zero out # elements that are "very" small in the dense matrix # See parameter for default value. # Get the ndarray version of the dense matrix dense_matrix = matrix.todense().getA() # Since complex values can't be compared, must split # the matrix into real and imaginary components # Find the real values in between -eps and eps bool_real = np.logical_and(dense_matrix.real > -eps, dense_matrix.real < eps) # Find the imaginary values between -eps and eps bool_imag = np.logical_and(dense_matrix.imag > -eps, dense_matrix.imag < eps) # Replaces values between -eps and eps with 0 corrected_real = np.where(bool_real, 0.0, dense_matrix.real) corrected_imag = np.where(bool_imag, 0.0, dense_matrix.imag) # Convert the matrix with real values into imaginary values corrected_imag = corrected_imag * complex(1j) # Recombine the real and imaginary components corrected_dense = corrected_real + corrected_imag # Check if it's diagonal row_indices = corrected_dense.nonzero()[0] col_indices = corrected_dense.nonzero()[1] # Check if the rows indices and columns indices are the same # If they match, then matrix only contains elements along diagonal bool_indices = row_indices == col_indices is_diagonal = bool_indices.all() first_element = corrected_dense[0][0] # If the first element is a zero, then can't rescale matrix # and definitely not diagonal if (first_element == 0.0 + 0.0j): return False # The dimensions of the dense matrix should still # be 2^nqubits if there are elements all along the # the main diagonal trace_of_corrected = (corrected_dense/first_element).trace() expected_trace = pow(2, nqubits) has_correct_trace = trace_of_corrected == expected_trace # If only looking for identity matrices # first element must be a 1 real_is_one = abs(first_element.real - 1.0) < eps imag_is_zero = abs(first_element.imag) < eps is_one = real_is_one and imag_is_zero is_identity = is_one if identity_only else True return bool(is_diagonal and has_correct_trace and is_identity) def is_scalar_nonsparse_matrix(circuit, nqubits, identity_only, eps=None): """Checks if a given circuit, in matrix form, is equivalent to a scalar value. Parameters ========== circuit : Gate tuple Sequence of quantum gates representing a quantum circuit nqubits : int Number of qubits in the circuit identity_only : bool Check for only identity matrices eps : number This argument is ignored. It is just for signature compatibility with is_scalar_sparse_matrix. Note: Used in situations when is_scalar_sparse_matrix has bugs """ matrix = represent(Mul(*circuit), nqubits=nqubits) # In some cases, represent returns a 1D scalar value in place # of a multi-dimensional scalar matrix if (isinstance(matrix, Number)): return matrix == 1 if identity_only else True # If represent returns a matrix, check if the matrix is diagonal # and if every item along the diagonal is the same else: # Added up the diagonal elements matrix_trace = matrix.trace() # Divide the trace by the first element in the matrix # if matrix is not required to be the identity matrix adjusted_matrix_trace = (matrix_trace/matrix[0] if not identity_only else matrix_trace) is_identity = matrix[0] == 1.0 if identity_only else True has_correct_trace = adjusted_matrix_trace == pow(2, nqubits) # The matrix is scalar if it's diagonal and the adjusted trace # value is equal to 2^nqubits return bool( matrix.is_diagonal() and has_correct_trace and is_identity) if np and scipy: is_scalar_matrix = is_scalar_sparse_matrix else: is_scalar_matrix = is_scalar_nonsparse_matrix def _get_min_qubits(a_gate): if isinstance(a_gate, Pow): return a_gate.base.min_qubits else: return a_gate.min_qubits def ll_op(left, right): """Perform a LL operation. A LL operation multiplies both left and right circuits with the dagger of the left circuit's leftmost gate, and the dagger is multiplied on the left side of both circuits. If a LL is possible, it returns the new gate rule as a 2-tuple (LHS, RHS), where LHS is the left circuit and and RHS is the right circuit of the new rule. If a LL is not possible, None is returned. Parameters ========== left : Gate tuple The left circuit of a gate rule expression. right : Gate tuple The right circuit of a gate rule expression. Examples ======== Generate a new gate rule using a LL operation: >>> from sympy.physics.quantum.identitysearch import ll_op >>> from sympy.physics.quantum.gate import X, Y, Z >>> x = X(0); y = Y(0); z = Z(0) >>> ll_op((x, y, z), ()) ((Y(0), Z(0)), (X(0),)) >>> ll_op((y, z), (x,)) ((Z(0),), (Y(0), X(0))) """ if (len(left) > 0): ll_gate = left[0] ll_gate_is_unitary = is_scalar_matrix( (Dagger(ll_gate), ll_gate), _get_min_qubits(ll_gate), True) if (len(left) > 0 and ll_gate_is_unitary): # Get the new left side w/o the leftmost gate new_left = left[1:len(left)] # Add the leftmost gate to the left position on the right side new_right = (Dagger(ll_gate),) + right # Return the new gate rule return (new_left, new_right) return None def lr_op(left, right): """Perform a LR operation. A LR operation multiplies both left and right circuits with the dagger of the left circuit's rightmost gate, and the dagger is multiplied on the right side of both circuits. If a LR is possible, it returns the new gate rule as a 2-tuple (LHS, RHS), where LHS is the left circuit and and RHS is the right circuit of the new rule. If a LR is not possible, None is returned. Parameters ========== left : Gate tuple The left circuit of a gate rule expression. right : Gate tuple The right circuit of a gate rule expression. Examples ======== Generate a new gate rule using a LR operation: >>> from sympy.physics.quantum.identitysearch import lr_op >>> from sympy.physics.quantum.gate import X, Y, Z >>> x = X(0); y = Y(0); z = Z(0) >>> lr_op((x, y, z), ()) ((X(0), Y(0)), (Z(0),)) >>> lr_op((x, y), (z,)) ((X(0),), (Z(0), Y(0))) """ if (len(left) > 0): lr_gate = left[len(left) - 1] lr_gate_is_unitary = is_scalar_matrix( (Dagger(lr_gate), lr_gate), _get_min_qubits(lr_gate), True) if (len(left) > 0 and lr_gate_is_unitary): # Get the new left side w/o the rightmost gate new_left = left[0:len(left) - 1] # Add the rightmost gate to the right position on the right side new_right = right + (Dagger(lr_gate),) # Return the new gate rule return (new_left, new_right) return None def rl_op(left, right): """Perform a RL operation. A RL operation multiplies both left and right circuits with the dagger of the right circuit's leftmost gate, and the dagger is multiplied on the left side of both circuits. If a RL is possible, it returns the new gate rule as a 2-tuple (LHS, RHS), where LHS is the left circuit and and RHS is the right circuit of the new rule. If a RL is not possible, None is returned. Parameters ========== left : Gate tuple The left circuit of a gate rule expression. right : Gate tuple The right circuit of a gate rule expression. Examples ======== Generate a new gate rule using a RL operation: >>> from sympy.physics.quantum.identitysearch import rl_op >>> from sympy.physics.quantum.gate import X, Y, Z >>> x = X(0); y = Y(0); z = Z(0) >>> rl_op((x,), (y, z)) ((Y(0), X(0)), (Z(0),)) >>> rl_op((x, y), (z,)) ((Z(0), X(0), Y(0)), ()) """ if (len(right) > 0): rl_gate = right[0] rl_gate_is_unitary = is_scalar_matrix( (Dagger(rl_gate), rl_gate), _get_min_qubits(rl_gate), True) if (len(right) > 0 and rl_gate_is_unitary): # Get the new right side w/o the leftmost gate new_right = right[1:len(right)] # Add the leftmost gate to the left position on the left side new_left = (Dagger(rl_gate),) + left # Return the new gate rule return (new_left, new_right) return None def rr_op(left, right): """Perform a RR operation. A RR operation multiplies both left and right circuits with the dagger of the right circuit's rightmost gate, and the dagger is multiplied on the right side of both circuits. If a RR is possible, it returns the new gate rule as a 2-tuple (LHS, RHS), where LHS is the left circuit and and RHS is the right circuit of the new rule. If a RR is not possible, None is returned. Parameters ========== left : Gate tuple The left circuit of a gate rule expression. right : Gate tuple The right circuit of a gate rule expression. Examples ======== Generate a new gate rule using a RR operation: >>> from sympy.physics.quantum.identitysearch import rr_op >>> from sympy.physics.quantum.gate import X, Y, Z >>> x = X(0); y = Y(0); z = Z(0) >>> rr_op((x, y), (z,)) ((X(0), Y(0), Z(0)), ()) >>> rr_op((x,), (y, z)) ((X(0), Z(0)), (Y(0),)) """ if (len(right) > 0): rr_gate = right[len(right) - 1] rr_gate_is_unitary = is_scalar_matrix( (Dagger(rr_gate), rr_gate), _get_min_qubits(rr_gate), True) if (len(right) > 0 and rr_gate_is_unitary): # Get the new right side w/o the rightmost gate new_right = right[0:len(right) - 1] # Add the rightmost gate to the right position on the right side new_left = left + (Dagger(rr_gate),) # Return the new gate rule return (new_left, new_right) return None def generate_gate_rules(gate_seq, return_as_muls=False): """Returns a set of gate rules. Each gate rules is represented as a 2-tuple of tuples or Muls. An empty tuple represents an arbitrary scalar value. This function uses the four operations (LL, LR, RL, RR) to generate the gate rules. A gate rule is an expression such as ABC = D or AB = CD, where A, B, C, and D are gates. Each value on either side of the equal sign represents a circuit. The four operations allow one to find a set of equivalent circuits from a gate identity. The letters denoting the operation tell the user what activities to perform on each expression. The first letter indicates which side of the equal sign to focus on. The second letter indicates which gate to focus on given the side. Once this information is determined, the inverse of the gate is multiplied on both circuits to create a new gate rule. For example, given the identity, ABCD = 1, a LL operation means look at the left value and multiply both left sides by the inverse of the leftmost gate A. If A is Hermitian, the inverse of A is still A. The resulting new rule is BCD = A. The following is a summary of the four operations. Assume that in the examples, all gates are Hermitian. LL : left circuit, left multiply ABCD = E -> AABCD = AE -> BCD = AE LR : left circuit, right multiply ABCD = E -> ABCDD = ED -> ABC = ED RL : right circuit, left multiply ABC = ED -> EABC = EED -> EABC = D RR : right circuit, right multiply AB = CD -> ABD = CDD -> ABD = C The number of gate rules generated is n*(n+1), where n is the number of gates in the sequence (unproven). Parameters ========== gate_seq : Gate tuple, Mul, or Number A variable length tuple or Mul of Gates whose product is equal to a scalar matrix return_as_muls : bool True to return a set of Muls; False to return a set of tuples Examples ======== Find the gate rules of the current circuit using tuples: >>> from sympy.physics.quantum.identitysearch import generate_gate_rules >>> from sympy.physics.quantum.gate import X, Y, Z >>> x = X(0); y = Y(0); z = Z(0) >>> generate_gate_rules((x, x)) {((X(0),), (X(0),)), ((X(0), X(0)), ())} >>> generate_gate_rules((x, y, z)) {((), (X(0), Z(0), Y(0))), ((), (Y(0), X(0), Z(0))), ((), (Z(0), Y(0), X(0))), ((X(0),), (Z(0), Y(0))), ((Y(0),), (X(0), Z(0))), ((Z(0),), (Y(0), X(0))), ((X(0), Y(0)), (Z(0),)), ((Y(0), Z(0)), (X(0),)), ((Z(0), X(0)), (Y(0),)), ((X(0), Y(0), Z(0)), ()), ((Y(0), Z(0), X(0)), ()), ((Z(0), X(0), Y(0)), ())} Find the gate rules of the current circuit using Muls: >>> generate_gate_rules(x*x, return_as_muls=True) {(1, 1)} >>> generate_gate_rules(x*y*z, return_as_muls=True) {(1, X(0)*Z(0)*Y(0)), (1, Y(0)*X(0)*Z(0)), (1, Z(0)*Y(0)*X(0)), (X(0)*Y(0), Z(0)), (Y(0)*Z(0), X(0)), (Z(0)*X(0), Y(0)), (X(0)*Y(0)*Z(0), 1), (Y(0)*Z(0)*X(0), 1), (Z(0)*X(0)*Y(0), 1), (X(0), Z(0)*Y(0)), (Y(0), X(0)*Z(0)), (Z(0), Y(0)*X(0))} """ if isinstance(gate_seq, Number): if return_as_muls: return {(Integer(1), Integer(1))} else: return {((), ())} elif isinstance(gate_seq, Mul): gate_seq = gate_seq.args # Each item in queue is a 3-tuple: # i) first item is the left side of an equality # ii) second item is the right side of an equality # iii) third item is the number of operations performed # The argument, gate_seq, will start on the left side, and # the right side will be empty, implying the presence of an # identity. queue = deque() # A set of gate rules rules = set() # Maximum number of operations to perform max_ops = len(gate_seq) def process_new_rule(new_rule, ops): if new_rule is not None: new_left, new_right = new_rule if new_rule not in rules and (new_right, new_left) not in rules: rules.add(new_rule) # If haven't reached the max limit on operations if ops + 1 < max_ops: queue.append(new_rule + (ops + 1,)) queue.append((gate_seq, (), 0)) rules.add((gate_seq, ())) while len(queue) > 0: left, right, ops = queue.popleft() # Do a LL new_rule = ll_op(left, right) process_new_rule(new_rule, ops) # Do a LR new_rule = lr_op(left, right) process_new_rule(new_rule, ops) # Do a RL new_rule = rl_op(left, right) process_new_rule(new_rule, ops) # Do a RR new_rule = rr_op(left, right) process_new_rule(new_rule, ops) if return_as_muls: # Convert each rule as tuples into a rule as muls mul_rules = set() for rule in rules: left, right = rule mul_rules.add((Mul(*left), Mul(*right))) rules = mul_rules return rules def generate_equivalent_ids(gate_seq, return_as_muls=False): """Returns a set of equivalent gate identities. A gate identity is a quantum circuit such that the product of the gates in the circuit is equal to a scalar value. For example, XYZ = i, where X, Y, Z are the Pauli gates and i is the imaginary value, is considered a gate identity. This function uses the four operations (LL, LR, RL, RR) to generate the gate rules and, subsequently, to locate equivalent gate identities. Note that all equivalent identities are reachable in n operations from the starting gate identity, where n is the number of gates in the sequence. The max number of gate identities is 2n, where n is the number of gates in the sequence (unproven). Parameters ========== gate_seq : Gate tuple, Mul, or Number A variable length tuple or Mul of Gates whose product is equal to a scalar matrix. return_as_muls: bool True to return as Muls; False to return as tuples Examples ======== Find equivalent gate identities from the current circuit with tuples: >>> from sympy.physics.quantum.identitysearch import generate_equivalent_ids >>> from sympy.physics.quantum.gate import X, Y, Z >>> x = X(0); y = Y(0); z = Z(0) >>> generate_equivalent_ids((x, x)) {(X(0), X(0))} >>> generate_equivalent_ids((x, y, z)) {(X(0), Y(0), Z(0)), (X(0), Z(0), Y(0)), (Y(0), X(0), Z(0)), (Y(0), Z(0), X(0)), (Z(0), X(0), Y(0)), (Z(0), Y(0), X(0))} Find equivalent gate identities from the current circuit with Muls: >>> generate_equivalent_ids(x*x, return_as_muls=True) {1} >>> generate_equivalent_ids(x*y*z, return_as_muls=True) {X(0)*Y(0)*Z(0), X(0)*Z(0)*Y(0), Y(0)*X(0)*Z(0), Y(0)*Z(0)*X(0), Z(0)*X(0)*Y(0), Z(0)*Y(0)*X(0)} """ if isinstance(gate_seq, Number): return {Integer(1)} elif isinstance(gate_seq, Mul): gate_seq = gate_seq.args # Filter through the gate rules and keep the rules # with an empty tuple either on the left or right side # A set of equivalent gate identities eq_ids = set() gate_rules = generate_gate_rules(gate_seq) for rule in gate_rules: l, r = rule if l == (): eq_ids.add(r) elif r == (): eq_ids.add(l) if return_as_muls: convert_to_mul = lambda id_seq: Mul(*id_seq) eq_ids = set(map(convert_to_mul, eq_ids)) return eq_ids class GateIdentity(Basic): """Wrapper class for circuits that reduce to a scalar value. A gate identity is a quantum circuit such that the product of the gates in the circuit is equal to a scalar value. For example, XYZ = i, where X, Y, Z are the Pauli gates and i is the imaginary value, is considered a gate identity. Parameters ========== args : Gate tuple A variable length tuple of Gates that form an identity. Examples ======== Create a GateIdentity and look at its attributes: >>> from sympy.physics.quantum.identitysearch import GateIdentity >>> from sympy.physics.quantum.gate import X, Y, Z >>> x = X(0); y = Y(0); z = Z(0) >>> an_identity = GateIdentity(x, y, z) >>> an_identity.circuit X(0)*Y(0)*Z(0) >>> an_identity.equivalent_ids {(X(0), Y(0), Z(0)), (X(0), Z(0), Y(0)), (Y(0), X(0), Z(0)), (Y(0), Z(0), X(0)), (Z(0), X(0), Y(0)), (Z(0), Y(0), X(0))} """ def __new__(cls, *args): # args should be a tuple - a variable length argument list obj = Basic.__new__(cls, *args) obj._circuit = Mul(*args) obj._rules = generate_gate_rules(args) obj._eq_ids = generate_equivalent_ids(args) return obj @property def circuit(self): return self._circuit @property def gate_rules(self): return self._rules @property def equivalent_ids(self): return self._eq_ids @property def sequence(self): return self.args def __str__(self): """Returns the string of gates in a tuple.""" return str(self.circuit) def is_degenerate(identity_set, gate_identity): """Checks if a gate identity is a permutation of another identity. Parameters ========== identity_set : set A Python set with GateIdentity objects. gate_identity : GateIdentity The GateIdentity to check for existence in the set. Examples ======== Check if the identity is a permutation of another identity: >>> from sympy.physics.quantum.identitysearch import ( ... GateIdentity, is_degenerate) >>> from sympy.physics.quantum.gate import X, Y, Z >>> x = X(0); y = Y(0); z = Z(0) >>> an_identity = GateIdentity(x, y, z) >>> id_set = {an_identity} >>> another_id = (y, z, x) >>> is_degenerate(id_set, another_id) True >>> another_id = (x, x) >>> is_degenerate(id_set, another_id) False """ # For now, just iteratively go through the set and check if the current # gate_identity is a permutation of an identity in the set for an_id in identity_set: if (gate_identity in an_id.equivalent_ids): return True return False def is_reducible(circuit, nqubits, begin, end): """Determines if a circuit is reducible by checking if its subcircuits are scalar values. Parameters ========== circuit : Gate tuple A tuple of Gates representing a circuit. The circuit to check if a gate identity is contained in a subcircuit. nqubits : int The number of qubits the circuit operates on. begin : int The leftmost gate in the circuit to include in a subcircuit. end : int The rightmost gate in the circuit to include in a subcircuit. Examples ======== Check if the circuit can be reduced: >>> from sympy.physics.quantum.identitysearch import is_reducible >>> from sympy.physics.quantum.gate import X, Y, Z >>> x = X(0); y = Y(0); z = Z(0) >>> is_reducible((x, y, z), 1, 0, 3) True Check if an interval in the circuit can be reduced: >>> is_reducible((x, y, z), 1, 1, 3) False >>> is_reducible((x, y, y), 1, 1, 3) True """ current_circuit = () # Start from the gate at "end" and go down to almost the gate at "begin" for ndx in reversed(range(begin, end)): next_gate = circuit[ndx] current_circuit = (next_gate,) + current_circuit # If a circuit as a matrix is equivalent to a scalar value if (is_scalar_matrix(current_circuit, nqubits, False)): return True return False def bfs_identity_search(gate_list, nqubits, max_depth=None, identity_only=False): """Constructs a set of gate identities from the list of possible gates. Performs a breadth first search over the space of gate identities. This allows the finding of the shortest gate identities first. Parameters ========== gate_list : list, Gate A list of Gates from which to search for gate identities. nqubits : int The number of qubits the quantum circuit operates on. max_depth : int The longest quantum circuit to construct from gate_list. identity_only : bool True to search for gate identities that reduce to identity; False to search for gate identities that reduce to a scalar. Examples ======== Find a list of gate identities: >>> from sympy.physics.quantum.identitysearch import bfs_identity_search >>> from sympy.physics.quantum.gate import X, Y, Z >>> x = X(0); y = Y(0); z = Z(0) >>> bfs_identity_search([x], 1, max_depth=2) {GateIdentity(X(0), X(0))} >>> bfs_identity_search([x, y, z], 1) {GateIdentity(X(0), X(0)), GateIdentity(Y(0), Y(0)), GateIdentity(Z(0), Z(0)), GateIdentity(X(0), Y(0), Z(0))} Find a list of identities that only equal to 1: >>> bfs_identity_search([x, y, z], 1, identity_only=True) {GateIdentity(X(0), X(0)), GateIdentity(Y(0), Y(0)), GateIdentity(Z(0), Z(0))} """ if max_depth is None or max_depth <= 0: max_depth = len(gate_list) id_only = identity_only # Start with an empty sequence (implicitly contains an IdentityGate) queue = deque([()]) # Create an empty set of gate identities ids = set() # Begin searching for gate identities in given space. while (len(queue) > 0): current_circuit = queue.popleft() for next_gate in gate_list: new_circuit = current_circuit + (next_gate,) # Determines if a (strict) subcircuit is a scalar matrix circuit_reducible = is_reducible(new_circuit, nqubits, 1, len(new_circuit)) # In many cases when the matrix is a scalar value, # the evaluated matrix will actually be an integer if (is_scalar_matrix(new_circuit, nqubits, id_only) and not is_degenerate(ids, new_circuit) and not circuit_reducible): ids.add(GateIdentity(*new_circuit)) elif (len(new_circuit) < max_depth and not circuit_reducible): queue.append(new_circuit) return ids def random_identity_search(gate_list, numgates, nqubits): """Randomly selects numgates from gate_list and checks if it is a gate identity. If the circuit is a gate identity, the circuit is returned; Otherwise, None is returned. """ gate_size = len(gate_list) circuit = () for i in range(numgates): next_gate = gate_list[randint(0, gate_size - 1)] circuit = circuit + (next_gate,) is_scalar = is_scalar_matrix(circuit, nqubits, False) return circuit if is_scalar else None
394d305ac5d216f86b1738d6b09e9c97737c0747c775caf8c2ec0035282ed151
""" Definition of physical dimensions. Unit systems will be constructed on top of these dimensions. Most of the examples in the doc use MKS system and are presented from the computer point of view: from a human point, adding length to time is not legal in MKS but it is in natural system; for a computer in natural system there is no time dimension (but a velocity dimension instead) - in the basis - so the question of adding time to length has no meaning. """ from typing import Dict as tDict import collections from functools import reduce from sympy import (Integer, Matrix, S, Symbol, sympify, Basic, Tuple, Dict, default_sort_key) from sympy.functions.elementary.trigonometric import TrigonometricFunction from sympy.core.expr import Expr from sympy.core.power import Pow from sympy.utilities.exceptions import SymPyDeprecationWarning class _QuantityMapper: _quantity_scale_factors_global = {} # type: tDict[Expr, Expr] _quantity_dimensional_equivalence_map_global = {} # type: tDict[Expr, Expr] _quantity_dimension_global = {} # type: tDict[Expr, Expr] def __init__(self, *args, **kwargs): self._quantity_dimension_map = {} self._quantity_scale_factors = {} def set_quantity_dimension(self, unit, dimension): from sympy.physics.units import Quantity dimension = sympify(dimension) if not isinstance(dimension, Dimension): if dimension == 1: dimension = Dimension(1) else: raise ValueError("expected dimension or 1") elif isinstance(dimension, Quantity): dimension = self.get_quantity_dimension(dimension) self._quantity_dimension_map[unit] = dimension def set_quantity_scale_factor(self, unit, scale_factor): from sympy.physics.units import Quantity from sympy.physics.units.prefixes import Prefix scale_factor = sympify(scale_factor) # replace all prefixes by their ratio to canonical units: scale_factor = scale_factor.replace( lambda x: isinstance(x, Prefix), lambda x: x.scale_factor ) # replace all quantities by their ratio to canonical units: scale_factor = scale_factor.replace( lambda x: isinstance(x, Quantity), lambda x: self.get_quantity_scale_factor(x) ) self._quantity_scale_factors[unit] = scale_factor def get_quantity_dimension(self, unit): from sympy.physics.units import Quantity # First look-up the local dimension map, then the global one: if unit in self._quantity_dimension_map: return self._quantity_dimension_map[unit] if unit in self._quantity_dimension_global: return self._quantity_dimension_global[unit] if unit in self._quantity_dimensional_equivalence_map_global: dep_unit = self._quantity_dimensional_equivalence_map_global[unit] if isinstance(dep_unit, Quantity): return self.get_quantity_dimension(dep_unit) else: return Dimension(self.get_dimensional_expr(dep_unit)) if isinstance(unit, Quantity): return Dimension(unit.name) else: return Dimension(1) def get_quantity_scale_factor(self, unit): if unit in self._quantity_scale_factors: return self._quantity_scale_factors[unit] if unit in self._quantity_scale_factors_global: mul_factor, other_unit = self._quantity_scale_factors_global[unit] return mul_factor*self.get_quantity_scale_factor(other_unit) return S.One class Dimension(Expr): """ This class represent the dimension of a physical quantities. The ``Dimension`` constructor takes as parameters a name and an optional symbol. For example, in classical mechanics we know that time is different from temperature and dimensions make this difference (but they do not provide any measure of these quantites. >>> from sympy.physics.units import Dimension >>> length = Dimension('length') >>> length Dimension(length) >>> time = Dimension('time') >>> time Dimension(time) Dimensions can be composed using multiplication, division and exponentiation (by a number) to give new dimensions. Addition and subtraction is defined only when the two objects are the same dimension. >>> velocity = length / time >>> velocity Dimension(length/time) It is possible to use a dimension system object to get the dimensionsal dependencies of a dimension, for example the dimension system used by the SI units convention can be used: >>> from sympy.physics.units.systems.si import dimsys_SI >>> dimsys_SI.get_dimensional_dependencies(velocity) {'length': 1, 'time': -1} >>> length + length Dimension(length) >>> l2 = length**2 >>> l2 Dimension(length**2) >>> dimsys_SI.get_dimensional_dependencies(l2) {'length': 2} """ _op_priority = 13.0 # XXX: This doesn't seem to be used anywhere... _dimensional_dependencies = dict() # type: ignore is_commutative = True is_number = False # make sqrt(M**2) --> M is_positive = True is_real = True def __new__(cls, name, symbol=None): if isinstance(name, str): name = Symbol(name) else: name = sympify(name) if not isinstance(name, Expr): raise TypeError("Dimension name needs to be a valid math expression") if isinstance(symbol, str): symbol = Symbol(symbol) elif symbol is not None: assert isinstance(symbol, Symbol) if symbol is not None: obj = Expr.__new__(cls, name, symbol) else: obj = Expr.__new__(cls, name) obj._name = name obj._symbol = symbol return obj @property def name(self): return self._name @property def symbol(self): return self._symbol def __hash__(self): return Expr.__hash__(self) def __eq__(self, other): if isinstance(other, Dimension): return self.name == other.name return False def __str__(self): """ Display the string representation of the dimension. """ if self.symbol is None: return "Dimension(%s)" % (self.name) else: return "Dimension(%s, %s)" % (self.name, self.symbol) def __repr__(self): return self.__str__() def __neg__(self): return self def __add__(self, other): from sympy.physics.units.quantities import Quantity other = sympify(other) if isinstance(other, Basic): if other.has(Quantity): raise TypeError("cannot sum dimension and quantity") if isinstance(other, Dimension) and self == other: return self return super().__add__(other) return self def __radd__(self, other): return self.__add__(other) def __sub__(self, other): # there is no notion of ordering (or magnitude) among dimension, # subtraction is equivalent to addition when the operation is legal return self + other def __rsub__(self, other): # there is no notion of ordering (or magnitude) among dimension, # subtraction is equivalent to addition when the operation is legal return self + other def __pow__(self, other): return self._eval_power(other) def _eval_power(self, other): other = sympify(other) return Dimension(self.name**other) def __mul__(self, other): from sympy.physics.units.quantities import Quantity if isinstance(other, Basic): if other.has(Quantity): raise TypeError("cannot sum dimension and quantity") if isinstance(other, Dimension): return Dimension(self.name*other.name) if not other.free_symbols: # other.is_number cannot be used return self return super().__mul__(other) return self def __rmul__(self, other): return self.__mul__(other) def __truediv__(self, other): return self*Pow(other, -1) def __rtruediv__(self, other): return other * pow(self, -1) @classmethod def _from_dimensional_dependencies(cls, dependencies): return reduce(lambda x, y: x * y, ( Dimension(d)**e for d, e in dependencies.items() ), 1) @classmethod def _get_dimensional_dependencies_for_name(cls, name): from sympy.physics.units.systems.si import dimsys_default SymPyDeprecationWarning( deprecated_since_version="1.2", issue=13336, feature="do not call from `Dimension` objects.", useinstead="DimensionSystem" ).warn() return dimsys_default.get_dimensional_dependencies(name) @property def is_dimensionless(self): """ Check if the dimension object really has a dimension. A dimension should have at least one component with non-zero power. """ if self.name == 1: return True from sympy.physics.units.systems.si import dimsys_default SymPyDeprecationWarning( deprecated_since_version="1.2", issue=13336, feature="wrong class", ).warn() dimensional_dependencies=dimsys_default return dimensional_dependencies.get_dimensional_dependencies(self) == {} def has_integer_powers(self, dim_sys): """ Check if the dimension object has only integer powers. All the dimension powers should be integers, but rational powers may appear in intermediate steps. This method may be used to check that the final result is well-defined. """ for dpow in dim_sys.get_dimensional_dependencies(self).values(): if not isinstance(dpow, (int, Integer)): return False return True # Create dimensions according the the base units in MKSA. # For other unit systems, they can be derived by transforming the base # dimensional dependency dictionary. class DimensionSystem(Basic, _QuantityMapper): r""" DimensionSystem represents a coherent set of dimensions. The constructor takes three parameters: - base dimensions; - derived dimensions: these are defined in terms of the base dimensions (for example velocity is defined from the division of length by time); - dependency of dimensions: how the derived dimensions depend on the base dimensions. Optionally either the ``derived_dims`` or the ``dimensional_dependencies`` may be omitted. """ def __new__(cls, base_dims, derived_dims=[], dimensional_dependencies={}, name=None, descr=None): dimensional_dependencies = dict(dimensional_dependencies) if (name is not None) or (descr is not None): SymPyDeprecationWarning( deprecated_since_version="1.2", issue=13336, useinstead="do not define a `name` or `descr`", ).warn() def parse_dim(dim): if isinstance(dim, str): dim = Dimension(Symbol(dim)) elif isinstance(dim, Dimension): pass elif isinstance(dim, Symbol): dim = Dimension(dim) else: raise TypeError("%s wrong type" % dim) return dim base_dims = [parse_dim(i) for i in base_dims] derived_dims = [parse_dim(i) for i in derived_dims] for dim in base_dims: dim = dim.name if (dim in dimensional_dependencies and (len(dimensional_dependencies[dim]) != 1 or dimensional_dependencies[dim].get(dim, None) != 1)): raise IndexError("Repeated value in base dimensions") dimensional_dependencies[dim] = Dict({dim: 1}) def parse_dim_name(dim): if isinstance(dim, Dimension): return dim.name elif isinstance(dim, str): return Symbol(dim) elif isinstance(dim, Symbol): return dim else: raise TypeError("unrecognized type %s for %s" % (type(dim), dim)) for dim in dimensional_dependencies.keys(): dim = parse_dim(dim) if (dim not in derived_dims) and (dim not in base_dims): derived_dims.append(dim) def parse_dict(d): return Dict({parse_dim_name(i): j for i, j in d.items()}) # Make sure everything is a SymPy type: dimensional_dependencies = {parse_dim_name(i): parse_dict(j) for i, j in dimensional_dependencies.items()} for dim in derived_dims: if dim in base_dims: raise ValueError("Dimension %s both in base and derived" % dim) if dim.name not in dimensional_dependencies: # TODO: should this raise a warning? dimensional_dependencies[dim.name] = Dict({dim.name: 1}) base_dims.sort(key=default_sort_key) derived_dims.sort(key=default_sort_key) base_dims = Tuple(*base_dims) derived_dims = Tuple(*derived_dims) dimensional_dependencies = Dict({i: Dict(j) for i, j in dimensional_dependencies.items()}) obj = Basic.__new__(cls, base_dims, derived_dims, dimensional_dependencies) return obj @property def base_dims(self): return self.args[0] @property def derived_dims(self): return self.args[1] @property def dimensional_dependencies(self): return self.args[2] def _get_dimensional_dependencies_for_name(self, name): if isinstance(name, Dimension): name = name.name if isinstance(name, str): name = Symbol(name) if name.is_Symbol: # Dimensions not included in the dependencies are considered # as base dimensions: return dict(self.dimensional_dependencies.get(name, {name: 1})) if name.is_number or name.is_NumberSymbol: return {} get_for_name = self._get_dimensional_dependencies_for_name if name.is_Mul: ret = collections.defaultdict(int) dicts = [get_for_name(i) for i in name.args] for d in dicts: for k, v in d.items(): ret[k] += v return {k: v for (k, v) in ret.items() if v != 0} if name.is_Add: dicts = [get_for_name(i) for i in name.args] if all([d == dicts[0] for d in dicts[1:]]): return dicts[0] raise TypeError("Only equivalent dimensions can be added or subtracted.") if name.is_Pow: dim_base = get_for_name(name.base) dim_exp = get_for_name(name.exp) if dim_exp == {} or name.exp.is_Symbol: return {k: v*name.exp for (k, v) in dim_base.items()} else: raise TypeError("The exponent for the power operator must be a Symbol or dimensionless.") if name.is_Function: args = (Dimension._from_dimensional_dependencies( get_for_name(arg)) for arg in name.args) result = name.func(*args) dicts = [get_for_name(i) for i in name.args] if isinstance(result, Dimension): return self.get_dimensional_dependencies(result) elif result.func == name.func: if isinstance(name, TrigonometricFunction): if dicts[0] == {} or dicts[0] == {Symbol('angle'): 1}: return {} else: raise TypeError("The input argument for the function {} must be dimensionless or have dimensions of angle.".format(name.func)) else: if all( (item == {} for item in dicts) ): return {} else: raise TypeError("The input arguments for the function {} must be dimensionless.".format(name.func)) else: return get_for_name(result) raise TypeError("Type {} not implemented for get_dimensional_dependencies".format(type(name))) def get_dimensional_dependencies(self, name, mark_dimensionless=False): dimdep = self._get_dimensional_dependencies_for_name(name) if mark_dimensionless and dimdep == {}: return {'dimensionless': 1} return {str(i): j for i, j in dimdep.items()} def equivalent_dims(self, dim1, dim2): deps1 = self.get_dimensional_dependencies(dim1) deps2 = self.get_dimensional_dependencies(dim2) return deps1 == deps2 def extend(self, new_base_dims, new_derived_dims=[], new_dim_deps={}, name=None, description=None): if (name is not None) or (description is not None): SymPyDeprecationWarning( deprecated_since_version="1.2", issue=13336, feature="name and descriptions of DimensionSystem", useinstead="do not specify `name` or `description`", ).warn() deps = dict(self.dimensional_dependencies) deps.update(new_dim_deps) new_dim_sys = DimensionSystem( tuple(self.base_dims) + tuple(new_base_dims), tuple(self.derived_dims) + tuple(new_derived_dims), deps ) new_dim_sys._quantity_dimension_map.update(self._quantity_dimension_map) new_dim_sys._quantity_scale_factors.update(self._quantity_scale_factors) return new_dim_sys @staticmethod def sort_dims(dims): """ Useless method, kept for compatibility with previous versions. DO NOT USE. Sort dimensions given in argument using their str function. This function will ensure that we get always the same tuple for a given set of dimensions. """ SymPyDeprecationWarning( deprecated_since_version="1.2", issue=13336, feature="sort_dims", useinstead="sorted(..., key=default_sort_key)", ).warn() return tuple(sorted(dims, key=str)) def __getitem__(self, key): """ Useless method, kept for compatibility with previous versions. DO NOT USE. Shortcut to the get_dim method, using key access. """ SymPyDeprecationWarning( deprecated_since_version="1.2", issue=13336, feature="the get [ ] operator", useinstead="the dimension definition", ).warn() d = self.get_dim(key) #TODO: really want to raise an error? if d is None: raise KeyError(key) return d def __call__(self, unit): """ Useless method, kept for compatibility with previous versions. DO NOT USE. Wrapper to the method print_dim_base """ SymPyDeprecationWarning( deprecated_since_version="1.2", issue=13336, feature="call DimensionSystem", useinstead="the dimension definition", ).warn() return self.print_dim_base(unit) def is_dimensionless(self, dimension): """ Check if the dimension object really has a dimension. A dimension should have at least one component with non-zero power. """ if dimension.name == 1: return True return self.get_dimensional_dependencies(dimension) == {} @property def list_can_dims(self): """ Useless method, kept for compatibility with previous versions. DO NOT USE. List all canonical dimension names. """ dimset = set() for i in self.base_dims: dimset.update(set(self.get_dimensional_dependencies(i).keys())) return tuple(sorted(dimset, key=str)) @property def inv_can_transf_matrix(self): """ Useless method, kept for compatibility with previous versions. DO NOT USE. Compute the inverse transformation matrix from the base to the canonical dimension basis. It corresponds to the matrix where columns are the vector of base dimensions in canonical basis. This matrix will almost never be used because dimensions are always defined with respect to the canonical basis, so no work has to be done to get them in this basis. Nonetheless if this matrix is not square (or not invertible) it means that we have chosen a bad basis. """ matrix = reduce(lambda x, y: x.row_join(y), [self.dim_can_vector(d) for d in self.base_dims]) return matrix @property def can_transf_matrix(self): """ Useless method, kept for compatibility with previous versions. DO NOT USE. Return the canonical transformation matrix from the canonical to the base dimension basis. It is the inverse of the matrix computed with inv_can_transf_matrix(). """ #TODO: the inversion will fail if the system is inconsistent, for # example if the matrix is not a square return reduce(lambda x, y: x.row_join(y), [self.dim_can_vector(d) for d in sorted(self.base_dims, key=str)] ).inv() def dim_can_vector(self, dim): """ Useless method, kept for compatibility with previous versions. DO NOT USE. Dimensional representation in terms of the canonical base dimensions. """ vec = [] for d in self.list_can_dims: vec.append(self.get_dimensional_dependencies(dim).get(d, 0)) return Matrix(vec) def dim_vector(self, dim): """ Useless method, kept for compatibility with previous versions. DO NOT USE. Vector representation in terms of the base dimensions. """ return self.can_transf_matrix * Matrix(self.dim_can_vector(dim)) def print_dim_base(self, dim): """ Give the string expression of a dimension in term of the basis symbols. """ dims = self.dim_vector(dim) symbols = [i.symbol if i.symbol is not None else i.name for i in self.base_dims] res = S.One for (s, p) in zip(symbols, dims): res *= s**p return res @property def dim(self): """ Useless method, kept for compatibility with previous versions. DO NOT USE. Give the dimension of the system. That is return the number of dimensions forming the basis. """ return len(self.base_dims) @property def is_consistent(self): """ Useless method, kept for compatibility with previous versions. DO NOT USE. Check if the system is well defined. """ # not enough or too many base dimensions compared to independent # dimensions # in vector language: the set of vectors do not form a basis return self.inv_can_transf_matrix.is_square
4fc2c0d8144d141dae7af740debbeca855e197dcafe929c8f89f33644b02a838
from .vector import Vector, _check_vector from .frame import _check_frame from warnings import warn __all__ = ['Point'] class Point: """This object represents a point in a dynamic system. It stores the: position, velocity, and acceleration of a point. The position is a vector defined as the vector distance from a parent point to this point. Parameters ========== name : string The display name of the Point Examples ======== >>> from sympy.physics.vector import Point, ReferenceFrame, dynamicsymbols >>> from sympy.physics.vector import init_vprinting >>> init_vprinting(pretty_print=False) >>> N = ReferenceFrame('N') >>> O = Point('O') >>> P = Point('P') >>> u1, u2, u3 = dynamicsymbols('u1 u2 u3') >>> O.set_vel(N, u1 * N.x + u2 * N.y + u3 * N.z) >>> O.acc(N) u1'*N.x + u2'*N.y + u3'*N.z symbols() can be used to create multiple Points in a single step, for example: >>> from sympy.physics.vector import Point, ReferenceFrame, dynamicsymbols >>> from sympy.physics.vector import init_vprinting >>> init_vprinting(pretty_print=False) >>> from sympy import symbols >>> N = ReferenceFrame('N') >>> u1, u2 = dynamicsymbols('u1 u2') >>> A, B = symbols('A B', cls=Point) >>> type(A) <class 'sympy.physics.vector.point.Point'> >>> A.set_vel(N, u1 * N.x + u2 * N.y) >>> B.set_vel(N, u2 * N.x + u1 * N.y) >>> A.acc(N) - B.acc(N) (u1' - u2')*N.x + (-u1' + u2')*N.y """ def __init__(self, name): """Initialization of a Point object. """ self.name = name self._pos_dict = {} self._vel_dict = {} self._acc_dict = {} self._pdlist = [self._pos_dict, self._vel_dict, self._acc_dict] def __str__(self): return self.name __repr__ = __str__ def _check_point(self, other): if not isinstance(other, Point): raise TypeError('A Point must be supplied') def _pdict_list(self, other, num): """Returns a list of points that gives the shortest path with respect to position, velocity, or acceleration from this point to the provided point. Parameters ========== other : Point A point that may be related to this point by position, velocity, or acceleration. num : integer 0 for searching the position tree, 1 for searching the velocity tree, and 2 for searching the acceleration tree. Returns ======= list of Points A sequence of points from self to other. Notes ===== It isn't clear if num = 1 or num = 2 actually works because the keys to ``_vel_dict`` and ``_acc_dict`` are :class:`ReferenceFrame` objects which do not have the ``_pdlist`` attribute. """ outlist = [[self]] oldlist = [[]] while outlist != oldlist: oldlist = outlist[:] for i, v in enumerate(outlist): templist = v[-1]._pdlist[num].keys() for i2, v2 in enumerate(templist): if not v.__contains__(v2): littletemplist = v + [v2] if not outlist.__contains__(littletemplist): outlist.append(littletemplist) for i, v in enumerate(oldlist): if v[-1] != other: outlist.remove(v) outlist.sort(key=len) if len(outlist) != 0: return outlist[0] raise ValueError('No Connecting Path found between ' + other.name + ' and ' + self.name) def a1pt_theory(self, otherpoint, outframe, interframe): """Sets the acceleration of this point with the 1-point theory. The 1-point theory for point acceleration looks like this: ^N a^P = ^B a^P + ^N a^O + ^N alpha^B x r^OP + ^N omega^B x (^N omega^B x r^OP) + 2 ^N omega^B x ^B v^P where O is a point fixed in B, P is a point moving in B, and B is rotating in frame N. Parameters ========== otherpoint : Point The first point of the 1-point theory (O) outframe : ReferenceFrame The frame we want this point's acceleration defined in (N) fixedframe : ReferenceFrame The intermediate frame in this calculation (B) Examples ======== >>> from sympy.physics.vector import Point, ReferenceFrame >>> from sympy.physics.vector import dynamicsymbols >>> from sympy.physics.vector import init_vprinting >>> init_vprinting(pretty_print=False) >>> q = dynamicsymbols('q') >>> q2 = dynamicsymbols('q2') >>> qd = dynamicsymbols('q', 1) >>> q2d = dynamicsymbols('q2', 1) >>> N = ReferenceFrame('N') >>> B = ReferenceFrame('B') >>> B.set_ang_vel(N, 5 * B.y) >>> O = Point('O') >>> P = O.locatenew('P', q * B.x) >>> P.set_vel(B, qd * B.x + q2d * B.y) >>> O.set_vel(N, 0) >>> P.a1pt_theory(O, N, B) (-25*q + q'')*B.x + q2''*B.y - 10*q'*B.z """ _check_frame(outframe) _check_frame(interframe) self._check_point(otherpoint) dist = self.pos_from(otherpoint) v = self.vel(interframe) a1 = otherpoint.acc(outframe) a2 = self.acc(interframe) omega = interframe.ang_vel_in(outframe) alpha = interframe.ang_acc_in(outframe) self.set_acc(outframe, a2 + 2 * (omega ^ v) + a1 + (alpha ^ dist) + (omega ^ (omega ^ dist))) return self.acc(outframe) def a2pt_theory(self, otherpoint, outframe, fixedframe): """Sets the acceleration of this point with the 2-point theory. The 2-point theory for point acceleration looks like this: ^N a^P = ^N a^O + ^N alpha^B x r^OP + ^N omega^B x (^N omega^B x r^OP) where O and P are both points fixed in frame B, which is rotating in frame N. Parameters ========== otherpoint : Point The first point of the 2-point theory (O) outframe : ReferenceFrame The frame we want this point's acceleration defined in (N) fixedframe : ReferenceFrame The frame in which both points are fixed (B) Examples ======== >>> from sympy.physics.vector import Point, ReferenceFrame, dynamicsymbols >>> from sympy.physics.vector import init_vprinting >>> init_vprinting(pretty_print=False) >>> q = dynamicsymbols('q') >>> qd = dynamicsymbols('q', 1) >>> N = ReferenceFrame('N') >>> B = N.orientnew('B', 'Axis', [q, N.z]) >>> O = Point('O') >>> P = O.locatenew('P', 10 * B.x) >>> O.set_vel(N, 5 * N.x) >>> P.a2pt_theory(O, N, B) - 10*q'**2*B.x + 10*q''*B.y """ _check_frame(outframe) _check_frame(fixedframe) self._check_point(otherpoint) dist = self.pos_from(otherpoint) a = otherpoint.acc(outframe) omega = fixedframe.ang_vel_in(outframe) alpha = fixedframe.ang_acc_in(outframe) self.set_acc(outframe, a + (alpha ^ dist) + (omega ^ (omega ^ dist))) return self.acc(outframe) def acc(self, frame): """The acceleration Vector of this Point in a ReferenceFrame. Parameters ========== frame : ReferenceFrame The frame in which the returned acceleration vector will be defined in Examples ======== >>> from sympy.physics.vector import Point, ReferenceFrame >>> N = ReferenceFrame('N') >>> p1 = Point('p1') >>> p1.set_acc(N, 10 * N.x) >>> p1.acc(N) 10*N.x """ _check_frame(frame) if not (frame in self._acc_dict): if self._vel_dict[frame] != 0: return (self._vel_dict[frame]).dt(frame) else: return Vector(0) return self._acc_dict[frame] def locatenew(self, name, value): """Creates a new point with a position defined from this point. Parameters ========== name : str The name for the new point value : Vector The position of the new point relative to this point Examples ======== >>> from sympy.physics.vector import ReferenceFrame, Point >>> N = ReferenceFrame('N') >>> P1 = Point('P1') >>> P2 = P1.locatenew('P2', 10 * N.x) """ if not isinstance(name, str): raise TypeError('Must supply a valid name') if value == 0: value = Vector(0) value = _check_vector(value) p = Point(name) p.set_pos(self, value) self.set_pos(p, -value) return p def pos_from(self, otherpoint): """Returns a Vector distance between this Point and the other Point. Parameters ========== otherpoint : Point The otherpoint we are locating this one relative to Examples ======== >>> from sympy.physics.vector import Point, ReferenceFrame >>> N = ReferenceFrame('N') >>> p1 = Point('p1') >>> p2 = Point('p2') >>> p1.set_pos(p2, 10 * N.x) >>> p1.pos_from(p2) 10*N.x """ outvec = Vector(0) plist = self._pdict_list(otherpoint, 0) for i in range(len(plist) - 1): outvec += plist[i]._pos_dict[plist[i + 1]] return outvec def set_acc(self, frame, value): """Used to set the acceleration of this Point in a ReferenceFrame. Parameters ========== frame : ReferenceFrame The frame in which this point's acceleration is defined value : Vector The vector value of this point's acceleration in the frame Examples ======== >>> from sympy.physics.vector import Point, ReferenceFrame >>> N = ReferenceFrame('N') >>> p1 = Point('p1') >>> p1.set_acc(N, 10 * N.x) >>> p1.acc(N) 10*N.x """ if value == 0: value = Vector(0) value = _check_vector(value) _check_frame(frame) self._acc_dict.update({frame: value}) def set_pos(self, otherpoint, value): """Used to set the position of this point w.r.t. another point. Parameters ========== otherpoint : Point The other point which this point's location is defined relative to value : Vector The vector which defines the location of this point Examples ======== >>> from sympy.physics.vector import Point, ReferenceFrame >>> N = ReferenceFrame('N') >>> p1 = Point('p1') >>> p2 = Point('p2') >>> p1.set_pos(p2, 10 * N.x) >>> p1.pos_from(p2) 10*N.x """ if value == 0: value = Vector(0) value = _check_vector(value) self._check_point(otherpoint) self._pos_dict.update({otherpoint: value}) otherpoint._pos_dict.update({self: -value}) def set_vel(self, frame, value): """Sets the velocity Vector of this Point in a ReferenceFrame. Parameters ========== frame : ReferenceFrame The frame in which this point's velocity is defined value : Vector The vector value of this point's velocity in the frame Examples ======== >>> from sympy.physics.vector import Point, ReferenceFrame >>> N = ReferenceFrame('N') >>> p1 = Point('p1') >>> p1.set_vel(N, 10 * N.x) >>> p1.vel(N) 10*N.x """ if value == 0: value = Vector(0) value = _check_vector(value) _check_frame(frame) self._vel_dict.update({frame: value}) def v1pt_theory(self, otherpoint, outframe, interframe): """Sets the velocity of this point with the 1-point theory. The 1-point theory for point velocity looks like this: ^N v^P = ^B v^P + ^N v^O + ^N omega^B x r^OP where O is a point fixed in B, P is a point moving in B, and B is rotating in frame N. Parameters ========== otherpoint : Point The first point of the 1-point theory (O) outframe : ReferenceFrame The frame we want this point's velocity defined in (N) interframe : ReferenceFrame The intermediate frame in this calculation (B) Examples ======== >>> from sympy.physics.vector import Point, ReferenceFrame >>> from sympy.physics.vector import dynamicsymbols >>> from sympy.physics.vector import init_vprinting >>> init_vprinting(pretty_print=False) >>> q = dynamicsymbols('q') >>> q2 = dynamicsymbols('q2') >>> qd = dynamicsymbols('q', 1) >>> q2d = dynamicsymbols('q2', 1) >>> N = ReferenceFrame('N') >>> B = ReferenceFrame('B') >>> B.set_ang_vel(N, 5 * B.y) >>> O = Point('O') >>> P = O.locatenew('P', q * B.x) >>> P.set_vel(B, qd * B.x + q2d * B.y) >>> O.set_vel(N, 0) >>> P.v1pt_theory(O, N, B) q'*B.x + q2'*B.y - 5*q*B.z """ _check_frame(outframe) _check_frame(interframe) self._check_point(otherpoint) dist = self.pos_from(otherpoint) v1 = self.vel(interframe) v2 = otherpoint.vel(outframe) omega = interframe.ang_vel_in(outframe) self.set_vel(outframe, v1 + v2 + (omega ^ dist)) return self.vel(outframe) def v2pt_theory(self, otherpoint, outframe, fixedframe): """Sets the velocity of this point with the 2-point theory. The 2-point theory for point velocity looks like this: ^N v^P = ^N v^O + ^N omega^B x r^OP where O and P are both points fixed in frame B, which is rotating in frame N. Parameters ========== otherpoint : Point The first point of the 2-point theory (O) outframe : ReferenceFrame The frame we want this point's velocity defined in (N) fixedframe : ReferenceFrame The frame in which both points are fixed (B) Examples ======== >>> from sympy.physics.vector import Point, ReferenceFrame, dynamicsymbols >>> from sympy.physics.vector import init_vprinting >>> init_vprinting(pretty_print=False) >>> q = dynamicsymbols('q') >>> qd = dynamicsymbols('q', 1) >>> N = ReferenceFrame('N') >>> B = N.orientnew('B', 'Axis', [q, N.z]) >>> O = Point('O') >>> P = O.locatenew('P', 10 * B.x) >>> O.set_vel(N, 5 * N.x) >>> P.v2pt_theory(O, N, B) 5*N.x + 10*q'*B.y """ _check_frame(outframe) _check_frame(fixedframe) self._check_point(otherpoint) dist = self.pos_from(otherpoint) v = otherpoint.vel(outframe) omega = fixedframe.ang_vel_in(outframe) self.set_vel(outframe, v + (omega ^ dist)) return self.vel(outframe) def vel(self, frame): """The velocity Vector of this Point in the ReferenceFrame. Parameters ========== frame : ReferenceFrame The frame in which the returned velocity vector will be defined in Examples ======== >>> from sympy.physics.vector import Point, ReferenceFrame, dynamicsymbols >>> N = ReferenceFrame('N') >>> p1 = Point('p1') >>> p1.set_vel(N, 10 * N.x) >>> p1.vel(N) 10*N.x Velocities will be automatically calculated if possible, otherwise a ``ValueError`` will be returned. If it is possible to calculate multiple different velocities from the relative points, the points defined most directly relative to this point will be used. In the case of inconsistent relative positions of points, incorrect velocities may be returned. It is up to the user to define prior relative positions and velocities of points in a self-consistent way. >>> p = Point('p') >>> q = dynamicsymbols('q') >>> p.set_vel(N, 10 * N.x) >>> p2 = Point('p2') >>> p2.set_pos(p, q*N.x) >>> p2.vel(N) (Derivative(q(t), t) + 10)*N.x """ _check_frame(frame) if not (frame in self._vel_dict): valid_neighbor_found = False is_cyclic = False visited = [] queue = [self] candidate_neighbor = [] while queue: #BFS to find nearest point node = queue.pop(0) if node not in visited: visited.append(node) for neighbor, neighbor_pos in node._pos_dict.items(): if neighbor in visited: continue try: neighbor_pos.express(frame) #Checks if pos vector is valid except ValueError: continue if neighbor in queue: is_cyclic = True try : neighbor_velocity = neighbor._vel_dict[frame] #Checks if point has its vel defined in req frame except KeyError: queue.append(neighbor) continue candidate_neighbor.append(neighbor) if not valid_neighbor_found: self.set_vel(frame, self.pos_from(neighbor).dt(frame) + neighbor_velocity) valid_neighbor_found = True if is_cyclic: warn('Kinematic loops are defined among the positions of points. This is likely not desired and may cause errors in your calculations.') if len(candidate_neighbor) > 1: warn('Velocity automatically calculated based on point ' + candidate_neighbor[0].name + ' but it is also possible from points(s):' + str(candidate_neighbor[1:]) + '. Velocities from these points are not necessarily the same. This may cause errors in your calculations.') if valid_neighbor_found: return self._vel_dict[frame] else: raise ValueError('Velocity of point ' + self.name + ' has not been' ' defined in ReferenceFrame ' + frame.name) return self._vel_dict[frame] def partial_velocity(self, frame, *gen_speeds): """Returns the partial velocities of the linear velocity vector of this point in the given frame with respect to one or more provided generalized speeds. Parameters ========== frame : ReferenceFrame The frame with which the velocity is defined in. gen_speeds : functions of time The generalized speeds. Returns ======= partial_velocities : tuple of Vector The partial velocity vectors corresponding to the provided generalized speeds. Examples ======== >>> from sympy.physics.vector import ReferenceFrame, Point >>> from sympy.physics.vector import dynamicsymbols >>> N = ReferenceFrame('N') >>> A = ReferenceFrame('A') >>> p = Point('p') >>> u1, u2 = dynamicsymbols('u1, u2') >>> p.set_vel(N, u1 * N.x + u2 * A.y) >>> p.partial_velocity(N, u1) N.x >>> p.partial_velocity(N, u1, u2) (N.x, A.y) """ partials = [self.vel(frame).diff(speed, frame, var_in_dcm=False) for speed in gen_speeds] if len(partials) == 1: return partials[0] else: return tuple(partials)
fb7b2fd593bb85a17c0a88a8c88d0d90ffc251a13283b495d245b92e9fd55c52
from sympy.core.backend import (diff, expand, sin, cos, sympify, eye, symbols, ImmutableMatrix as Matrix, MatrixBase) from sympy import (trigsimp, solve, Symbol, Dummy) from sympy.physics.vector.vector import Vector, _check_vector from sympy.utilities.misc import translate __all__ = ['CoordinateSym', 'ReferenceFrame'] class CoordinateSym(Symbol): """ A coordinate symbol/base scalar associated wrt a Reference Frame. Ideally, users should not instantiate this class. Instances of this class must only be accessed through the corresponding frame as 'frame[index]'. CoordinateSyms having the same frame and index parameters are equal (even though they may be instantiated separately). Parameters ========== name : string The display name of the CoordinateSym frame : ReferenceFrame The reference frame this base scalar belongs to index : 0, 1 or 2 The index of the dimension denoted by this coordinate variable Examples ======== >>> from sympy.physics.vector import ReferenceFrame, CoordinateSym >>> A = ReferenceFrame('A') >>> A[1] A_y >>> type(A[0]) <class 'sympy.physics.vector.frame.CoordinateSym'> >>> a_y = CoordinateSym('a_y', A, 1) >>> a_y == A[1] True """ def __new__(cls, name, frame, index): # We can't use the cached Symbol.__new__ because this class depends on # frame and index, which are not passed to Symbol.__xnew__. assumptions = {} super()._sanitize(assumptions, cls) obj = super().__xnew__(cls, name, **assumptions) _check_frame(frame) if index not in range(0, 3): raise ValueError("Invalid index specified") obj._id = (frame, index) return obj @property def frame(self): return self._id[0] def __eq__(self, other): #Check if the other object is a CoordinateSym of the same frame #and same index if isinstance(other, CoordinateSym): if other._id == self._id: return True return False def __ne__(self, other): return not self == other def __hash__(self): return tuple((self._id[0].__hash__(), self._id[1])).__hash__() class ReferenceFrame: """A reference frame in classical mechanics. ReferenceFrame is a class used to represent a reference frame in classical mechanics. It has a standard basis of three unit vectors in the frame's x, y, and z directions. It also can have a rotation relative to a parent frame; this rotation is defined by a direction cosine matrix relating this frame's basis vectors to the parent frame's basis vectors. It can also have an angular velocity vector, defined in another frame. """ _count = 0 def __init__(self, name, indices=None, latexs=None, variables=None): """ReferenceFrame initialization method. A ReferenceFrame has a set of orthonormal basis vectors, along with orientations relative to other ReferenceFrames and angular velocities relative to other ReferenceFrames. Parameters ========== indices : tuple of str Enables the reference frame's basis unit vectors to be accessed by Python's square bracket indexing notation using the provided three indice strings and alters the printing of the unit vectors to reflect this choice. latexs : tuple of str Alters the LaTeX printing of the reference frame's basis unit vectors to the provided three valid LaTeX strings. Examples ======== >>> from sympy.physics.vector import ReferenceFrame, vlatex >>> N = ReferenceFrame('N') >>> N.x N.x >>> O = ReferenceFrame('O', indices=('1', '2', '3')) >>> O.x O['1'] >>> O['1'] O['1'] >>> P = ReferenceFrame('P', latexs=('A1', 'A2', 'A3')) >>> vlatex(P.x) 'A1' symbols() can be used to create multiple Reference Frames in one step, for example: >>> from sympy.physics.vector import ReferenceFrame >>> from sympy import symbols >>> A, B, C = symbols('A B C', cls=ReferenceFrame) >>> D, E = symbols('D E', cls=ReferenceFrame, indices=('1', '2', '3')) >>> A[0] A_x >>> D.x D['1'] >>> E.y E['2'] >>> type(A) == type(D) True """ if not isinstance(name, str): raise TypeError('Need to supply a valid name') # The if statements below are for custom printing of basis-vectors for # each frame. # First case, when custom indices are supplied if indices is not None: if not isinstance(indices, (tuple, list)): raise TypeError('Supply the indices as a list') if len(indices) != 3: raise ValueError('Supply 3 indices') for i in indices: if not isinstance(i, str): raise TypeError('Indices must be strings') self.str_vecs = [(name + '[\'' + indices[0] + '\']'), (name + '[\'' + indices[1] + '\']'), (name + '[\'' + indices[2] + '\']')] self.pretty_vecs = [(name.lower() + "_" + indices[0]), (name.lower() + "_" + indices[1]), (name.lower() + "_" + indices[2])] self.latex_vecs = [(r"\mathbf{\hat{%s}_{%s}}" % (name.lower(), indices[0])), (r"\mathbf{\hat{%s}_{%s}}" % (name.lower(), indices[1])), (r"\mathbf{\hat{%s}_{%s}}" % (name.lower(), indices[2]))] self.indices = indices # Second case, when no custom indices are supplied else: self.str_vecs = [(name + '.x'), (name + '.y'), (name + '.z')] self.pretty_vecs = [name.lower() + "_x", name.lower() + "_y", name.lower() + "_z"] self.latex_vecs = [(r"\mathbf{\hat{%s}_x}" % name.lower()), (r"\mathbf{\hat{%s}_y}" % name.lower()), (r"\mathbf{\hat{%s}_z}" % name.lower())] self.indices = ['x', 'y', 'z'] # Different step, for custom latex basis vectors if latexs is not None: if not isinstance(latexs, (tuple, list)): raise TypeError('Supply the indices as a list') if len(latexs) != 3: raise ValueError('Supply 3 indices') for i in latexs: if not isinstance(i, str): raise TypeError('Latex entries must be strings') self.latex_vecs = latexs self.name = name self._var_dict = {} #The _dcm_dict dictionary will only store the dcms of adjacent parent-child #relationships. The _dcm_cache dictionary will store calculated dcm along with #all content of _dcm_dict for faster retrieval of dcms. self._dcm_dict = {} self._dcm_cache = {} self._ang_vel_dict = {} self._ang_acc_dict = {} self._dlist = [self._dcm_dict, self._ang_vel_dict, self._ang_acc_dict] self._cur = 0 self._x = Vector([(Matrix([1, 0, 0]), self)]) self._y = Vector([(Matrix([0, 1, 0]), self)]) self._z = Vector([(Matrix([0, 0, 1]), self)]) #Associate coordinate symbols wrt this frame if variables is not None: if not isinstance(variables, (tuple, list)): raise TypeError('Supply the variable names as a list/tuple') if len(variables) != 3: raise ValueError('Supply 3 variable names') for i in variables: if not isinstance(i, str): raise TypeError('Variable names must be strings') else: variables = [name + '_x', name + '_y', name + '_z'] self.varlist = (CoordinateSym(variables[0], self, 0), \ CoordinateSym(variables[1], self, 1), \ CoordinateSym(variables[2], self, 2)) ReferenceFrame._count += 1 self.index = ReferenceFrame._count def __getitem__(self, ind): """ Returns basis vector for the provided index, if the index is a string. If the index is a number, returns the coordinate variable correspon- -ding to that index. """ if not isinstance(ind, str): if ind < 3: return self.varlist[ind] else: raise ValueError("Invalid index provided") if self.indices[0] == ind: return self.x if self.indices[1] == ind: return self.y if self.indices[2] == ind: return self.z else: raise ValueError('Not a defined index') def __iter__(self): return iter([self.x, self.y, self.z]) def __str__(self): """Returns the name of the frame. """ return self.name __repr__ = __str__ def _dict_list(self, other, num): """Returns an inclusive list of reference frames that connect this reference frame to the provided reference frame. Parameters ========== other : ReferenceFrame The other reference frame to look for a connecting relationship to. num : integer ``0``, ``1``, and ``2`` will look for orientation, angular velocity, and angular acceleration relationships between the two frames, respectively. Returns ======= list Inclusive list of reference frames that connect this reference frame to the other reference frame. Examples ======== >>> from sympy.physics.vector import ReferenceFrame >>> A = ReferenceFrame('A') >>> B = ReferenceFrame('B') >>> C = ReferenceFrame('C') >>> D = ReferenceFrame('D') >>> B.orient_axis(A, A.x, 1.0) >>> C.orient_axis(B, B.x, 1.0) >>> D.orient_axis(C, C.x, 1.0) >>> D._dict_list(A, 0) [D, C, B, A] Raises ====== ValueError When no path is found between the two reference frames or ``num`` is an incorrect value. """ connect_type = {0: 'orientation', 1: 'angular velocity', 2: 'angular acceleration'} if num not in connect_type.keys(): raise ValueError('Valid values for num are 0, 1, or 2.') possible_connecting_paths = [[self]] oldlist = [[]] while possible_connecting_paths != oldlist: oldlist = possible_connecting_paths[:] # make a copy for frame_list in possible_connecting_paths: frames_adjacent_to_last = frame_list[-1]._dlist[num].keys() for adjacent_frame in frames_adjacent_to_last: if adjacent_frame not in frame_list: connecting_path = frame_list + [adjacent_frame] if connecting_path not in possible_connecting_paths: possible_connecting_paths.append(connecting_path) for connecting_path in oldlist: if connecting_path[-1] != other: possible_connecting_paths.remove(connecting_path) possible_connecting_paths.sort(key=len) if len(possible_connecting_paths) != 0: return possible_connecting_paths[0] # selects the shortest path msg = 'No connecting {} path found between {} and {}.' raise ValueError(msg.format(connect_type[num], self.name, other.name)) def _w_diff_dcm(self, otherframe): """Angular velocity from time differentiating the DCM. """ from sympy.physics.vector.functions import dynamicsymbols dcm2diff = otherframe.dcm(self) diffed = dcm2diff.diff(dynamicsymbols._t) angvelmat = diffed * dcm2diff.T w1 = trigsimp(expand(angvelmat[7]), recursive=True) w2 = trigsimp(expand(angvelmat[2]), recursive=True) w3 = trigsimp(expand(angvelmat[3]), recursive=True) return Vector([(Matrix([w1, w2, w3]), otherframe)]) def variable_map(self, otherframe): """ Returns a dictionary which expresses the coordinate variables of this frame in terms of the variables of otherframe. If Vector.simp is True, returns a simplified version of the mapped values. Else, returns them without simplification. Simplification of the expressions may take time. Parameters ========== otherframe : ReferenceFrame The other frame to map the variables to Examples ======== >>> from sympy.physics.vector import ReferenceFrame, dynamicsymbols >>> A = ReferenceFrame('A') >>> q = dynamicsymbols('q') >>> B = A.orientnew('B', 'Axis', [q, A.z]) >>> A.variable_map(B) {A_x: B_x*cos(q(t)) - B_y*sin(q(t)), A_y: B_x*sin(q(t)) + B_y*cos(q(t)), A_z: B_z} """ _check_frame(otherframe) if (otherframe, Vector.simp) in self._var_dict: return self._var_dict[(otherframe, Vector.simp)] else: vars_matrix = self.dcm(otherframe) * Matrix(otherframe.varlist) mapping = {} for i, x in enumerate(self): if Vector.simp: mapping[self.varlist[i]] = trigsimp(vars_matrix[i], method='fu') else: mapping[self.varlist[i]] = vars_matrix[i] self._var_dict[(otherframe, Vector.simp)] = mapping return mapping def ang_acc_in(self, otherframe): """Returns the angular acceleration Vector of the ReferenceFrame. Effectively returns the Vector: ^N alpha ^B which represent the angular acceleration of B in N, where B is self, and N is otherframe. Parameters ========== otherframe : ReferenceFrame The ReferenceFrame which the angular acceleration is returned in. Examples ======== >>> from sympy.physics.vector import ReferenceFrame >>> N = ReferenceFrame('N') >>> A = ReferenceFrame('A') >>> V = 10 * N.x >>> A.set_ang_acc(N, V) >>> A.ang_acc_in(N) 10*N.x """ _check_frame(otherframe) if otherframe in self._ang_acc_dict: return self._ang_acc_dict[otherframe] else: return self.ang_vel_in(otherframe).dt(otherframe) def ang_vel_in(self, otherframe): """Returns the angular velocity Vector of the ReferenceFrame. Effectively returns the Vector: ^N omega ^B which represent the angular velocity of B in N, where B is self, and N is otherframe. Parameters ========== otherframe : ReferenceFrame The ReferenceFrame which the angular velocity is returned in. Examples ======== >>> from sympy.physics.vector import ReferenceFrame >>> N = ReferenceFrame('N') >>> A = ReferenceFrame('A') >>> V = 10 * N.x >>> A.set_ang_vel(N, V) >>> A.ang_vel_in(N) 10*N.x """ _check_frame(otherframe) flist = self._dict_list(otherframe, 1) outvec = Vector(0) for i in range(len(flist) - 1): outvec += flist[i]._ang_vel_dict[flist[i + 1]] return outvec def dcm(self, otherframe): r"""Returns the direction cosine matrix relative to the provided reference frame. The returned matrix can be used to express the orthogonal unit vectors of this frame in terms of the orthogonal unit vectors of ``otherframe``. Parameters ========== otherframe : ReferenceFrame The reference frame which the direction cosine matrix of this frame is formed relative to. Examples ======== The following example rotates the reference frame A relative to N by a simple rotation and then calculates the direction cosine matrix of N relative to A. >>> from sympy import symbols, sin, cos >>> from sympy.physics.vector import ReferenceFrame >>> q1 = symbols('q1') >>> N = ReferenceFrame('N') >>> A = N.orientnew('A', 'Axis', (q1, N.x)) >>> N.dcm(A) Matrix([ [1, 0, 0], [0, cos(q1), -sin(q1)], [0, sin(q1), cos(q1)]]) The second row of the above direction cosine matrix represents the ``N.y`` unit vector in N expressed in A. Like so: >>> Ny = 0*A.x + cos(q1)*A.y - sin(q1)*A.z Thus, expressing ``N.y`` in A should return the same result: >>> N.y.express(A) cos(q1)*A.y - sin(q1)*A.z Notes ===== It is import to know what form of the direction cosine matrix is returned. If ``B.dcm(A)`` is called, it means the "direction cosine matrix of B relative to A". This is the matrix :math:`^{\mathbf{A}} \mathbf{R} ^{\mathbf{B}}` shown in the following relationship: .. math:: \begin{bmatrix} \hat{\mathbf{b}}_1 \\ \hat{\mathbf{b}}_2 \\ \hat{\mathbf{b}}_3 \end{bmatrix} = {}^A\mathbf{R}^B \begin{bmatrix} \hat{\mathbf{a}}_1 \\ \hat{\mathbf{a}}_2 \\ \hat{\mathbf{a}}_3 \end{bmatrix}. :math:`{}^A\mathbf{R}^B` is the matrix that expresses the B unit vectors in terms of the A unit vectors. """ _check_frame(otherframe) # Check if the dcm wrt that frame has already been calculated if otherframe in self._dcm_cache: return self._dcm_cache[otherframe] flist = self._dict_list(otherframe, 0) outdcm = eye(3) for i in range(len(flist) - 1): outdcm = outdcm * flist[i]._dcm_dict[flist[i + 1]] # After calculation, store the dcm in dcm cache for faster future # retrieval self._dcm_cache[otherframe] = outdcm otherframe._dcm_cache[self] = outdcm.T return outdcm def _dcm(self, parent, parent_orient): # If parent.oreint(self) is already defined,then # update the _dcm_dict of parent while over write # all content of self._dcm_dict and self._dcm_cache # with new dcm relation. # Else update _dcm_cache and _dcm_dict of both # self and parent. frames = self._dcm_cache.keys() dcm_dict_del = [] dcm_cache_del = [] if parent in frames: for frame in frames: if frame in self._dcm_dict: dcm_dict_del += [frame] dcm_cache_del += [frame] # Reset the _dcm_cache of this frame, and remove it from the # _dcm_caches of the frames it is linked to. Also remove it from the # _dcm_dict of its parent for frame in dcm_dict_del: del frame._dcm_dict[self] for frame in dcm_cache_del: del frame._dcm_cache[self] # Reset the _dcm_dict self._dcm_dict = self._dlist[0] = {} # Reset the _dcm_cache self._dcm_cache = {} # Add the dcm relationship to _dcm_dict self._dcm_dict.update({parent: parent_orient.T}) parent._dcm_dict.update({self: parent_orient}) # Update the dcm cache self._dcm_cache.update({parent: parent_orient.T}) parent._dcm_cache.update({self: parent_orient}) def orient_axis(self, parent, axis, angle): """Sets the orientation of this reference frame with respect to a parent reference frame by rotating through an angle about an axis fixed in the parent reference frame. Parameters ========== parent : ReferenceFrame Reference frame that this reference frame will be rotated relative to. axis : Vector Vector fixed in the parent frame about about which this frame is rotated. It need not be a unit vector and the rotation follows the right hand rule. angle : sympifiable Angle in radians by which it the frame is to be rotated. Examples ======== Setup variables for the examples: >>> from sympy import symbols >>> from sympy.physics.vector import ReferenceFrame >>> q1 = symbols('q1') >>> N = ReferenceFrame('N') >>> B = ReferenceFrame('B') >>> B.orient_axis(N, N.x, q1) The ``orient_axis()`` method generates a direction cosine matrix and its transpose which defines the orientation of B relative to N and vice versa. Once orient is called, ``dcm()`` outputs the appropriate direction cosine matrix: >>> B.dcm(N) Matrix([ [1, 0, 0], [0, cos(q1), sin(q1)], [0, -sin(q1), cos(q1)]]) >>> N.dcm(B) Matrix([ [1, 0, 0], [0, cos(q1), -sin(q1)], [0, sin(q1), cos(q1)]]) The following two lines show that the sense of the rotation can be defined by negating the vector direction or the angle. Both lines produce the same result. >>> B.orient_axis(N, -N.x, q1) >>> B.orient_axis(N, N.x, -q1) """ from sympy.physics.vector.functions import dynamicsymbols _check_frame(parent) amount = sympify(angle) theta = amount axis = _check_vector(axis) parent_orient_axis = [] if not axis.dt(parent) == 0: raise ValueError('Axis cannot be time-varying.') unit_axis = axis.express(parent).normalize() unit_col = unit_axis.args[0][0] parent_orient_axis = ( (eye(3) - unit_col * unit_col.T) * cos(theta) + Matrix([[0, -unit_col[2], unit_col[1]], [unit_col[2], 0, -unit_col[0]], [-unit_col[1], unit_col[0], 0]]) * sin(theta) + unit_col * unit_col.T) self._dcm(parent, parent_orient_axis) thetad = (amount).diff(dynamicsymbols._t) wvec = thetad*axis.express(parent).normalize() self._ang_vel_dict.update({parent: wvec}) parent._ang_vel_dict.update({self: -wvec}) self._var_dict = {} def orient_explicit(self, parent, dcm): """Sets the orientation of this reference frame relative to a parent reference frame by explicitly setting the direction cosine matrix. Parameters ========== parent : ReferenceFrame Reference frame that this reference frame will be rotated relative to. dcm : Matrix, shape(3, 3) Direction cosine matrix that specifies the relative rotation between the two reference frames. Examples ======== Setup variables for the examples: >>> from sympy import symbols, Matrix, sin, cos >>> from sympy.physics.vector import ReferenceFrame >>> q1 = symbols('q1') >>> A = ReferenceFrame('A') >>> B = ReferenceFrame('B') >>> N = ReferenceFrame('N') A simple rotation of ``A`` relative to ``N`` about ``N.x`` is defined by the following direction cosine matrix: >>> dcm = Matrix([[1, 0, 0], ... [0, cos(q1), -sin(q1)], ... [0, sin(q1), cos(q1)]]) >>> A.orient_explicit(N, dcm) >>> A.dcm(N) Matrix([ [1, 0, 0], [0, cos(q1), sin(q1)], [0, -sin(q1), cos(q1)]]) This is equivalent to using ``orient_axis()``: >>> B.orient_axis(N, N.x, q1) >>> B.dcm(N) Matrix([ [1, 0, 0], [0, cos(q1), sin(q1)], [0, -sin(q1), cos(q1)]]) **Note carefully that** ``N.dcm(B)`` **(the transpose) would be passed into** ``orient_explicit()`` **for** ``A.dcm(N)`` **to match** ``B.dcm(N)``: >>> A.orient_explicit(N, N.dcm(B)) >>> A.dcm(N) Matrix([ [1, 0, 0], [0, cos(q1), sin(q1)], [0, -sin(q1), cos(q1)]]) """ _check_frame(parent) # amounts must be a Matrix type object # (e.g. sympy.matrices.dense.MutableDenseMatrix). if not isinstance(dcm, MatrixBase): raise TypeError("Amounts must be a sympy Matrix type object.") parent_orient_dcm = [] parent_orient_dcm = dcm self._dcm(parent, parent_orient_dcm) wvec = self._w_diff_dcm(parent) self._ang_vel_dict.update({parent: wvec}) parent._ang_vel_dict.update({self: -wvec}) self._var_dict = {} def _rot(self, axis, angle): """DCM for simple axis 1,2,or 3 rotations.""" if axis == 1: return Matrix([[1, 0, 0], [0, cos(angle), -sin(angle)], [0, sin(angle), cos(angle)]]) elif axis == 2: return Matrix([[cos(angle), 0, sin(angle)], [0, 1, 0], [-sin(angle), 0, cos(angle)]]) elif axis == 3: return Matrix([[cos(angle), -sin(angle), 0], [sin(angle), cos(angle), 0], [0, 0, 1]]) def orient_body_fixed(self, parent, angles, rotation_order): """Rotates this reference frame relative to the parent reference frame by right hand rotating through three successive body fixed simple axis rotations. Each subsequent axis of rotation is about the "body fixed" unit vectors of a new intermediate reference frame. This type of rotation is also referred to rotating through the `Euler and Tait-Bryan Angles`_. .. _Euler and Tait-Bryan Angles: https://en.wikipedia.org/wiki/Euler_angles Parameters ========== parent : ReferenceFrame Reference frame that this reference frame will be rotated relative to. angles : 3-tuple of sympifiable Three angles in radians used for the successive rotations. rotation_order : 3 character string or 3 digit integer Order of the rotations about each intermediate reference frames' unit vectors. The Euler rotation about the X, Z', X'' axes can be specified by the strings ``'XZX'``, ``'131'``, or the integer ``131``. There are 12 unique valid rotation orders (6 Euler and 6 Tait-Bryan): zxz, xyx, yzy, zyz, xzx, yxy, xyz, yzx, zxy, xzy, zyx, and yxz. Examples ======== Setup variables for the examples: >>> from sympy import symbols >>> from sympy.physics.vector import ReferenceFrame >>> q1, q2, q3 = symbols('q1, q2, q3') >>> N = ReferenceFrame('N') >>> B = ReferenceFrame('B') >>> B1 = ReferenceFrame('B1') >>> B2 = ReferenceFrame('B2') For example, a classic Euler Angle rotation can be done by: >>> B.orient_body_fixed(N, (q1, q2, q3), 'XYX') >>> B.dcm(N) Matrix([ [ cos(q2), sin(q1)*sin(q2), -sin(q2)*cos(q1)], [sin(q2)*sin(q3), -sin(q1)*sin(q3)*cos(q2) + cos(q1)*cos(q3), sin(q1)*cos(q3) + sin(q3)*cos(q1)*cos(q2)], [sin(q2)*cos(q3), -sin(q1)*cos(q2)*cos(q3) - sin(q3)*cos(q1), -sin(q1)*sin(q3) + cos(q1)*cos(q2)*cos(q3)]]) This rotates reference frame B relative to reference frame N through ``q1`` about ``N.x``, then rotates B again through ``q2`` about ``B.y``, and finally through ``q3`` about ``B.x``. It is equivalent to three successive ``orient_axis()`` calls: >>> B1.orient_axis(N, N.x, q1) >>> B2.orient_axis(B1, B1.y, q2) >>> B.orient_axis(B2, B2.x, q3) >>> B.dcm(N) Matrix([ [ cos(q2), sin(q1)*sin(q2), -sin(q2)*cos(q1)], [sin(q2)*sin(q3), -sin(q1)*sin(q3)*cos(q2) + cos(q1)*cos(q3), sin(q1)*cos(q3) + sin(q3)*cos(q1)*cos(q2)], [sin(q2)*cos(q3), -sin(q1)*cos(q2)*cos(q3) - sin(q3)*cos(q1), -sin(q1)*sin(q3) + cos(q1)*cos(q2)*cos(q3)]]) Acceptable rotation orders are of length 3, expressed in as a string ``'XYZ'`` or ``'123'`` or integer ``123``. Rotations about an axis twice in a row are prohibited. >>> B.orient_body_fixed(N, (q1, q2, 0), 'ZXZ') >>> B.orient_body_fixed(N, (q1, q2, 0), '121') >>> B.orient_body_fixed(N, (q1, q2, q3), 123) """ _check_frame(parent) amounts = list(angles) for i, v in enumerate(amounts): if not isinstance(v, Vector): amounts[i] = sympify(v) approved_orders = ('123', '231', '312', '132', '213', '321', '121', '131', '212', '232', '313', '323', '') # make sure XYZ => 123 rot_order = translate(str(rotation_order), 'XYZxyz', '123123') if rot_order not in approved_orders: raise TypeError('The rotation order is not a valid order.') parent_orient_body = [] if not (len(amounts) == 3 & len(rot_order) == 3): raise TypeError('Body orientation takes 3 values & 3 orders') a1 = int(rot_order[0]) a2 = int(rot_order[1]) a3 = int(rot_order[2]) parent_orient_body = (self._rot(a1, amounts[0]) * self._rot(a2, amounts[1]) * self._rot(a3, amounts[2])) self._dcm(parent, parent_orient_body) try: from sympy.polys.polyerrors import CoercionFailed from sympy.physics.vector.functions import kinematic_equations q1, q2, q3 = amounts u1, u2, u3 = symbols('u1, u2, u3', cls=Dummy) templist = kinematic_equations([u1, u2, u3], [q1, q2, q3], 'body', rot_order) templist = [expand(i) for i in templist] td = solve(templist, [u1, u2, u3]) u1 = expand(td[u1]) u2 = expand(td[u2]) u3 = expand(td[u3]) wvec = u1 * self.x + u2 * self.y + u3 * self.z except (CoercionFailed, AssertionError): wvec = self._w_diff_dcm(parent) self._ang_vel_dict.update({parent: wvec}) parent._ang_vel_dict.update({self: -wvec}) self._var_dict = {} def orient_space_fixed(self, parent, angles, rotation_order): """Rotates this reference frame relative to the parent reference frame by right hand rotating through three successive space fixed simple axis rotations. Each subsequent axis of rotation is about the "space fixed" unit vectors of the parent reference frame. Parameters ========== parent : ReferenceFrame Reference frame that this reference frame will be rotated relative to. angles : 3-tuple of sympifiable Three angles in radians used for the successive rotations. rotation_order : 3 character string or 3 digit integer Order of the rotations about the parent reference frame's unit vectors. The order can be specified by the strings ``'XZX'``, ``'131'``, or the integer ``131``. There are 12 unique valid rotation orders. Examples ======== Setup variables for the examples: >>> from sympy import symbols >>> from sympy.physics.vector import ReferenceFrame >>> q1, q2, q3 = symbols('q1, q2, q3') >>> N = ReferenceFrame('N') >>> B = ReferenceFrame('B') >>> B1 = ReferenceFrame('B1') >>> B2 = ReferenceFrame('B2') >>> B.orient_space_fixed(N, (q1, q2, q3), '312') >>> B.dcm(N) Matrix([ [ sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3), sin(q1)*cos(q2), sin(q1)*sin(q2)*cos(q3) - sin(q3)*cos(q1)], [-sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1), cos(q1)*cos(q2), sin(q1)*sin(q3) + sin(q2)*cos(q1)*cos(q3)], [ sin(q3)*cos(q2), -sin(q2), cos(q2)*cos(q3)]]) is equivalent to: >>> B1.orient_axis(N, N.z, q1) >>> B2.orient_axis(B1, N.x, q2) >>> B.orient_axis(B2, N.y, q3) >>> B.dcm(N).simplify() Matrix([ [ sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3), sin(q1)*cos(q2), sin(q1)*sin(q2)*cos(q3) - sin(q3)*cos(q1)], [-sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1), cos(q1)*cos(q2), sin(q1)*sin(q3) + sin(q2)*cos(q1)*cos(q3)], [ sin(q3)*cos(q2), -sin(q2), cos(q2)*cos(q3)]]) It is worth noting that space-fixed and body-fixed rotations are related by the order of the rotations, i.e. the reverse order of body fixed will give space fixed and vice versa. >>> B.orient_space_fixed(N, (q1, q2, q3), '231') >>> B.dcm(N) Matrix([ [cos(q1)*cos(q2), sin(q1)*sin(q3) + sin(q2)*cos(q1)*cos(q3), -sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1)], [ -sin(q2), cos(q2)*cos(q3), sin(q3)*cos(q2)], [sin(q1)*cos(q2), sin(q1)*sin(q2)*cos(q3) - sin(q3)*cos(q1), sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3)]]) >>> B.orient_body_fixed(N, (q3, q2, q1), '132') >>> B.dcm(N) Matrix([ [cos(q1)*cos(q2), sin(q1)*sin(q3) + sin(q2)*cos(q1)*cos(q3), -sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1)], [ -sin(q2), cos(q2)*cos(q3), sin(q3)*cos(q2)], [sin(q1)*cos(q2), sin(q1)*sin(q2)*cos(q3) - sin(q3)*cos(q1), sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3)]]) """ _check_frame(parent) amounts = list(angles) for i, v in enumerate(amounts): if not isinstance(v, Vector): amounts[i] = sympify(v) approved_orders = ('123', '231', '312', '132', '213', '321', '121', '131', '212', '232', '313', '323', '') # make sure XYZ => 123 rot_order = translate(str(rotation_order), 'XYZxyz', '123123') if rot_order not in approved_orders: raise TypeError('The supplied order is not an approved type') parent_orient_space = [] if not (len(amounts) == 3 & len(rot_order) == 3): raise TypeError('Space orientation takes 3 values & 3 orders') a1 = int(rot_order[0]) a2 = int(rot_order[1]) a3 = int(rot_order[2]) parent_orient_space = (self._rot(a3, amounts[2]) * self._rot(a2, amounts[1]) * self._rot(a1, amounts[0])) self._dcm(parent, parent_orient_space) try: from sympy.polys.polyerrors import CoercionFailed from sympy.physics.vector.functions import kinematic_equations q1, q2, q3 = amounts u1, u2, u3 = symbols('u1, u2, u3', cls=Dummy) templist = kinematic_equations([u1, u2, u3], [q1, q2, q3], 'space', rot_order) templist = [expand(i) for i in templist] td = solve(templist, [u1, u2, u3]) u1 = expand(td[u1]) u2 = expand(td[u2]) u3 = expand(td[u3]) wvec = u1 * self.x + u2 * self.y + u3 * self.z except (CoercionFailed, AssertionError): wvec = self._w_diff_dcm(parent) self._ang_vel_dict.update({parent: wvec}) parent._ang_vel_dict.update({self: -wvec}) self._var_dict = {} def orient_quaternion(self, parent, numbers): """Sets the orientation of this reference frame relative to a parent reference frame via an orientation quaternion. An orientation quaternion is defined as a finite rotation a unit vector, ``(lambda_x, lambda_y, lambda_z)``, by an angle ``theta``. The orientation quaternion is described by four parameters: - ``q0 = cos(theta/2)`` - ``q1 = lambda_x*sin(theta/2)`` - ``q2 = lambda_y*sin(theta/2)`` - ``q3 = lambda_z*sin(theta/2)`` See `Quaternions and Spatial Rotation <https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation>`_ on Wikipedia for more information. Parameters ========== parent : ReferenceFrame Reference frame that this reference frame will be rotated relative to. numbers : 4-tuple of sympifiable The four quaternion scalar numbers as defined above: ``q0``, ``q1``, ``q2``, ``q3``. Examples ======== Setup variables for the examples: >>> from sympy import symbols >>> from sympy.physics.vector import ReferenceFrame >>> q0, q1, q2, q3 = symbols('q0 q1 q2 q3') >>> N = ReferenceFrame('N') >>> B = ReferenceFrame('B') Set the orientation: >>> B.orient_quaternion(N, (q0, q1, q2, q3)) >>> B.dcm(N) Matrix([ [q0**2 + q1**2 - q2**2 - q3**2, 2*q0*q3 + 2*q1*q2, -2*q0*q2 + 2*q1*q3], [ -2*q0*q3 + 2*q1*q2, q0**2 - q1**2 + q2**2 - q3**2, 2*q0*q1 + 2*q2*q3], [ 2*q0*q2 + 2*q1*q3, -2*q0*q1 + 2*q2*q3, q0**2 - q1**2 - q2**2 + q3**2]]) """ from sympy.physics.vector.functions import dynamicsymbols _check_frame(parent) numbers = list(numbers) for i, v in enumerate(numbers): if not isinstance(v, Vector): numbers[i] = sympify(v) parent_orient_quaternion = [] if not (isinstance(numbers, (list, tuple)) & (len(numbers) == 4)): raise TypeError('Amounts are a list or tuple of length 4') q0, q1, q2, q3 = numbers parent_orient_quaternion = ( Matrix([[q0**2 + q1**2 - q2**2 - q3**2, 2 * (q1 * q2 - q0 * q3), 2 * (q0 * q2 + q1 * q3)], [2 * (q1 * q2 + q0 * q3), q0**2 - q1**2 + q2**2 - q3**2, 2 * (q2 * q3 - q0 * q1)], [2 * (q1 * q3 - q0 * q2), 2 * (q0 * q1 + q2 * q3), q0**2 - q1**2 - q2**2 + q3**2]])) self._dcm(parent, parent_orient_quaternion) t = dynamicsymbols._t q0, q1, q2, q3 = numbers q0d = diff(q0, t) q1d = diff(q1, t) q2d = diff(q2, t) q3d = diff(q3, t) w1 = 2 * (q1d * q0 + q2d * q3 - q3d * q2 - q0d * q1) w2 = 2 * (q2d * q0 + q3d * q1 - q1d * q3 - q0d * q2) w3 = 2 * (q3d * q0 + q1d * q2 - q2d * q1 - q0d * q3) wvec = Vector([(Matrix([w1, w2, w3]), self)]) self._ang_vel_dict.update({parent: wvec}) parent._ang_vel_dict.update({self: -wvec}) self._var_dict = {} def orient(self, parent, rot_type, amounts, rot_order=''): """Sets the orientation of this reference frame relative to another (parent) reference frame. .. note:: It is now recommended to use the ``.orient_axis, .orient_body_fixed, .orient_space_fixed, .orient_quaternion`` methods for the different rotation types. Parameters ========== parent : ReferenceFrame Reference frame that this reference frame will be rotated relative to. rot_type : str The method used to generate the direction cosine matrix. Supported methods are: - ``'Axis'``: simple rotations about a single common axis - ``'DCM'``: for setting the direction cosine matrix directly - ``'Body'``: three successive rotations about new intermediate axes, also called "Euler and Tait-Bryan angles" - ``'Space'``: three successive rotations about the parent frames' unit vectors - ``'Quaternion'``: rotations defined by four parameters which result in a singularity free direction cosine matrix amounts : Expressions defining the rotation angles or direction cosine matrix. These must match the ``rot_type``. See examples below for details. The input types are: - ``'Axis'``: 2-tuple (expr/sym/func, Vector) - ``'DCM'``: Matrix, shape(3,3) - ``'Body'``: 3-tuple of expressions, symbols, or functions - ``'Space'``: 3-tuple of expressions, symbols, or functions - ``'Quaternion'``: 4-tuple of expressions, symbols, or functions rot_order : str or int, optional If applicable, the order of the successive of rotations. The string ``'123'`` and integer ``123`` are equivalent, for example. Required for ``'Body'`` and ``'Space'``. """ _check_frame(parent) approved_orders = ('123', '231', '312', '132', '213', '321', '121', '131', '212', '232', '313', '323', '') rot_order = translate(str(rot_order), 'XYZxyz', '123123') rot_type = rot_type.upper() if rot_order not in approved_orders: raise TypeError('The supplied order is not an approved type') if rot_type == 'AXIS': self.orient_axis(parent, amounts[1], amounts[0]) elif rot_type == 'DCM': self.orient_explicit(parent, amounts) elif rot_type == 'BODY': self.orient_body_fixed(parent, amounts, rot_order) elif rot_type == 'SPACE': self.orient_space_fixed(parent, amounts, rot_order) elif rot_type == 'QUATERNION': self.orient_quaternion(parent, amounts) else: raise NotImplementedError('That is not an implemented rotation') def orientnew(self, newname, rot_type, amounts, rot_order='', variables=None, indices=None, latexs=None): r"""Returns a new reference frame oriented with respect to this reference frame. See ``ReferenceFrame.orient()`` for detailed examples of how to orient reference frames. Parameters ========== newname : str Name for the new reference frame. rot_type : str The method used to generate the direction cosine matrix. Supported methods are: - ``'Axis'``: simple rotations about a single common axis - ``'DCM'``: for setting the direction cosine matrix directly - ``'Body'``: three successive rotations about new intermediate axes, also called "Euler and Tait-Bryan angles" - ``'Space'``: three successive rotations about the parent frames' unit vectors - ``'Quaternion'``: rotations defined by four parameters which result in a singularity free direction cosine matrix amounts : Expressions defining the rotation angles or direction cosine matrix. These must match the ``rot_type``. See examples below for details. The input types are: - ``'Axis'``: 2-tuple (expr/sym/func, Vector) - ``'DCM'``: Matrix, shape(3,3) - ``'Body'``: 3-tuple of expressions, symbols, or functions - ``'Space'``: 3-tuple of expressions, symbols, or functions - ``'Quaternion'``: 4-tuple of expressions, symbols, or functions rot_order : str or int, optional If applicable, the order of the successive of rotations. The string ``'123'`` and integer ``123`` are equivalent, for example. Required for ``'Body'`` and ``'Space'``. indices : tuple of str Enables the reference frame's basis unit vectors to be accessed by Python's square bracket indexing notation using the provided three indice strings and alters the printing of the unit vectors to reflect this choice. latexs : tuple of str Alters the LaTeX printing of the reference frame's basis unit vectors to the provided three valid LaTeX strings. Examples ======== >>> from sympy import symbols >>> from sympy.physics.vector import ReferenceFrame, vlatex >>> q0, q1, q2, q3 = symbols('q0 q1 q2 q3') >>> N = ReferenceFrame('N') Create a new reference frame A rotated relative to N through a simple rotation. >>> A = N.orientnew('A', 'Axis', (q0, N.x)) Create a new reference frame B rotated relative to N through body-fixed rotations. >>> B = N.orientnew('B', 'Body', (q1, q2, q3), '123') Create a new reference frame C rotated relative to N through a simple rotation with unique indices and LaTeX printing. >>> C = N.orientnew('C', 'Axis', (q0, N.x), indices=('1', '2', '3'), ... latexs=(r'\hat{\mathbf{c}}_1',r'\hat{\mathbf{c}}_2', ... r'\hat{\mathbf{c}}_3')) >>> C['1'] C['1'] >>> print(vlatex(C['1'])) \hat{\mathbf{c}}_1 """ newframe = self.__class__(newname, variables=variables, indices=indices, latexs=latexs) approved_orders = ('123', '231', '312', '132', '213', '321', '121', '131', '212', '232', '313', '323', '') rot_order = translate(str(rot_order), 'XYZxyz', '123123') rot_type = rot_type.upper() if rot_order not in approved_orders: raise TypeError('The supplied order is not an approved type') if rot_type == 'AXIS': newframe.orient_axis(self, amounts[1], amounts[0]) elif rot_type == 'DCM': newframe.orient_explicit(self, amounts) elif rot_type == 'BODY': newframe.orient_body_fixed(self, amounts, rot_order) elif rot_type == 'SPACE': newframe.orient_space_fixed(self, amounts, rot_order) elif rot_type == 'QUATERNION': newframe.orient_quaternion(self, amounts) else: raise NotImplementedError('That is not an implemented rotation') return newframe def set_ang_acc(self, otherframe, value): """Define the angular acceleration Vector in a ReferenceFrame. Defines the angular acceleration of this ReferenceFrame, in another. Angular acceleration can be defined with respect to multiple different ReferenceFrames. Care must be taken to not create loops which are inconsistent. Parameters ========== otherframe : ReferenceFrame A ReferenceFrame to define the angular acceleration in value : Vector The Vector representing angular acceleration Examples ======== >>> from sympy.physics.vector import ReferenceFrame >>> N = ReferenceFrame('N') >>> A = ReferenceFrame('A') >>> V = 10 * N.x >>> A.set_ang_acc(N, V) >>> A.ang_acc_in(N) 10*N.x """ if value == 0: value = Vector(0) value = _check_vector(value) _check_frame(otherframe) self._ang_acc_dict.update({otherframe: value}) otherframe._ang_acc_dict.update({self: -value}) def set_ang_vel(self, otherframe, value): """Define the angular velocity vector in a ReferenceFrame. Defines the angular velocity of this ReferenceFrame, in another. Angular velocity can be defined with respect to multiple different ReferenceFrames. Care must be taken to not create loops which are inconsistent. Parameters ========== otherframe : ReferenceFrame A ReferenceFrame to define the angular velocity in value : Vector The Vector representing angular velocity Examples ======== >>> from sympy.physics.vector import ReferenceFrame >>> N = ReferenceFrame('N') >>> A = ReferenceFrame('A') >>> V = 10 * N.x >>> A.set_ang_vel(N, V) >>> A.ang_vel_in(N) 10*N.x """ if value == 0: value = Vector(0) value = _check_vector(value) _check_frame(otherframe) self._ang_vel_dict.update({otherframe: value}) otherframe._ang_vel_dict.update({self: -value}) @property def x(self): """The basis Vector for the ReferenceFrame, in the x direction. """ return self._x @property def y(self): """The basis Vector for the ReferenceFrame, in the y direction. """ return self._y @property def z(self): """The basis Vector for the ReferenceFrame, in the z direction. """ return self._z def partial_velocity(self, frame, *gen_speeds): """Returns the partial angular velocities of this frame in the given frame with respect to one or more provided generalized speeds. Parameters ========== frame : ReferenceFrame The frame with which the angular velocity is defined in. gen_speeds : functions of time The generalized speeds. Returns ======= partial_velocities : tuple of Vector The partial angular velocity vectors corresponding to the provided generalized speeds. Examples ======== >>> from sympy.physics.vector import ReferenceFrame, dynamicsymbols >>> N = ReferenceFrame('N') >>> A = ReferenceFrame('A') >>> u1, u2 = dynamicsymbols('u1, u2') >>> A.set_ang_vel(N, u1 * A.x + u2 * N.y) >>> A.partial_velocity(N, u1) A.x >>> A.partial_velocity(N, u1, u2) (A.x, N.y) """ partials = [self.ang_vel_in(frame).diff(speed, frame, var_in_dcm=False) for speed in gen_speeds] if len(partials) == 1: return partials[0] else: return tuple(partials) def _check_frame(other): from .vector import VectorTypeError if not isinstance(other, ReferenceFrame): raise VectorTypeError(other, ReferenceFrame('A'))
e884211e08c8fb90338bf6ff7afd9d11fe3695a8bce9dd7c8c7328cf48157632
""" This module can be used to solve 2D beam bending problems with singularity functions in mechanics. """ from sympy.core import S, Symbol, diff, symbols from sympy.solvers import linsolve from sympy.printing import sstr from sympy.functions import SingularityFunction, Piecewise, factorial from sympy.core import sympify from sympy.integrals import integrate from sympy.series import limit from sympy.plotting import plot, PlotGrid from sympy.geometry.entity import GeometryEntity from sympy.external import import_module from sympy import lambdify, Add from sympy.core.compatibility import iterable from sympy.utilities.decorator import doctest_depends_on numpy = import_module('numpy', import_kwargs={'fromlist':['arange']}) class Beam: """ A Beam is a structural element that is capable of withstanding load primarily by resisting against bending. Beams are characterized by their cross sectional profile(Second moment of area), their length and their material. .. note:: While solving a beam bending problem, a user should choose its own sign convention and should stick to it. The results will automatically follow the chosen sign convention. However, the chosen sign convention must respect the rule that, on the positive side of beam's axis (in respect to current section), a loading force giving positive shear yields a negative moment, as below (the curved arrow shows the positive moment and rotation): .. image:: allowed-sign-conventions.png Examples ======== There is a beam of length 4 meters. A constant distributed load of 6 N/m is applied from half of the beam till the end. There are two simple supports below the beam, one at the starting point and another at the ending point of the beam. The deflection of the beam at the end is restricted. Using the sign convention of downwards forces being positive. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols, Piecewise >>> E, I = symbols('E, I') >>> R1, R2 = symbols('R1, R2') >>> b = Beam(4, E, I) >>> b.apply_load(R1, 0, -1) >>> b.apply_load(6, 2, 0) >>> b.apply_load(R2, 4, -1) >>> b.bc_deflection = [(0, 0), (4, 0)] >>> b.boundary_conditions {'deflection': [(0, 0), (4, 0)], 'slope': []} >>> b.load R1*SingularityFunction(x, 0, -1) + R2*SingularityFunction(x, 4, -1) + 6*SingularityFunction(x, 2, 0) >>> b.solve_for_reaction_loads(R1, R2) >>> b.load -3*SingularityFunction(x, 0, -1) + 6*SingularityFunction(x, 2, 0) - 9*SingularityFunction(x, 4, -1) >>> b.shear_force() 3*SingularityFunction(x, 0, 0) - 6*SingularityFunction(x, 2, 1) + 9*SingularityFunction(x, 4, 0) >>> b.bending_moment() 3*SingularityFunction(x, 0, 1) - 3*SingularityFunction(x, 2, 2) + 9*SingularityFunction(x, 4, 1) >>> b.slope() (-3*SingularityFunction(x, 0, 2)/2 + SingularityFunction(x, 2, 3) - 9*SingularityFunction(x, 4, 2)/2 + 7)/(E*I) >>> b.deflection() (7*x - SingularityFunction(x, 0, 3)/2 + SingularityFunction(x, 2, 4)/4 - 3*SingularityFunction(x, 4, 3)/2)/(E*I) >>> b.deflection().rewrite(Piecewise) (7*x - Piecewise((x**3, x > 0), (0, True))/2 - 3*Piecewise(((x - 4)**3, x - 4 > 0), (0, True))/2 + Piecewise(((x - 2)**4, x - 2 > 0), (0, True))/4)/(E*I) """ def __init__(self, length, elastic_modulus, second_moment, area=Symbol('A'), variable=Symbol('x'), base_char='C'): """Initializes the class. Parameters ========== length : Sympifyable A Symbol or value representing the Beam's length. elastic_modulus : Sympifyable A SymPy expression representing the Beam's Modulus of Elasticity. It is a measure of the stiffness of the Beam material. It can also be a continuous function of position along the beam. second_moment : Sympifyable or Geometry object Describes the cross-section of the beam via a SymPy expression representing the Beam's second moment of area. It is a geometrical property of an area which reflects how its points are distributed with respect to its neutral axis. It can also be a continuous function of position along the beam. Alternatively ``second_moment`` can be a shape object such as a ``Polygon`` from the geometry module representing the shape of the cross-section of the beam. In such cases, it is assumed that the x-axis of the shape object is aligned with the bending axis of the beam. The second moment of area will be computed from the shape object internally. area : Symbol/float Represents the cross-section area of beam variable : Symbol, optional A Symbol object that will be used as the variable along the beam while representing the load, shear, moment, slope and deflection curve. By default, it is set to ``Symbol('x')``. base_char : String, optional A String that will be used as base character to generate sequential symbols for integration constants in cases where boundary conditions are not sufficient to solve them. """ self.length = length self.elastic_modulus = elastic_modulus if isinstance(second_moment, GeometryEntity): self.cross_section = second_moment else: self.cross_section = None self.second_moment = second_moment self.variable = variable self._base_char = base_char self._boundary_conditions = {'deflection': [], 'slope': []} self._load = 0 self._area = area self._applied_supports = [] self._support_as_loads = [] self._applied_loads = [] self._reaction_loads = {} self._composite_type = None self._hinge_position = None def __str__(self): shape_description = self._cross_section if self._cross_section else self._second_moment str_sol = 'Beam({}, {}, {})'.format(sstr(self._length), sstr(self._elastic_modulus), sstr(shape_description)) return str_sol @property def reaction_loads(self): """ Returns the reaction forces in a dictionary.""" return self._reaction_loads @property def length(self): """Length of the Beam.""" return self._length @length.setter def length(self, l): self._length = sympify(l) @property def area(self): """Cross-sectional area of the Beam. """ return self._area @area.setter def area(self, a): self._area = sympify(a) @property def variable(self): """ A symbol that can be used as a variable along the length of the beam while representing load distribution, shear force curve, bending moment, slope curve and the deflection curve. By default, it is set to ``Symbol('x')``, but this property is mutable. Examples ======== >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I, A = symbols('E, I, A') >>> x, y, z = symbols('x, y, z') >>> b = Beam(4, E, I) >>> b.variable x >>> b.variable = y >>> b.variable y >>> b = Beam(4, E, I, A, z) >>> b.variable z """ return self._variable @variable.setter def variable(self, v): if isinstance(v, Symbol): self._variable = v else: raise TypeError("""The variable should be a Symbol object.""") @property def elastic_modulus(self): """Young's Modulus of the Beam. """ return self._elastic_modulus @elastic_modulus.setter def elastic_modulus(self, e): self._elastic_modulus = sympify(e) @property def second_moment(self): """Second moment of area of the Beam. """ return self._second_moment @second_moment.setter def second_moment(self, i): self._cross_section = None if isinstance(i, GeometryEntity): raise ValueError("To update cross-section geometry use `cross_section` attribute") else: self._second_moment = sympify(i) @property def cross_section(self): """Cross-section of the beam""" return self._cross_section @cross_section.setter def cross_section(self, s): if s: self._second_moment = s.second_moment_of_area()[0] self._cross_section = s @property def boundary_conditions(self): """ Returns a dictionary of boundary conditions applied on the beam. The dictionary has three keywords namely moment, slope and deflection. The value of each keyword is a list of tuple, where each tuple contains location and value of a boundary condition in the format (location, value). Examples ======== There is a beam of length 4 meters. The bending moment at 0 should be 4 and at 4 it should be 0. The slope of the beam should be 1 at 0. The deflection should be 2 at 0. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> b = Beam(4, E, I) >>> b.bc_deflection = [(0, 2)] >>> b.bc_slope = [(0, 1)] >>> b.boundary_conditions {'deflection': [(0, 2)], 'slope': [(0, 1)]} Here the deflection of the beam should be ``2`` at ``0``. Similarly, the slope of the beam should be ``1`` at ``0``. """ return self._boundary_conditions @property def bc_slope(self): return self._boundary_conditions['slope'] @bc_slope.setter def bc_slope(self, s_bcs): self._boundary_conditions['slope'] = s_bcs @property def bc_deflection(self): return self._boundary_conditions['deflection'] @bc_deflection.setter def bc_deflection(self, d_bcs): self._boundary_conditions['deflection'] = d_bcs def join(self, beam, via="fixed"): """ This method joins two beams to make a new composite beam system. Passed Beam class instance is attached to the right end of calling object. This method can be used to form beams having Discontinuous values of Elastic modulus or Second moment. Parameters ========== beam : Beam class object The Beam object which would be connected to the right of calling object. via : String States the way two Beam object would get connected - For axially fixed Beams, via="fixed" - For Beams connected via hinge, via="hinge" Examples ======== There is a cantilever beam of length 4 meters. For first 2 meters its moment of inertia is `1.5*I` and `I` for the other end. A pointload of magnitude 4 N is applied from the top at its free end. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> R1, R2 = symbols('R1, R2') >>> b1 = Beam(2, E, 1.5*I) >>> b2 = Beam(2, E, I) >>> b = b1.join(b2, "fixed") >>> b.apply_load(20, 4, -1) >>> b.apply_load(R1, 0, -1) >>> b.apply_load(R2, 0, -2) >>> b.bc_slope = [(0, 0)] >>> b.bc_deflection = [(0, 0)] >>> b.solve_for_reaction_loads(R1, R2) >>> b.load 80*SingularityFunction(x, 0, -2) - 20*SingularityFunction(x, 0, -1) + 20*SingularityFunction(x, 4, -1) >>> b.slope() (-((-80*SingularityFunction(x, 0, 1) + 10*SingularityFunction(x, 0, 2) - 10*SingularityFunction(x, 4, 2))/I + 120/I)/E + 80.0/(E*I))*SingularityFunction(x, 2, 0) - 0.666666666666667*(-80*SingularityFunction(x, 0, 1) + 10*SingularityFunction(x, 0, 2) - 10*SingularityFunction(x, 4, 2))*SingularityFunction(x, 0, 0)/(E*I) + 0.666666666666667*(-80*SingularityFunction(x, 0, 1) + 10*SingularityFunction(x, 0, 2) - 10*SingularityFunction(x, 4, 2))*SingularityFunction(x, 2, 0)/(E*I) """ x = self.variable E = self.elastic_modulus new_length = self.length + beam.length if self.second_moment != beam.second_moment: new_second_moment = Piecewise((self.second_moment, x<=self.length), (beam.second_moment, x<=new_length)) else: new_second_moment = self.second_moment if via == "fixed": new_beam = Beam(new_length, E, new_second_moment, x) new_beam._composite_type = "fixed" return new_beam if via == "hinge": new_beam = Beam(new_length, E, new_second_moment, x) new_beam._composite_type = "hinge" new_beam._hinge_position = self.length return new_beam def apply_support(self, loc, type="fixed"): """ This method applies support to a particular beam object. Parameters ========== loc : Sympifyable Location of point at which support is applied. type : String Determines type of Beam support applied. To apply support structure with - zero degree of freedom, type = "fixed" - one degree of freedom, type = "pin" - two degrees of freedom, type = "roller" Examples ======== There is a beam of length 30 meters. A moment of magnitude 120 Nm is applied in the clockwise direction at the end of the beam. A pointload of magnitude 8 N is applied from the top of the beam at the starting point. There are two simple supports below the beam. One at the end and another one at a distance of 10 meters from the start. The deflection is restricted at both the supports. Using the sign convention of upward forces and clockwise moment being positive. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> b = Beam(30, E, I) >>> b.apply_support(10, 'roller') >>> b.apply_support(30, 'roller') >>> b.apply_load(-8, 0, -1) >>> b.apply_load(120, 30, -2) >>> R_10, R_30 = symbols('R_10, R_30') >>> b.solve_for_reaction_loads(R_10, R_30) >>> b.load -8*SingularityFunction(x, 0, -1) + 6*SingularityFunction(x, 10, -1) + 120*SingularityFunction(x, 30, -2) + 2*SingularityFunction(x, 30, -1) >>> b.slope() (-4*SingularityFunction(x, 0, 2) + 3*SingularityFunction(x, 10, 2) + 120*SingularityFunction(x, 30, 1) + SingularityFunction(x, 30, 2) + 4000/3)/(E*I) """ loc = sympify(loc) self._applied_supports.append((loc, type)) if type == "pin" or type == "roller": reaction_load = Symbol('R_'+str(loc)) self.apply_load(reaction_load, loc, -1) self.bc_deflection.append((loc, 0)) else: reaction_load = Symbol('R_'+str(loc)) reaction_moment = Symbol('M_'+str(loc)) self.apply_load(reaction_load, loc, -1) self.apply_load(reaction_moment, loc, -2) self.bc_deflection.append((loc, 0)) self.bc_slope.append((loc, 0)) self._support_as_loads.append((reaction_moment, loc, -2, None)) self._support_as_loads.append((reaction_load, loc, -1, None)) def apply_load(self, value, start, order, end=None): """ This method adds up the loads given to a particular beam object. Parameters ========== value : Sympifyable The value inserted should have the units [Force/(Distance**(n+1)] where n is the order of applied load. Units for applied loads: - For moments, unit = kN*m - For point loads, unit = kN - For constant distributed load, unit = kN/m - For ramp loads, unit = kN/m/m - For parabolic ramp loads, unit = kN/m/m/m - ... so on. start : Sympifyable The starting point of the applied load. For point moments and point forces this is the location of application. order : Integer The order of the applied load. - For moments, order = -2 - For point loads, order =-1 - For constant distributed load, order = 0 - For ramp loads, order = 1 - For parabolic ramp loads, order = 2 - ... so on. end : Sympifyable, optional An optional argument that can be used if the load has an end point within the length of the beam. Examples ======== There is a beam of length 4 meters. A moment of magnitude 3 Nm is applied in the clockwise direction at the starting point of the beam. A point load of magnitude 4 N is applied from the top of the beam at 2 meters from the starting point and a parabolic ramp load of magnitude 2 N/m is applied below the beam starting from 2 meters to 3 meters away from the starting point of the beam. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> b = Beam(4, E, I) >>> b.apply_load(-3, 0, -2) >>> b.apply_load(4, 2, -1) >>> b.apply_load(-2, 2, 2, end=3) >>> b.load -3*SingularityFunction(x, 0, -2) + 4*SingularityFunction(x, 2, -1) - 2*SingularityFunction(x, 2, 2) + 2*SingularityFunction(x, 3, 0) + 4*SingularityFunction(x, 3, 1) + 2*SingularityFunction(x, 3, 2) """ x = self.variable value = sympify(value) start = sympify(start) order = sympify(order) self._applied_loads.append((value, start, order, end)) self._load += value*SingularityFunction(x, start, order) if end: # load has an end point within the length of the beam. self._handle_end(x, value, start, order, end, type="apply") def remove_load(self, value, start, order, end=None): """ This method removes a particular load present on the beam object. Returns a ValueError if the load passed as an argument is not present on the beam. Parameters ========== value : Sympifyable The magnitude of an applied load. start : Sympifyable The starting point of the applied load. For point moments and point forces this is the location of application. order : Integer The order of the applied load. - For moments, order= -2 - For point loads, order=-1 - For constant distributed load, order=0 - For ramp loads, order=1 - For parabolic ramp loads, order=2 - ... so on. end : Sympifyable, optional An optional argument that can be used if the load has an end point within the length of the beam. Examples ======== There is a beam of length 4 meters. A moment of magnitude 3 Nm is applied in the clockwise direction at the starting point of the beam. A pointload of magnitude 4 N is applied from the top of the beam at 2 meters from the starting point and a parabolic ramp load of magnitude 2 N/m is applied below the beam starting from 2 meters to 3 meters away from the starting point of the beam. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> b = Beam(4, E, I) >>> b.apply_load(-3, 0, -2) >>> b.apply_load(4, 2, -1) >>> b.apply_load(-2, 2, 2, end=3) >>> b.load -3*SingularityFunction(x, 0, -2) + 4*SingularityFunction(x, 2, -1) - 2*SingularityFunction(x, 2, 2) + 2*SingularityFunction(x, 3, 0) + 4*SingularityFunction(x, 3, 1) + 2*SingularityFunction(x, 3, 2) >>> b.remove_load(-2, 2, 2, end = 3) >>> b.load -3*SingularityFunction(x, 0, -2) + 4*SingularityFunction(x, 2, -1) """ x = self.variable value = sympify(value) start = sympify(start) order = sympify(order) if (value, start, order, end) in self._applied_loads: self._load -= value*SingularityFunction(x, start, order) self._applied_loads.remove((value, start, order, end)) else: msg = "No such load distribution exists on the beam object." raise ValueError(msg) if end: # load has an end point within the length of the beam. self._handle_end(x, value, start, order, end, type="remove") def _handle_end(self, x, value, start, order, end, type): """ This functions handles the optional `end` value in the `apply_load` and `remove_load` functions. When the value of end is not NULL, this function will be executed. """ if order.is_negative: msg = ("If 'end' is provided the 'order' of the load cannot " "be negative, i.e. 'end' is only valid for distributed " "loads.") raise ValueError(msg) # NOTE : A Taylor series can be used to define the summation of # singularity functions that subtract from the load past the end # point such that it evaluates to zero past 'end'. f = value*x**order if type == "apply": # iterating for "apply_load" method for i in range(0, order + 1): self._load -= (f.diff(x, i).subs(x, end - start) * SingularityFunction(x, end, i)/factorial(i)) elif type == "remove": # iterating for "remove_load" method for i in range(0, order + 1): self._load += (f.diff(x, i).subs(x, end - start) * SingularityFunction(x, end, i)/factorial(i)) @property def load(self): """ Returns a Singularity Function expression which represents the load distribution curve of the Beam object. Examples ======== There is a beam of length 4 meters. A moment of magnitude 3 Nm is applied in the clockwise direction at the starting point of the beam. A point load of magnitude 4 N is applied from the top of the beam at 2 meters from the starting point and a parabolic ramp load of magnitude 2 N/m is applied below the beam starting from 3 meters away from the starting point of the beam. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> b = Beam(4, E, I) >>> b.apply_load(-3, 0, -2) >>> b.apply_load(4, 2, -1) >>> b.apply_load(-2, 3, 2) >>> b.load -3*SingularityFunction(x, 0, -2) + 4*SingularityFunction(x, 2, -1) - 2*SingularityFunction(x, 3, 2) """ return self._load @property def applied_loads(self): """ Returns a list of all loads applied on the beam object. Each load in the list is a tuple of form (value, start, order, end). Examples ======== There is a beam of length 4 meters. A moment of magnitude 3 Nm is applied in the clockwise direction at the starting point of the beam. A pointload of magnitude 4 N is applied from the top of the beam at 2 meters from the starting point. Another pointload of magnitude 5 N is applied at same position. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> b = Beam(4, E, I) >>> b.apply_load(-3, 0, -2) >>> b.apply_load(4, 2, -1) >>> b.apply_load(5, 2, -1) >>> b.load -3*SingularityFunction(x, 0, -2) + 9*SingularityFunction(x, 2, -1) >>> b.applied_loads [(-3, 0, -2, None), (4, 2, -1, None), (5, 2, -1, None)] """ return self._applied_loads def _solve_hinge_beams(self, *reactions): """Method to find integration constants and reactional variables in a composite beam connected via hinge. This method resolves the composite Beam into its sub-beams and then equations of shear force, bending moment, slope and deflection are evaluated for both of them separately. These equations are then solved for unknown reactions and integration constants using the boundary conditions applied on the Beam. Equal deflection of both sub-beams at the hinge joint gives us another equation to solve the system. Examples ======== A combined beam, with constant fkexural rigidity E*I, is formed by joining a Beam of length 2*l to the right of another Beam of length l. The whole beam is fixed at both of its both end. A point load of magnitude P is also applied from the top at a distance of 2*l from starting point. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> l=symbols('l', positive=True) >>> b1=Beam(l ,E,I) >>> b2=Beam(2*l ,E,I) >>> b=b1.join(b2,"hinge") >>> M1, A1, M2, A2, P = symbols('M1 A1 M2 A2 P') >>> b.apply_load(A1,0,-1) >>> b.apply_load(M1,0,-2) >>> b.apply_load(P,2*l,-1) >>> b.apply_load(A2,3*l,-1) >>> b.apply_load(M2,3*l,-2) >>> b.bc_slope=[(0,0), (3*l, 0)] >>> b.bc_deflection=[(0,0), (3*l, 0)] >>> b.solve_for_reaction_loads(M1, A1, M2, A2) >>> b.reaction_loads {A1: -5*P/18, A2: -13*P/18, M1: 5*P*l/18, M2: -4*P*l/9} >>> b.slope() (5*P*l*SingularityFunction(x, 0, 1)/18 - 5*P*SingularityFunction(x, 0, 2)/36 + 5*P*SingularityFunction(x, l, 2)/36)*SingularityFunction(x, 0, 0)/(E*I) - (5*P*l*SingularityFunction(x, 0, 1)/18 - 5*P*SingularityFunction(x, 0, 2)/36 + 5*P*SingularityFunction(x, l, 2)/36)*SingularityFunction(x, l, 0)/(E*I) + (P*l**2/18 - 4*P*l*SingularityFunction(-l + x, 2*l, 1)/9 - 5*P*SingularityFunction(-l + x, 0, 2)/36 + P*SingularityFunction(-l + x, l, 2)/2 - 13*P*SingularityFunction(-l + x, 2*l, 2)/36)*SingularityFunction(x, l, 0)/(E*I) >>> b.deflection() (5*P*l*SingularityFunction(x, 0, 2)/36 - 5*P*SingularityFunction(x, 0, 3)/108 + 5*P*SingularityFunction(x, l, 3)/108)*SingularityFunction(x, 0, 0)/(E*I) - (5*P*l*SingularityFunction(x, 0, 2)/36 - 5*P*SingularityFunction(x, 0, 3)/108 + 5*P*SingularityFunction(x, l, 3)/108)*SingularityFunction(x, l, 0)/(E*I) + (5*P*l**3/54 + P*l**2*(-l + x)/18 - 2*P*l*SingularityFunction(-l + x, 2*l, 2)/9 - 5*P*SingularityFunction(-l + x, 0, 3)/108 + P*SingularityFunction(-l + x, l, 3)/6 - 13*P*SingularityFunction(-l + x, 2*l, 3)/108)*SingularityFunction(x, l, 0)/(E*I) """ x = self.variable l = self._hinge_position E = self._elastic_modulus I = self._second_moment if isinstance(I, Piecewise): I1 = I.args[0][0] I2 = I.args[1][0] else: I1 = I2 = I load_1 = 0 # Load equation on first segment of composite beam load_2 = 0 # Load equation on second segment of composite beam # Distributing load on both segments for load in self.applied_loads: if load[1] < l: load_1 += load[0]*SingularityFunction(x, load[1], load[2]) if load[2] == 0: load_1 -= load[0]*SingularityFunction(x, load[3], load[2]) elif load[2] > 0: load_1 -= load[0]*SingularityFunction(x, load[3], load[2]) + load[0]*SingularityFunction(x, load[3], 0) elif load[1] == l: load_1 += load[0]*SingularityFunction(x, load[1], load[2]) load_2 += load[0]*SingularityFunction(x, load[1] - l, load[2]) elif load[1] > l: load_2 += load[0]*SingularityFunction(x, load[1] - l, load[2]) if load[2] == 0: load_2 -= load[0]*SingularityFunction(x, load[3] - l, load[2]) elif load[2] > 0: load_2 -= load[0]*SingularityFunction(x, load[3] - l, load[2]) + load[0]*SingularityFunction(x, load[3] - l, 0) h = Symbol('h') # Force due to hinge load_1 += h*SingularityFunction(x, l, -1) load_2 -= h*SingularityFunction(x, 0, -1) eq = [] shear_1 = integrate(load_1, x) shear_curve_1 = limit(shear_1, x, l) eq.append(shear_curve_1) bending_1 = integrate(shear_1, x) moment_curve_1 = limit(bending_1, x, l) eq.append(moment_curve_1) shear_2 = integrate(load_2, x) shear_curve_2 = limit(shear_2, x, self.length - l) eq.append(shear_curve_2) bending_2 = integrate(shear_2, x) moment_curve_2 = limit(bending_2, x, self.length - l) eq.append(moment_curve_2) C1 = Symbol('C1') C2 = Symbol('C2') C3 = Symbol('C3') C4 = Symbol('C4') slope_1 = S.One/(E*I1)*(integrate(bending_1, x) + C1) def_1 = S.One/(E*I1)*(integrate((E*I)*slope_1, x) + C1*x + C2) slope_2 = S.One/(E*I2)*(integrate(integrate(integrate(load_2, x), x), x) + C3) def_2 = S.One/(E*I2)*(integrate((E*I)*slope_2, x) + C4) for position, value in self.bc_slope: if position<l: eq.append(slope_1.subs(x, position) - value) else: eq.append(slope_2.subs(x, position - l) - value) for position, value in self.bc_deflection: if position<l: eq.append(def_1.subs(x, position) - value) else: eq.append(def_2.subs(x, position - l) - value) eq.append(def_1.subs(x, l) - def_2.subs(x, 0)) # Deflection of both the segments at hinge would be equal constants = list(linsolve(eq, C1, C2, C3, C4, h, *reactions)) reaction_values = list(constants[0])[5:] self._reaction_loads = dict(zip(reactions, reaction_values)) self._load = self._load.subs(self._reaction_loads) # Substituting constants and reactional load and moments with their corresponding values slope_1 = slope_1.subs({C1: constants[0][0], h:constants[0][4]}).subs(self._reaction_loads) def_1 = def_1.subs({C1: constants[0][0], C2: constants[0][1], h:constants[0][4]}).subs(self._reaction_loads) slope_2 = slope_2.subs({x: x-l, C3: constants[0][2], h:constants[0][4]}).subs(self._reaction_loads) def_2 = def_2.subs({x: x-l,C3: constants[0][2], C4: constants[0][3], h:constants[0][4]}).subs(self._reaction_loads) self._hinge_beam_slope = slope_1*SingularityFunction(x, 0, 0) - slope_1*SingularityFunction(x, l, 0) + slope_2*SingularityFunction(x, l, 0) self._hinge_beam_deflection = def_1*SingularityFunction(x, 0, 0) - def_1*SingularityFunction(x, l, 0) + def_2*SingularityFunction(x, l, 0) def solve_for_reaction_loads(self, *reactions): """ Solves for the reaction forces. Examples ======== There is a beam of length 30 meters. A moment of magnitude 120 Nm is applied in the clockwise direction at the end of the beam. A pointload of magnitude 8 N is applied from the top of the beam at the starting point. There are two simple supports below the beam. One at the end and another one at a distance of 10 meters from the start. The deflection is restricted at both the supports. Using the sign convention of upward forces and clockwise moment being positive. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> R1, R2 = symbols('R1, R2') >>> b = Beam(30, E, I) >>> b.apply_load(-8, 0, -1) >>> b.apply_load(R1, 10, -1) # Reaction force at x = 10 >>> b.apply_load(R2, 30, -1) # Reaction force at x = 30 >>> b.apply_load(120, 30, -2) >>> b.bc_deflection = [(10, 0), (30, 0)] >>> b.load R1*SingularityFunction(x, 10, -1) + R2*SingularityFunction(x, 30, -1) - 8*SingularityFunction(x, 0, -1) + 120*SingularityFunction(x, 30, -2) >>> b.solve_for_reaction_loads(R1, R2) >>> b.reaction_loads {R1: 6, R2: 2} >>> b.load -8*SingularityFunction(x, 0, -1) + 6*SingularityFunction(x, 10, -1) + 120*SingularityFunction(x, 30, -2) + 2*SingularityFunction(x, 30, -1) """ if self._composite_type == "hinge": return self._solve_hinge_beams(*reactions) x = self.variable l = self.length C3 = Symbol('C3') C4 = Symbol('C4') shear_curve = limit(self.shear_force(), x, l) moment_curve = limit(self.bending_moment(), x, l) slope_eqs = [] deflection_eqs = [] slope_curve = integrate(self.bending_moment(), x) + C3 for position, value in self._boundary_conditions['slope']: eqs = slope_curve.subs(x, position) - value slope_eqs.append(eqs) deflection_curve = integrate(slope_curve, x) + C4 for position, value in self._boundary_conditions['deflection']: eqs = deflection_curve.subs(x, position) - value deflection_eqs.append(eqs) solution = list((linsolve([shear_curve, moment_curve] + slope_eqs + deflection_eqs, (C3, C4) + reactions).args)[0]) solution = solution[2:] self._reaction_loads = dict(zip(reactions, solution)) self._load = self._load.subs(self._reaction_loads) def shear_force(self): """ Returns a Singularity Function expression which represents the shear force curve of the Beam object. Examples ======== There is a beam of length 30 meters. A moment of magnitude 120 Nm is applied in the clockwise direction at the end of the beam. A pointload of magnitude 8 N is applied from the top of the beam at the starting point. There are two simple supports below the beam. One at the end and another one at a distance of 10 meters from the start. The deflection is restricted at both the supports. Using the sign convention of upward forces and clockwise moment being positive. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> R1, R2 = symbols('R1, R2') >>> b = Beam(30, E, I) >>> b.apply_load(-8, 0, -1) >>> b.apply_load(R1, 10, -1) >>> b.apply_load(R2, 30, -1) >>> b.apply_load(120, 30, -2) >>> b.bc_deflection = [(10, 0), (30, 0)] >>> b.solve_for_reaction_loads(R1, R2) >>> b.shear_force() 8*SingularityFunction(x, 0, 0) - 6*SingularityFunction(x, 10, 0) - 120*SingularityFunction(x, 30, -1) - 2*SingularityFunction(x, 30, 0) """ x = self.variable return -integrate(self.load, x) def max_shear_force(self): """Returns maximum Shear force and its coordinate in the Beam object.""" from sympy import solve, Mul, Interval shear_curve = self.shear_force() x = self.variable terms = shear_curve.args singularity = [] # Points at which shear function changes for term in terms: if isinstance(term, Mul): term = term.args[-1] # SingularityFunction in the term singularity.append(term.args[1]) singularity.sort() singularity = list(set(singularity)) intervals = [] # List of Intervals with discrete value of shear force shear_values = [] # List of values of shear force in each interval for i, s in enumerate(singularity): if s == 0: continue try: shear_slope = Piecewise((float("nan"), x<=singularity[i-1]),(self._load.rewrite(Piecewise), x<s), (float("nan"), True)) points = solve(shear_slope, x) val = [] for point in points: val.append(shear_curve.subs(x, point)) points.extend([singularity[i-1], s]) val.extend([limit(shear_curve, x, singularity[i-1], '+'), limit(shear_curve, x, s, '-')]) val = list(map(abs, val)) max_shear = max(val) shear_values.append(max_shear) intervals.append(points[val.index(max_shear)]) # If shear force in a particular Interval has zero or constant # slope, then above block gives NotImplementedError as # solve can't represent Interval solutions. except NotImplementedError: initial_shear = limit(shear_curve, x, singularity[i-1], '+') final_shear = limit(shear_curve, x, s, '-') # If shear_curve has a constant slope(it is a line). if shear_curve.subs(x, (singularity[i-1] + s)/2) == (initial_shear + final_shear)/2 and initial_shear != final_shear: shear_values.extend([initial_shear, final_shear]) intervals.extend([singularity[i-1], s]) else: # shear_curve has same value in whole Interval shear_values.append(final_shear) intervals.append(Interval(singularity[i-1], s)) shear_values = list(map(abs, shear_values)) maximum_shear = max(shear_values) point = intervals[shear_values.index(maximum_shear)] return (point, maximum_shear) def bending_moment(self): """ Returns a Singularity Function expression which represents the bending moment curve of the Beam object. Examples ======== There is a beam of length 30 meters. A moment of magnitude 120 Nm is applied in the clockwise direction at the end of the beam. A pointload of magnitude 8 N is applied from the top of the beam at the starting point. There are two simple supports below the beam. One at the end and another one at a distance of 10 meters from the start. The deflection is restricted at both the supports. Using the sign convention of upward forces and clockwise moment being positive. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> R1, R2 = symbols('R1, R2') >>> b = Beam(30, E, I) >>> b.apply_load(-8, 0, -1) >>> b.apply_load(R1, 10, -1) >>> b.apply_load(R2, 30, -1) >>> b.apply_load(120, 30, -2) >>> b.bc_deflection = [(10, 0), (30, 0)] >>> b.solve_for_reaction_loads(R1, R2) >>> b.bending_moment() 8*SingularityFunction(x, 0, 1) - 6*SingularityFunction(x, 10, 1) - 120*SingularityFunction(x, 30, 0) - 2*SingularityFunction(x, 30, 1) """ x = self.variable return integrate(self.shear_force(), x) def max_bmoment(self): """Returns maximum Shear force and its coordinate in the Beam object.""" from sympy import solve, Mul, Interval bending_curve = self.bending_moment() x = self.variable terms = bending_curve.args singularity = [] # Points at which bending moment changes for term in terms: if isinstance(term, Mul): term = term.args[-1] # SingularityFunction in the term singularity.append(term.args[1]) singularity.sort() singularity = list(set(singularity)) intervals = [] # List of Intervals with discrete value of bending moment moment_values = [] # List of values of bending moment in each interval for i, s in enumerate(singularity): if s == 0: continue try: moment_slope = Piecewise((float("nan"), x<=singularity[i-1]),(self.shear_force().rewrite(Piecewise), x<s), (float("nan"), True)) points = solve(moment_slope, x) val = [] for point in points: val.append(bending_curve.subs(x, point)) points.extend([singularity[i-1], s]) val.extend([limit(bending_curve, x, singularity[i-1], '+'), limit(bending_curve, x, s, '-')]) val = list(map(abs, val)) max_moment = max(val) moment_values.append(max_moment) intervals.append(points[val.index(max_moment)]) # If bending moment in a particular Interval has zero or constant # slope, then above block gives NotImplementedError as solve # can't represent Interval solutions. except NotImplementedError: initial_moment = limit(bending_curve, x, singularity[i-1], '+') final_moment = limit(bending_curve, x, s, '-') # If bending_curve has a constant slope(it is a line). if bending_curve.subs(x, (singularity[i-1] + s)/2) == (initial_moment + final_moment)/2 and initial_moment != final_moment: moment_values.extend([initial_moment, final_moment]) intervals.extend([singularity[i-1], s]) else: # bending_curve has same value in whole Interval moment_values.append(final_moment) intervals.append(Interval(singularity[i-1], s)) moment_values = list(map(abs, moment_values)) maximum_moment = max(moment_values) point = intervals[moment_values.index(maximum_moment)] return (point, maximum_moment) def point_cflexure(self): """ Returns a Set of point(s) with zero bending moment and where bending moment curve of the beam object changes its sign from negative to positive or vice versa. Examples ======== There is is 10 meter long overhanging beam. There are two simple supports below the beam. One at the start and another one at a distance of 6 meters from the start. Point loads of magnitude 10KN and 20KN are applied at 2 meters and 4 meters from start respectively. A Uniformly distribute load of magnitude of magnitude 3KN/m is also applied on top starting from 6 meters away from starting point till end. Using the sign convention of upward forces and clockwise moment being positive. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> b = Beam(10, E, I) >>> b.apply_load(-4, 0, -1) >>> b.apply_load(-46, 6, -1) >>> b.apply_load(10, 2, -1) >>> b.apply_load(20, 4, -1) >>> b.apply_load(3, 6, 0) >>> b.point_cflexure() [10/3] """ from sympy import solve, Piecewise # To restrict the range within length of the Beam moment_curve = Piecewise((float("nan"), self.variable<=0), (self.bending_moment(), self.variable<self.length), (float("nan"), True)) points = solve(moment_curve.rewrite(Piecewise), self.variable, domain=S.Reals) return points def slope(self): """ Returns a Singularity Function expression which represents the slope the elastic curve of the Beam object. Examples ======== There is a beam of length 30 meters. A moment of magnitude 120 Nm is applied in the clockwise direction at the end of the beam. A pointload of magnitude 8 N is applied from the top of the beam at the starting point. There are two simple supports below the beam. One at the end and another one at a distance of 10 meters from the start. The deflection is restricted at both the supports. Using the sign convention of upward forces and clockwise moment being positive. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> R1, R2 = symbols('R1, R2') >>> b = Beam(30, E, I) >>> b.apply_load(-8, 0, -1) >>> b.apply_load(R1, 10, -1) >>> b.apply_load(R2, 30, -1) >>> b.apply_load(120, 30, -2) >>> b.bc_deflection = [(10, 0), (30, 0)] >>> b.solve_for_reaction_loads(R1, R2) >>> b.slope() (-4*SingularityFunction(x, 0, 2) + 3*SingularityFunction(x, 10, 2) + 120*SingularityFunction(x, 30, 1) + SingularityFunction(x, 30, 2) + 4000/3)/(E*I) """ x = self.variable E = self.elastic_modulus I = self.second_moment if self._composite_type == "hinge": return self._hinge_beam_slope if not self._boundary_conditions['slope']: return diff(self.deflection(), x) if isinstance(I, Piecewise) and self._composite_type == "fixed": args = I.args slope = 0 prev_slope = 0 prev_end = 0 for i in range(len(args)): if i != 0: prev_end = args[i-1][1].args[1] slope_value = -S.One/E*integrate(self.bending_moment()/args[i][0], (x, prev_end, x)) if i != len(args) - 1: slope += (prev_slope + slope_value)*SingularityFunction(x, prev_end, 0) - \ (prev_slope + slope_value)*SingularityFunction(x, args[i][1].args[1], 0) else: slope += (prev_slope + slope_value)*SingularityFunction(x, prev_end, 0) prev_slope = slope_value.subs(x, args[i][1].args[1]) return slope C3 = Symbol('C3') slope_curve = -integrate(S.One/(E*I)*self.bending_moment(), x) + C3 bc_eqs = [] for position, value in self._boundary_conditions['slope']: eqs = slope_curve.subs(x, position) - value bc_eqs.append(eqs) constants = list(linsolve(bc_eqs, C3)) slope_curve = slope_curve.subs({C3: constants[0][0]}) return slope_curve def deflection(self): """ Returns a Singularity Function expression which represents the elastic curve or deflection of the Beam object. Examples ======== There is a beam of length 30 meters. A moment of magnitude 120 Nm is applied in the clockwise direction at the end of the beam. A pointload of magnitude 8 N is applied from the top of the beam at the starting point. There are two simple supports below the beam. One at the end and another one at a distance of 10 meters from the start. The deflection is restricted at both the supports. Using the sign convention of upward forces and clockwise moment being positive. >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> E, I = symbols('E, I') >>> R1, R2 = symbols('R1, R2') >>> b = Beam(30, E, I) >>> b.apply_load(-8, 0, -1) >>> b.apply_load(R1, 10, -1) >>> b.apply_load(R2, 30, -1) >>> b.apply_load(120, 30, -2) >>> b.bc_deflection = [(10, 0), (30, 0)] >>> b.solve_for_reaction_loads(R1, R2) >>> b.deflection() (4000*x/3 - 4*SingularityFunction(x, 0, 3)/3 + SingularityFunction(x, 10, 3) + 60*SingularityFunction(x, 30, 2) + SingularityFunction(x, 30, 3)/3 - 12000)/(E*I) """ x = self.variable E = self.elastic_modulus I = self.second_moment if self._composite_type == "hinge": return self._hinge_beam_deflection if not self._boundary_conditions['deflection'] and not self._boundary_conditions['slope']: if isinstance(I, Piecewise) and self._composite_type == "fixed": args = I.args prev_slope = 0 prev_def = 0 prev_end = 0 deflection = 0 for i in range(len(args)): if i != 0: prev_end = args[i-1][1].args[1] slope_value = -S.One/E*integrate(self.bending_moment()/args[i][0], (x, prev_end, x)) recent_segment_slope = prev_slope + slope_value deflection_value = integrate(recent_segment_slope, (x, prev_end, x)) if i != len(args) - 1: deflection += (prev_def + deflection_value)*SingularityFunction(x, prev_end, 0) \ - (prev_def + deflection_value)*SingularityFunction(x, args[i][1].args[1], 0) else: deflection += (prev_def + deflection_value)*SingularityFunction(x, prev_end, 0) prev_slope = slope_value.subs(x, args[i][1].args[1]) prev_def = deflection_value.subs(x, args[i][1].args[1]) return deflection base_char = self._base_char constants = symbols(base_char + '3:5') return S.One/(E*I)*integrate(-integrate(self.bending_moment(), x), x) + constants[0]*x + constants[1] elif not self._boundary_conditions['deflection']: base_char = self._base_char constant = symbols(base_char + '4') return integrate(self.slope(), x) + constant elif not self._boundary_conditions['slope'] and self._boundary_conditions['deflection']: if isinstance(I, Piecewise) and self._composite_type == "fixed": args = I.args prev_slope = 0 prev_def = 0 prev_end = 0 deflection = 0 for i in range(len(args)): if i != 0: prev_end = args[i-1][1].args[1] slope_value = -S.One/E*integrate(self.bending_moment()/args[i][0], (x, prev_end, x)) recent_segment_slope = prev_slope + slope_value deflection_value = integrate(recent_segment_slope, (x, prev_end, x)) if i != len(args) - 1: deflection += (prev_def + deflection_value)*SingularityFunction(x, prev_end, 0) \ - (prev_def + deflection_value)*SingularityFunction(x, args[i][1].args[1], 0) else: deflection += (prev_def + deflection_value)*SingularityFunction(x, prev_end, 0) prev_slope = slope_value.subs(x, args[i][1].args[1]) prev_def = deflection_value.subs(x, args[i][1].args[1]) return deflection base_char = self._base_char C3, C4 = symbols(base_char + '3:5') # Integration constants slope_curve = -integrate(self.bending_moment(), x) + C3 deflection_curve = integrate(slope_curve, x) + C4 bc_eqs = [] for position, value in self._boundary_conditions['deflection']: eqs = deflection_curve.subs(x, position) - value bc_eqs.append(eqs) constants = list(linsolve(bc_eqs, (C3, C4))) deflection_curve = deflection_curve.subs({C3: constants[0][0], C4: constants[0][1]}) return S.One/(E*I)*deflection_curve if isinstance(I, Piecewise) and self._composite_type == "fixed": args = I.args prev_slope = 0 prev_def = 0 prev_end = 0 deflection = 0 for i in range(len(args)): if i != 0: prev_end = args[i-1][1].args[1] slope_value = S.One/E*integrate(self.bending_moment()/args[i][0], (x, prev_end, x)) recent_segment_slope = prev_slope + slope_value deflection_value = integrate(recent_segment_slope, (x, prev_end, x)) if i != len(args) - 1: deflection += (prev_def + deflection_value)*SingularityFunction(x, prev_end, 0) \ - (prev_def + deflection_value)*SingularityFunction(x, args[i][1].args[1], 0) else: deflection += (prev_def + deflection_value)*SingularityFunction(x, prev_end, 0) prev_slope = slope_value.subs(x, args[i][1].args[1]) prev_def = deflection_value.subs(x, args[i][1].args[1]) return deflection C4 = Symbol('C4') deflection_curve = integrate(self.slope(), x) + C4 bc_eqs = [] for position, value in self._boundary_conditions['deflection']: eqs = deflection_curve.subs(x, position) - value bc_eqs.append(eqs) constants = list(linsolve(bc_eqs, C4)) deflection_curve = deflection_curve.subs({C4: constants[0][0]}) return deflection_curve def max_deflection(self): """ Returns point of max deflection and its corresponding deflection value in a Beam object. """ from sympy import solve, Piecewise # To restrict the range within length of the Beam slope_curve = Piecewise((float("nan"), self.variable<=0), (self.slope(), self.variable<self.length), (float("nan"), True)) points = solve(slope_curve.rewrite(Piecewise), self.variable, domain=S.Reals) deflection_curve = self.deflection() deflections = [deflection_curve.subs(self.variable, x) for x in points] deflections = list(map(abs, deflections)) if len(deflections) != 0: max_def = max(deflections) return (points[deflections.index(max_def)], max_def) else: return None def shear_stress(self): """ Returns an expression representing the Shear Stress curve of the Beam object. """ return self.shear_force()/self._area def plot_shear_force(self, subs=None): """ Returns a plot for Shear force present in the Beam object. Parameters ========== subs : dictionary Python dictionary containing Symbols as key and their corresponding values. Examples ======== There is a beam of length 8 meters. A constant distributed load of 10 KN/m is applied from half of the beam till the end. There are two simple supports below the beam, one at the starting point and another at the ending point of the beam. A pointload of magnitude 5 KN is also applied from top of the beam, at a distance of 4 meters from the starting point. Take E = 200 GPa and I = 400*(10**-6) meter**4. Using the sign convention of downwards forces being positive. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> R1, R2 = symbols('R1, R2') >>> b = Beam(8, 200*(10**9), 400*(10**-6)) >>> b.apply_load(5000, 2, -1) >>> b.apply_load(R1, 0, -1) >>> b.apply_load(R2, 8, -1) >>> b.apply_load(10000, 4, 0, end=8) >>> b.bc_deflection = [(0, 0), (8, 0)] >>> b.solve_for_reaction_loads(R1, R2) >>> b.plot_shear_force() Plot object containing: [0]: cartesian line: 13750*SingularityFunction(x, 0, 0) - 5000*SingularityFunction(x, 2, 0) - 10000*SingularityFunction(x, 4, 1) + 31250*SingularityFunction(x, 8, 0) + 10000*SingularityFunction(x, 8, 1) for x over (0.0, 8.0) """ shear_force = self.shear_force() if subs is None: subs = {} for sym in shear_force.atoms(Symbol): if sym == self.variable: continue if sym not in subs: raise ValueError('Value of %s was not passed.' %sym) if self.length in subs: length = subs[self.length] else: length = self.length return plot(shear_force.subs(subs), (self.variable, 0, length), title='Shear Force', xlabel=r'$\mathrm{x}$', ylabel=r'$\mathrm{V}$', line_color='g') def plot_bending_moment(self, subs=None): """ Returns a plot for Bending moment present in the Beam object. Parameters ========== subs : dictionary Python dictionary containing Symbols as key and their corresponding values. Examples ======== There is a beam of length 8 meters. A constant distributed load of 10 KN/m is applied from half of the beam till the end. There are two simple supports below the beam, one at the starting point and another at the ending point of the beam. A pointload of magnitude 5 KN is also applied from top of the beam, at a distance of 4 meters from the starting point. Take E = 200 GPa and I = 400*(10**-6) meter**4. Using the sign convention of downwards forces being positive. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> R1, R2 = symbols('R1, R2') >>> b = Beam(8, 200*(10**9), 400*(10**-6)) >>> b.apply_load(5000, 2, -1) >>> b.apply_load(R1, 0, -1) >>> b.apply_load(R2, 8, -1) >>> b.apply_load(10000, 4, 0, end=8) >>> b.bc_deflection = [(0, 0), (8, 0)] >>> b.solve_for_reaction_loads(R1, R2) >>> b.plot_bending_moment() Plot object containing: [0]: cartesian line: 13750*SingularityFunction(x, 0, 1) - 5000*SingularityFunction(x, 2, 1) - 5000*SingularityFunction(x, 4, 2) + 31250*SingularityFunction(x, 8, 1) + 5000*SingularityFunction(x, 8, 2) for x over (0.0, 8.0) """ bending_moment = self.bending_moment() if subs is None: subs = {} for sym in bending_moment.atoms(Symbol): if sym == self.variable: continue if sym not in subs: raise ValueError('Value of %s was not passed.' %sym) if self.length in subs: length = subs[self.length] else: length = self.length return plot(bending_moment.subs(subs), (self.variable, 0, length), title='Bending Moment', xlabel=r'$\mathrm{x}$', ylabel=r'$\mathrm{M}$', line_color='b') def plot_slope(self, subs=None): """ Returns a plot for slope of deflection curve of the Beam object. Parameters ========== subs : dictionary Python dictionary containing Symbols as key and their corresponding values. Examples ======== There is a beam of length 8 meters. A constant distributed load of 10 KN/m is applied from half of the beam till the end. There are two simple supports below the beam, one at the starting point and another at the ending point of the beam. A pointload of magnitude 5 KN is also applied from top of the beam, at a distance of 4 meters from the starting point. Take E = 200 GPa and I = 400*(10**-6) meter**4. Using the sign convention of downwards forces being positive. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> R1, R2 = symbols('R1, R2') >>> b = Beam(8, 200*(10**9), 400*(10**-6)) >>> b.apply_load(5000, 2, -1) >>> b.apply_load(R1, 0, -1) >>> b.apply_load(R2, 8, -1) >>> b.apply_load(10000, 4, 0, end=8) >>> b.bc_deflection = [(0, 0), (8, 0)] >>> b.solve_for_reaction_loads(R1, R2) >>> b.plot_slope() Plot object containing: [0]: cartesian line: -8.59375e-5*SingularityFunction(x, 0, 2) + 3.125e-5*SingularityFunction(x, 2, 2) + 2.08333333333333e-5*SingularityFunction(x, 4, 3) - 0.0001953125*SingularityFunction(x, 8, 2) - 2.08333333333333e-5*SingularityFunction(x, 8, 3) + 0.00138541666666667 for x over (0.0, 8.0) """ slope = self.slope() if subs is None: subs = {} for sym in slope.atoms(Symbol): if sym == self.variable: continue if sym not in subs: raise ValueError('Value of %s was not passed.' %sym) if self.length in subs: length = subs[self.length] else: length = self.length return plot(slope.subs(subs), (self.variable, 0, length), title='Slope', xlabel=r'$\mathrm{x}$', ylabel=r'$\theta$', line_color='m') def plot_deflection(self, subs=None): """ Returns a plot for deflection curve of the Beam object. Parameters ========== subs : dictionary Python dictionary containing Symbols as key and their corresponding values. Examples ======== There is a beam of length 8 meters. A constant distributed load of 10 KN/m is applied from half of the beam till the end. There are two simple supports below the beam, one at the starting point and another at the ending point of the beam. A pointload of magnitude 5 KN is also applied from top of the beam, at a distance of 4 meters from the starting point. Take E = 200 GPa and I = 400*(10**-6) meter**4. Using the sign convention of downwards forces being positive. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> R1, R2 = symbols('R1, R2') >>> b = Beam(8, 200*(10**9), 400*(10**-6)) >>> b.apply_load(5000, 2, -1) >>> b.apply_load(R1, 0, -1) >>> b.apply_load(R2, 8, -1) >>> b.apply_load(10000, 4, 0, end=8) >>> b.bc_deflection = [(0, 0), (8, 0)] >>> b.solve_for_reaction_loads(R1, R2) >>> b.plot_deflection() Plot object containing: [0]: cartesian line: 0.00138541666666667*x - 2.86458333333333e-5*SingularityFunction(x, 0, 3) + 1.04166666666667e-5*SingularityFunction(x, 2, 3) + 5.20833333333333e-6*SingularityFunction(x, 4, 4) - 6.51041666666667e-5*SingularityFunction(x, 8, 3) - 5.20833333333333e-6*SingularityFunction(x, 8, 4) for x over (0.0, 8.0) """ deflection = self.deflection() if subs is None: subs = {} for sym in deflection.atoms(Symbol): if sym == self.variable: continue if sym not in subs: raise ValueError('Value of %s was not passed.' %sym) if self.length in subs: length = subs[self.length] else: length = self.length return plot(deflection.subs(subs), (self.variable, 0, length), title='Deflection', xlabel=r'$\mathrm{x}$', ylabel=r'$\delta$', line_color='r') def plot_loading_results(self, subs=None): """ Returns a subplot of Shear Force, Bending Moment, Slope and Deflection of the Beam object. Parameters ========== subs : dictionary Python dictionary containing Symbols as key and their corresponding values. Examples ======== There is a beam of length 8 meters. A constant distributed load of 10 KN/m is applied from half of the beam till the end. There are two simple supports below the beam, one at the starting point and another at the ending point of the beam. A pointload of magnitude 5 KN is also applied from top of the beam, at a distance of 4 meters from the starting point. Take E = 200 GPa and I = 400*(10**-6) meter**4. Using the sign convention of downwards forces being positive. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> R1, R2 = symbols('R1, R2') >>> b = Beam(8, 200*(10**9), 400*(10**-6)) >>> b.apply_load(5000, 2, -1) >>> b.apply_load(R1, 0, -1) >>> b.apply_load(R2, 8, -1) >>> b.apply_load(10000, 4, 0, end=8) >>> b.bc_deflection = [(0, 0), (8, 0)] >>> b.solve_for_reaction_loads(R1, R2) >>> axes = b.plot_loading_results() """ length = self.length variable = self.variable if subs is None: subs = {} for sym in self.deflection().atoms(Symbol): if sym == self.variable: continue if sym not in subs: raise ValueError('Value of %s was not passed.' %sym) if self.length in subs: length = subs[self.length] else: length = self.length ax1 = plot(self.shear_force().subs(subs), (variable, 0, length), title="Shear Force", xlabel=r'$\mathrm{x}$', ylabel=r'$\mathrm{V}$', line_color='g', show=False) ax2 = plot(self.bending_moment().subs(subs), (variable, 0, length), title="Bending Moment", xlabel=r'$\mathrm{x}$', ylabel=r'$\mathrm{M}$', line_color='b', show=False) ax3 = plot(self.slope().subs(subs), (variable, 0, length), title="Slope", xlabel=r'$\mathrm{x}$', ylabel=r'$\theta$', line_color='m', show=False) ax4 = plot(self.deflection().subs(subs), (variable, 0, length), title="Deflection", xlabel=r'$\mathrm{x}$', ylabel=r'$\delta$', line_color='r', show=False) return PlotGrid(4, 1, ax1, ax2, ax3, ax4) @doctest_depends_on(modules=('numpy',)) def draw(self, pictorial=True): """ Returns a plot object representing the beam diagram of the beam. .. note:: The user must be careful while entering load values. The draw function assumes a sign convention which is used for plotting loads. Given a right handed coordinate system with XYZ coordinates, the beam's length is assumed to be along the positive X axis. The draw function recognizes positve loads(with n>-2) as loads acting along negative Y direction and positve moments acting along positive Z direction. Parameters ========== pictorial: Boolean (default=True) Setting ``pictorial=True`` would simply create a pictorial (scaled) view of the beam diagram not with the exact dimensions. Although setting ``pictorial=False`` would create a beam diagram with the exact dimensions on the plot Examples ======== .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.physics.continuum_mechanics.beam import Beam >>> from sympy import symbols >>> R1, R2 = symbols('R1, R2') >>> E, I = symbols('E, I') >>> b = Beam(50, 20, 30) >>> b.apply_load(10, 2, -1) >>> b.apply_load(R1, 10, -1) >>> b.apply_load(R2, 30, -1) >>> b.apply_load(90, 5, 0, 23) >>> b.apply_load(10, 30, 1, 50) >>> b.apply_support(50, "pin") >>> b.apply_support(0, "fixed") >>> b.apply_support(20, "roller") >>> p = b.draw() >>> p Plot object containing: [0]: cartesian line: 25*SingularityFunction(x, 5, 0) - 25*SingularityFunction(x, 23, 0) + SingularityFunction(x, 30, 1) - 20*SingularityFunction(x, 50, 0) - SingularityFunction(x, 50, 1) + 5 for x over (0.0, 50.0) [1]: cartesian line: 5 for x over (0.0, 50.0) >>> p.show() """ if not numpy: raise ImportError("To use this function numpy module is required") x = self.variable # checking whether length is an expression in terms of any Symbol. from sympy import Expr if isinstance(self.length, Expr): l = list(self.length.atoms(Symbol)) # assigning every Symbol a default value of 10 l = {i:10 for i in l} length = self.length.subs(l) else: l = {} length = self.length height = length/10 rectangles = [] rectangles.append({'xy':(0, 0), 'width':length, 'height': height, 'facecolor':"brown"}) annotations, markers, load_eq,load_eq1, fill = self._draw_load(pictorial, length, l) support_markers, support_rectangles = self._draw_supports(length, l) rectangles += support_rectangles markers += support_markers sing_plot = plot(height + load_eq, height + load_eq1, (x, 0, length), xlim=(-height, length + height), ylim=(-length, 1.25*length), annotations=annotations, markers=markers, rectangles=rectangles, line_color='brown', fill=fill, axis=False, show=False) return sing_plot def _draw_load(self, pictorial, length, l): loads = list(set(self.applied_loads) - set(self._support_as_loads)) height = length/10 x = self.variable annotations = [] markers = [] load_args = [] scaled_load = 0 load_args1 = [] scaled_load1 = 0 load_eq = 0 # For positive valued higher order loads load_eq1 = 0 # For negative valued higher order loads fill = None plus = 0 # For positive valued higher order loads minus = 0 # For negative valued higher order loads for load in loads: # check if the position of load is in terms of the beam length. if l: pos = load[1].subs(l) else: pos = load[1] # point loads if load[2] == -1: if isinstance(load[0], Symbol) or load[0].is_negative: annotations.append({'s':'', 'xy':(pos, 0), 'xytext':(pos, height - 4*height), 'arrowprops':dict(width= 1.5, headlength=5, headwidth=5, facecolor='black')}) else: annotations.append({'s':'', 'xy':(pos, height), 'xytext':(pos, height*4), 'arrowprops':dict(width= 1.5, headlength=4, headwidth=4, facecolor='black')}) # moment loads elif load[2] == -2: if load[0].is_negative: markers.append({'args':[[pos], [height/2]], 'marker': r'$\circlearrowright$', 'markersize':15}) else: markers.append({'args':[[pos], [height/2]], 'marker': r'$\circlearrowleft$', 'markersize':15}) # higher order loads elif load[2] >= 0: # `fill` will be assigned only when higher order loads are present value, start, order, end = load # Positive loads have their seperate equations if(value>0): plus = 1 # if pictorial is True we remake the load equation again with # some constant magnitude values. if pictorial: value = 10**(1-order) if order > 0 else length/2 scaled_load += value*SingularityFunction(x, start, order) if end: f2 = 10**(1-order)*x**order if order > 0 else length/2*x**order for i in range(0, order + 1): scaled_load -= (f2.diff(x, i).subs(x, end - start)* SingularityFunction(x, end, i)/factorial(i)) if pictorial: if isinstance(scaled_load, Add): load_args = scaled_load.args else: # when the load equation consists of only a single term load_args = (scaled_load,) load_eq = [i.subs(l) for i in load_args] else: if isinstance(self.load, Add): load_args = self.load.args else: load_args = (self.load,) load_eq = [i.subs(l) for i in load_args if list(i.atoms(SingularityFunction))[0].args[2] >= 0] load_eq = Add(*load_eq) # filling higher order loads with colour expr = height + load_eq.rewrite(Piecewise) y1 = lambdify(x, expr, 'numpy') # For loads with negative value else: minus = 1 # if pictorial is True we remake the load equation again with # some constant magnitude values. if pictorial: value = 10**(1-order) if order > 0 else length/2 scaled_load1 += value*SingularityFunction(x, start, order) if end: f2 = 10**(1-order)*x**order if order > 0 else length/2*x**order for i in range(0, order + 1): scaled_load1 -= (f2.diff(x, i).subs(x, end - start)* SingularityFunction(x, end, i)/factorial(i)) if pictorial: if isinstance(scaled_load1, Add): load_args1 = scaled_load1.args else: # when the load equation consists of only a single term load_args1 = (scaled_load1,) load_eq1 = [i.subs(l) for i in load_args1] else: if isinstance(self.load, Add): load_args1 = self.load.args1 else: load_args1 = (self.load,) load_eq1 = [i.subs(l) for i in load_args if list(i.atoms(SingularityFunction))[0].args[2] >= 0] load_eq1 = -Add(*load_eq1)-height # filling higher order loads with colour expr = height + load_eq1.rewrite(Piecewise) y1_ = lambdify(x, expr, 'numpy') y = numpy.arange(0, float(length), 0.001) y2 = float(height) if(plus == 1 and minus == 1): fill = {'x': y, 'y1': y1(y), 'y2': y1_(y), 'color':'darkkhaki'} elif(plus == 1): fill = {'x': y, 'y1': y1(y), 'y2': y2, 'color':'darkkhaki'} else: fill = {'x': y, 'y1': y1_(y), 'y2': y2 , 'color':'darkkhaki'} return annotations, markers, load_eq, load_eq1, fill def _draw_supports(self, length, l): height = float(length/10) support_markers = [] support_rectangles = [] for support in self._applied_supports: if l: pos = support[0].subs(l) else: pos = support[0] if support[1] == "pin": support_markers.append({'args':[pos, [0]], 'marker':6, 'markersize':13, 'color':"black"}) elif support[1] == "roller": support_markers.append({'args':[pos, [-height/2.5]], 'marker':'o', 'markersize':11, 'color':"black"}) elif support[1] == "fixed": if pos == 0: support_rectangles.append({'xy':(0, -3*height), 'width':-length/20, 'height':6*height + height, 'fill':False, 'hatch':'/////'}) else: support_rectangles.append({'xy':(length, -3*height), 'width':length/20, 'height': 6*height + height, 'fill':False, 'hatch':'/////'}) return support_markers, support_rectangles class Beam3D(Beam): """ This class handles loads applied in any direction of a 3D space along with unequal values of Second moment along different axes. .. note:: While solving a beam bending problem, a user should choose its own sign convention and should stick to it. The results will automatically follow the chosen sign convention. This class assumes that any kind of distributed load/moment is applied through out the span of a beam. Examples ======== There is a beam of l meters long. A constant distributed load of magnitude q is applied along y-axis from start till the end of beam. A constant distributed moment of magnitude m is also applied along z-axis from start till the end of beam. Beam is fixed at both of its end. So, deflection of the beam at the both ends is restricted. >>> from sympy.physics.continuum_mechanics.beam import Beam3D >>> from sympy import symbols, simplify, collect, factor >>> l, E, G, I, A = symbols('l, E, G, I, A') >>> b = Beam3D(l, E, G, I, A) >>> x, q, m = symbols('x, q, m') >>> b.apply_load(q, 0, 0, dir="y") >>> b.apply_moment_load(m, 0, -1, dir="z") >>> b.shear_force() [0, -q*x, 0] >>> b.bending_moment() [0, 0, -m*x + q*x**2/2] >>> b.bc_slope = [(0, [0, 0, 0]), (l, [0, 0, 0])] >>> b.bc_deflection = [(0, [0, 0, 0]), (l, [0, 0, 0])] >>> b.solve_slope_deflection() >>> factor(b.slope()) [0, 0, x*(-l + x)*(-A*G*l**3*q + 2*A*G*l**2*q*x - 12*E*I*l*q - 72*E*I*m + 24*E*I*q*x)/(12*E*I*(A*G*l**2 + 12*E*I))] >>> dx, dy, dz = b.deflection() >>> dy = collect(simplify(dy), x) >>> dx == dz == 0 True >>> dy == (x*(12*A*E*G*I*l**3*q - 24*A*E*G*I*l**2*m + 144*E**2*I**2*l*q + ... x**3*(A**2*G**2*l**2*q + 12*A*E*G*I*q) + ... x**2*(-2*A**2*G**2*l**3*q - 24*A*E*G*I*l*q - 48*A*E*G*I*m) + ... x*(A**2*G**2*l**4*q + 72*A*E*G*I*l*m - 144*E**2*I**2*q) ... )/(24*A*E*G*I*(A*G*l**2 + 12*E*I))) True References ========== .. [1] http://homes.civil.aau.dk/jc/FemteSemester/Beams3D.pdf """ def __init__(self, length, elastic_modulus, shear_modulus , second_moment, area, variable=Symbol('x')): """Initializes the class. Parameters ========== length : Sympifyable A Symbol or value representing the Beam's length. elastic_modulus : Sympifyable A SymPy expression representing the Beam's Modulus of Elasticity. It is a measure of the stiffness of the Beam material. shear_modulus : Sympifyable A SymPy expression representing the Beam's Modulus of rigidity. It is a measure of rigidity of the Beam material. second_moment : Sympifyable or list A list of two elements having SymPy expression representing the Beam's Second moment of area. First value represent Second moment across y-axis and second across z-axis. Single SymPy expression can be passed if both values are same area : Sympifyable A SymPy expression representing the Beam's cross-sectional area in a plane prependicular to length of the Beam. variable : Symbol, optional A Symbol object that will be used as the variable along the beam while representing the load, shear, moment, slope and deflection curve. By default, it is set to ``Symbol('x')``. """ super().__init__(length, elastic_modulus, second_moment, variable) self.shear_modulus = shear_modulus self._area = area self._load_vector = [0, 0, 0] self._moment_load_vector = [0, 0, 0] self._load_Singularity = [0, 0, 0] self._slope = [0, 0, 0] self._deflection = [0, 0, 0] @property def shear_modulus(self): """Young's Modulus of the Beam. """ return self._shear_modulus @shear_modulus.setter def shear_modulus(self, e): self._shear_modulus = sympify(e) @property def second_moment(self): """Second moment of area of the Beam. """ return self._second_moment @second_moment.setter def second_moment(self, i): if isinstance(i, list): i = [sympify(x) for x in i] self._second_moment = i else: self._second_moment = sympify(i) @property def area(self): """Cross-sectional area of the Beam. """ return self._area @area.setter def area(self, a): self._area = sympify(a) @property def load_vector(self): """ Returns a three element list representing the load vector. """ return self._load_vector @property def moment_load_vector(self): """ Returns a three element list representing moment loads on Beam. """ return self._moment_load_vector @property def boundary_conditions(self): """ Returns a dictionary of boundary conditions applied on the beam. The dictionary has two keywords namely slope and deflection. The value of each keyword is a list of tuple, where each tuple contains location and value of a boundary condition in the format (location, value). Further each value is a list corresponding to slope or deflection(s) values along three axes at that location. Examples ======== There is a beam of length 4 meters. The slope at 0 should be 4 along the x-axis and 0 along others. At the other end of beam, deflection along all the three axes should be zero. >>> from sympy.physics.continuum_mechanics.beam import Beam3D >>> from sympy import symbols >>> l, E, G, I, A, x = symbols('l, E, G, I, A, x') >>> b = Beam3D(30, E, G, I, A, x) >>> b.bc_slope = [(0, (4, 0, 0))] >>> b.bc_deflection = [(4, [0, 0, 0])] >>> b.boundary_conditions {'deflection': [(4, [0, 0, 0])], 'slope': [(0, (4, 0, 0))]} Here the deflection of the beam should be ``0`` along all the three axes at ``4``. Similarly, the slope of the beam should be ``4`` along x-axis and ``0`` along y and z axis at ``0``. """ return self._boundary_conditions def polar_moment(self): """ Returns the polar moment of area of the beam about the X axis with respect to the centroid. Examples ======== >>> from sympy.physics.continuum_mechanics.beam import Beam3D >>> from sympy import symbols >>> l, E, G, I, A = symbols('l, E, G, I, A') >>> b = Beam3D(l, E, G, I, A) >>> b.polar_moment() 2*I >>> I1 = [9, 15] >>> b = Beam3D(l, E, G, I1, A) >>> b.polar_moment() 24 """ if not iterable(self.second_moment): return 2*self.second_moment return sum(self.second_moment) def apply_load(self, value, start, order, dir="y"): """ This method adds up the force load to a particular beam object. Parameters ========== value : Sympifyable The magnitude of an applied load. dir : String Axis along which load is applied. order : Integer The order of the applied load. - For point loads, order=-1 - For constant distributed load, order=0 - For ramp loads, order=1 - For parabolic ramp loads, order=2 - ... so on. """ x = self.variable value = sympify(value) start = sympify(start) order = sympify(order) if dir == "x": if not order == -1: self._load_vector[0] += value self._load_Singularity[0] += value*SingularityFunction(x, start, order) elif dir == "y": if not order == -1: self._load_vector[1] += value self._load_Singularity[1] += value*SingularityFunction(x, start, order) else: if not order == -1: self._load_vector[2] += value self._load_Singularity[2] += value*SingularityFunction(x, start, order) def apply_moment_load(self, value, start, order, dir="y"): """ This method adds up the moment loads to a particular beam object. Parameters ========== value : Sympifyable The magnitude of an applied moment. dir : String Axis along which moment is applied. order : Integer The order of the applied load. - For point moments, order=-2 - For constant distributed moment, order=-1 - For ramp moments, order=0 - For parabolic ramp moments, order=1 - ... so on. """ x = self.variable value = sympify(value) start = sympify(start) order = sympify(order) if dir == "x": if not order == -2: self._moment_load_vector[0] += value self._load_Singularity[0] += value*SingularityFunction(x, start, order) elif dir == "y": if not order == -2: self._moment_load_vector[1] += value self._load_Singularity[0] += value*SingularityFunction(x, start, order) else: if not order == -2: self._moment_load_vector[2] += value self._load_Singularity[0] += value*SingularityFunction(x, start, order) def apply_support(self, loc, type="fixed"): if type == "pin" or type == "roller": reaction_load = Symbol('R_'+str(loc)) self._reaction_loads[reaction_load] = reaction_load self.bc_deflection.append((loc, [0, 0, 0])) else: reaction_load = Symbol('R_'+str(loc)) reaction_moment = Symbol('M_'+str(loc)) self._reaction_loads[reaction_load] = [reaction_load, reaction_moment] self.bc_deflection.append((loc, [0, 0, 0])) self.bc_slope.append((loc, [0, 0, 0])) def solve_for_reaction_loads(self, *reaction): """ Solves for the reaction forces. Examples ======== There is a beam of length 30 meters. It it supported by rollers at of its end. A constant distributed load of magnitude 8 N is applied from start till its end along y-axis. Another linear load having slope equal to 9 is applied along z-axis. >>> from sympy.physics.continuum_mechanics.beam import Beam3D >>> from sympy import symbols >>> l, E, G, I, A, x = symbols('l, E, G, I, A, x') >>> b = Beam3D(30, E, G, I, A, x) >>> b.apply_load(8, start=0, order=0, dir="y") >>> b.apply_load(9*x, start=0, order=0, dir="z") >>> b.bc_deflection = [(0, [0, 0, 0]), (30, [0, 0, 0])] >>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4') >>> b.apply_load(R1, start=0, order=-1, dir="y") >>> b.apply_load(R2, start=30, order=-1, dir="y") >>> b.apply_load(R3, start=0, order=-1, dir="z") >>> b.apply_load(R4, start=30, order=-1, dir="z") >>> b.solve_for_reaction_loads(R1, R2, R3, R4) >>> b.reaction_loads {R1: -120, R2: -120, R3: -1350, R4: -2700} """ x = self.variable l = self.length q = self._load_Singularity shear_curves = [integrate(load, x) for load in q] moment_curves = [integrate(shear, x) for shear in shear_curves] for i in range(3): react = [r for r in reaction if (shear_curves[i].has(r) or moment_curves[i].has(r))] if len(react) == 0: continue shear_curve = limit(shear_curves[i], x, l) moment_curve = limit(moment_curves[i], x, l) sol = list((linsolve([shear_curve, moment_curve], react).args)[0]) sol_dict = dict(zip(react, sol)) reaction_loads = self._reaction_loads # Check if any of the evaluated rection exists in another direction # and if it exists then it should have same value. for key in sol_dict: if key in reaction_loads and sol_dict[key] != reaction_loads[key]: raise ValueError("Ambiguous solution for %s in different directions." % key) self._reaction_loads.update(sol_dict) def shear_force(self): """ Returns a list of three expressions which represents the shear force curve of the Beam object along all three axes. """ x = self.variable q = self._load_vector return [integrate(-q[0], x), integrate(-q[1], x), integrate(-q[2], x)] def axial_force(self): """ Returns expression of Axial shear force present inside the Beam object. """ return self.shear_force()[0] def shear_stress(self): """ Returns a list of three expressions which represents the shear stress curve of the Beam object along all three axes. """ return [self.shear_force()[0]/self._area, self.shear_force()[1]/self._area, self.shear_force()[2]/self._area] def axial_stress(self): """ Returns expression of Axial stress present inside the Beam object. """ return self.axial_force()/self._area def bending_moment(self): """ Returns a list of three expressions which represents the bending moment curve of the Beam object along all three axes. """ x = self.variable m = self._moment_load_vector shear = self.shear_force() return [integrate(-m[0], x), integrate(-m[1] + shear[2], x), integrate(-m[2] - shear[1], x) ] def torsional_moment(self): """ Returns expression of Torsional moment present inside the Beam object. """ return self.bending_moment()[0] def solve_slope_deflection(self): from sympy import dsolve, Function, Derivative, Eq x = self.variable l = self.length E = self.elastic_modulus G = self.shear_modulus I = self.second_moment if isinstance(I, list): I_y, I_z = I[0], I[1] else: I_y = I_z = I A = self._area load = self._load_vector moment = self._moment_load_vector defl = Function('defl') theta = Function('theta') # Finding deflection along x-axis(and corresponding slope value by differentiating it) # Equation used: Derivative(E*A*Derivative(def_x(x), x), x) + load_x = 0 eq = Derivative(E*A*Derivative(defl(x), x), x) + load[0] def_x = dsolve(Eq(eq, 0), defl(x)).args[1] # Solving constants originated from dsolve C1 = Symbol('C1') C2 = Symbol('C2') constants = list((linsolve([def_x.subs(x, 0), def_x.subs(x, l)], C1, C2).args)[0]) def_x = def_x.subs({C1:constants[0], C2:constants[1]}) slope_x = def_x.diff(x) self._deflection[0] = def_x self._slope[0] = slope_x # Finding deflection along y-axis and slope across z-axis. System of equation involved: # 1: Derivative(E*I_z*Derivative(theta_z(x), x), x) + G*A*(Derivative(defl_y(x), x) - theta_z(x)) + moment_z = 0 # 2: Derivative(G*A*(Derivative(defl_y(x), x) - theta_z(x)), x) + load_y = 0 C_i = Symbol('C_i') # Substitute value of `G*A*(Derivative(defl_y(x), x) - theta_z(x))` from (2) in (1) eq1 = Derivative(E*I_z*Derivative(theta(x), x), x) + (integrate(-load[1], x) + C_i) + moment[2] slope_z = dsolve(Eq(eq1, 0)).args[1] # Solve for constants originated from using dsolve on eq1 constants = list((linsolve([slope_z.subs(x, 0), slope_z.subs(x, l)], C1, C2).args)[0]) slope_z = slope_z.subs({C1:constants[0], C2:constants[1]}) # Put value of slope obtained back in (2) to solve for `C_i` and find deflection across y-axis eq2 = G*A*(Derivative(defl(x), x)) + load[1]*x - C_i - G*A*slope_z def_y = dsolve(Eq(eq2, 0), defl(x)).args[1] # Solve for constants originated from using dsolve on eq2 constants = list((linsolve([def_y.subs(x, 0), def_y.subs(x, l)], C1, C_i).args)[0]) self._deflection[1] = def_y.subs({C1:constants[0], C_i:constants[1]}) self._slope[2] = slope_z.subs(C_i, constants[1]) # Finding deflection along z-axis and slope across y-axis. System of equation involved: # 1: Derivative(E*I_y*Derivative(theta_y(x), x), x) - G*A*(Derivative(defl_z(x), x) + theta_y(x)) + moment_y = 0 # 2: Derivative(G*A*(Derivative(defl_z(x), x) + theta_y(x)), x) + load_z = 0 # Substitute value of `G*A*(Derivative(defl_y(x), x) + theta_z(x))` from (2) in (1) eq1 = Derivative(E*I_y*Derivative(theta(x), x), x) + (integrate(load[2], x) - C_i) + moment[1] slope_y = dsolve(Eq(eq1, 0)).args[1] # Solve for constants originated from using dsolve on eq1 constants = list((linsolve([slope_y.subs(x, 0), slope_y.subs(x, l)], C1, C2).args)[0]) slope_y = slope_y.subs({C1:constants[0], C2:constants[1]}) # Put value of slope obtained back in (2) to solve for `C_i` and find deflection across z-axis eq2 = G*A*(Derivative(defl(x), x)) + load[2]*x - C_i + G*A*slope_y def_z = dsolve(Eq(eq2,0)).args[1] # Solve for constants originated from using dsolve on eq2 constants = list((linsolve([def_z.subs(x, 0), def_z.subs(x, l)], C1, C_i).args)[0]) self._deflection[2] = def_z.subs({C1:constants[0], C_i:constants[1]}) self._slope[1] = slope_y.subs(C_i, constants[1]) def slope(self): """ Returns a three element list representing slope of deflection curve along all the three axes. """ return self._slope def deflection(self): """ Returns a three element list representing deflection curve along all the three axes. """ return self._deflection def _plot_shear_force(self, dir, subs=None): shear_force = self.shear_force() if dir == 'x': dir_num = 0 color = 'r' elif dir == 'y': dir_num = 1 color = 'g' elif dir == 'z': dir_num = 2 color = 'b' if subs is None: subs = {} for sym in shear_force[dir_num].atoms(Symbol): if sym == self.variable: continue if sym not in subs: raise ValueError('Value of %s was not passed.' %sym) if self.length in subs: length = subs[self.length] else: length = self.length return plot(shear_force[dir_num].subs(subs), (self.variable, 0, length), show = False, title='Shear Force along %c direction'%dir, xlabel=r'$\mathrm{%c}$'%dir, ylabel=r'$\mathrm{V[%c]}$'%dir, line_color=color) def plot_shear_force(self, dir="all", subs=None): """ Returns a plot for Shear force along all three directions present in the Beam object. Parameters ========== dir : string (default : "all") Direction along which shear force plot is required. If no direction is specified, all plots are displayed. subs : dictionary Python dictionary containing Symbols as key and their corresponding values. Examples ======== There is a beam of length 20 meters. It it supported by rollers at of its end. A linear load having slope equal to 12 is applied along y-axis. A constant distributed load of magnitude 15 N is applied from start till its end along z-axis. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.physics.continuum_mechanics.beam import Beam3D >>> from sympy import symbols >>> l, E, G, I, A, x = symbols('l, E, G, I, A, x') >>> b = Beam3D(20, E, G, I, A, x) >>> b.apply_load(15, start=0, order=0, dir="z") >>> b.apply_load(12*x, start=0, order=0, dir="y") >>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])] >>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4') >>> b.apply_load(R1, start=0, order=-1, dir="z") >>> b.apply_load(R2, start=20, order=-1, dir="z") >>> b.apply_load(R3, start=0, order=-1, dir="y") >>> b.apply_load(R4, start=20, order=-1, dir="y") >>> b.solve_for_reaction_loads(R1, R2, R3, R4) >>> b.plot_shear_force() PlotGrid object containing: Plot[0]:Plot object containing: [0]: cartesian line: 0 for x over (0.0, 20.0) Plot[1]:Plot object containing: [0]: cartesian line: -6*x**2 for x over (0.0, 20.0) Plot[2]:Plot object containing: [0]: cartesian line: -15*x for x over (0.0, 20.0) """ Px = self._plot_shear_force('x') Py = self._plot_shear_force('y') Pz = self._plot_shear_force('z') # For shear force along x direction if dir == "x": return Px.show() # For shear force along y direction elif dir == "y": return Py.show() # For shear force along z direction elif dir == "z": return Pz.show() # For shear force along all direction else: return PlotGrid(3, 1, Px, Py, Pz)
d149aa22ddbebbc5b036402ab27395b7d565901f4ad024482588906a5b49ef7c
__all__ = [ 'TWave', 'RayTransferMatrix', 'FreeSpace', 'FlatRefraction', 'CurvedRefraction', 'FlatMirror', 'CurvedMirror', 'ThinLens', 'GeometricRay', 'BeamParameter', 'waist2rayleigh', 'rayleigh2waist', 'geometric_conj_ab', 'geometric_conj_af', 'geometric_conj_bf', 'gaussian_conj', 'conjugate_gauss_beams', 'Medium', 'refraction_angle', 'deviation', 'fresnel_coefficients', 'brewster_angle', 'critical_angle', 'lens_makers_formula', 'mirror_formula', 'lens_formula', 'hyperfocal_distance', 'transverse_magnification', 'jones_vector', 'stokes_vector', 'jones_2_stokes', 'linear_polarizer', 'phase_retarder', 'half_wave_retarder', 'quarter_wave_retarder', 'transmissive_filter', 'reflective_filter', 'mueller_matrix', 'polarizing_beam_splitter', ] from .waves import TWave from .gaussopt import (RayTransferMatrix, FreeSpace, FlatRefraction, CurvedRefraction, FlatMirror, CurvedMirror, ThinLens, GeometricRay, BeamParameter, waist2rayleigh, rayleigh2waist, geometric_conj_ab, geometric_conj_af, geometric_conj_bf, gaussian_conj, conjugate_gauss_beams) from .medium import Medium from .utils import (refraction_angle, deviation, fresnel_coefficients, brewster_angle, critical_angle, lens_makers_formula, mirror_formula, lens_formula, hyperfocal_distance, transverse_magnification) from .polarization import (jones_vector, stokes_vector, jones_2_stokes, linear_polarizer, phase_retarder, half_wave_retarder, quarter_wave_retarder, transmissive_filter, reflective_filter, mueller_matrix, polarizing_beam_splitter)
c46c16ad746bce2c297370e86c6f72b3c0d486f1422c4839f67141a0f2b291f3
""" This module has all the classes and functions related to waves in optics. **Contains** * TWave """ __all__ = ['TWave'] from sympy import (sympify, pi, sin, cos, sqrt, Number, Symbol, S, symbols, Derivative, atan2) from sympy.core.expr import Expr from sympy.physics.units import speed_of_light, meter, second c = speed_of_light.convert_to(meter/second) class TWave(Expr): r""" This is a simple transverse sine wave travelling in a one-dimensional space. Basic properties are required at the time of creation of the object, but they can be changed later with respective methods provided. Explanation =========== It is represented as :math:`A \times cos(k*x - \omega \times t + \phi )`, where :math:`A` is the amplitude, :math:`\omega` is the angular frequency, :math:`k` is the wavenumber (spatial frequency), :math:`x` is a spatial variable to represent the position on the dimension on which the wave propagates, and :math:`\phi` is the phase angle of the wave. Arguments ========= amplitude : Sympifyable Amplitude of the wave. frequency : Sympifyable Frequency of the wave. phase : Sympifyable Phase angle of the wave. time_period : Sympifyable Time period of the wave. n : Sympifyable Refractive index of the medium. Raises ======= ValueError : When neither frequency nor time period is provided or they are not consistent. TypeError : When anything other than TWave objects is added. Examples ======== >>> from sympy import symbols >>> from sympy.physics.optics import TWave >>> A1, phi1, A2, phi2, f = symbols('A1, phi1, A2, phi2, f') >>> w1 = TWave(A1, f, phi1) >>> w2 = TWave(A2, f, phi2) >>> w3 = w1 + w2 # Superposition of two waves >>> w3 TWave(sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2) + A2**2), f, atan2(A1*sin(phi1) + A2*sin(phi2), A1*cos(phi1) + A2*cos(phi2))) >>> w3.amplitude sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2) + A2**2) >>> w3.phase atan2(A1*sin(phi1) + A2*sin(phi2), A1*cos(phi1) + A2*cos(phi2)) >>> w3.speed 299792458*meter/(second*n) >>> w3.angular_velocity 2*pi*f """ def __init__( self, amplitude, frequency=None, phase=S.Zero, time_period=None, n=Symbol('n')): frequency = sympify(frequency) amplitude = sympify(amplitude) phase = sympify(phase) time_period = sympify(time_period) n = sympify(n) self._frequency = frequency self._amplitude = amplitude self._phase = phase self._time_period = time_period self._n = n if time_period is not None: self._frequency = 1/self._time_period if frequency is not None: self._time_period = 1/self._frequency if time_period is not None: if frequency != 1/time_period: raise ValueError("frequency and time_period should be consistent.") if frequency is None and time_period is None: raise ValueError("Either frequency or time period is needed.") @property def frequency(self): """ Returns the frequency of the wave, in cycles per second. Examples ======== >>> from sympy import symbols >>> from sympy.physics.optics import TWave >>> A, phi, f = symbols('A, phi, f') >>> w = TWave(A, f, phi) >>> w.frequency f """ return self._frequency @property def time_period(self): """ Returns the temporal period of the wave, in seconds per cycle. Examples ======== >>> from sympy import symbols >>> from sympy.physics.optics import TWave >>> A, phi, f = symbols('A, phi, f') >>> w = TWave(A, f, phi) >>> w.time_period 1/f """ return self._time_period @property def wavelength(self): """ Returns the wavelength (spatial period) of the wave, in meters per cycle. It depends on the medium of the wave. Examples ======== >>> from sympy import symbols >>> from sympy.physics.optics import TWave >>> A, phi, f = symbols('A, phi, f') >>> w = TWave(A, f, phi) >>> w.wavelength 299792458*meter/(second*f*n) """ return c/(self._frequency*self._n) @property def amplitude(self): """ Returns the amplitude of the wave. Examples ======== >>> from sympy import symbols >>> from sympy.physics.optics import TWave >>> A, phi, f = symbols('A, phi, f') >>> w = TWave(A, f, phi) >>> w.amplitude A """ return self._amplitude @property def phase(self): """ Returns the phase angle of the wave, in radians. Examples ======== >>> from sympy import symbols >>> from sympy.physics.optics import TWave >>> A, phi, f = symbols('A, phi, f') >>> w = TWave(A, f, phi) >>> w.phase phi """ return self._phase @property def speed(self): """ Returns the propagation speed of the wave, in meters per second. It is dependent on the propagation medium. Examples ======== >>> from sympy import symbols >>> from sympy.physics.optics import TWave >>> A, phi, f = symbols('A, phi, f') >>> w = TWave(A, f, phi) >>> w.speed 299792458*meter/(second*n) """ return self.wavelength*self._frequency @property def angular_velocity(self): """ Returns the angular velocity of the wave, in radians per second. Examples ======== >>> from sympy import symbols >>> from sympy.physics.optics import TWave >>> A, phi, f = symbols('A, phi, f') >>> w = TWave(A, f, phi) >>> w.angular_velocity 2*pi*f """ return 2*pi*self._frequency @property def wavenumber(self): """ Returns the wavenumber of the wave, in radians per meter. Examples ======== >>> from sympy import symbols >>> from sympy.physics.optics import TWave >>> A, phi, f = symbols('A, phi, f') >>> w = TWave(A, f, phi) >>> w.wavenumber pi*second*f*n/(149896229*meter) """ return 2*pi/self.wavelength def __str__(self): """String representation of a TWave.""" from sympy.printing import sstr return type(self).__name__ + sstr(self.args) __repr__ = __str__ def __add__(self, other): """ Addition of two waves will result in their superposition. The type of interference will depend on their phase angles. """ if isinstance(other, TWave): if self._frequency == other._frequency and self.wavelength == other.wavelength: return TWave(sqrt(self._amplitude**2 + other._amplitude**2 + 2 * self._amplitude*other._amplitude*cos( self._phase - other.phase)), self._frequency, atan2(self._amplitude*sin(self._phase) + other._amplitude*sin(other._phase), self._amplitude*cos(self._phase) + other._amplitude*cos(other._phase)) ) else: raise NotImplementedError("Interference of waves with different frequencies" " has not been implemented.") else: raise TypeError(type(other).__name__ + " and TWave objects can't be added.") def __mul__(self, other): """ Multiplying a wave by a scalar rescales the amplitude of the wave. """ other = sympify(other) if isinstance(other, Number): return TWave(self._amplitude*other, *self.args[1:]) else: raise TypeError(type(other).__name__ + " and TWave objects can't be multiplied.") def __sub__(self, other): return self.__add__(-1*other) def __neg__(self): return self.__mul__(-1) def __radd__(self, other): return self.__add__(other) def __rmul__(self, other): return self.__mul__(other) def __rsub__(self, other): return (-self).__radd__(other) def _eval_rewrite_as_sin(self, *args, **kwargs): return self._amplitude*sin(self.wavenumber*Symbol('x') - self.angular_velocity*Symbol('t') + self._phase + pi/2, evaluate=False) def _eval_rewrite_as_cos(self, *args, **kwargs): return self._amplitude*cos(self.wavenumber*Symbol('x') - self.angular_velocity*Symbol('t') + self._phase) def _eval_rewrite_as_pde(self, *args, **kwargs): from sympy import Function mu, epsilon, x, t = symbols('mu, epsilon, x, t') E = Function('E') return Derivative(E(x, t), x, 2) + mu*epsilon*Derivative(E(x, t), t, 2) def _eval_rewrite_as_exp(self, *args, **kwargs): from sympy import exp, I return self._amplitude*exp(I*(self.wavenumber*Symbol('x') - self.angular_velocity*Symbol('t') + self._phase))
7e051180d522bb483346382e5847414ae10172fca94ae8f440d83b68f9e83398
from sympy.physics.units.systems.si import dimsys_SI from sympy import S, Symbol, sqrt, cos, acos, log, atan2, pi, Abs from sympy.physics.units.dimensions import Dimension from sympy.physics.units.definitions.dimension_definitions import ( length, time, mass, force, pressure, angle ) from sympy.physics.units import foot from sympy.testing.pytest import raises def test_Dimension_definition(): assert dimsys_SI.get_dimensional_dependencies(length) == {"length": 1} assert length.name == Symbol("length") assert length.symbol == Symbol("L") halflength = sqrt(length) assert dimsys_SI.get_dimensional_dependencies(halflength) == {"length": S.Half} def test_Dimension_error_definition(): # tuple with more or less than two entries raises(TypeError, lambda: Dimension(("length", 1, 2))) raises(TypeError, lambda: Dimension(["length"])) # non-number power raises(TypeError, lambda: Dimension({"length": "a"})) # non-number with named argument raises(TypeError, lambda: Dimension({"length": (1, 2)})) # symbol should by Symbol or str raises(AssertionError, lambda: Dimension("length", symbol=1)) def test_str(): assert str(Dimension("length")) == "Dimension(length)" assert str(Dimension("length", "L")) == "Dimension(length, L)" def test_Dimension_properties(): assert dimsys_SI.is_dimensionless(length) is False assert dimsys_SI.is_dimensionless(length/length) is True assert dimsys_SI.is_dimensionless(Dimension("undefined")) is False assert length.has_integer_powers(dimsys_SI) is True assert (length**(-1)).has_integer_powers(dimsys_SI) is True assert (length**1.5).has_integer_powers(dimsys_SI) is False def test_Dimension_add_sub(): assert length + length == length assert length - length == length assert -length == length raises(TypeError, lambda: length + foot) raises(TypeError, lambda: foot + length) raises(TypeError, lambda: length - foot) raises(TypeError, lambda: foot - length) # issue 14547 - only raise error for dimensional args; allow # others to pass x = Symbol('x') e = length + x assert e == x + length and e.is_Add and set(e.args) == {length, x} e = length + 1 assert e == 1 + length == 1 - length and e.is_Add and set(e.args) == {length, 1} assert dimsys_SI.get_dimensional_dependencies(mass * length / time**2 + force) == \ {'length': 1, 'mass': 1, 'time': -2} assert dimsys_SI.get_dimensional_dependencies(mass * length / time**2 + force - pressure * length**2) == \ {'length': 1, 'mass': 1, 'time': -2} raises(TypeError, lambda: dimsys_SI.get_dimensional_dependencies(mass * length / time**2 + pressure)) def test_Dimension_mul_div_exp(): assert 2*length == length*2 == length/2 == length assert 2/length == 1/length x = Symbol('x') m = x*length assert m == length*x and m.is_Mul and set(m.args) == {x, length} d = x/length assert d == x*length**-1 and d.is_Mul and set(d.args) == {x, 1/length} d = length/x assert d == length*x**-1 and d.is_Mul and set(d.args) == {1/x, length} velo = length / time assert (length * length) == length ** 2 assert dimsys_SI.get_dimensional_dependencies(length * length) == {"length": 2} assert dimsys_SI.get_dimensional_dependencies(length ** 2) == {"length": 2} assert dimsys_SI.get_dimensional_dependencies(length * time) == { "length": 1, "time": 1} assert dimsys_SI.get_dimensional_dependencies(velo) == { "length": 1, "time": -1} assert dimsys_SI.get_dimensional_dependencies(velo ** 2) == {"length": 2, "time": -2} assert dimsys_SI.get_dimensional_dependencies(length / length) == {} assert dimsys_SI.get_dimensional_dependencies(velo / length * time) == {} assert dimsys_SI.get_dimensional_dependencies(length ** -1) == {"length": -1} assert dimsys_SI.get_dimensional_dependencies(velo ** -1.5) == {"length": -1.5, "time": 1.5} length_a = length**"a" assert dimsys_SI.get_dimensional_dependencies(length_a) == {"length": Symbol("a")} assert dimsys_SI.get_dimensional_dependencies(length**pi) == {"length": pi} assert dimsys_SI.get_dimensional_dependencies(length**(length/length)) == {"length": Dimension(1)} raises(TypeError, lambda: dimsys_SI.get_dimensional_dependencies(length**length)) assert length != 1 assert length / length != 1 length_0 = length ** 0 assert dimsys_SI.get_dimensional_dependencies(length_0) == {} # issue 18738 a = Symbol('a') b = Symbol('b') c = sqrt(a**2 + b**2) c_dim = c.subs({a: length, b: length}) assert dimsys_SI.equivalent_dims(c_dim, length) def test_Dimension_functions(): raises(TypeError, lambda: dimsys_SI.get_dimensional_dependencies(cos(length))) raises(TypeError, lambda: dimsys_SI.get_dimensional_dependencies(acos(angle))) raises(TypeError, lambda: dimsys_SI.get_dimensional_dependencies(atan2(length, time))) raises(TypeError, lambda: dimsys_SI.get_dimensional_dependencies(log(length))) raises(TypeError, lambda: dimsys_SI.get_dimensional_dependencies(log(100, length))) raises(TypeError, lambda: dimsys_SI.get_dimensional_dependencies(log(length, 10))) assert dimsys_SI.get_dimensional_dependencies(pi) == {} assert dimsys_SI.get_dimensional_dependencies(cos(1)) == {} assert dimsys_SI.get_dimensional_dependencies(cos(angle)) == {} assert dimsys_SI.get_dimensional_dependencies(atan2(length, length)) == {} assert dimsys_SI.get_dimensional_dependencies(log(length / length, length / length)) == {} assert dimsys_SI.get_dimensional_dependencies(Abs(length)) == {"length": 1} assert dimsys_SI.get_dimensional_dependencies(Abs(length / length)) == {} assert dimsys_SI.get_dimensional_dependencies(sqrt(-1)) == {}
42bbe6f56c6eb4ee6df93e035e015ee1cd035d3f429b06e29e368cab10200d7e
from sympy import (symbols, sin, cos, pi, zeros, eye, simplify, ImmutableMatrix as Matrix) from sympy.physics.vector import (ReferenceFrame, Vector, CoordinateSym, dynamicsymbols, time_derivative, express, dot) from sympy.physics.vector.frame import _check_frame from sympy.physics.vector.vector import VectorTypeError from sympy.testing.pytest import raises Vector.simp = True def test_dict_list(): A = ReferenceFrame('A') B = ReferenceFrame('B') C = ReferenceFrame('C') D = ReferenceFrame('D') E = ReferenceFrame('E') F = ReferenceFrame('F') B.orient_axis(A, A.x, 1.0) C.orient_axis(B, B.x, 1.0) D.orient_axis(C, C.x, 1.0) assert D._dict_list(A, 0) == [D, C, B, A] E.orient_axis(D, D.x, 1.0) assert C._dict_list(A, 0) == [C, B, A] assert C._dict_list(E, 0) == [C, D, E] # only 0, 1, 2 permitted for second argument raises(ValueError, lambda: C._dict_list(E, 5)) # no connecting path raises(ValueError, lambda: F._dict_list(A, 0)) def test_coordinate_vars(): """Tests the coordinate variables functionality""" A = ReferenceFrame('A') assert CoordinateSym('Ax', A, 0) == A[0] assert CoordinateSym('Ax', A, 1) == A[1] assert CoordinateSym('Ax', A, 2) == A[2] raises(ValueError, lambda: CoordinateSym('Ax', A, 3)) q = dynamicsymbols('q') qd = dynamicsymbols('q', 1) assert isinstance(A[0], CoordinateSym) and \ isinstance(A[0], CoordinateSym) and \ isinstance(A[0], CoordinateSym) assert A.variable_map(A) == {A[0]:A[0], A[1]:A[1], A[2]:A[2]} assert A[0].frame == A B = A.orientnew('B', 'Axis', [q, A.z]) assert B.variable_map(A) == {B[2]: A[2], B[1]: -A[0]*sin(q) + A[1]*cos(q), B[0]: A[0]*cos(q) + A[1]*sin(q)} assert A.variable_map(B) == {A[0]: B[0]*cos(q) - B[1]*sin(q), A[1]: B[0]*sin(q) + B[1]*cos(q), A[2]: B[2]} assert time_derivative(B[0], A) == -A[0]*sin(q)*qd + A[1]*cos(q)*qd assert time_derivative(B[1], A) == -A[0]*cos(q)*qd - A[1]*sin(q)*qd assert time_derivative(B[2], A) == 0 assert express(B[0], A, variables=True) == A[0]*cos(q) + A[1]*sin(q) assert express(B[1], A, variables=True) == -A[0]*sin(q) + A[1]*cos(q) assert express(B[2], A, variables=True) == A[2] assert time_derivative(A[0]*A.x + A[1]*A.y + A[2]*A.z, B) == A[1]*qd*A.x - A[0]*qd*A.y assert time_derivative(B[0]*B.x + B[1]*B.y + B[2]*B.z, A) == - B[1]*qd*B.x + B[0]*qd*B.y assert express(B[0]*B[1]*B[2], A, variables=True) == \ A[2]*(-A[0]*sin(q) + A[1]*cos(q))*(A[0]*cos(q) + A[1]*sin(q)) assert (time_derivative(B[0]*B[1]*B[2], A) - (A[2]*(-A[0]**2*cos(2*q) - 2*A[0]*A[1]*sin(2*q) + A[1]**2*cos(2*q))*qd)).trigsimp() == 0 assert express(B[0]*B.x + B[1]*B.y + B[2]*B.z, A) == \ (B[0]*cos(q) - B[1]*sin(q))*A.x + (B[0]*sin(q) + \ B[1]*cos(q))*A.y + B[2]*A.z assert express(B[0]*B.x + B[1]*B.y + B[2]*B.z, A, variables=True) == \ A[0]*A.x + A[1]*A.y + A[2]*A.z assert express(A[0]*A.x + A[1]*A.y + A[2]*A.z, B) == \ (A[0]*cos(q) + A[1]*sin(q))*B.x + \ (-A[0]*sin(q) + A[1]*cos(q))*B.y + A[2]*B.z assert express(A[0]*A.x + A[1]*A.y + A[2]*A.z, B, variables=True) == \ B[0]*B.x + B[1]*B.y + B[2]*B.z N = B.orientnew('N', 'Axis', [-q, B.z]) assert N.variable_map(A) == {N[0]: A[0], N[2]: A[2], N[1]: A[1]} C = A.orientnew('C', 'Axis', [q, A.x + A.y + A.z]) mapping = A.variable_map(C) assert mapping[A[0]] == 2*C[0]*cos(q)/3 + C[0]/3 - 2*C[1]*sin(q + pi/6)/3 +\ C[1]/3 - 2*C[2]*cos(q + pi/3)/3 + C[2]/3 assert mapping[A[1]] == -2*C[0]*cos(q + pi/3)/3 + \ C[0]/3 + 2*C[1]*cos(q)/3 + C[1]/3 - 2*C[2]*sin(q + pi/6)/3 + C[2]/3 assert mapping[A[2]] == -2*C[0]*sin(q + pi/6)/3 + C[0]/3 - \ 2*C[1]*cos(q + pi/3)/3 + C[1]/3 + 2*C[2]*cos(q)/3 + C[2]/3 def test_ang_vel(): q1, q2, q3, q4 = dynamicsymbols('q1 q2 q3 q4') q1d, q2d, q3d, q4d = dynamicsymbols('q1 q2 q3 q4', 1) N = ReferenceFrame('N') A = N.orientnew('A', 'Axis', [q1, N.z]) B = A.orientnew('B', 'Axis', [q2, A.x]) C = B.orientnew('C', 'Axis', [q3, B.y]) D = N.orientnew('D', 'Axis', [q4, N.y]) u1, u2, u3 = dynamicsymbols('u1 u2 u3') assert A.ang_vel_in(N) == (q1d)*A.z assert B.ang_vel_in(N) == (q2d)*B.x + (q1d)*A.z assert C.ang_vel_in(N) == (q3d)*C.y + (q2d)*B.x + (q1d)*A.z A2 = N.orientnew('A2', 'Axis', [q4, N.y]) assert N.ang_vel_in(N) == 0 assert N.ang_vel_in(A) == -q1d*N.z assert N.ang_vel_in(B) == -q1d*A.z - q2d*B.x assert N.ang_vel_in(C) == -q1d*A.z - q2d*B.x - q3d*B.y assert N.ang_vel_in(A2) == -q4d*N.y assert A.ang_vel_in(N) == q1d*N.z assert A.ang_vel_in(A) == 0 assert A.ang_vel_in(B) == - q2d*B.x assert A.ang_vel_in(C) == - q2d*B.x - q3d*B.y assert A.ang_vel_in(A2) == q1d*N.z - q4d*N.y assert B.ang_vel_in(N) == q1d*A.z + q2d*A.x assert B.ang_vel_in(A) == q2d*A.x assert B.ang_vel_in(B) == 0 assert B.ang_vel_in(C) == -q3d*B.y assert B.ang_vel_in(A2) == q1d*A.z + q2d*A.x - q4d*N.y assert C.ang_vel_in(N) == q1d*A.z + q2d*A.x + q3d*B.y assert C.ang_vel_in(A) == q2d*A.x + q3d*C.y assert C.ang_vel_in(B) == q3d*B.y assert C.ang_vel_in(C) == 0 assert C.ang_vel_in(A2) == q1d*A.z + q2d*A.x + q3d*B.y - q4d*N.y assert A2.ang_vel_in(N) == q4d*A2.y assert A2.ang_vel_in(A) == q4d*A2.y - q1d*N.z assert A2.ang_vel_in(B) == q4d*N.y - q1d*A.z - q2d*A.x assert A2.ang_vel_in(C) == q4d*N.y - q1d*A.z - q2d*A.x - q3d*B.y assert A2.ang_vel_in(A2) == 0 C.set_ang_vel(N, u1*C.x + u2*C.y + u3*C.z) assert C.ang_vel_in(N) == (u1)*C.x + (u2)*C.y + (u3)*C.z assert N.ang_vel_in(C) == (-u1)*C.x + (-u2)*C.y + (-u3)*C.z assert C.ang_vel_in(D) == (u1)*C.x + (u2)*C.y + (u3)*C.z + (-q4d)*D.y assert D.ang_vel_in(C) == (-u1)*C.x + (-u2)*C.y + (-u3)*C.z + (q4d)*D.y q0 = dynamicsymbols('q0') q0d = dynamicsymbols('q0', 1) E = N.orientnew('E', 'Quaternion', (q0, q1, q2, q3)) assert E.ang_vel_in(N) == ( 2 * (q1d * q0 + q2d * q3 - q3d * q2 - q0d * q1) * E.x + 2 * (q2d * q0 + q3d * q1 - q1d * q3 - q0d * q2) * E.y + 2 * (q3d * q0 + q1d * q2 - q2d * q1 - q0d * q3) * E.z) F = N.orientnew('F', 'Body', (q1, q2, q3), 313) assert F.ang_vel_in(N) == ((sin(q2)*sin(q3)*q1d + cos(q3)*q2d)*F.x + (sin(q2)*cos(q3)*q1d - sin(q3)*q2d)*F.y + (cos(q2)*q1d + q3d)*F.z) G = N.orientnew('G', 'Axis', (q1, N.x + N.y)) assert G.ang_vel_in(N) == q1d * (N.x + N.y).normalize() assert N.ang_vel_in(G) == -q1d * (N.x + N.y).normalize() def test_dcm(): q1, q2, q3, q4 = dynamicsymbols('q1 q2 q3 q4') N = ReferenceFrame('N') A = N.orientnew('A', 'Axis', [q1, N.z]) B = A.orientnew('B', 'Axis', [q2, A.x]) C = B.orientnew('C', 'Axis', [q3, B.y]) D = N.orientnew('D', 'Axis', [q4, N.y]) E = N.orientnew('E', 'Space', [q1, q2, q3], '123') assert N.dcm(C) == Matrix([ [- sin(q1) * sin(q2) * sin(q3) + cos(q1) * cos(q3), - sin(q1) * cos(q2), sin(q1) * sin(q2) * cos(q3) + sin(q3) * cos(q1)], [sin(q1) * cos(q3) + sin(q2) * sin(q3) * cos(q1), cos(q1) * cos(q2), sin(q1) * sin(q3) - sin(q2) * cos(q1) * cos(q3)], [- sin(q3) * cos(q2), sin(q2), cos(q2) * cos(q3)]]) # This is a little touchy. Is it ok to use simplify in assert? test_mat = D.dcm(C) - Matrix( [[cos(q1) * cos(q3) * cos(q4) - sin(q3) * (- sin(q4) * cos(q2) + sin(q1) * sin(q2) * cos(q4)), - sin(q2) * sin(q4) - sin(q1) * cos(q2) * cos(q4), sin(q3) * cos(q1) * cos(q4) + cos(q3) * (- sin(q4) * cos(q2) + sin(q1) * sin(q2) * cos(q4))], [sin(q1) * cos(q3) + sin(q2) * sin(q3) * cos(q1), cos(q1) * cos(q2), sin(q1) * sin(q3) - sin(q2) * cos(q1) * cos(q3)], [sin(q4) * cos(q1) * cos(q3) - sin(q3) * (cos(q2) * cos(q4) + sin(q1) * sin(q2) * sin(q4)), sin(q2) * cos(q4) - sin(q1) * sin(q4) * cos(q2), sin(q3) * sin(q4) * cos(q1) + cos(q3) * (cos(q2) * cos(q4) + sin(q1) * sin(q2) * sin(q4))]]) assert test_mat.expand() == zeros(3, 3) assert E.dcm(N) == Matrix( [[cos(q2)*cos(q3), sin(q3)*cos(q2), -sin(q2)], [sin(q1)*sin(q2)*cos(q3) - sin(q3)*cos(q1), sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3), sin(q1)*cos(q2)], [sin(q1)*sin(q3) + sin(q2)*cos(q1)*cos(q3), - sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1), cos(q1)*cos(q2)]]) def test_w_diff_dcm1(): # Ref: # Dynamics Theory and Applications, Kane 1985 # Sec. 2.1 ANGULAR VELOCITY A = ReferenceFrame('A') B = ReferenceFrame('B') c11, c12, c13 = dynamicsymbols('C11 C12 C13') c21, c22, c23 = dynamicsymbols('C21 C22 C23') c31, c32, c33 = dynamicsymbols('C31 C32 C33') c11d, c12d, c13d = dynamicsymbols('C11 C12 C13', level=1) c21d, c22d, c23d = dynamicsymbols('C21 C22 C23', level=1) c31d, c32d, c33d = dynamicsymbols('C31 C32 C33', level=1) DCM = Matrix([ [c11, c12, c13], [c21, c22, c23], [c31, c32, c33] ]) B.orient(A, 'DCM', DCM) b1a = (B.x).express(A) b2a = (B.y).express(A) b3a = (B.z).express(A) # Equation (2.1.1) B.set_ang_vel(A, B.x*(dot((b3a).dt(A), B.y)) + B.y*(dot((b1a).dt(A), B.z)) + B.z*(dot((b2a).dt(A), B.x))) # Equation (2.1.21) expr = ( (c12*c13d + c22*c23d + c32*c33d)*B.x + (c13*c11d + c23*c21d + c33*c31d)*B.y + (c11*c12d + c21*c22d + c31*c32d)*B.z) assert B.ang_vel_in(A) - expr == 0 def test_w_diff_dcm2(): q1, q2, q3 = dynamicsymbols('q1:4') N = ReferenceFrame('N') A = N.orientnew('A', 'axis', [q1, N.x]) B = A.orientnew('B', 'axis', [q2, A.y]) C = B.orientnew('C', 'axis', [q3, B.z]) DCM = C.dcm(N).T D = N.orientnew('D', 'DCM', DCM) # Frames D and C are the same ReferenceFrame, # since they have equal DCM respect to frame N. # Therefore, D and C should have same angle velocity in N. assert D.dcm(N) == C.dcm(N) == Matrix([ [cos(q2)*cos(q3), sin(q1)*sin(q2)*cos(q3) + sin(q3)*cos(q1), sin(q1)*sin(q3) - sin(q2)*cos(q1)*cos(q3)], [-sin(q3)*cos(q2), -sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3), sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1)], [sin(q2), -sin(q1)*cos(q2), cos(q1)*cos(q2)]]) assert (D.ang_vel_in(N) - C.ang_vel_in(N)).express(N).simplify() == 0 def test_orientnew_respects_parent_class(): class MyReferenceFrame(ReferenceFrame): pass B = MyReferenceFrame('B') C = B.orientnew('C', 'Axis', [0, B.x]) assert isinstance(C, MyReferenceFrame) def test_orientnew_respects_input_indices(): N = ReferenceFrame('N') q1 = dynamicsymbols('q1') A = N.orientnew('a', 'Axis', [q1, N.z]) #modify default indices: minds = [x+'1' for x in N.indices] B = N.orientnew('b', 'Axis', [q1, N.z], indices=minds) assert N.indices == A.indices assert B.indices == minds def test_orientnew_respects_input_latexs(): N = ReferenceFrame('N') q1 = dynamicsymbols('q1') A = N.orientnew('a', 'Axis', [q1, N.z]) #build default and alternate latex_vecs: def_latex_vecs = [(r"\mathbf{\hat{%s}_%s}" % (A.name.lower(), A.indices[0])), (r"\mathbf{\hat{%s}_%s}" % (A.name.lower(), A.indices[1])), (r"\mathbf{\hat{%s}_%s}" % (A.name.lower(), A.indices[2]))] name = 'b' indices = [x+'1' for x in N.indices] new_latex_vecs = [(r"\mathbf{\hat{%s}_{%s}}" % (name.lower(), indices[0])), (r"\mathbf{\hat{%s}_{%s}}" % (name.lower(), indices[1])), (r"\mathbf{\hat{%s}_{%s}}" % (name.lower(), indices[2]))] B = N.orientnew(name, 'Axis', [q1, N.z], latexs=new_latex_vecs) assert A.latex_vecs == def_latex_vecs assert B.latex_vecs == new_latex_vecs assert B.indices != indices def test_orientnew_respects_input_variables(): N = ReferenceFrame('N') q1 = dynamicsymbols('q1') A = N.orientnew('a', 'Axis', [q1, N.z]) #build non-standard variable names name = 'b' new_variables = ['notb_'+x+'1' for x in N.indices] B = N.orientnew(name, 'Axis', [q1, N.z], variables=new_variables) for j,var in enumerate(A.varlist): assert var.name == A.name + '_' + A.indices[j] for j,var in enumerate(B.varlist): assert var.name == new_variables[j] def test_issue_10348(): u = dynamicsymbols('u:3') I = ReferenceFrame('I') I.orientnew('A', 'space', u, 'XYZ') def test_issue_11503(): A = ReferenceFrame("A") A.orientnew("B", "Axis", [35, A.y]) C = ReferenceFrame("C") A.orient(C, "Axis", [70, C.z]) def test_partial_velocity(): N = ReferenceFrame('N') A = ReferenceFrame('A') u1, u2 = dynamicsymbols('u1, u2') A.set_ang_vel(N, u1 * A.x + u2 * N.y) assert N.partial_velocity(A, u1) == -A.x assert N.partial_velocity(A, u1, u2) == (-A.x, -N.y) assert A.partial_velocity(N, u1) == A.x assert A.partial_velocity(N, u1, u2) == (A.x, N.y) assert N.partial_velocity(N, u1) == 0 assert A.partial_velocity(A, u1) == 0 def test_issue_11498(): A = ReferenceFrame('A') B = ReferenceFrame('B') # Identity transformation A.orient(B, 'DCM', eye(3)) assert A.dcm(B) == Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) assert B.dcm(A) == Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) # x -> y # y -> -z # z -> -x A.orient(B, 'DCM', Matrix([[0, 1, 0], [0, 0, -1], [-1, 0, 0]])) assert B.dcm(A) == Matrix([[0, 1, 0], [0, 0, -1], [-1, 0, 0]]) assert A.dcm(B) == Matrix([[0, 0, -1], [1, 0, 0], [0, -1, 0]]) assert B.dcm(A).T == A.dcm(B) def test_reference_frame(): raises(TypeError, lambda: ReferenceFrame(0)) raises(TypeError, lambda: ReferenceFrame('N', 0)) raises(ValueError, lambda: ReferenceFrame('N', [0, 1])) raises(TypeError, lambda: ReferenceFrame('N', [0, 1, 2])) raises(TypeError, lambda: ReferenceFrame('N', ['a', 'b', 'c'], 0)) raises(ValueError, lambda: ReferenceFrame('N', ['a', 'b', 'c'], [0, 1])) raises(TypeError, lambda: ReferenceFrame('N', ['a', 'b', 'c'], [0, 1, 2])) raises(TypeError, lambda: ReferenceFrame('N', ['a', 'b', 'c'], ['a', 'b', 'c'], 0)) raises(ValueError, lambda: ReferenceFrame('N', ['a', 'b', 'c'], ['a', 'b', 'c'], [0, 1])) raises(TypeError, lambda: ReferenceFrame('N', ['a', 'b', 'c'], ['a', 'b', 'c'], [0, 1, 2])) N = ReferenceFrame('N') assert N[0] == CoordinateSym('N_x', N, 0) assert N[1] == CoordinateSym('N_y', N, 1) assert N[2] == CoordinateSym('N_z', N, 2) raises(ValueError, lambda: N[3]) N = ReferenceFrame('N', ['a', 'b', 'c']) assert N['a'] == N.x assert N['b'] == N.y assert N['c'] == N.z raises(ValueError, lambda: N['d']) assert str(N) == 'N' A = ReferenceFrame('A') B = ReferenceFrame('B') q0, q1, q2, q3 = symbols('q0 q1 q2 q3') raises(TypeError, lambda: A.orient(B, 'DCM', 0)) raises(TypeError, lambda: B.orient(N, 'Space', [q1, q2, q3], '222')) raises(TypeError, lambda: B.orient(N, 'Axis', [q1, N.x + 2 * N.y], '222')) raises(TypeError, lambda: B.orient(N, 'Axis', q1)) raises(IndexError, lambda: B.orient(N, 'Axis', [q1])) raises(TypeError, lambda: B.orient(N, 'Quaternion', [q0, q1, q2, q3], '222')) raises(TypeError, lambda: B.orient(N, 'Quaternion', q0)) raises(TypeError, lambda: B.orient(N, 'Quaternion', [q0, q1, q2])) raises(NotImplementedError, lambda: B.orient(N, 'Foo', [q0, q1, q2])) raises(TypeError, lambda: B.orient(N, 'Body', [q1, q2], '232')) raises(TypeError, lambda: B.orient(N, 'Space', [q1, q2], '232')) N.set_ang_acc(B, 0) assert N.ang_acc_in(B) == Vector(0) N.set_ang_vel(B, 0) assert N.ang_vel_in(B) == Vector(0) def test_check_frame(): raises(VectorTypeError, lambda: _check_frame(0)) def test_dcm_diff_16824(): # NOTE : This is a regression test for the bug introduced in PR 14758, # identified in 16824, and solved by PR 16828. # This is the solution to Problem 2.2 on page 264 in Kane & Lenvinson's # 1985 book. q1, q2, q3 = dynamicsymbols('q1:4') s1 = sin(q1) c1 = cos(q1) s2 = sin(q2) c2 = cos(q2) s3 = sin(q3) c3 = cos(q3) dcm = Matrix([[c2*c3, s1*s2*c3 - s3*c1, c1*s2*c3 + s3*s1], [c2*s3, s1*s2*s3 + c3*c1, c1*s2*s3 - c3*s1], [-s2, s1*c2, c1*c2]]) A = ReferenceFrame('A') B = ReferenceFrame('B') B.orient(A, 'DCM', dcm) AwB = B.ang_vel_in(A) alpha2 = s3*c2*q1.diff() + c3*q2.diff() beta2 = s1*c2*q3.diff() + c1*q2.diff() assert simplify(AwB.dot(A.y) - alpha2) == 0 assert simplify(AwB.dot(B.y) - beta2) == 0 def test_orient_explicit(): A = ReferenceFrame('A') B = ReferenceFrame('B') A.orient_explicit(B, eye(3)) assert A.dcm(B) == Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) def test_orient_axis(): A = ReferenceFrame('A') B = ReferenceFrame('B') assert A.orient_axis(B,-B.x, 1) == A.orient_axis(B, B.x, -1) def test_orient_body(): A = ReferenceFrame('A') B = ReferenceFrame('B') B.orient_body_fixed(A, (1,1,0), 'XYX') assert B.dcm(A) == Matrix([[cos(1), sin(1)**2, -sin(1)*cos(1)], [0, cos(1), sin(1)], [sin(1), -sin(1)*cos(1), cos(1)**2]]) def test_orient_space(): A = ReferenceFrame('A') B = ReferenceFrame('B') B.orient_space_fixed(A, (0,0,0), '123') assert B.dcm(A) == Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) def test_orient_quaternion(): A = ReferenceFrame('A') B = ReferenceFrame('B') B.orient_quaternion(A, (0,0,0,0)) assert B.dcm(A) == Matrix([[0, 0, 0], [0, 0, 0], [0, 0, 0]]) def test_frame_dict(): A = ReferenceFrame('A') B = ReferenceFrame('B') C = ReferenceFrame('C') a, b, c = symbols('a b c') B.orient_axis(A, A.x, a) assert A._dcm_dict == {B: Matrix([[1, 0, 0],[0, cos(a), -sin(a)],[0, sin(a), cos(a)]])} assert B._dcm_dict == {A: Matrix([[1, 0, 0],[0, cos(a), sin(a)],[0, -sin(a), cos(a)]])} assert C._dcm_dict == {} B.orient_axis(C, C.x, b) # Previous relation is not wiped assert A._dcm_dict == {B: Matrix([[1, 0, 0],[0, cos(a), -sin(a)],[0, sin(a), cos(a)]])} assert B._dcm_dict == {A: Matrix([[1, 0, 0],[0, cos(a), sin(a)],[0, -sin(a), cos(a)]]), \ C: Matrix([[1, 0, 0],[0, cos(b), sin(b)],[0, -sin(b), cos(b)]])} assert C._dcm_dict == {B: Matrix([[1, 0, 0],[0, cos(b), -sin(b)],[0, sin(b), cos(b)]])} A.orient_axis(B, B.x, c) # Previous relation is updated assert B._dcm_dict == {C: Matrix([[1, 0, 0],[0, cos(b), sin(b)],[0, -sin(b), cos(b)]]),\ A: Matrix([[1, 0, 0],[0, cos(c), -sin(c)],[0, sin(c), cos(c)]])} assert A._dcm_dict == {B: Matrix([[1, 0, 0],[0, cos(c), sin(c)],[0, -sin(c), cos(c)]])} assert C._dcm_dict == {B: Matrix([[1, 0, 0],[0, cos(b), -sin(b)],[0, sin(b), cos(b)]])} def test_dcm_cache_dict(): A = ReferenceFrame('A') B = ReferenceFrame('B') C = ReferenceFrame('C') D = ReferenceFrame('D') a, b, c = symbols('a b c') B.orient_axis(A, A.x, a) C.orient_axis(B, B.x, b) D.orient_axis(C, C.x, c) assert D._dcm_dict == {C: Matrix([[1, 0, 0],[0, cos(c), sin(c)],[0, -sin(c), cos(c)]])} assert C._dcm_dict == {B: Matrix([[1, 0, 0],[0, cos(b), sin(b)],[0, -sin(b), cos(b)]]), \ D: Matrix([[1, 0, 0],[0, cos(c), -sin(c)],[0, sin(c), cos(c)]])} assert B._dcm_dict == {A: Matrix([[1, 0, 0],[0, cos(a), sin(a)],[0, -sin(a), cos(a)]]), \ C: Matrix([[1, 0, 0],[0, cos(b), -sin(b)],[0, sin(b), cos(b)]])} assert A._dcm_dict == {B: Matrix([[1, 0, 0],[0, cos(a), -sin(a)],[0, sin(a), cos(a)]])} assert D._dcm_dict == D._dcm_cache D.dcm(A) # Check calculated dcm relation is stored in _dcm_cache and not in _dcm_dict assert list(A._dcm_cache.keys()) == [A, B, D] assert list(D._dcm_cache.keys()) == [C, A] assert list(A._dcm_dict.keys()) == [B] assert list(D._dcm_dict.keys()) == [C] assert A._dcm_dict != A._dcm_cache A.orient_axis(B, B.x, b) # _dcm_cache of A is wiped out and new relation is stored. assert A._dcm_dict == {B: Matrix([[1, 0, 0],[0, cos(b), sin(b)],[0, -sin(b), cos(b)]])} assert A._dcm_dict == A._dcm_cache assert B._dcm_dict == {C: Matrix([[1, 0, 0],[0, cos(b), -sin(b)],[0, sin(b), cos(b)]]), \ A: Matrix([[1, 0, 0],[0, cos(b), -sin(b)],[0, sin(b), cos(b)]])}
24c60ca9b04cdf262ea908896f9c9ed0c73b0ce108951e66c8c19d99a676fcb1
from sympy import (symbols, Symbol, pi, sqrt, cos, sin, Derivative, Function, simplify, I, atan2) from sympy.abc import epsilon, mu from sympy.functions.elementary.exponential import exp from sympy.physics.units import speed_of_light, m, s from sympy.physics.optics import TWave from sympy.testing.pytest import raises c = speed_of_light.convert_to(m/s) def test_twave(): A1, phi1, A2, phi2, f = symbols('A1, phi1, A2, phi2, f') n = Symbol('n') # Refractive index t = Symbol('t') # Time x = Symbol('x') # Spatial variable E = Function('E') w1 = TWave(A1, f, phi1) w2 = TWave(A2, f, phi2) assert w1.amplitude == A1 assert w1.frequency == f assert w1.phase == phi1 assert w1.wavelength == c/(f*n) assert w1.time_period == 1/f assert w1.angular_velocity == 2*pi*f assert w1.wavenumber == 2*pi*f*n/c assert w1.speed == c/n w3 = w1 + w2 assert w3.amplitude == sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2) + A2**2) assert w3.frequency == f assert w3.phase == atan2(A1*sin(phi1) + A2*sin(phi2), A1*cos(phi1) + A2*cos(phi2)) assert w3.wavelength == c/(f*n) assert w3.time_period == 1/f assert w3.angular_velocity == 2*pi*f assert w3.wavenumber == 2*pi*f*n/c assert w3.speed == c/n assert simplify(w3.rewrite(sin) - w2.rewrite(sin) - w1.rewrite(sin)) == 0 assert w3.rewrite('pde') == epsilon*mu*Derivative(E(x, t), t, t) + Derivative(E(x, t), x, x) assert w3.rewrite(cos) == sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2) + A2**2)*cos(pi*f*n*x*s/(149896229*m) - 2*pi*f*t + atan2(A1*sin(phi1) + A2*sin(phi2), A1*cos(phi1) + A2*cos(phi2))) assert w3.rewrite(exp) == sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2) + A2**2)*exp(I*(-2*pi*f*t + atan2(A1*sin(phi1) + A2*sin(phi2), A1*cos(phi1) + A2*cos(phi2)) + pi*s*f*n*x/(149896229*m))) w4 = TWave(A1, None, 0, 1/f) assert w4.frequency == f w5 = w1 - w2 assert w5.amplitude == sqrt(A1**2 - 2*A1*A2*cos(phi1 - phi2) + A2**2) assert w5.frequency == f assert w5.phase == atan2(A1*sin(phi1) - A2*sin(phi2), A1*cos(phi1) - A2*cos(phi2)) assert w5.wavelength == c/(f*n) assert w5.time_period == 1/f assert w5.angular_velocity == 2*pi*f assert w5.wavenumber == 2*pi*f*n/c assert w5.speed == c/n assert simplify(w5.rewrite(sin) - w1.rewrite(sin) + w2.rewrite(sin)) == 0 assert w5.rewrite('pde') == epsilon*mu*Derivative(E(x, t), t, t) + Derivative(E(x, t), x, x) assert w5.rewrite(cos) == sqrt(A1**2 - 2*A1*A2*cos(phi1 - phi2) + A2**2)*cos(-2*pi*f*t + atan2(A1*sin(phi1) - A2*sin(phi2), A1*cos(phi1) - A2*cos(phi2)) + pi*s*f*n*x/(149896229*m)) assert w5.rewrite(exp) == sqrt(A1**2 - 2*A1*A2*cos(phi1 - phi2) + A2**2)*exp(I*(-2*pi*f*t + atan2(A1*sin(phi1) - A2*sin(phi2), A1*cos(phi1) - A2*cos(phi2)) + pi*s*f*n*x/(149896229*m))) w6 = 2*w1 assert w6.amplitude == 2*A1 assert w6.frequency == f assert w6.phase == phi1 w7 = -w6 assert w7.amplitude == -2*A1 assert w7.frequency == f assert w7.phase == phi1 raises(ValueError, lambda:TWave(A1)) raises(ValueError, lambda:TWave(A1, f, phi1, t))
08b734e38bd0e2193696c33f5e7a1200916a51ac205f43145a3c105a48745eab
import itertools from collections.abc import Iterable from sympy import S, Tuple, diff, Basic from sympy.core.sympify import _sympify from sympy.tensor.array.ndim_array import NDimArray from sympy.tensor.array.dense_ndim_array import DenseNDimArray, ImmutableDenseNDimArray from sympy.tensor.array.sparse_ndim_array import SparseNDimArray def _arrayfy(a): from sympy.matrices import MatrixBase if isinstance(a, NDimArray): return a if isinstance(a, (MatrixBase, list, tuple, Tuple)): return ImmutableDenseNDimArray(a) return a def tensorproduct(*args): """ Tensor product among scalars or array-like objects. Examples ======== >>> from sympy.tensor.array import tensorproduct, Array >>> from sympy.abc import x, y, z, t >>> A = Array([[1, 2], [3, 4]]) >>> B = Array([x, y]) >>> tensorproduct(A, B) [[[x, y], [2*x, 2*y]], [[3*x, 3*y], [4*x, 4*y]]] >>> tensorproduct(A, x) [[x, 2*x], [3*x, 4*x]] >>> tensorproduct(A, B, B) [[[[x**2, x*y], [x*y, y**2]], [[2*x**2, 2*x*y], [2*x*y, 2*y**2]]], [[[3*x**2, 3*x*y], [3*x*y, 3*y**2]], [[4*x**2, 4*x*y], [4*x*y, 4*y**2]]]] Applying this function on two matrices will result in a rank 4 array. >>> from sympy import Matrix, eye >>> m = Matrix([[x, y], [z, t]]) >>> p = tensorproduct(eye(3), m) >>> p [[[[x, y], [z, t]], [[0, 0], [0, 0]], [[0, 0], [0, 0]]], [[[0, 0], [0, 0]], [[x, y], [z, t]], [[0, 0], [0, 0]]], [[[0, 0], [0, 0]], [[0, 0], [0, 0]], [[x, y], [z, t]]]] """ from sympy.tensor.array import SparseNDimArray, ImmutableSparseNDimArray if len(args) == 0: return S.One if len(args) == 1: return _arrayfy(args[0]) from sympy.tensor.array.expressions.array_expressions import _CodegenArrayAbstract from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct from sympy.tensor.array.expressions.array_expressions import _ArrayExpr from sympy import MatrixSymbol if any(isinstance(arg, (_ArrayExpr, _CodegenArrayAbstract, MatrixSymbol)) for arg in args): return ArrayTensorProduct(*args) if len(args) > 2: return tensorproduct(tensorproduct(args[0], args[1]), *args[2:]) # length of args is 2: a, b = map(_arrayfy, args) if not isinstance(a, NDimArray) or not isinstance(b, NDimArray): return a*b if isinstance(a, SparseNDimArray) and isinstance(b, SparseNDimArray): lp = len(b) new_array = {k1*lp + k2: v1*v2 for k1, v1 in a._sparse_array.items() for k2, v2 in b._sparse_array.items()} return ImmutableSparseNDimArray(new_array, a.shape + b.shape) product_list = [i*j for i in Flatten(a) for j in Flatten(b)] return ImmutableDenseNDimArray(product_list, a.shape + b.shape) def _util_contraction_diagonal(array, *contraction_or_diagonal_axes): array = _arrayfy(array) # Verify contraction_axes: taken_dims = set() for axes_group in contraction_or_diagonal_axes: if not isinstance(axes_group, Iterable): raise ValueError("collections of contraction/diagonal axes expected") dim = array.shape[axes_group[0]] for d in axes_group: if d in taken_dims: raise ValueError("dimension specified more than once") if dim != array.shape[d]: raise ValueError("cannot contract or diagonalize between axes of different dimension") taken_dims.add(d) rank = array.rank() remaining_shape = [dim for i, dim in enumerate(array.shape) if i not in taken_dims] cum_shape = [0]*rank _cumul = 1 for i in range(rank): cum_shape[rank - i - 1] = _cumul _cumul *= int(array.shape[rank - i - 1]) # DEFINITION: by absolute position it is meant the position along the one # dimensional array containing all the tensor components. # Possible future work on this module: move computation of absolute # positions to a class method. # Determine absolute positions of the uncontracted indices: remaining_indices = [[cum_shape[i]*j for j in range(array.shape[i])] for i in range(rank) if i not in taken_dims] # Determine absolute positions of the contracted indices: summed_deltas = [] for axes_group in contraction_or_diagonal_axes: lidx = [] for js in range(array.shape[axes_group[0]]): lidx.append(sum([cum_shape[ig] * js for ig in axes_group])) summed_deltas.append(lidx) return array, remaining_indices, remaining_shape, summed_deltas def tensorcontraction(array, *contraction_axes): """ Contraction of an array-like object on the specified axes. Examples ======== >>> from sympy import Array, tensorcontraction >>> from sympy import Matrix, eye >>> tensorcontraction(eye(3), (0, 1)) 3 >>> A = Array(range(18), (3, 2, 3)) >>> A [[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]], [[12, 13, 14], [15, 16, 17]]] >>> tensorcontraction(A, (0, 2)) [21, 30] Matrix multiplication may be emulated with a proper combination of ``tensorcontraction`` and ``tensorproduct`` >>> from sympy import tensorproduct >>> from sympy.abc import a,b,c,d,e,f,g,h >>> m1 = Matrix([[a, b], [c, d]]) >>> m2 = Matrix([[e, f], [g, h]]) >>> p = tensorproduct(m1, m2) >>> p [[[[a*e, a*f], [a*g, a*h]], [[b*e, b*f], [b*g, b*h]]], [[[c*e, c*f], [c*g, c*h]], [[d*e, d*f], [d*g, d*h]]]] >>> tensorcontraction(p, (1, 2)) [[a*e + b*g, a*f + b*h], [c*e + d*g, c*f + d*h]] >>> m1*m2 Matrix([ [a*e + b*g, a*f + b*h], [c*e + d*g, c*f + d*h]]) """ from sympy.tensor.array.expressions.array_expressions import ArrayContraction from sympy.tensor.array.expressions.array_expressions import _CodegenArrayAbstract from sympy.tensor.array.expressions.array_expressions import _ArrayExpr from sympy import MatrixSymbol if isinstance(array, (_ArrayExpr, _CodegenArrayAbstract, MatrixSymbol)): return ArrayContraction(array, *contraction_axes) array, remaining_indices, remaining_shape, summed_deltas = _util_contraction_diagonal(array, *contraction_axes) # Compute the contracted array: # # 1. external for loops on all uncontracted indices. # Uncontracted indices are determined by the combinatorial product of # the absolute positions of the remaining indices. # 2. internal loop on all contracted indices. # It sums the values of the absolute contracted index and the absolute # uncontracted index for the external loop. contracted_array = [] for icontrib in itertools.product(*remaining_indices): index_base_position = sum(icontrib) isum = S.Zero for sum_to_index in itertools.product(*summed_deltas): idx = array._get_tuple_index(index_base_position + sum(sum_to_index)) isum += array[idx] contracted_array.append(isum) if len(remaining_indices) == 0: assert len(contracted_array) == 1 return contracted_array[0] return type(array)(contracted_array, remaining_shape) def tensordiagonal(array, *diagonal_axes): """ Diagonalization of an array-like object on the specified axes. This is equivalent to multiplying the expression by Kronecker deltas uniting the axes. The diagonal indices are put at the end of the axes. Examples ======== ``tensordiagonal`` acting on a 2-dimensional array by axes 0 and 1 is equivalent to the diagonal of the matrix: >>> from sympy import Array, tensordiagonal >>> from sympy import Matrix, eye >>> tensordiagonal(eye(3), (0, 1)) [1, 1, 1] >>> from sympy.abc import a,b,c,d >>> m1 = Matrix([[a, b], [c, d]]) >>> tensordiagonal(m1, [0, 1]) [a, d] In case of higher dimensional arrays, the diagonalized out dimensions are appended removed and appended as a single dimension at the end: >>> A = Array(range(18), (3, 2, 3)) >>> A [[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]], [[12, 13, 14], [15, 16, 17]]] >>> tensordiagonal(A, (0, 2)) [[0, 7, 14], [3, 10, 17]] >>> from sympy import permutedims >>> tensordiagonal(A, (0, 2)) == permutedims(Array([A[0, :, 0], A[1, :, 1], A[2, :, 2]]), [1, 0]) True """ if any([len(i) <= 1 for i in diagonal_axes]): raise ValueError("need at least two axes to diagonalize") from sympy.tensor.array.expressions.array_expressions import _ArrayExpr from sympy.tensor.array.expressions.array_expressions import _CodegenArrayAbstract from sympy.tensor.array.expressions.array_expressions import ArrayDiagonal from sympy import MatrixSymbol if isinstance(array, (_ArrayExpr, _CodegenArrayAbstract, MatrixSymbol)): return ArrayDiagonal(array, *diagonal_axes) array, remaining_indices, remaining_shape, diagonal_deltas = _util_contraction_diagonal(array, *diagonal_axes) # Compute the diagonalized array: # # 1. external for loops on all undiagonalized indices. # Undiagonalized indices are determined by the combinatorial product of # the absolute positions of the remaining indices. # 2. internal loop on all diagonal indices. # It appends the values of the absolute diagonalized index and the absolute # undiagonalized index for the external loop. diagonalized_array = [] diagonal_shape = [len(i) for i in diagonal_deltas] for icontrib in itertools.product(*remaining_indices): index_base_position = sum(icontrib) isum = [] for sum_to_index in itertools.product(*diagonal_deltas): idx = array._get_tuple_index(index_base_position + sum(sum_to_index)) isum.append(array[idx]) isum = type(array)(isum).reshape(*diagonal_shape) diagonalized_array.append(isum) return type(array)(diagonalized_array, remaining_shape + diagonal_shape) def derive_by_array(expr, dx): r""" Derivative by arrays. Supports both arrays and scalars. Explanation =========== Given the array `A_{i_1, \ldots, i_N}` and the array `X_{j_1, \ldots, j_M}` this function will return a new array `B` defined by `B_{j_1,\ldots,j_M,i_1,\ldots,i_N} := \frac{\partial A_{i_1,\ldots,i_N}}{\partial X_{j_1,\ldots,j_M}}` Examples ======== >>> from sympy import derive_by_array >>> from sympy.abc import x, y, z, t >>> from sympy import cos >>> derive_by_array(cos(x*t), x) -t*sin(t*x) >>> derive_by_array(cos(x*t), [x, y, z, t]) [-t*sin(t*x), 0, 0, -x*sin(t*x)] >>> derive_by_array([x, y**2*z], [[x, y], [z, t]]) [[[1, 0], [0, 2*y*z]], [[0, y**2], [0, 0]]] """ from sympy.matrices import MatrixBase from sympy.tensor.array import SparseNDimArray array_types = (Iterable, MatrixBase, NDimArray) if isinstance(dx, array_types): dx = ImmutableDenseNDimArray(dx) for i in dx: if not i._diff_wrt: raise ValueError("cannot derive by this array") if isinstance(expr, array_types): if isinstance(expr, NDimArray): expr = expr.as_immutable() else: expr = ImmutableDenseNDimArray(expr) if isinstance(dx, array_types): if isinstance(expr, SparseNDimArray): lp = len(expr) new_array = {k + i*lp: v for i, x in enumerate(Flatten(dx)) for k, v in expr.diff(x)._sparse_array.items()} else: new_array = [[y.diff(x) for y in Flatten(expr)] for x in Flatten(dx)] return type(expr)(new_array, dx.shape + expr.shape) else: return expr.diff(dx) else: expr = _sympify(expr) if isinstance(dx, array_types): return ImmutableDenseNDimArray([expr.diff(i) for i in Flatten(dx)], dx.shape) else: dx = _sympify(dx) return diff(expr, dx) def permutedims(expr, perm): """ Permutes the indices of an array. Parameter specifies the permutation of the indices. Examples ======== >>> from sympy.abc import x, y, z, t >>> from sympy import sin >>> from sympy import Array, permutedims >>> a = Array([[x, y, z], [t, sin(x), 0]]) >>> a [[x, y, z], [t, sin(x), 0]] >>> permutedims(a, (1, 0)) [[x, t], [y, sin(x)], [z, 0]] If the array is of second order, ``transpose`` can be used: >>> from sympy import transpose >>> transpose(a) [[x, t], [y, sin(x)], [z, 0]] Examples on higher dimensions: >>> b = Array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) >>> permutedims(b, (2, 1, 0)) [[[1, 5], [3, 7]], [[2, 6], [4, 8]]] >>> permutedims(b, (1, 2, 0)) [[[1, 5], [2, 6]], [[3, 7], [4, 8]]] ``Permutation`` objects are also allowed: >>> from sympy.combinatorics import Permutation >>> permutedims(b, Permutation([1, 2, 0])) [[[1, 5], [2, 6]], [[3, 7], [4, 8]]] """ from sympy.tensor.array import SparseNDimArray from sympy.tensor.array.expressions.array_expressions import _ArrayExpr from sympy.tensor.array.expressions.array_expressions import _CodegenArrayAbstract from sympy.tensor.array.expressions.array_expressions import PermuteDims from sympy import MatrixSymbol if isinstance(expr, (_ArrayExpr, _CodegenArrayAbstract, MatrixSymbol)): return PermuteDims(expr, perm) if not isinstance(expr, NDimArray): expr = ImmutableDenseNDimArray(expr) from sympy.combinatorics import Permutation if not isinstance(perm, Permutation): perm = Permutation(list(perm)) if perm.size != expr.rank(): raise ValueError("wrong permutation size") # Get the inverse permutation: iperm = ~perm new_shape = perm(expr.shape) if isinstance(expr, SparseNDimArray): return type(expr)({tuple(perm(expr._get_tuple_index(k))): v for k, v in expr._sparse_array.items()}, new_shape) indices_span = perm([range(i) for i in expr.shape]) new_array = [None]*len(expr) for i, idx in enumerate(itertools.product(*indices_span)): t = iperm(idx) new_array[i] = expr[t] return type(expr)(new_array, new_shape) class Flatten(Basic): ''' Flatten an iterable object to a list in a lazy-evaluation way. Notes ===== This class is an iterator with which the memory cost can be economised. Optimisation has been considered to ameliorate the performance for some specific data types like DenseNDimArray and SparseNDimArray. Examples ======== >>> from sympy.tensor.array.arrayop import Flatten >>> from sympy.tensor.array import Array >>> A = Array(range(6)).reshape(2, 3) >>> Flatten(A) Flatten([[0, 1, 2], [3, 4, 5]]) >>> [i for i in Flatten(A)] [0, 1, 2, 3, 4, 5] ''' def __init__(self, iterable): from sympy.matrices.matrices import MatrixBase from sympy.tensor.array import NDimArray if not isinstance(iterable, (Iterable, MatrixBase)): raise NotImplementedError("Data type not yet supported") if isinstance(iterable, list): iterable = NDimArray(iterable) self._iter = iterable self._idx = 0 def __iter__(self): return self def __next__(self): from sympy.matrices.matrices import MatrixBase if len(self._iter) > self._idx: if isinstance(self._iter, DenseNDimArray): result = self._iter._array[self._idx] elif isinstance(self._iter, SparseNDimArray): if self._idx in self._iter._sparse_array: result = self._iter._sparse_array[self._idx] else: result = 0 elif isinstance(self._iter, MatrixBase): result = self._iter[self._idx] elif hasattr(self._iter, '__next__'): result = next(self._iter) else: result = self._iter[self._idx] else: raise StopIteration self._idx += 1 return result def next(self): return self.__next__()
3923d4d76063552658500bd97bd3525f6d7429f02a0024c0ee44ee7dd2fa3d62
from collections import defaultdict from sympy import Sum, Mul, KroneckerDelta, Indexed, IndexedBase, Add from sympy.combinatorics import Permutation from sympy.matrices.expressions.matexpr import MatrixElement from sympy.tensor.array.expressions.array_expressions import PermuteDims, ArrayDiagonal, \ ArrayContraction, ArrayTensorProduct, ArrayAdd from sympy.tensor.array.expressions.utils import _get_argindex, _get_diagonal_indices def convert_indexed_to_array(expr, first_indices=None): r""" Parse indexed expression into a form useful for code generation. Examples ======== >>> from sympy.tensor.array.expressions.conv_indexed_to_array import convert_indexed_to_array >>> from sympy import MatrixSymbol, Sum, symbols >>> i, j, k, d = symbols("i j k d") >>> M = MatrixSymbol("M", d, d) >>> N = MatrixSymbol("N", d, d) Recognize the trace in summation form: >>> expr = Sum(M[i, i], (i, 0, d-1)) >>> convert_indexed_to_array(expr) ArrayContraction(M, (0, 1)) Recognize the extraction of the diagonal by using the same index `i` on both axes of the matrix: >>> expr = M[i, i] >>> convert_indexed_to_array(expr) ArrayDiagonal(M, (0, 1)) This function can help perform the transformation expressed in two different mathematical notations as: `\sum_{j=0}^{N-1} A_{i,j} B_{j,k} \Longrightarrow \mathbf{A}\cdot \mathbf{B}` Recognize the matrix multiplication in summation form: >>> expr = Sum(M[i, j]*N[j, k], (j, 0, d-1)) >>> convert_indexed_to_array(expr) ArrayContraction(ArrayTensorProduct(M, N), (1, 2)) Specify that ``k`` has to be the starting index: >>> convert_indexed_to_array(expr, first_indices=[k]) ArrayContraction(ArrayTensorProduct(N, M), (0, 3)) """ result, indices = _convert_indexed_to_array(expr) if not first_indices: return result for i in first_indices: if i not in indices: first_indices.remove(i) first_indices.extend([i for i in indices if i not in first_indices]) permutation = [first_indices.index(i) for i in indices] return PermuteDims(result, permutation) def _convert_indexed_to_array(expr): if isinstance(expr, Sum): function = expr.function summation_indices = expr.variables subexpr, subindices = _convert_indexed_to_array(function) # Check dimensional consistency: shape = subexpr.shape if shape: for ind, istart, iend in expr.limits: i = _get_argindex(subindices, ind) if istart != 0 or iend+1 != shape[i]: raise ValueError("summation index and array dimension mismatch: %s" % ind) contraction_indices = [] subindices = list(subindices) if isinstance(subexpr, ArrayDiagonal): diagonal_indices = list(subexpr.diagonal_indices) dindices = subindices[-len(diagonal_indices):] subindices = subindices[:-len(diagonal_indices)] for index in summation_indices: if index in dindices: position = dindices.index(index) contraction_indices.append(diagonal_indices[position]) diagonal_indices[position] = None diagonal_indices = [i for i in diagonal_indices if i is not None] for i, ind in enumerate(subindices): if ind in summation_indices: pass if diagonal_indices: subexpr = ArrayDiagonal(subexpr.expr, *diagonal_indices) else: subexpr = subexpr.expr axes_contraction = defaultdict(list) for i, ind in enumerate(subindices): if ind in summation_indices: axes_contraction[ind].append(i) subindices[i] = None for k, v in axes_contraction.items(): contraction_indices.append(tuple(v)) free_indices = [i for i in subindices if i is not None] indices_ret = list(free_indices) indices_ret.sort(key=lambda x: free_indices.index(x)) return ArrayContraction( subexpr, *contraction_indices, free_indices=free_indices ), tuple(indices_ret) if isinstance(expr, Mul): args, indices = zip(*[_convert_indexed_to_array(arg) for arg in expr.args]) # Check if there are KroneckerDelta objects: kronecker_delta_repl = {} for arg in args: if not isinstance(arg, KroneckerDelta): continue # Diagonalize two indices: i, j = arg.indices kindices = set(arg.indices) if i in kronecker_delta_repl: kindices.update(kronecker_delta_repl[i]) if j in kronecker_delta_repl: kindices.update(kronecker_delta_repl[j]) kindices = frozenset(kindices) for index in kindices: kronecker_delta_repl[index] = kindices # Remove KroneckerDelta objects, their relations should be handled by # ArrayDiagonal: newargs = [] newindices = [] for arg, loc_indices in zip(args, indices): if isinstance(arg, KroneckerDelta): continue newargs.append(arg) newindices.append(loc_indices) flattened_indices = [kronecker_delta_repl.get(j, j) for i in newindices for j in i] diagonal_indices, ret_indices = _get_diagonal_indices(flattened_indices) tp = ArrayTensorProduct(*newargs) if diagonal_indices: return (ArrayDiagonal(tp, *diagonal_indices), ret_indices) else: return tp, ret_indices if isinstance(expr, MatrixElement): indices = expr.args[1:] diagonal_indices, ret_indices = _get_diagonal_indices(indices) if diagonal_indices: return (ArrayDiagonal(expr.args[0], *diagonal_indices), ret_indices) else: return expr.args[0], ret_indices if isinstance(expr, Indexed): indices = expr.indices diagonal_indices, ret_indices = _get_diagonal_indices(indices) if diagonal_indices: return (ArrayDiagonal(expr.base, *diagonal_indices), ret_indices) else: return expr.args[0], ret_indices if isinstance(expr, IndexedBase): raise NotImplementedError if isinstance(expr, KroneckerDelta): return expr, expr.indices if isinstance(expr, Add): args, indices = zip(*[_convert_indexed_to_array(arg) for arg in expr.args]) args = list(args) # Check if all indices are compatible. Otherwise expand the dimensions: index0set = set(indices[0]) index0 = indices[0] for i in range(1, len(args)): if set(indices[i]) != index0set: raise NotImplementedError("indices must be the same") permutation = Permutation([index0.index(j) for j in indices[i]]) # Perform index permutations: args[i] = PermuteDims(args[i], permutation) return ArrayAdd(*args), index0 return expr, ()
ac3f3e25aede3afc79729b8754e69651f712d8c689ce1d06e07d8c90bf31d477
import itertools from typing import Tuple from functools import reduce, singledispatch from itertools import accumulate from sympy import S, Trace, MatrixExpr, Transpose, DiagMatrix, Mul, ZeroMatrix from sympy.combinatorics.permutations import _af_invert, Permutation from sympy.matrices.common import MatrixCommon from sympy.matrices.expressions.applyfunc import ElementwiseApplyFunction from sympy.tensor.array.expressions.array_expressions import PermuteDims, ArrayDiagonal, \ ArrayTensorProduct, OneArray, get_rank, _get_subrank, ZeroArray, ArrayContraction, \ ArrayAdd, _CodegenArrayAbstract, get_shape, ArrayElementwiseApplyFunc, _ArrayExpr from sympy.tensor.array.expressions.utils import _get_mapping_from_subranks def _support_function_tp1_recognize(contraction_indices, args): subranks = [get_rank(i) for i in args] coeff = reduce(lambda x, y: x*y, [arg for arg, srank in zip(args, subranks) if srank == 0], S.One) mapping = _get_mapping_from_subranks(subranks) new_contraction_indices = list(contraction_indices) newargs = args[:] # make a copy of the list removed = [None for i in newargs] cumul = list(accumulate([0] + [get_rank(arg) for arg in args])) new_perms = [list(range(cumul[i], cumul[i+1])) for i, arg in enumerate(args)] for pi, contraction_pair in enumerate(contraction_indices): if len(contraction_pair) != 2: continue i1, i2 = contraction_pair a1, e1 = mapping[i1] a2, e2 = mapping[i2] while removed[a1] is not None: a1, e1 = removed[a1] while removed[a2] is not None: a2, e2 = removed[a2] if a1 == a2: trace_arg = newargs[a1] newargs[a1] = Trace(trace_arg)._normalize() new_contraction_indices[pi] = None continue if not isinstance(newargs[a1], MatrixExpr) or not isinstance(newargs[a2], MatrixExpr): continue arg1 = newargs[a1] arg2 = newargs[a2] if (e1 == 1 and e2 == 1) or (e1 == 0 and e2 == 0): arg2 = Transpose(arg2) if e1 == 1: argnew = arg1*arg2 else: argnew = arg2*arg1 removed[a2] = a1, e1 new_perms[a1][e1] = new_perms[a2][1 - e2] new_perms[a2] = None newargs[a1] = argnew newargs[a2] = None new_contraction_indices[pi] = None new_contraction_indices = [i for i in new_contraction_indices if i is not None] newargs2 = [arg for arg in newargs if arg is not None] if len(newargs2) == 0: return coeff tp = _a2m_tensor_product(*newargs2) tc = ArrayContraction(tp, *new_contraction_indices) new_perms2 = ArrayContraction._push_indices_up(contraction_indices, [i for i in new_perms if i is not None]) permutation = _af_invert([j for i in new_perms2 for j in i if j is not None]) if permutation == [1, 0] and len(newargs2) == 1: return Transpose(newargs2[0]).doit() tperm = PermuteDims(tc, permutation) return tperm @singledispatch def _array2matrix(expr): return expr @_array2matrix.register(ZeroArray) def _(expr: ZeroArray): if get_rank(expr) == 2: return ZeroMatrix(*expr.shape) else: return expr @_array2matrix.register(ArrayTensorProduct) def _(expr: ArrayTensorProduct): return _a2m_tensor_product(*[_array2matrix(arg) for arg in expr.args]) @_array2matrix.register(ArrayContraction) def _(expr: ArrayContraction): expr = expr.flatten_contraction_of_diagonal() expr = expr.split_multiple_contractions() subexpr = expr.expr contraction_indices: Tuple[Tuple[int]] = expr.contraction_indices if isinstance(subexpr, ArrayTensorProduct): newexpr = ArrayContraction(_array2matrix(subexpr), *contraction_indices) contraction_indices = newexpr.contraction_indices if any(i > 2 for i in newexpr.subranks): addends = ArrayAdd(*[_a2m_tensor_product(*j) for j in itertools.product(*[i.args if isinstance(i, ArrayAdd) else [i] for i in expr.expr.args])]) newexpr = ArrayContraction(addends, *contraction_indices) if isinstance(newexpr, ArrayAdd): ret = _array2matrix(newexpr) return ret assert isinstance(newexpr, ArrayContraction) ret = _support_function_tp1_recognize(contraction_indices, list(newexpr.expr.args)) return ret elif not isinstance(subexpr, _CodegenArrayAbstract): ret = _array2matrix(subexpr) if isinstance(ret, MatrixExpr): assert expr.contraction_indices == ((0, 1),) return _a2m_trace(ret) else: return ArrayContraction(ret, *expr.contraction_indices) @_array2matrix.register(ArrayDiagonal) def _(expr: ArrayDiagonal): expr2 = _array2matrix(expr.expr) pexpr = _array_diag2contr_diagmatrix(ArrayDiagonal(expr2, *expr.diagonal_indices)) if expr == pexpr: return expr return _array2matrix(pexpr) @_array2matrix.register(PermuteDims) def _(expr: PermuteDims): if expr.permutation.array_form == [1, 0]: return _a2m_transpose(_array2matrix(expr.expr)) elif isinstance(expr.expr, ArrayTensorProduct): ranks = expr.expr.subranks inv_permutation = expr.permutation**(-1) newrange = [inv_permutation(i) for i in range(sum(ranks))] newpos = [] counter = 0 for rank in ranks: newpos.append(newrange[counter:counter+rank]) counter += rank newargs = [] newperm = [] scalars = [] for pos, arg in zip(newpos, expr.expr.args): if len(pos) == 0: scalars.append(_array2matrix(arg)) elif pos == sorted(pos): newargs.append((_array2matrix(arg), pos[0])) newperm.extend(pos) elif len(pos) == 2: newargs.append((_a2m_transpose(_array2matrix(arg)), pos[0])) newperm.extend(reversed(pos)) else: raise NotImplementedError() newargs = [i[0] for i in newargs] return PermuteDims(_a2m_tensor_product(*scalars, *newargs), _af_invert(newperm)) elif isinstance(expr.expr, ArrayContraction): mat_mul_lines = _array2matrix(expr.expr) if not isinstance(mat_mul_lines, ArrayTensorProduct): flat_cyclic_form = [j for i in expr.permutation.cyclic_form for j in i] expr_shape = get_shape(expr) if all(expr_shape[i] == 1 for i in flat_cyclic_form): return mat_mul_lines return mat_mul_lines permutation = Permutation(2*len(mat_mul_lines.args)-1)*expr.permutation permuted = [permutation(i) for i in range(2*len(mat_mul_lines.args))] args_array = [None for i in mat_mul_lines.args] for i in range(len(mat_mul_lines.args)): p1 = permuted[2*i] p2 = permuted[2*i+1] if p1 // 2 != p2 // 2: return PermuteDims(mat_mul_lines, permutation) pos = p1 // 2 if p1 > p2: args_array[i] = _a2m_transpose(mat_mul_lines.args[pos]) else: args_array[i] = mat_mul_lines.args[pos] return _a2m_tensor_product(*args_array) else: raise NotImplementedError() @_array2matrix.register(ArrayAdd) def _(expr: ArrayAdd): addends = [_array2matrix(arg) for arg in expr.args] return _a2m_add(*addends) @_array2matrix.register(ArrayElementwiseApplyFunc) def _(expr: ArrayElementwiseApplyFunc): subexpr = _array2matrix(expr.expr) if isinstance(subexpr, MatrixExpr): return ElementwiseApplyFunction(expr.function, subexpr) else: return ArrayElementwiseApplyFunc(expr.function, subexpr) @singledispatch def _remove_trivial_dims(expr): return expr, [] @_remove_trivial_dims.register(ArrayTensorProduct) def _(expr: ArrayTensorProduct): # Recognize expressions like [x, y] with shape (k, 1, k, 1) as `x*y.T`. # The matrix expression has to be equivalent to the tensor product of the # matrices, with trivial dimensions (i.e. dim=1) dropped. # That is, add contractions over trivial dimensions: removed = [] newargs = [] cumul = list(accumulate([0] + [get_rank(arg) for arg in expr.args])) pending = None prev_i = None for i, arg in enumerate(expr.args): current_range = list(range(cumul[i], cumul[i+1])) if isinstance(arg, OneArray): removed.extend(current_range) continue if not isinstance(arg, (MatrixExpr, MatrixCommon)): rarg, rem = _remove_trivial_dims(arg) removed.extend(rem) newargs.append(rarg) continue elif getattr(arg, "is_Identity", False): if arg.shape == (1, 1): # Ignore identity matrices of shape (1, 1) - they are equivalent to scalar 1. removed.extend(current_range) continue k = arg.shape[0] if pending == k: # OK, there is already removed.extend(current_range) continue elif pending is None: newargs.append(arg) pending = k prev_i = i elif pending != k: pending = k prev_i = i newargs.append(arg) elif arg.shape == (1, 1): arg, _ = _remove_trivial_dims(arg) # Matrix is equivalent to scalar: if len(newargs) == 0: newargs.append(arg) elif 1 in get_shape(newargs[-1]): if newargs[-1].shape[1] == 1: newargs[-1] = newargs[-1]*arg else: newargs[-1] = arg*newargs[-1] removed.extend(current_range) else: newargs.append(arg) elif 1 in arg.shape: k = [i for i in arg.shape if i != 1][0] if pending is None: pending = k prev_i = i newargs.append(arg) elif pending == k: prev = newargs[-1] if prev.is_Identity: removed.extend([cumul[prev_i], cumul[prev_i]+1]) newargs[-1] = arg prev_i = i continue if prev.shape[0] == 1: d1 = cumul[prev_i] prev = _a2m_transpose(prev) else: d1 = cumul[prev_i] + 1 if arg.shape[1] == 1: d2 = cumul[i] + 1 arg = _a2m_transpose(arg) else: d2 = cumul[i] newargs[-1] = prev*arg pending = None removed.extend([d1, d2]) else: newargs.append(arg) pending = k prev_i = i else: newargs.append(arg) pending = None return _a2m_tensor_product(*newargs), sorted(removed) @_remove_trivial_dims.register(ArrayAdd) def _(expr: ArrayAdd): rec = [_remove_trivial_dims(arg) for arg in expr.args] newargs, removed = zip(*rec) if len(set(map(tuple, removed))) != 1: return expr, [] return _a2m_add(*newargs), removed[0] @_remove_trivial_dims.register(PermuteDims) def _(expr: PermuteDims): subexpr, subremoved = _remove_trivial_dims(expr.expr) p = expr.permutation.array_form pinv = _af_invert(expr.permutation.array_form) shift = list(accumulate([1 if i in subremoved else 0 for i in range(len(p))])) premoved = [pinv[i] for i in subremoved] p2 = [e - shift[e] for i, e in enumerate(p) if e not in subremoved] # TODO: check if subremoved should be permuted as well... newexpr = PermuteDims(subexpr, p2) if newexpr != expr: newexpr = _array2matrix(newexpr) return newexpr, sorted(premoved) @_remove_trivial_dims.register(ArrayContraction) def _(expr: ArrayContraction): newexpr, removed = _remove_trivial_dims(expr.expr) new_contraction_indices = [tuple(j for j in i if j not in removed) for i in expr.contraction_indices] # Remove possible empty tuples "()": new_contraction_indices = [i for i in new_contraction_indices if i] return ArrayContraction(newexpr, *new_contraction_indices), removed @_remove_trivial_dims.register(ArrayDiagonal) def _(expr: ArrayDiagonal): newexpr, removed = _remove_trivial_dims(expr.expr) new_diag_indices = [tuple(j for j in i if j not in removed) for i in expr.diagonal_indices] return ArrayDiagonal(newexpr, *new_diag_indices), removed @_remove_trivial_dims.register(ElementwiseApplyFunction) def _(expr: ElementwiseApplyFunction): subexpr, removed = _remove_trivial_dims(expr.expr) if subexpr.shape == (1, 1): # TODO: move this to ElementwiseApplyFunction return expr.function(subexpr), removed + [0, 1] return ElementwiseApplyFunction(expr.function, subexpr) @_remove_trivial_dims.register(ArrayElementwiseApplyFunc) def _(expr: ArrayElementwiseApplyFunc): subexpr, removed = _remove_trivial_dims(expr.expr) return ArrayElementwiseApplyFunc(expr.function, subexpr), removed def convert_array_to_matrix(expr): r""" Recognize matrix expressions in codegen objects. If more than one matrix multiplication line have been detected, return a list with the matrix expressions. Examples ======== >>> from sympy.tensor.array.expressions.conv_indexed_to_array import convert_indexed_to_array >>> from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct >>> from sympy import MatrixSymbol, Sum >>> from sympy.abc import i, j, k, l, N >>> from sympy.tensor.array.expressions.array_expressions import ArrayContraction >>> from sympy.tensor.array.expressions.conv_matrix_to_array import convert_matrix_to_array >>> from sympy.tensor.array.expressions.conv_array_to_matrix import convert_array_to_matrix >>> A = MatrixSymbol("A", N, N) >>> B = MatrixSymbol("B", N, N) >>> C = MatrixSymbol("C", N, N) >>> D = MatrixSymbol("D", N, N) >>> expr = Sum(A[i, j]*B[j, k], (j, 0, N-1)) >>> cg = convert_indexed_to_array(expr) >>> convert_array_to_matrix(cg) A*B >>> cg = convert_indexed_to_array(expr, first_indices=[k]) >>> convert_array_to_matrix(cg) B.T*A.T Transposition is detected: >>> expr = Sum(A[j, i]*B[j, k], (j, 0, N-1)) >>> cg = convert_indexed_to_array(expr) >>> convert_array_to_matrix(cg) A.T*B >>> cg = convert_indexed_to_array(expr, first_indices=[k]) >>> convert_array_to_matrix(cg) B.T*A Detect the trace: >>> expr = Sum(A[i, i], (i, 0, N-1)) >>> cg = convert_indexed_to_array(expr) >>> convert_array_to_matrix(cg) Trace(A) Recognize some more complex traces: >>> expr = Sum(A[i, j]*B[j, i], (i, 0, N-1), (j, 0, N-1)) >>> cg = convert_indexed_to_array(expr) >>> convert_array_to_matrix(cg) Trace(A*B) More complicated expressions: >>> expr = Sum(A[i, j]*B[k, j]*A[l, k], (j, 0, N-1), (k, 0, N-1)) >>> cg = convert_indexed_to_array(expr) >>> convert_array_to_matrix(cg) A*B.T*A.T Expressions constructed from matrix expressions do not contain literal indices, the positions of free indices are returned instead: >>> expr = A*B >>> cg = convert_matrix_to_array(expr) >>> convert_array_to_matrix(cg) A*B If more than one line of matrix multiplications is detected, return separate matrix multiplication factors embedded in a tensor product object: >>> cg = ArrayContraction(ArrayTensorProduct(A, B, C, D), (1, 2), (5, 6)) >>> convert_array_to_matrix(cg) ArrayTensorProduct(A*B, C*D) The two lines have free indices at axes 0, 3 and 4, 7, respectively. """ rec = _array2matrix(expr) rec, removed = _remove_trivial_dims(rec) return rec def _array_diag2contr_diagmatrix(expr: ArrayDiagonal): if isinstance(expr.expr, ArrayTensorProduct): args = list(expr.expr.args) diag_indices = list(expr.diagonal_indices) mapping = _get_mapping_from_subranks([_get_subrank(arg) for arg in args]) tuple_links = [[mapping[j] for j in i] for i in diag_indices] contr_indices = [] total_rank = get_rank(expr) replaced = [False for arg in args] for i, (abs_pos, rel_pos) in enumerate(zip(diag_indices, tuple_links)): if len(abs_pos) != 2: continue (pos1_outer, pos1_inner), (pos2_outer, pos2_inner) = rel_pos arg1 = args[pos1_outer] arg2 = args[pos2_outer] if get_rank(arg1) != 2 or get_rank(arg2) != 2: if replaced[pos1_outer]: diag_indices[i] = None if replaced[pos2_outer]: diag_indices[i] = None continue pos1_in2 = 1 - pos1_inner pos2_in2 = 1 - pos2_inner if arg1.shape[pos1_in2] == 1: darg1 = DiagMatrix(arg1) args.append(darg1) contr_indices.append(((pos2_outer, pos2_inner), (len(args)-1, pos1_inner))) total_rank += 1 diag_indices[i] = None args[pos1_outer] = OneArray(arg1.shape[pos1_in2]) replaced[pos1_outer] = True elif arg2.shape[pos2_in2] == 1: darg2 = DiagMatrix(arg2) args.append(darg2) contr_indices.append(((pos1_outer, pos1_inner), (len(args)-1, pos2_inner))) total_rank += 1 diag_indices[i] = None args[pos2_outer] = OneArray(arg2.shape[pos2_in2]) replaced[pos2_outer] = True diag_indices_new = [i for i in diag_indices if i is not None] cumul = list(accumulate([0] + [get_rank(arg) for arg in args])) contr_indices2 = [tuple(cumul[a] + b for a, b in i) for i in contr_indices] tc = ArrayContraction( ArrayTensorProduct(*args), *contr_indices2 ) td = ArrayDiagonal(tc, *diag_indices_new) return td return expr def _a2m_mul(*args): if all(not isinstance(i, _CodegenArrayAbstract) for i in args): from sympy import MatMul return MatMul(*args).doit() else: return ArrayContraction( ArrayTensorProduct(*args), *[(2*i-1, 2*i) for i in range(1, len(args))] ) def _a2m_tensor_product(*args): scalars = [] arrays = [] for arg in args: if isinstance(arg, (MatrixExpr, _ArrayExpr, _CodegenArrayAbstract)): arrays.append(arg) else: scalars.append(arg) scalar = Mul.fromiter(scalars) if len(arrays) == 0: return scalar if scalar != 1: if isinstance(arrays[0], _CodegenArrayAbstract): arrays = [scalar] + arrays else: arrays[0] *= scalar return ArrayTensorProduct(*arrays) def _a2m_add(*args): if all(not isinstance(i, _CodegenArrayAbstract) for i in args): from sympy import MatAdd return MatAdd(*args).doit() else: return ArrayAdd(*args) def _a2m_trace(arg): if isinstance(arg, _CodegenArrayAbstract): return ArrayContraction(arg, (0, 1)) else: from sympy import Trace return Trace(arg) def _a2m_transpose(arg): if isinstance(arg, _CodegenArrayAbstract): return PermuteDims(arg, [1, 0]) else: from sympy import Transpose return Transpose(arg).doit()
8aa8d435687a227720b01e5ed7e23a6fff579c8878bbb9f67bae6b94cbd311da
from sympy import Mul, Basic, MatMul, MatAdd, Transpose, Trace, Pow, \ MatPow, symbols, Dummy, Lambda, HadamardProduct, HadamardPower, S from sympy.matrices.expressions.matexpr import MatrixExpr from sympy.tensor.array.expressions.array_expressions import ArrayDiagonal, ArrayTensorProduct, \ PermuteDims, ArrayAdd, ArrayContraction, ArrayElementwiseApplyFunc def convert_matrix_to_array(expr: MatrixExpr) -> Basic: if isinstance(expr, MatMul): args_nonmat = [] args = [] for arg in expr.args: if isinstance(arg, MatrixExpr): args.append(arg) else: args_nonmat.append(convert_matrix_to_array(arg)) contractions = [(2*i+1, 2*i+2) for i in range(len(args)-1)] scalar = ArrayTensorProduct.fromiter(args_nonmat) if args_nonmat else S.One if scalar == 1: tprod = ArrayTensorProduct( *[convert_matrix_to_array(arg) for arg in args]) else: tprod = ArrayTensorProduct( scalar, *[convert_matrix_to_array(arg) for arg in args]) return ArrayContraction( tprod, *contractions ) elif isinstance(expr, MatAdd): return ArrayAdd( *[convert_matrix_to_array(arg) for arg in expr.args] ) elif isinstance(expr, Transpose): return PermuteDims( convert_matrix_to_array(expr.args[0]), [1, 0] ) elif isinstance(expr, Trace): inner_expr = convert_matrix_to_array(expr.arg) return ArrayContraction(inner_expr, (0, len(inner_expr.shape) - 1)) elif isinstance(expr, Mul): return ArrayTensorProduct.fromiter(convert_matrix_to_array(i) for i in expr.args) elif isinstance(expr, Pow): base = convert_matrix_to_array(expr.base) if (expr.exp > 0) == True: return ArrayTensorProduct.fromiter(base for i in range(expr.exp)) else: return expr elif isinstance(expr, MatPow): base = convert_matrix_to_array(expr.base) if expr.exp.is_Integer != True: b = symbols("b", cls=Dummy) return ArrayElementwiseApplyFunc(Lambda(b, b**expr.exp), convert_matrix_to_array(base)) elif (expr.exp > 0) == True: return convert_matrix_to_array(MatMul.fromiter(base for i in range(expr.exp))) else: return expr elif isinstance(expr, HadamardProduct): tp = ArrayTensorProduct.fromiter([convert_matrix_to_array(arg) for arg in expr.args]) diag = [[2*i for i in range(len(expr.args))], [2*i+1 for i in range(len(expr.args))]] return ArrayDiagonal(tp, *diag) elif isinstance(expr, HadamardPower): base, exp = expr.args if exp.is_Integer and exp > 0: return convert_matrix_to_array(HadamardProduct.fromiter(base for i in range(exp))) else: raise NotImplementedError("conversion of Hadamard symbolic power is currently not supported") else: return expr
24ca4df9ba9c8646768c8fc6b018c3cce2f7a3c492391ed19220db84eb5869d2
import bisect from collections import defaultdict from sympy import Tuple, Integer def _get_mapping_from_subranks(subranks): mapping = {} counter = 0 for i, rank in enumerate(subranks): for j in range(rank): mapping[counter] = (i, j) counter += 1 return mapping def _get_contraction_links(args, subranks, *contraction_indices): mapping = _get_mapping_from_subranks(subranks) contraction_tuples = [[mapping[j] for j in i] for i in contraction_indices] dlinks = defaultdict(dict) for links in contraction_tuples: if len(links) == 2: (arg1, pos1), (arg2, pos2) = links dlinks[arg1][pos1] = (arg2, pos2) dlinks[arg2][pos2] = (arg1, pos1) continue return args, dict(dlinks) def _sort_contraction_indices(pairing_indices): pairing_indices = [Tuple(*sorted(i)) for i in pairing_indices] pairing_indices.sort(key=lambda x: min(x)) return pairing_indices def _get_diagonal_indices(flattened_indices): axes_contraction = defaultdict(list) for i, ind in enumerate(flattened_indices): if isinstance(ind, (int, Integer)): # If the indices is a number, there can be no diagonal operation: continue axes_contraction[ind].append(i) axes_contraction = {k: v for k, v in axes_contraction.items() if len(v) > 1} # Put the diagonalized indices at the end: ret_indices = [i for i in flattened_indices if i not in axes_contraction] diag_indices = list(axes_contraction) diag_indices.sort(key=lambda x: flattened_indices.index(x)) diagonal_indices = [tuple(axes_contraction[i]) for i in diag_indices] ret_indices += diag_indices ret_indices = tuple(ret_indices) return diagonal_indices, ret_indices def _get_argindex(subindices, ind): for i, sind in enumerate(subindices): if ind == sind: return i if isinstance(sind, (set, frozenset)) and ind in sind: return i raise IndexError("%s not found in %s" % (ind, subindices)) def _apply_recursively_over_nested_lists(func, arr): if isinstance(arr, (tuple, list, Tuple)): return tuple(_apply_recursively_over_nested_lists(func, i) for i in arr) elif isinstance(arr, Tuple): return Tuple.fromiter(_apply_recursively_over_nested_lists(func, i) for i in arr) else: return func(arr) def _build_push_indices_up_func_transformation(flattened_contraction_indices): shifts = {0: 0} i = 0 cumulative = 0 while i < len(flattened_contraction_indices): j = 1 while i+j < len(flattened_contraction_indices): if flattened_contraction_indices[i] + j != flattened_contraction_indices[i+j]: break j += 1 cumulative += j shifts[flattened_contraction_indices[i]] = cumulative i += j shift_keys = sorted(shifts.keys()) def func(idx): return shifts[shift_keys[bisect.bisect_right(shift_keys, idx)-1]] def transform(j): if j in flattened_contraction_indices: return None else: return j - func(j) return transform def _build_push_indices_down_func_transformation(flattened_contraction_indices): N = flattened_contraction_indices[-1]+2 shifts = [i for i in range(N) if i not in flattened_contraction_indices] def transform(j): if j < len(shifts): return shifts[j] else: return j + shifts[-1] - len(shifts) + 1 return transform
54c4c1da12f2d637692a7d1d3988af4f300dcea2ab73c02da9e3052aac049ab8
import operator from functools import reduce import itertools from itertools import accumulate from sympy import Expr, ImmutableDenseNDimArray, S, Symbol, Integer, ZeroMatrix, Basic, tensorproduct, Add, permutedims, \ Tuple, tensordiagonal, Lambda, Dummy, Function, MatrixExpr, NDimArray, Indexed, IndexedBase, default_sort_key, \ tensorcontraction, diagonalize_vector from sympy.matrices.expressions.matexpr import MatrixElement from sympy.tensor.array.expressions.utils import _apply_recursively_over_nested_lists, _sort_contraction_indices, \ _get_mapping_from_subranks, _build_push_indices_up_func_transformation, _get_contraction_links, \ _build_push_indices_down_func_transformation from sympy.combinatorics import Permutation from sympy.combinatorics.permutations import _af_invert from sympy.core.sympify import _sympify class _ArrayExpr(Expr): pass class ArraySymbol(_ArrayExpr): """ Symbol representing an array expression """ def __new__(cls, symbol, *shape): if isinstance(symbol, str): symbol = Symbol(symbol) # symbol = _sympify(symbol) shape = map(_sympify, shape) obj = Expr.__new__(cls, symbol, *shape) return obj @property def name(self): return self._args[0] @property def shape(self): return self._args[1:] def __getitem__(self, item): return ArrayElement(self, item) def as_explicit(self): if any(not isinstance(i, (int, Integer)) for i in self.shape): raise ValueError("cannot express explicit array with symbolic shape") data = [self[i] for i in itertools.product(*[range(j) for j in self.shape])] return ImmutableDenseNDimArray(data).reshape(*self.shape) class ArrayElement(_ArrayExpr): """ An element of an array. """ def __new__(cls, name, indices): if isinstance(name, str): name = Symbol(name) name = _sympify(name) indices = _sympify(indices) if hasattr(name, "shape"): if any([(i >= s) == True for i, s in zip(indices, name.shape)]): raise ValueError("shape is out of bounds") if any([(i < 0) == True for i in indices]): raise ValueError("shape contains negative values") obj = Expr.__new__(cls, name, indices) return obj @property def name(self): return self._args[0] @property def indices(self): return self._args[1] class ZeroArray(_ArrayExpr): """ Symbolic array of zeros. Equivalent to ``ZeroMatrix`` for matrices. """ def __new__(cls, *shape): if len(shape) == 0: return S.Zero shape = map(_sympify, shape) obj = Expr.__new__(cls, *shape) return obj @property def shape(self): return self._args def as_explicit(self): if any(not i.is_Integer for i in self.shape): raise ValueError("Cannot return explicit form for symbolic shape.") return ImmutableDenseNDimArray.zeros(*self.shape) class OneArray(_ArrayExpr): """ Symbolic array of ones. """ def __new__(cls, *shape): if len(shape) == 0: return S.One shape = map(_sympify, shape) obj = Expr.__new__(cls, *shape) return obj @property def shape(self): return self._args def as_explicit(self): if any(not i.is_Integer for i in self.shape): raise ValueError("Cannot return explicit form for symbolic shape.") return ImmutableDenseNDimArray([S.One for i in range(reduce(operator.mul, self.shape))]).reshape(*self.shape) class _CodegenArrayAbstract(Basic): @property def subranks(self): """ Returns the ranks of the objects in the uppermost tensor product inside the current object. In case no tensor products are contained, return the atomic ranks. Examples ======== >>> from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct, ArrayContraction >>> from sympy import MatrixSymbol >>> M = MatrixSymbol("M", 3, 3) >>> N = MatrixSymbol("N", 3, 3) >>> P = MatrixSymbol("P", 3, 3) Important: do not confuse the rank of the matrix with the rank of an array. >>> tp = ArrayTensorProduct(M, N, P) >>> tp.subranks [2, 2, 2] >>> co = ArrayContraction(tp, (1, 2), (3, 4)) >>> co.subranks [2, 2, 2] """ return self._subranks[:] def subrank(self): """ The sum of ``subranks``. """ return sum(self.subranks) @property def shape(self): return self._shape class ArrayTensorProduct(_CodegenArrayAbstract): r""" Class to represent the tensor product of array-like objects. """ def __new__(cls, *args): args = [_sympify(arg) for arg in args] args = cls._flatten(args) ranks = [get_rank(arg) for arg in args] # Check if there are nested permutation and lift them up: permutation_cycles = [] for i, arg in enumerate(args): if not isinstance(arg, PermuteDims): continue permutation_cycles.extend([[k + sum(ranks[:i]) for k in j] for j in arg.permutation.cyclic_form]) args[i] = arg.expr if permutation_cycles: return PermuteDims(ArrayTensorProduct(*args), Permutation(sum(ranks)-1)*Permutation(permutation_cycles)) if len(args) == 1: return args[0] # If any object is a ZeroArray, return a ZeroArray: if any(isinstance(arg, (ZeroArray, ZeroMatrix)) for arg in args): shapes = reduce(operator.add, [get_shape(i) for i in args], ()) return ZeroArray(*shapes) # If there are contraction objects inside, transform the whole # expression into `ArrayContraction`: contractions = {i: arg for i, arg in enumerate(args) if isinstance(arg, ArrayContraction)} if contractions: ranks = [_get_subrank(arg) if isinstance(arg, ArrayContraction) else get_rank(arg) for arg in args] cumulative_ranks = list(accumulate([0] + ranks))[:-1] tp = cls(*[arg.expr if isinstance(arg, ArrayContraction) else arg for arg in args]) contraction_indices = [tuple(cumulative_ranks[i] + k for k in j) for i, arg in contractions.items() for j in arg.contraction_indices] return ArrayContraction(tp, *contraction_indices) diagonals = {i: arg for i, arg in enumerate(args) if isinstance(arg, ArrayDiagonal)} if diagonals: permutation = [] last_perm = [] ranks = [get_rank(arg) for arg in args] cumulative_ranks = list(accumulate([0] + ranks))[:-1] for i, arg in enumerate(args): if isinstance(arg, ArrayDiagonal): i1 = get_rank(arg) - len(arg.diagonal_indices) i2 = len(arg.diagonal_indices) permutation.extend([cumulative_ranks[i] + j for j in range(i1)]) last_perm.extend([cumulative_ranks[i] + j for j in range(i1, i1 + i2)]) else: permutation.extend([cumulative_ranks[i] + j for j in range(get_rank(arg))]) permutation.extend(last_perm) tp = cls(*[arg.expr if isinstance(arg, ArrayDiagonal) else arg for arg in args]) ranks2 = [_get_subrank(arg) if isinstance(arg, ArrayDiagonal) else get_rank(arg) for arg in args] cumulative_ranks2 = list(accumulate([0] + ranks2))[:-1] diagonal_indices = [tuple(cumulative_ranks2[i] + k for k in j) for i, arg in diagonals.items() for j in arg.diagonal_indices] return PermuteDims(ArrayDiagonal(tp, *diagonal_indices), permutation) obj = Basic.__new__(cls, *args) obj._subranks = ranks shapes = [get_shape(i) for i in args] if any(i is None for i in shapes): obj._shape = None else: obj._shape = tuple(j for i in shapes for j in i) return obj @classmethod def _flatten(cls, args): args = [i for arg in args for i in (arg.args if isinstance(arg, cls) else [arg])] return args def as_explicit(self): return tensorproduct(*[arg.as_explicit() if hasattr(arg, "as_explicit") else arg for arg in self.args]) class ArrayAdd(_CodegenArrayAbstract): r""" Class for elementwise array additions. """ def __new__(cls, *args): args = [_sympify(arg) for arg in args] ranks = [get_rank(arg) for arg in args] ranks = list(set(ranks)) if len(ranks) != 1: raise ValueError("summing arrays of different ranks") shapes = [arg.shape for arg in args] if len({i for i in shapes if i is not None}) > 1: raise ValueError("mismatching shapes in addition") # Flatten: args = cls._flatten_args(args) args = [arg for arg in args if not isinstance(arg, (ZeroArray, ZeroMatrix))] if len(args) == 0: if any(i for i in shapes if i is None): raise NotImplementedError("cannot handle addition of ZeroMatrix/ZeroArray and undefined shape object") return ZeroArray(*shapes[0]) elif len(args) == 1: return args[0] obj = Basic.__new__(cls, *args) obj._subranks = ranks if any(i is None for i in shapes): obj._shape = None else: obj._shape = shapes[0] return obj @classmethod def _flatten_args(cls, args): new_args = [] for arg in args: if isinstance(arg, ArrayAdd): new_args.extend(arg.args) else: new_args.append(arg) return new_args def as_explicit(self): return Add.fromiter([arg.as_explicit() for arg in self.args]) class PermuteDims(_CodegenArrayAbstract): r""" Class to represent permutation of axes of arrays. Examples ======== >>> from sympy.tensor.array.expressions.array_expressions import PermuteDims >>> from sympy import MatrixSymbol >>> M = MatrixSymbol("M", 3, 3) >>> cg = PermuteDims(M, [1, 0]) The object ``cg`` represents the transposition of ``M``, as the permutation ``[1, 0]`` will act on its indices by switching them: `M_{ij} \Rightarrow M_{ji}` This is evident when transforming back to matrix form: >>> from sympy.tensor.array.expressions.conv_array_to_matrix import convert_array_to_matrix >>> convert_array_to_matrix(cg) M.T >>> N = MatrixSymbol("N", 3, 2) >>> cg = PermuteDims(N, [1, 0]) >>> cg.shape (2, 3) Permutations of tensor products are simplified in order to achieve a standard form: >>> from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct >>> M = MatrixSymbol("M", 4, 5) >>> tp = ArrayTensorProduct(M, N) >>> tp.shape (4, 5, 3, 2) >>> perm1 = PermuteDims(tp, [2, 3, 1, 0]) The args ``(M, N)`` have been sorted and the permutation has been simplified, the expression is equivalent: >>> perm1.expr.args (N, M) >>> perm1.shape (3, 2, 5, 4) >>> perm1.permutation (2 3) The permutation in its array form has been simplified from ``[2, 3, 1, 0]`` to ``[0, 1, 3, 2]``, as the arguments of the tensor product `M` and `N` have been switched: >>> perm1.permutation.array_form [0, 1, 3, 2] We can nest a second permutation: >>> perm2 = PermuteDims(perm1, [1, 0, 2, 3]) >>> perm2.shape (2, 3, 5, 4) >>> perm2.permutation.array_form [1, 0, 3, 2] """ def __new__(cls, expr, permutation, nest_permutation=True): from sympy.combinatorics import Permutation expr = _sympify(expr) permutation = Permutation(permutation) permutation_size = permutation.size expr_rank = get_rank(expr) if permutation_size != expr_rank: raise ValueError("Permutation size must be the length of the shape of expr") if isinstance(expr, PermuteDims): subexpr = expr.expr subperm = expr.permutation permutation = permutation * subperm expr = subexpr if isinstance(expr, ArrayContraction): expr, permutation = cls._handle_nested_contraction(expr, permutation) if isinstance(expr, ArrayTensorProduct): expr, permutation = cls._sort_components(expr, permutation) if isinstance(expr, (ZeroArray, ZeroMatrix)): return ZeroArray(*[expr.shape[i] for i in permutation.array_form]) plist = permutation.array_form if plist == sorted(plist): return expr obj = Basic.__new__(cls, expr, permutation) obj._subranks = [get_rank(expr)] shape = expr.shape if shape is None: obj._shape = None else: obj._shape = tuple(shape[permutation(i)] for i in range(len(shape))) return obj @property def expr(self): return self.args[0] @property def permutation(self): return self.args[1] @classmethod def _sort_components(cls, expr, permutation): # Get the permutation in its image-form: perm_image_form = _af_invert(permutation.array_form) args = list(expr.args) # Starting index global position for every arg: cumul = list(accumulate([0] + expr.subranks)) # Split `perm_image_form` into a list of list corresponding to the indices # of every argument: perm_image_form_in_components = [perm_image_form[cumul[i]:cumul[i+1]] for i in range(len(args))] # Create an index, target-position-key array: ps = [(i, sorted(comp)) for i, comp in enumerate(perm_image_form_in_components)] # Sort the array according to the target-position-key: # In this way, we define a canonical way to sort the arguments according # to the permutation. ps.sort(key=lambda x: x[1]) # Read the inverse-permutation (i.e. image-form) of the args: perm_args_image_form = [i[0] for i in ps] # Apply the args-permutation to the `args`: args_sorted = [args[i] for i in perm_args_image_form] # Apply the args-permutation to the array-form of the permutation of the axes (of `expr`): perm_image_form_sorted_args = [perm_image_form_in_components[i] for i in perm_args_image_form] new_permutation = Permutation(_af_invert([j for i in perm_image_form_sorted_args for j in i])) return ArrayTensorProduct(*args_sorted), new_permutation @classmethod def _handle_nested_contraction(cls, expr, permutation): if not isinstance(expr, ArrayContraction): return expr, permutation if not isinstance(expr.expr, ArrayTensorProduct): return expr, permutation args = expr.expr.args subranks = [get_rank(arg) for arg in expr.expr.args] contraction_indices = expr.contraction_indices contraction_indices_flat = [j for i in contraction_indices for j in i] cumul = list(accumulate([0] + subranks)) # Spread the permutation in its array form across the args in the corresponding # tensor-product arguments with free indices: permutation_array_blocks_up = [] image_form = _af_invert(permutation.array_form) counter = 0 for i, e in enumerate(subranks): current = [] for j in range(cumul[i], cumul[i+1]): if j in contraction_indices_flat: continue current.append(image_form[counter]) counter += 1 permutation_array_blocks_up.append(current) # Get the map of axis repositioning for every argument of tensor-product: index_blocks = [[j for j in range(cumul[i], cumul[i+1])] for i, e in enumerate(expr.subranks)] index_blocks_up = expr._push_indices_up(expr.contraction_indices, index_blocks) inverse_permutation = permutation**(-1) index_blocks_up_permuted = [[inverse_permutation(j) for j in i if j is not None] for i in index_blocks_up] # Sorting key is a list of tuple, first element is the index of `args`, second element of # the tuple is the sorting key to sort `args` of the tensor product: sorting_keys = list(enumerate(index_blocks_up_permuted)) sorting_keys.sort(key=lambda x: x[1]) # Now we can get the permutation acting on the args in its image-form: new_perm_image_form = [i[0] for i in sorting_keys] # Apply the args-level permutation to various elements: new_index_blocks = [index_blocks[i] for i in new_perm_image_form] new_index_perm_array_form = _af_invert([j for i in new_index_blocks for j in i]) new_args = [args[i] for i in new_perm_image_form] new_contraction_indices = [tuple(new_index_perm_array_form[j] for j in i) for i in contraction_indices] new_expr = ArrayContraction(ArrayTensorProduct(*new_args), *new_contraction_indices) new_permutation = Permutation(_af_invert([j for i in [permutation_array_blocks_up[k] for k in new_perm_image_form] for j in i])) return new_expr, new_permutation @classmethod def _check_permutation_mapping(cls, expr, permutation): subranks = expr.subranks index2arg = [i for i, arg in enumerate(expr.args) for j in range(expr.subranks[i])] permuted_indices = [permutation(i) for i in range(expr.subrank())] new_args = list(expr.args) arg_candidate_index = index2arg[permuted_indices[0]] current_indices = [] new_permutation = [] inserted_arg_cand_indices = set([]) for i, idx in enumerate(permuted_indices): if index2arg[idx] != arg_candidate_index: new_permutation.extend(current_indices) current_indices = [] arg_candidate_index = index2arg[idx] current_indices.append(idx) arg_candidate_rank = subranks[arg_candidate_index] if len(current_indices) == arg_candidate_rank: new_permutation.extend(sorted(current_indices)) local_current_indices = [j - min(current_indices) for j in current_indices] i1 = index2arg[i] new_args[i1] = PermuteDims(new_args[i1], Permutation(local_current_indices)) inserted_arg_cand_indices.add(arg_candidate_index) current_indices = [] new_permutation.extend(current_indices) # TODO: swap args positions in order to simplify the expression: # TODO: this should be in a function args_positions = list(range(len(new_args))) # Get possible shifts: maps = {} cumulative_subranks = [0] + list(accumulate(subranks)) for i in range(0, len(subranks)): s = set([index2arg[new_permutation[j]] for j in range(cumulative_subranks[i], cumulative_subranks[i+1])]) if len(s) != 1: continue elem = next(iter(s)) if i != elem: maps[i] = elem # Find cycles in the map: lines = [] current_line = [] while maps: if len(current_line) == 0: k, v = maps.popitem() current_line.append(k) else: k = current_line[-1] if k not in maps: current_line = [] continue v = maps.pop(k) if v in current_line: lines.append(current_line) current_line = [] continue current_line.append(v) for line in lines: for i, e in enumerate(line): args_positions[line[(i + 1) % len(line)]] = e # TODO: function in order to permute the args: permutation_blocks = [[new_permutation[cumulative_subranks[i] + j] for j in range(e)] for i, e in enumerate(subranks)] new_args = [new_args[i] for i in args_positions] new_permutation_blocks = [permutation_blocks[i] for i in args_positions] new_permutation2 = [j for i in new_permutation_blocks for j in i] return ArrayTensorProduct(*new_args), Permutation(new_permutation2) # **(-1) @classmethod def _check_if_there_are_closed_cycles(cls, expr, permutation): args = list(expr.args) subranks = expr.subranks cyclic_form = permutation.cyclic_form cumulative_subranks = [0] + list(accumulate(subranks)) cyclic_min = [min(i) for i in cyclic_form] cyclic_max = [max(i) for i in cyclic_form] cyclic_keep = [] for i, cycle in enumerate(cyclic_form): flag = True for j in range(0, len(cumulative_subranks) - 1): if cyclic_min[i] >= cumulative_subranks[j] and cyclic_max[i] < cumulative_subranks[j+1]: # Found a sinkable cycle. args[j] = PermuteDims(args[j], Permutation([[k - cumulative_subranks[j] for k in cyclic_form[i]]])) flag = False break if flag: cyclic_keep.append(cyclic_form[i]) return ArrayTensorProduct(*args), Permutation(cyclic_keep, size=permutation.size) def nest_permutation(self): r""" DEPRECATED. """ ret = self._nest_permutation(self.expr, self.permutation) if ret is None: return self return ret @classmethod def _nest_permutation(cls, expr, permutation): if isinstance(expr, ArrayTensorProduct): return PermuteDims(*cls._check_if_there_are_closed_cycles(expr, permutation)) elif isinstance(expr, ArrayContraction): # Invert tree hierarchy: put the contraction above. cycles = permutation.cyclic_form newcycles = ArrayContraction._convert_outer_indices_to_inner_indices(expr, *cycles) newpermutation = Permutation(newcycles) new_contr_indices = [tuple(newpermutation(j) for j in i) for i in expr.contraction_indices] return ArrayContraction(PermuteDims(expr.expr, newpermutation), *new_contr_indices) elif isinstance(expr, ArrayAdd): return ArrayAdd(*[PermuteDims(arg, permutation) for arg in expr.args]) return None def as_explicit(self): return permutedims(self.expr.as_explicit(), self.permutation) class ArrayDiagonal(_CodegenArrayAbstract): r""" Class to represent the diagonal operator. Explanation =========== In a 2-dimensional array it returns the diagonal, this looks like the operation: `A_{ij} \rightarrow A_{ii}` The diagonal over axes 1 and 2 (the second and third) of the tensor product of two 2-dimensional arrays `A \otimes B` is `\Big[ A_{ab} B_{cd} \Big]_{abcd} \rightarrow \Big[ A_{ai} B_{id} \Big]_{adi}` In this last example the array expression has been reduced from 4-dimensional to 3-dimensional. Notice that no contraction has occurred, rather there is a new index `i` for the diagonal, contraction would have reduced the array to 2 dimensions. Notice that the diagonalized out dimensions are added as new dimensions at the end of the indices. """ def __new__(cls, expr, *diagonal_indices): expr = _sympify(expr) diagonal_indices = [Tuple(*sorted(i)) for i in diagonal_indices] if isinstance(expr, ArrayAdd): return ArrayAdd(*[ArrayDiagonal(arg, *diagonal_indices) for arg in expr.args]) if isinstance(expr, ArrayDiagonal): return cls._flatten(expr, *diagonal_indices) if isinstance(expr, PermuteDims): return cls._handle_nested_permutedims_in_diag(expr, *diagonal_indices) shape = expr.shape if shape is not None: cls._validate(expr, *diagonal_indices) # Get new shape: positions, shape = cls._get_positions_shape(shape, diagonal_indices) else: positions = None if len(diagonal_indices) == 0: return expr if isinstance(expr, (ZeroArray, ZeroMatrix)): return ZeroArray(*shape) obj = Basic.__new__(cls, expr, *diagonal_indices) obj._positions = positions obj._subranks = _get_subranks(expr) obj._shape = shape return obj @staticmethod def _validate(expr, *diagonal_indices): # Check that no diagonalization happens on indices with mismatched # dimensions: shape = expr.shape for i in diagonal_indices: if len({shape[j] for j in i}) != 1: raise ValueError("diagonalizing indices of different dimensions") if len(i) <= 1: raise ValueError("need at least two axes to diagonalize") @staticmethod def _remove_trivial_dimensions(shape, *diagonal_indices): return [tuple(j for j in i) for i in diagonal_indices if shape[i[0]] != 1] @property def expr(self): return self.args[0] @property def diagonal_indices(self): return self.args[1:] @staticmethod def _flatten(expr, *outer_diagonal_indices): inner_diagonal_indices = expr.diagonal_indices all_inner = [j for i in inner_diagonal_indices for j in i] all_inner.sort() # TODO: add API for total rank and cumulative rank: total_rank = _get_subrank(expr) inner_rank = len(all_inner) outer_rank = total_rank - inner_rank shifts = [0 for i in range(outer_rank)] counter = 0 pointer = 0 for i in range(outer_rank): while pointer < inner_rank and counter >= all_inner[pointer]: counter += 1 pointer += 1 shifts[i] += pointer counter += 1 outer_diagonal_indices = tuple(tuple(shifts[j] + j for j in i) for i in outer_diagonal_indices) diagonal_indices = inner_diagonal_indices + outer_diagonal_indices return ArrayDiagonal(expr.expr, *diagonal_indices) @classmethod def _handle_nested_permutedims_in_diag(cls, expr: PermuteDims, *diagonal_indices): back_diagonal_indices = [[expr.permutation(j) for j in i] for i in diagonal_indices] nondiag = [i for i in range(get_rank(expr)) if not any(i in j for j in diagonal_indices)] back_nondiag = [expr.permutation(i) for i in nondiag] remap = {e: i for i, e in enumerate(sorted(back_nondiag))} new_permutation1 = [remap[i] for i in back_nondiag] shift = len(new_permutation1) diag_block_perm = [i + shift for i in range(len(back_diagonal_indices))] new_permutation = new_permutation1 + diag_block_perm return PermuteDims( ArrayDiagonal( expr.expr, *back_diagonal_indices ), new_permutation ) def _push_indices_down_nonstatic(self, indices): transform = lambda x: self._positions[x] if x < len(self._positions) else None return _apply_recursively_over_nested_lists(transform, indices) def _push_indices_up_nonstatic(self, indices): def transform(x): for i, e in enumerate(self._positions): if (isinstance(e, int) and x == e) or (isinstance(e, tuple) and x in e): return i return _apply_recursively_over_nested_lists(transform, indices) @classmethod def _push_indices_down(cls, diagonal_indices, indices, rank): positions, shape = cls._get_positions_shape(range(rank), diagonal_indices) transform = lambda x: positions[x] if x < len(positions) else None return _apply_recursively_over_nested_lists(transform, indices) @classmethod def _push_indices_up(cls, diagonal_indices, indices, rank): positions, shape = cls._get_positions_shape(range(rank), diagonal_indices) def transform(x): for i, e in enumerate(positions): if (isinstance(e, int) and x == e) or (isinstance(e, tuple) and x in e): return i return _apply_recursively_over_nested_lists(transform, indices) @classmethod def _get_positions_shape(cls, shape, diagonal_indices): data1 = tuple((i, shp) for i, shp in enumerate(shape) if not any(i in j for j in diagonal_indices)) pos1, shp1 = zip(*data1) if data1 else ((), ()) data2 = tuple((i, shape[i[0]]) for i in diagonal_indices) pos2, shp2 = zip(*data2) if data2 else ((), ()) positions = pos1 + pos2 shape = shp1 + shp2 return positions, shape def as_explicit(self): return tensordiagonal(self.expr.as_explicit(), *self.diagonal_indices) class ArrayElementwiseApplyFunc(_CodegenArrayAbstract): def __new__(cls, function, element): if not isinstance(function, Lambda): d = Dummy('d') function = Lambda(d, function(d)) obj = _CodegenArrayAbstract.__new__(cls, function, element) obj._subranks = _get_subranks(element) return obj @property def function(self): return self.args[0] @property def expr(self): return self.args[1] @property def shape(self): return self.expr.shape def _get_function_fdiff(self): d = Dummy("d") function = self.function(d) fdiff = function.diff(d) if isinstance(fdiff, Function): fdiff = type(fdiff) else: fdiff = Lambda(d, fdiff) return fdiff class ArrayContraction(_CodegenArrayAbstract): r""" This class is meant to represent contractions of arrays in a form easily processable by the code printers. """ def __new__(cls, expr, *contraction_indices, **kwargs): contraction_indices = _sort_contraction_indices(contraction_indices) expr = _sympify(expr) if len(contraction_indices) == 0: return expr if isinstance(expr, ArrayContraction): return cls._flatten(expr, *contraction_indices) if isinstance(expr, (ZeroArray, ZeroMatrix)): contraction_indices_flat = [j for i in contraction_indices for j in i] shape = [e for i, e in enumerate(expr.shape) if i not in contraction_indices_flat] return ZeroArray(*shape) if isinstance(expr, PermuteDims): return cls._handle_nested_permute_dims(expr, *contraction_indices) if isinstance(expr, ArrayTensorProduct): expr, contraction_indices = cls._sort_fully_contracted_args(expr, contraction_indices) expr, contraction_indices = cls._lower_contraction_to_addends(expr, contraction_indices) if len(contraction_indices) == 0: return expr if isinstance(expr, ArrayDiagonal): return cls._handle_nested_diagonal(expr, *contraction_indices) if isinstance(expr, ArrayAdd): return ArrayAdd(*[ArrayContraction(i, *contraction_indices) for i in expr.args]) obj = Basic.__new__(cls, expr, *contraction_indices) obj._subranks = _get_subranks(expr) obj._mapping = _get_mapping_from_subranks(obj._subranks) free_indices_to_position = {i: i for i in range(sum(obj._subranks)) if all([i not in cind for cind in contraction_indices])} obj._free_indices_to_position = free_indices_to_position shape = expr.shape cls._validate(expr, *contraction_indices) if shape: shape = tuple(shp for i, shp in enumerate(shape) if not any(i in j for j in contraction_indices)) obj._shape = shape return obj def __mul__(self, other): if other == 1: return self else: raise NotImplementedError("Product of N-dim arrays is not uniquely defined. Use another method.") def __rmul__(self, other): if other == 1: return self else: raise NotImplementedError("Product of N-dim arrays is not uniquely defined. Use another method.") @staticmethod def _validate(expr, *contraction_indices): shape = expr.shape if shape is None: return # Check that no contraction happens when the shape is mismatched: for i in contraction_indices: if len({shape[j] for j in i if shape[j] != -1}) != 1: raise ValueError("contracting indices of different dimensions") @classmethod def _push_indices_down(cls, contraction_indices, indices): flattened_contraction_indices = [j for i in contraction_indices for j in i] flattened_contraction_indices.sort() transform = _build_push_indices_down_func_transformation(flattened_contraction_indices) return _apply_recursively_over_nested_lists(transform, indices) @classmethod def _push_indices_up(cls, contraction_indices, indices): flattened_contraction_indices = [j for i in contraction_indices for j in i] flattened_contraction_indices.sort() transform = _build_push_indices_up_func_transformation(flattened_contraction_indices) return _apply_recursively_over_nested_lists(transform, indices) @classmethod def _lower_contraction_to_addends(cls, expr, contraction_indices): if isinstance(expr, ArrayAdd): raise NotImplementedError() if not isinstance(expr, ArrayTensorProduct): return expr, contraction_indices subranks = expr.subranks cumranks = list(accumulate([0] + subranks)) contraction_indices_remaining = [] contraction_indices_args = [[] for i in expr.args] backshift = set([]) for i, contraction_group in enumerate(contraction_indices): for j in range(len(expr.args)): if not isinstance(expr.args[j], ArrayAdd): continue if all(cumranks[j] <= k < cumranks[j+1] for k in contraction_group): contraction_indices_args[j].append([k - cumranks[j] for k in contraction_group]) backshift.update(contraction_group) break else: contraction_indices_remaining.append(contraction_group) if len(contraction_indices_remaining) == len(contraction_indices): return expr, contraction_indices total_rank = get_rank(expr) shifts = list(accumulate([1 if i in backshift else 0 for i in range(total_rank)])) contraction_indices_remaining = [Tuple.fromiter(j - shifts[j] for j in i) for i in contraction_indices_remaining] ret = ArrayTensorProduct(*[ ArrayContraction(arg, *contr) for arg, contr in zip(expr.args, contraction_indices_args) ]) return ret, contraction_indices_remaining def split_multiple_contractions(self): """ Recognize multiple contractions and attempt at rewriting them as paired-contractions. """ from sympy import ask, Q contraction_indices = self.contraction_indices if isinstance(self.expr, ArrayTensorProduct): args = list(self.expr.args) else: args = [self.expr] # TODO: unify API, best location in ArrayTensorProduct subranks = [get_rank(i) for i in args] # TODO: unify API mapping = _get_mapping_from_subranks(subranks) reverse_mapping = {v:k for k, v in mapping.items()} new_contraction_indices = [] for indl, links in enumerate(contraction_indices): if len(links) <= 2: new_contraction_indices.append(links) continue # Check multiple contractions: # # Examples: # # * `A_ij b_j0 C_jk` ===> `A*DiagMatrix(b)*C` # # Care for: # - matrix being diagonalized (i.e. `A_ii`) # - vectors being diagonalized (i.e. `a_i0`) # Also consider the case of diagonal matrices being contracted: current_dimension = self.expr.shape[links[0]] tuple_links = [mapping[i] for i in links] arg_indices, arg_positions = zip(*tuple_links) args_updates = {} if len(arg_indices) != len(set(arg_indices)): # Maybe trace should be supported? raise NotImplementedError() not_vectors = [] vectors = [] for arg_ind, arg_pos in tuple_links: mat = args[arg_ind] other_arg_pos = 1-arg_pos other_arg_abs = reverse_mapping[arg_ind, other_arg_pos] if (((1 not in mat.shape) and (not ask(Q.diagonal(mat)))) or ((current_dimension == 1) is True and mat.shape != (1, 1)) or any([other_arg_abs in l for li, l in enumerate(contraction_indices) if li != indl]) ): not_vectors.append((arg_ind, arg_pos)) continue args_updates[arg_ind] = diagonalize_vector(mat) vectors.append((arg_ind, arg_pos)) vectors.append((arg_ind, 1-arg_pos)) if len(not_vectors) > 2: new_contraction_indices.append(links) continue if len(not_vectors) == 0: new_sequence = vectors[:1] + vectors[2:] elif len(not_vectors) == 1: new_sequence = not_vectors[:1] + vectors[:-1] else: new_sequence = not_vectors[:1] + vectors + not_vectors[1:] for i in range(0, len(new_sequence) - 1, 2): arg1, pos1 = new_sequence[i] arg2, pos2 = new_sequence[i+1] if arg1 == arg2: raise NotImplementedError continue abspos1 = reverse_mapping[arg1, pos1] abspos2 = reverse_mapping[arg2, pos2] new_contraction_indices.append((abspos1, abspos2)) for ind, newarg in args_updates.items(): args[ind] = newarg return ArrayContraction( ArrayTensorProduct(*args), *new_contraction_indices ) def flatten_contraction_of_diagonal(self): if not isinstance(self.expr, ArrayDiagonal): return self contraction_down = self.expr._push_indices_down(self.expr.diagonal_indices, self.contraction_indices) new_contraction_indices = [] diagonal_indices = self.expr.diagonal_indices[:] for i in contraction_down: contraction_group = list(i) for j in i: diagonal_with = [k for k in diagonal_indices if j in k] contraction_group.extend([l for k in diagonal_with for l in k]) diagonal_indices = [k for k in diagonal_indices if k not in diagonal_with] new_contraction_indices.append(sorted(set(contraction_group))) new_contraction_indices = ArrayDiagonal._push_indices_up(diagonal_indices, new_contraction_indices) return ArrayContraction( ArrayDiagonal( self.expr.expr, *diagonal_indices ), *new_contraction_indices ) @staticmethod def _get_free_indices_to_position_map(free_indices, contraction_indices): free_indices_to_position = {} flattened_contraction_indices = [j for i in contraction_indices for j in i] counter = 0 for ind in free_indices: while counter in flattened_contraction_indices: counter += 1 free_indices_to_position[ind] = counter counter += 1 return free_indices_to_position @staticmethod def _get_index_shifts(expr): """ Get the mapping of indices at the positions before the contraction occurs. Examples ======== >>> from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct >>> from sympy.tensor.array.expressions.array_expressions import ArrayContraction >>> from sympy import MatrixSymbol >>> M = MatrixSymbol("M", 3, 3) >>> N = MatrixSymbol("N", 3, 3) >>> cg = ArrayContraction(ArrayTensorProduct(M, N), [1, 2]) >>> cg._get_index_shifts(cg) [0, 2] Indeed, ``cg`` after the contraction has two dimensions, 0 and 1. They need to be shifted by 0 and 2 to get the corresponding positions before the contraction (that is, 0 and 3). """ inner_contraction_indices = expr.contraction_indices all_inner = [j for i in inner_contraction_indices for j in i] all_inner.sort() # TODO: add API for total rank and cumulative rank: total_rank = _get_subrank(expr) inner_rank = len(all_inner) outer_rank = total_rank - inner_rank shifts = [0 for i in range(outer_rank)] counter = 0 pointer = 0 for i in range(outer_rank): while pointer < inner_rank and counter >= all_inner[pointer]: counter += 1 pointer += 1 shifts[i] += pointer counter += 1 return shifts @staticmethod def _convert_outer_indices_to_inner_indices(expr, *outer_contraction_indices): shifts = ArrayContraction._get_index_shifts(expr) outer_contraction_indices = tuple(tuple(shifts[j] + j for j in i) for i in outer_contraction_indices) return outer_contraction_indices @staticmethod def _flatten(expr, *outer_contraction_indices): inner_contraction_indices = expr.contraction_indices outer_contraction_indices = ArrayContraction._convert_outer_indices_to_inner_indices(expr, *outer_contraction_indices) contraction_indices = inner_contraction_indices + outer_contraction_indices return ArrayContraction(expr.expr, *contraction_indices) @classmethod def _handle_nested_permute_dims(cls, expr, *contraction_indices): permutation = expr.permutation plist = permutation.array_form new_contraction_indices = [tuple(permutation(j) for j in i) for i in contraction_indices] new_plist = [i for i in plist if all(i not in j for j in new_contraction_indices)] new_plist = cls._push_indices_up(new_contraction_indices, new_plist) return PermuteDims( ArrayContraction(expr.expr, *new_contraction_indices), Permutation(new_plist) ) @classmethod def _handle_nested_diagonal(cls, expr: 'ArrayDiagonal', *contraction_indices): diagonal_indices = list(expr.diagonal_indices) down_contraction_indices = expr._push_indices_down(expr.diagonal_indices, contraction_indices, get_rank(expr.expr)) # Flatten diagonally contracted indices: down_contraction_indices = [[k for j in i for k in (j if isinstance(j, (tuple, Tuple)) else [j])] for i in down_contraction_indices] new_contraction_indices = [] for contr_indgrp in down_contraction_indices: ind = contr_indgrp[:] for j, diag_indgrp in enumerate(diagonal_indices): if diag_indgrp is None: continue if any(i in diag_indgrp for i in contr_indgrp): ind.extend(diag_indgrp) diagonal_indices[j] = None new_contraction_indices.append(sorted(set(ind))) new_diagonal_indices_down = [i for i in diagonal_indices if i is not None] new_diagonal_indices = ArrayContraction._push_indices_up(new_contraction_indices, new_diagonal_indices_down) return ArrayDiagonal( ArrayContraction(expr.expr, *new_contraction_indices), *new_diagonal_indices ) @classmethod def _sort_fully_contracted_args(cls, expr, contraction_indices): if expr.shape is None: return expr, contraction_indices cumul = list(accumulate([0] + expr.subranks)) index_blocks = [list(range(cumul[i], cumul[i+1])) for i in range(len(expr.args))] contraction_indices_flat = {j for i in contraction_indices for j in i} fully_contracted = [all(j in contraction_indices_flat for j in range(cumul[i], cumul[i+1])) for i, arg in enumerate(expr.args)] new_pos = sorted(range(len(expr.args)), key=lambda x: (0, default_sort_key(expr.args[x])) if fully_contracted[x] else (1,)) new_args = [expr.args[i] for i in new_pos] new_index_blocks_flat = [j for i in new_pos for j in index_blocks[i]] index_permutation_array_form = _af_invert(new_index_blocks_flat) new_contraction_indices = [tuple(index_permutation_array_form[j] for j in i) for i in contraction_indices] new_contraction_indices = _sort_contraction_indices(new_contraction_indices) return ArrayTensorProduct(*new_args), new_contraction_indices def _get_contraction_tuples(self): r""" Return tuples containing the argument index and position within the argument of the index position. Examples ======== >>> from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct >>> from sympy import MatrixSymbol >>> from sympy.abc import N >>> from sympy.tensor.array.expressions.array_expressions import ArrayContraction >>> A = MatrixSymbol("A", N, N) >>> B = MatrixSymbol("B", N, N) >>> cg = ArrayContraction(ArrayTensorProduct(A, B), (1, 2)) >>> cg._get_contraction_tuples() [[(0, 1), (1, 0)]] Notes ===== Here the contraction pair `(1, 2)` meaning that the 2nd and 3rd indices of the tensor product `A\otimes B` are contracted, has been transformed into `(0, 1)` and `(1, 0)`, identifying the same indices in a different notation. `(0, 1)` is the second index (1) of the first argument (i.e. 0 or `A`). `(1, 0)` is the first index (i.e. 0) of the second argument (i.e. 1 or `B`). """ mapping = self._mapping return [[mapping[j] for j in i] for i in self.contraction_indices] @staticmethod def _contraction_tuples_to_contraction_indices(expr, contraction_tuples): # TODO: check that `expr` has `.subranks`: ranks = expr.subranks cumulative_ranks = [0] + list(accumulate(ranks)) return [tuple(cumulative_ranks[j]+k for j, k in i) for i in contraction_tuples] @property def free_indices(self): return self._free_indices[:] @property def free_indices_to_position(self): return dict(self._free_indices_to_position) @property def expr(self): return self.args[0] @property def contraction_indices(self): return self.args[1:] def _contraction_indices_to_components(self): expr = self.expr if not isinstance(expr, ArrayTensorProduct): raise NotImplementedError("only for contractions of tensor products") ranks = expr.subranks mapping = {} counter = 0 for i, rank in enumerate(ranks): for j in range(rank): mapping[counter] = (i, j) counter += 1 return mapping def sort_args_by_name(self): """ Sort arguments in the tensor product so that their order is lexicographical. Examples ======== >>> from sympy.tensor.array.expressions.conv_matrix_to_array import convert_matrix_to_array >>> from sympy import MatrixSymbol >>> from sympy.abc import N >>> A = MatrixSymbol("A", N, N) >>> B = MatrixSymbol("B", N, N) >>> C = MatrixSymbol("C", N, N) >>> D = MatrixSymbol("D", N, N) >>> cg = convert_matrix_to_array(C*D*A*B) >>> cg ArrayContraction(ArrayTensorProduct(A, D, C, B), (0, 3), (1, 6), (2, 5)) >>> cg.sort_args_by_name() ArrayContraction(ArrayTensorProduct(A, D, B, C), (0, 3), (1, 4), (2, 7)) """ expr = self.expr if not isinstance(expr, ArrayTensorProduct): return self args = expr.args sorted_data = sorted(enumerate(args), key=lambda x: default_sort_key(x[1])) pos_sorted, args_sorted = zip(*sorted_data) reordering_map = {i: pos_sorted.index(i) for i, arg in enumerate(args)} contraction_tuples = self._get_contraction_tuples() contraction_tuples = [[(reordering_map[j], k) for j, k in i] for i in contraction_tuples] c_tp = ArrayTensorProduct(*args_sorted) new_contr_indices = self._contraction_tuples_to_contraction_indices( c_tp, contraction_tuples ) return ArrayContraction(c_tp, *new_contr_indices) def _get_contraction_links(self): r""" Returns a dictionary of links between arguments in the tensor product being contracted. See the example for an explanation of the values. Examples ======== >>> from sympy import MatrixSymbol >>> from sympy.abc import N >>> from sympy.tensor.array.expressions.conv_matrix_to_array import convert_matrix_to_array >>> A = MatrixSymbol("A", N, N) >>> B = MatrixSymbol("B", N, N) >>> C = MatrixSymbol("C", N, N) >>> D = MatrixSymbol("D", N, N) Matrix multiplications are pairwise contractions between neighboring matrices: `A_{ij} B_{jk} C_{kl} D_{lm}` >>> cg = convert_matrix_to_array(A*B*C*D) >>> cg ArrayContraction(ArrayTensorProduct(B, C, A, D), (0, 5), (1, 2), (3, 6)) >>> cg._get_contraction_links() {0: {0: (2, 1), 1: (1, 0)}, 1: {0: (0, 1), 1: (3, 0)}, 2: {1: (0, 0)}, 3: {0: (1, 1)}} This dictionary is interpreted as follows: argument in position 0 (i.e. matrix `A`) has its second index (i.e. 1) contracted to `(1, 0)`, that is argument in position 1 (matrix `B`) on the first index slot of `B`, this is the contraction provided by the index `j` from `A`. The argument in position 1 (that is, matrix `B`) has two contractions, the ones provided by the indices `j` and `k`, respectively the first and second indices (0 and 1 in the sub-dict). The link `(0, 1)` and `(2, 0)` respectively. `(0, 1)` is the index slot 1 (the 2nd) of argument in position 0 (that is, `A_{\ldot j}`), and so on. """ args, dlinks = _get_contraction_links([self], self.subranks, *self.contraction_indices) return dlinks def as_explicit(self): return tensorcontraction(self.expr.as_explicit(), *self.contraction_indices) def get_rank(expr): if isinstance(expr, (MatrixExpr, MatrixElement)): return 2 if isinstance(expr, _CodegenArrayAbstract): return len(expr.shape) if isinstance(expr, NDimArray): return expr.rank() if isinstance(expr, Indexed): return expr.rank if isinstance(expr, IndexedBase): shape = expr.shape if shape is None: return -1 else: return len(shape) if hasattr(expr, "shape"): return len(expr.shape) return 0 def _get_subrank(expr): if isinstance(expr, _CodegenArrayAbstract): return expr.subrank() return get_rank(expr) def _get_subranks(expr): if isinstance(expr, _CodegenArrayAbstract): return expr.subranks else: return [get_rank(expr)] def get_shape(expr): if hasattr(expr, "shape"): return expr.shape return () def nest_permutation(expr): if isinstance(expr, PermuteDims): return expr.nest_permutation() else: return expr
e4fa93730e54beaed8274f49af2b642b84ff4fcac152a952411d92da5b99c038
import operator from functools import reduce, singledispatch from sympy import Expr, Transpose, Identity, MatrixSymbol, S, Inverse, MatrixExpr, HadamardProduct from sympy.combinatorics.permutations import _af_invert from sympy.matrices.expressions.applyfunc import ElementwiseApplyFunction from sympy.tensor.array.expressions.array_expressions import ZeroArray, ArraySymbol, ArrayTensorProduct, \ ArrayAdd, PermuteDims, ArrayDiagonal, ArrayElementwiseApplyFunc, get_rank, \ get_shape, ArrayContraction from sympy.tensor.array.expressions.conv_matrix_to_array import convert_matrix_to_array @singledispatch def array_derive(expr, x): raise NotImplementedError(f"not implemented for type {type(expr)}") @array_derive.register(Expr) def _(expr: Expr, x: Expr): return ZeroArray(*x.shape) @array_derive.register(ArrayTensorProduct) def _(expr: ArrayTensorProduct, x: Expr): args = expr.args addend_list = [] for i, arg in enumerate(expr.args): darg = array_derive(arg, x) if darg == 0: continue args_prev = args[:i] args_succ = args[i+1:] shape_prev = reduce(operator.add, map(get_shape, args_prev), ()) shape_succ = reduce(operator.add, map(get_shape, args_succ), ()) addend = ArrayTensorProduct(*args_prev, darg, *args_succ) tot1 = len(get_shape(x)) tot2 = tot1 + len(shape_prev) tot3 = tot2 + len(get_shape(arg)) tot4 = tot3 + len(shape_succ) perm = [i for i in range(tot1, tot2)] + \ [i for i in range(tot1)] + [i for i in range(tot2, tot3)] + \ [i for i in range(tot3, tot4)] addend = PermuteDims(addend, _af_invert(perm)) addend_list.append(addend) if len(addend_list) == 1: return addend_list[0] elif len(addend_list) == 0: return S.Zero else: return ArrayAdd(*addend_list) @array_derive.register(ArraySymbol) def _(expr: ArraySymbol, x: Expr): if expr == x: return PermuteDims( ArrayTensorProduct.fromiter(Identity(i) for i in expr.shape), [2*i for i in range(len(expr.shape))] + [2*i+1 for i in range(len(expr.shape))] ) return ZeroArray(*(x.shape + expr.shape)) @array_derive.register(MatrixSymbol) def _(expr: MatrixSymbol, x: Expr): m, n = expr.shape if expr == x: return PermuteDims( ArrayTensorProduct(Identity(m), Identity(n)), [0, 2, 1, 3] ) return ZeroArray(*(x.shape + expr.shape)) @array_derive.register(Identity) def _(expr: Identity, x: Expr): return ZeroArray(*(x.shape + expr.shape)) @array_derive.register(Transpose) def _(expr: Transpose, x: Expr): # D(A.T, A) ==> (m,n,i,j) ==> D(A_ji, A_mn) = d_mj d_ni # D(B.T, A) ==> (m,n,i,j) ==> D(B_ji, A_mn) fd = array_derive(expr.arg, x) return PermuteDims(fd, [0, 1, 3, 2]) @array_derive.register(Inverse) def _(expr: Inverse, x: Expr): mat = expr.I dexpr = array_derive(mat, x) tp = ArrayTensorProduct(-expr, dexpr, expr) mp = ArrayContraction(tp, (1, 4), (5, 6)) pp = PermuteDims(mp, [1, 2, 0, 3]) return pp @array_derive.register(ElementwiseApplyFunction) def _(expr: ElementwiseApplyFunction, x: Expr): assert get_rank(expr) == 2 assert get_rank(x) == 2 fdiff = expr._get_function_fdiff() dexpr = array_derive(expr.expr, x) tp = ArrayTensorProduct( ElementwiseApplyFunction(fdiff, expr.expr), dexpr ) td = ArrayDiagonal( tp, (0, 4), (1, 5) ) return td @array_derive.register(ArrayElementwiseApplyFunc) def _(expr: ArrayElementwiseApplyFunc, x: Expr): fdiff = expr._get_function_fdiff() subexpr = expr.expr dsubexpr = array_derive(subexpr, x) tp = ArrayTensorProduct( dsubexpr, ArrayElementwiseApplyFunc(fdiff, subexpr) ) b = get_rank(x) c = get_rank(expr) diag_indices = [(b + i, b + c + i) for i in range(c)] return ArrayDiagonal(tp, *diag_indices) @array_derive.register(MatrixExpr) def _(expr: MatrixExpr, x: Expr): cg = convert_matrix_to_array(expr) return array_derive(cg, x) @array_derive.register(HadamardProduct) def _(expr: HadamardProduct, x: Expr): raise NotImplementedError() @array_derive.register(ArrayContraction) def _(expr: ArrayContraction, x: Expr): fd = array_derive(expr.expr, x) rank_x = len(get_shape(x)) contraction_indices = expr.contraction_indices new_contraction_indices = [tuple(j + rank_x for j in i) for i in contraction_indices] return ArrayContraction(fd, *new_contraction_indices) @array_derive.register(ArrayDiagonal) def _(expr: ArrayDiagonal, x: Expr): dsubexpr = array_derive(expr.expr, x) rank_x = len(get_shape(x)) diag_indices = [[j + rank_x for j in i] for i in expr.diagonal_indices] return ArrayDiagonal(dsubexpr, *diag_indices) @array_derive.register(ArrayAdd) def _(expr: ArrayAdd, x: Expr): return ArrayAdd(*[array_derive(arg, x) for arg in expr.args]) @array_derive.register(PermuteDims) def _(expr: PermuteDims, x: Expr): de = array_derive(expr.expr, x) perm = [0, 1] + [i + 2 for i in expr.permutation.array_form] return PermuteDims(de, perm) def matrix_derive(expr, x): from sympy.tensor.array.expressions.conv_array_to_matrix import convert_array_to_matrix ce = convert_matrix_to_array(expr) dce = array_derive(ce, x) return convert_array_to_matrix(dce).doit()
dae68711529a978d7b2c060348923515bd3a0d2e76a663ef77e49f3d0e5caed0
from sympy import ( symbols, Identity, cos, ZeroMatrix) from sympy.tensor.array.expressions.conv_matrix_to_array import convert_matrix_to_array from sympy.tensor.array.expressions.conv_array_to_matrix import _support_function_tp1_recognize, \ _array_diag2contr_diagmatrix, convert_array_to_matrix, _remove_trivial_dims, _array2matrix from sympy import MatrixSymbol from sympy.combinatorics import Permutation from sympy.matrices.expressions.diagonal import DiagMatrix from sympy.matrices import Trace, MatMul, Transpose from sympy.tensor.array.expressions.array_expressions import ZeroArray, OneArray, \ ArrayTensorProduct, ArrayAdd, PermuteDims, ArrayDiagonal, \ ArrayContraction from sympy.testing.pytest import raises i, j, k, l, m, n = symbols("i j k l m n") I = Identity(k) I1 = Identity(1) M = MatrixSymbol("M", k, k) N = MatrixSymbol("N", k, k) P = MatrixSymbol("P", k, k) Q = MatrixSymbol("Q", k, k) A = MatrixSymbol("A", k, k) B = MatrixSymbol("B", k, k) C = MatrixSymbol("C", k, k) D = MatrixSymbol("D", k, k) X = MatrixSymbol("X", k, k) Y = MatrixSymbol("Y", k, k) a = MatrixSymbol("a", k, 1) b = MatrixSymbol("b", k, 1) c = MatrixSymbol("c", k, 1) d = MatrixSymbol("d", k, 1) x = MatrixSymbol("x", k, 1) def test_arrayexpr_convert_array_to_matrix(): cg = ArrayContraction(ArrayTensorProduct(M), (0, 1)) assert convert_array_to_matrix(cg) == Trace(M) cg = ArrayContraction(ArrayTensorProduct(M, N), (0, 1), (2, 3)) assert convert_array_to_matrix(cg) == Trace(M) * Trace(N) cg = ArrayContraction(ArrayTensorProduct(M, N), (0, 3), (1, 2)) assert convert_array_to_matrix(cg) == Trace(M * N) cg = ArrayContraction(ArrayTensorProduct(M, N), (0, 2), (1, 3)) assert convert_array_to_matrix(cg) == Trace(M * N.T) cg = convert_matrix_to_array(M * N * P) assert convert_array_to_matrix(cg) == M * N * P cg = convert_matrix_to_array(M * N.T * P) assert convert_array_to_matrix(cg) == M * N.T * P cg = ArrayContraction(ArrayTensorProduct(M,N,P,Q), (1, 2), (5, 6)) assert convert_array_to_matrix(cg) == ArrayTensorProduct(M * N, P * Q) cg = ArrayContraction(ArrayTensorProduct(-2, M, N), (1, 2)) assert convert_array_to_matrix(cg) == -2 * M * N a = MatrixSymbol("a", k, 1) b = MatrixSymbol("b", k, 1) c = MatrixSymbol("c", k, 1) cg = PermuteDims( ArrayContraction( ArrayTensorProduct( a, ArrayAdd( ArrayTensorProduct(b, c), ArrayTensorProduct(c, b), ) ), (2, 4)), [0, 1, 3, 2]) assert convert_array_to_matrix(cg) == a * (b.T * c + c.T * b) za = ZeroArray(m, n) assert convert_array_to_matrix(za) == ZeroMatrix(m, n) cg = ArrayTensorProduct(3, M) assert convert_array_to_matrix(cg) == 3 * M # TODO: not yet supported: # cg = ArrayDiagonal(ArrayTensorProduct(M, N, P), (0, 2, 4), (1, 3, 5)) # assert recognize_matrix_expression(cg) == HadamardProduct(M, N, P) # cg = ArrayDiagonal(ArrayTensorProduct(M, N, P), (0, 3, 4), (1, 2, 5)) # assert recognize_matrix_expression(cg) == HadamardProduct(M, N.T, P) x = MatrixSymbol("x", k, 1) cg = PermuteDims( ArrayContraction(ArrayTensorProduct(OneArray(1), x, OneArray(1), DiagMatrix(Identity(1))), (0, 5)), Permutation(1, 2, 3)) assert convert_array_to_matrix(cg) == x expr = ArrayAdd(M, PermuteDims(M, [1, 0])) assert convert_array_to_matrix(expr) == M + Transpose(M) def test_arrayexpr_convert_array_to_matrix2(): cg = ArrayContraction(ArrayTensorProduct(M, N), (1, 3)) assert convert_array_to_matrix(cg) == M * N.T cg = PermuteDims(ArrayTensorProduct(M, N), Permutation([0, 1, 3, 2])) assert convert_array_to_matrix(cg) == ArrayTensorProduct(M, N.T) cg = ArrayTensorProduct(M, PermuteDims(N, Permutation([1, 0]))) assert convert_array_to_matrix(cg) == ArrayTensorProduct(M, N.T) cg = ArrayContraction( PermuteDims( ArrayTensorProduct(M, N, P, Q), Permutation([0, 2, 3, 1, 4, 5, 7, 6])), (1, 2), (3, 5) ) assert convert_array_to_matrix(cg) == ArrayTensorProduct(M * P.T * Trace(N), Q.T) cg = ArrayContraction( ArrayTensorProduct(M, N, P, PermuteDims(Q, Permutation([1, 0]))), (1, 5), (2, 3) ) assert convert_array_to_matrix(cg) == ArrayTensorProduct(M * P.T * Trace(N), Q.T) cg = ArrayTensorProduct(M, PermuteDims(N, [1, 0])) assert convert_array_to_matrix(cg) == ArrayTensorProduct(M, N.T) cg = ArrayTensorProduct(PermuteDims(M, [1, 0]), PermuteDims(N, [1, 0])) assert convert_array_to_matrix(cg) == ArrayTensorProduct(M.T, N.T) cg = ArrayTensorProduct(PermuteDims(N, [1, 0]), PermuteDims(M, [1, 0])) assert convert_array_to_matrix(cg) == ArrayTensorProduct(N.T, M.T) def test_arrayexpr_convert_array_to_diagonalized_vector(): # Check matrix recognition over trivial dimensions: cg = ArrayTensorProduct(a, b) assert convert_array_to_matrix(cg) == a * b.T cg = ArrayTensorProduct(I1, a, b) assert convert_array_to_matrix(cg) == a * b.T # Recognize trace inside a tensor product: cg = ArrayContraction(ArrayTensorProduct(A, B, C), (0, 3), (1, 2)) assert convert_array_to_matrix(cg) == Trace(A * B) * C # Transform diagonal operator to contraction: cg = ArrayDiagonal(ArrayTensorProduct(A, a), (1, 2)) assert _array_diag2contr_diagmatrix(cg) == ArrayContraction(ArrayTensorProduct(A, OneArray(1), DiagMatrix(a)), (1, 3)) assert convert_array_to_matrix(cg) == A * DiagMatrix(a) cg = ArrayDiagonal(ArrayTensorProduct(a, b), (0, 2)) assert _array_diag2contr_diagmatrix(cg) == PermuteDims( ArrayContraction(ArrayTensorProduct(DiagMatrix(a), OneArray(1), b), (0, 3)), [1, 2, 0] ) assert convert_array_to_matrix(cg) == b.T * DiagMatrix(a) cg = ArrayDiagonal(ArrayTensorProduct(A, a), (0, 2)) assert _array_diag2contr_diagmatrix(cg) == ArrayContraction(ArrayTensorProduct(A, OneArray(1), DiagMatrix(a)), (0, 3)) assert convert_array_to_matrix(cg) == A.T * DiagMatrix(a) cg = ArrayDiagonal(ArrayTensorProduct(I, x, I1), (0, 2), (3, 5)) assert _array_diag2contr_diagmatrix(cg) == ArrayContraction(ArrayTensorProduct(I, OneArray(1), I1, DiagMatrix(x)), (0, 5)) assert convert_array_to_matrix(cg) == DiagMatrix(x) cg = ArrayDiagonal(ArrayTensorProduct(I, x, A, B), (1, 2), (5, 6)) assert _array_diag2contr_diagmatrix(cg) == ArrayDiagonal(ArrayContraction(ArrayTensorProduct(I, OneArray(1), A, B, DiagMatrix(x)), (1, 7)), (5, 6)) # TODO: not yet working # assert recognize_matrix_expression(cg) cg = ArrayDiagonal(ArrayTensorProduct(x, I1), (1, 2)) assert isinstance(cg, ArrayDiagonal) assert cg.diagonal_indices == ((1, 2),) assert convert_array_to_matrix(cg) == x cg = ArrayDiagonal(ArrayTensorProduct(x, I), (0, 2)) assert _array_diag2contr_diagmatrix(cg) == ArrayContraction(ArrayTensorProduct(OneArray(1), I, DiagMatrix(x)), (1, 3)) assert convert_array_to_matrix(cg).doit() == DiagMatrix(x) raises(ValueError, lambda: ArrayDiagonal(x, (1,))) # Ignore identity matrices with contractions: cg = ArrayContraction(ArrayTensorProduct(I, A, I, I), (0, 2), (1, 3), (5, 7)) assert cg.split_multiple_contractions() == cg assert convert_array_to_matrix(cg) == Trace(A) * I cg = ArrayContraction(ArrayTensorProduct(Trace(A) * I, I, I), (1, 5), (3, 4)) assert cg.split_multiple_contractions() == cg assert convert_array_to_matrix(cg).doit() == Trace(A) * I # Add DiagMatrix when required: cg = ArrayContraction(ArrayTensorProduct(A, a), (1, 2)) assert cg.split_multiple_contractions() == cg assert convert_array_to_matrix(cg) == A * a cg = ArrayContraction(ArrayTensorProduct(A, a, B), (1, 2, 4)) assert cg.split_multiple_contractions() == ArrayContraction(ArrayTensorProduct(A, DiagMatrix(a), B), (1, 2), (3, 4)) assert convert_array_to_matrix(cg) == A * DiagMatrix(a) * B cg = ArrayContraction(ArrayTensorProduct(A, a, B), (0, 2, 4)) assert cg.split_multiple_contractions() == ArrayContraction(ArrayTensorProduct(A, DiagMatrix(a), B), (0, 2), (3, 4)) assert convert_array_to_matrix(cg) == A.T * DiagMatrix(a) * B cg = ArrayContraction(ArrayTensorProduct(A, a, b, a.T, B), (0, 2, 4, 7, 9)) assert cg.split_multiple_contractions() == ArrayContraction(ArrayTensorProduct(A, DiagMatrix(a), DiagMatrix(b), DiagMatrix(a), B), (0, 2), (3, 4), (5, 7), (6, 9)) assert convert_array_to_matrix(cg).doit() == A.T * DiagMatrix(a) * DiagMatrix(b) * DiagMatrix(a) * B.T cg = ArrayContraction(ArrayTensorProduct(I1, I1, I1), (1, 2, 4)) assert cg.split_multiple_contractions() == ArrayContraction(ArrayTensorProduct(I1, I1, I1), (1, 2), (3, 4)) assert convert_array_to_matrix(cg).doit() == Identity(1) cg = ArrayContraction(ArrayTensorProduct(I, I, I, I, A), (1, 2, 8), (5, 6, 9)) assert convert_array_to_matrix(cg.split_multiple_contractions()).doit() == A cg = ArrayContraction(ArrayTensorProduct(A, a, C, a, B), (1, 2, 4), (5, 6, 8)) expected = ArrayContraction(ArrayTensorProduct(DiagMatrix(a), DiagMatrix(a), C, A, B), (0, 4), (1, 7), (2, 5), (3, 8)) assert cg.split_multiple_contractions() == expected assert convert_array_to_matrix(cg) == A * DiagMatrix(a) * C * DiagMatrix(a) * B cg = ArrayContraction(ArrayTensorProduct(a, I1, b, I1, (a.T*b).applyfunc(cos)), (1, 2, 8), (5, 6, 9)) assert cg.split_multiple_contractions().dummy_eq(ArrayContraction(ArrayTensorProduct((a.T * b).applyfunc(cos), I1, I1, a, b), (0, 2), (1, 4), (3, 7), (5, 9))) assert convert_array_to_matrix(cg).doit().dummy_eq(MatMul(a, (a.T * b).applyfunc(cos), b.T)) def test_arrayexpr_convert_array_contraction_tp_additions(): a = ArrayAdd( ArrayTensorProduct(M, N), ArrayTensorProduct(N, M) ) tp = ArrayTensorProduct(P, a, Q) expr = ArrayContraction(tp, (3, 4)) expected = ArrayTensorProduct( P, ArrayAdd( ArrayContraction(ArrayTensorProduct(M, N), (1, 2)), ArrayContraction(ArrayTensorProduct(N, M), (1, 2)), ), Q ) assert expr == expected assert convert_array_to_matrix(expr) == ArrayTensorProduct(P, M * N + N * M, Q) expr = ArrayContraction(tp, (1, 2), (3, 4), (5, 6)) result = ArrayContraction( ArrayTensorProduct( P, ArrayAdd( ArrayContraction(ArrayTensorProduct(M, N), (1, 2)), ArrayContraction(ArrayTensorProduct(N, M), (1, 2)), ), Q ), (1, 2), (3, 4)) assert expr == result assert convert_array_to_matrix(expr) == P * (M * N + N * M) * Q def test_arrayexpr_convert_array_to_implicit_matmul(): # Trivial dimensions are suppressed, so the result can be expressed in matrix form: cg = ArrayTensorProduct(a, b) assert convert_array_to_matrix(cg) == a * b.T cg = ArrayTensorProduct(a, I, b) assert convert_array_to_matrix(cg) == a * b.T cg = ArrayContraction(ArrayTensorProduct(I, I), (1, 2)) assert convert_array_to_matrix(cg) == I cg = PermuteDims(ArrayTensorProduct(I, Identity(1)), [0, 2, 1, 3]) assert convert_array_to_matrix(cg) == I def test_arrayexpr_convert_array_to_matrix_remove_trivial_dims(): # Tensor Product: assert _remove_trivial_dims(ArrayTensorProduct(a, b)) == (a * b.T, [1, 3]) assert _remove_trivial_dims(ArrayTensorProduct(a.T, b)) == (a * b.T, [0, 3]) assert _remove_trivial_dims(ArrayTensorProduct(a, b.T)) == (a * b.T, [1, 2]) assert _remove_trivial_dims(ArrayTensorProduct(a.T, b.T)) == (a * b.T, [0, 2]) assert _remove_trivial_dims(ArrayTensorProduct(I, a.T, b.T)) == (a * b.T, [0, 1, 2, 4]) assert _remove_trivial_dims(ArrayTensorProduct(a.T, I, b.T)) == (a * b.T, [0, 2, 3, 4]) assert _remove_trivial_dims(ArrayTensorProduct(a, I)) == (a, [2, 3]) assert _remove_trivial_dims(ArrayTensorProduct(I, a)) == (a, [0, 1]) assert _remove_trivial_dims(ArrayTensorProduct(a.T, b.T, c, d)) == ( ArrayTensorProduct(a * b.T, c * d.T), [0, 2, 5, 7]) assert _remove_trivial_dims(ArrayTensorProduct(a.T, I, b.T, c, d, I)) == ( ArrayTensorProduct(a * b.T, c * d.T, I), [0, 2, 3, 4, 7, 9]) # Addition: cg = ArrayAdd(ArrayTensorProduct(a, b), ArrayTensorProduct(c, d)) assert _remove_trivial_dims(cg) == (a * b.T + c * d.T, [1, 3]) # Permute Dims: cg = PermuteDims(ArrayTensorProduct(a, b), Permutation(3)(1, 2)) assert _remove_trivial_dims(cg) == (a * b.T, [2, 3]) cg = PermuteDims(ArrayTensorProduct(a, I, b), Permutation(5)(1, 2, 3, 4)) assert _remove_trivial_dims(cg) == (a * b.T, [1, 2, 4, 5]) cg = PermuteDims(ArrayTensorProduct(I, b, a), Permutation(5)(1, 2, 4, 5, 3)) assert _remove_trivial_dims(cg) == (b * a.T, [0, 3, 4, 5]) # Diagonal: cg = ArrayDiagonal(ArrayTensorProduct(M, a), (1, 2)) assert _remove_trivial_dims(cg) == (cg, []) # Contraction: cg = ArrayContraction(ArrayTensorProduct(M, a), (1, 2)) assert _remove_trivial_dims(cg) == (cg, []) def test_arrayexpr_convert_array_to_matrix_diag2contraction_diagmatrix(): cg = ArrayDiagonal(ArrayTensorProduct(M, a), (1, 2)) res = _array_diag2contr_diagmatrix(cg) assert res.shape == cg.shape assert res == ArrayContraction(ArrayTensorProduct(M, OneArray(1), DiagMatrix(a)), (1, 3)) raises(ValueError, lambda: ArrayDiagonal(ArrayTensorProduct(a, M), (1, 2))) cg = ArrayDiagonal(ArrayTensorProduct(a.T, M), (1, 2)) res = _array_diag2contr_diagmatrix(cg) assert res.shape == cg.shape assert res == ArrayContraction(ArrayTensorProduct(OneArray(1), M, DiagMatrix(a.T)), (1, 4)) cg = ArrayDiagonal(ArrayTensorProduct(a.T, M, N, b.T), (1, 2), (4, 7)) res = _array_diag2contr_diagmatrix(cg) assert res.shape == cg.shape assert res == ArrayContraction( ArrayTensorProduct(OneArray(1), M, N, OneArray(1), DiagMatrix(a.T), DiagMatrix(b.T)), (1, 7), (3, 9)) cg = ArrayDiagonal(ArrayTensorProduct(a, M, N, b.T), (0, 2), (4, 7)) res = _array_diag2contr_diagmatrix(cg) assert res.shape == cg.shape assert res == ArrayContraction( ArrayTensorProduct(OneArray(1), M, N, OneArray(1), DiagMatrix(a), DiagMatrix(b.T)), (1, 6), (3, 9)) cg = ArrayDiagonal(ArrayTensorProduct(a, M, N, b.T), (0, 4), (3, 7)) res = _array_diag2contr_diagmatrix(cg) assert res.shape == cg.shape assert res == ArrayContraction( ArrayTensorProduct(OneArray(1), M, N, OneArray(1), DiagMatrix(a), DiagMatrix(b.T)), (3, 6), (2, 9)) I1 = Identity(1) x = MatrixSymbol("x", k, 1) A = MatrixSymbol("A", k, k) cg = ArrayDiagonal(ArrayTensorProduct(x, A.T, I1), (0, 2)) assert _array_diag2contr_diagmatrix(cg).shape == cg.shape assert _array2matrix(cg).shape == cg.shape def test_arrayexpr_convert_array_to_matrix_support_function(): assert _support_function_tp1_recognize([], [2 * k]) == 2 * k assert _support_function_tp1_recognize([(1, 2)], [A, 2 * k, B, 3]) == 6 * k * A * B assert _support_function_tp1_recognize([(0, 3), (1, 2)], [A, B]) == Trace(A * B) assert _support_function_tp1_recognize([(1, 2)], [A, B]) == A * B assert _support_function_tp1_recognize([(0, 2)], [A, B]) == A.T * B assert _support_function_tp1_recognize([(1, 3)], [A, B]) == A * B.T assert _support_function_tp1_recognize([(0, 3)], [A, B]) == A.T * B.T assert _support_function_tp1_recognize([(1, 2), (5, 6)], [A, B, C, D]) == ArrayTensorProduct(A * B, C * D) assert _support_function_tp1_recognize([(1, 4), (3, 6)], [A, B, C, D]) == PermuteDims( ArrayTensorProduct(A * C, B * D), [0, 2, 1, 3]) assert _support_function_tp1_recognize([(0, 3), (1, 4)], [A, B, C]) == B * A * C assert _support_function_tp1_recognize([(9, 10), (1, 2), (5, 6), (3, 4), (7, 8)], [X, Y, A, B, C, D]) == X * Y * A * B * C * D assert _support_function_tp1_recognize([(9, 10), (1, 2), (5, 6), (3, 4)], [X, Y, A, B, C, D]) == ArrayTensorProduct(X * Y * A * B, C * D) assert _support_function_tp1_recognize([(1, 7), (3, 8), (4, 11)], [X, Y, A, B, C, D]) == PermuteDims( ArrayTensorProduct(X * B.T, Y * C, D * A), [0, 2, 5, 1, 3, 4] ) assert _support_function_tp1_recognize([(0, 1), (3, 6), (5, 8)], [X, A, B, C, D]) == PermuteDims( ArrayTensorProduct(Trace(X) * A * C, B * D), [0, 2, 1, 3]) assert _support_function_tp1_recognize([(1, 2), (3, 4), (5, 6), (7, 8)], [A, A, B, C, D]) == A ** 2 * B * C * D assert _support_function_tp1_recognize([(1, 2), (3, 4), (5, 6), (7, 8)], [X, A, B, C, D]) == X * A * B * C * D assert _support_function_tp1_recognize([(1, 6), (3, 8), (5, 10)], [X, Y, A, B, C, D]) == PermuteDims( ArrayTensorProduct(X * B, Y * C, A * D), [0, 2, 4, 1, 3, 5] ) assert _support_function_tp1_recognize([(1, 4), (3, 6)], [A, B, C, D]) == PermuteDims( ArrayTensorProduct(A * C, B * D), [0, 2, 1, 3]) assert _support_function_tp1_recognize([(0, 4), (1, 7), (2, 5), (3, 8)], [X, A, B, C, D]) == C*X.T*B*A*D assert _support_function_tp1_recognize([(0, 4), (1, 7), (2, 5), (3, 8)], [X, A, B, C, D]) == C*X.T*B*A*D
74496453b9a25e65fa19d278a5fe796f0b2ac948866f3e6466a435c572e4a5ac
from sympy import ImmutableDenseNDimArray, tensorproduct, MatrixSymbol, tensorcontraction, tensordiagonal, permutedims, \ Symbol from sympy.tensor.array.expressions.array_expressions import ZeroArray, OneArray, ArraySymbol, \ ArrayTensorProduct, PermuteDims, ArrayDiagonal, ArrayContraction from sympy.testing.pytest import raises def test_array_as_explicit_call(): assert ZeroArray(3, 2, 4).as_explicit() == ImmutableDenseNDimArray.zeros(3, 2, 4) assert OneArray(3, 2, 4).as_explicit() == ImmutableDenseNDimArray([1 for i in range(3*2*4)]).reshape(3, 2, 4) k = Symbol("k") X = ArraySymbol("X", k, 3, 2) raises(ValueError, lambda: X.as_explicit()) raises(ValueError, lambda: ZeroArray(k, 2, 3).as_explicit()) raises(ValueError, lambda: OneArray(2, k, 2).as_explicit()) A = ArraySymbol("A", 3, 3) B = ArraySymbol("B", 3, 3) texpr = tensorproduct(A, B) assert isinstance(texpr, ArrayTensorProduct) assert texpr.as_explicit() == tensorproduct(A.as_explicit(), B.as_explicit()) texpr = tensorcontraction(A, (0, 1)) assert isinstance(texpr, ArrayContraction) assert texpr.as_explicit() == A[0, 0] + A[1, 1] + A[2, 2] texpr = tensordiagonal(A, (0, 1)) assert isinstance(texpr, ArrayDiagonal) assert texpr.as_explicit() == ImmutableDenseNDimArray([A[0, 0], A[1, 1], A[2, 2]]) texpr = permutedims(A, [1, 0]) assert isinstance(texpr, PermuteDims) assert texpr.as_explicit() == permutedims(A.as_explicit(), [1, 0]) def test_array_as_explicit_matrix_symbol(): A = MatrixSymbol("A", 3, 3) B = MatrixSymbol("B", 3, 3) texpr = tensorproduct(A, B) assert isinstance(texpr, ArrayTensorProduct) assert texpr.as_explicit() == tensorproduct(A.as_explicit(), B.as_explicit()) texpr = tensorcontraction(A, (0, 1)) assert isinstance(texpr, ArrayContraction) assert texpr.as_explicit() == A[0, 0] + A[1, 1] + A[2, 2] texpr = tensordiagonal(A, (0, 1)) assert isinstance(texpr, ArrayDiagonal) assert texpr.as_explicit() == ImmutableDenseNDimArray([A[0, 0], A[1, 1], A[2, 2]]) texpr = permutedims(A, [1, 0]) assert isinstance(texpr, PermuteDims) assert texpr.as_explicit() == permutedims(A.as_explicit(), [1, 0])
983786d5091893814288a971135dc76211a040983f23e6118bd681b0a50c07bd
from sympy import Sum, MatrixSymbol, Identity, symbols, IndexedBase, KroneckerDelta from sympy.combinatorics import Permutation from sympy.tensor.array.expressions.array_expressions import ArrayContraction, ArrayTensorProduct, \ ArrayDiagonal, ArrayAdd, PermuteDims from sympy.tensor.array.expressions.conv_array_to_matrix import convert_array_to_matrix from sympy.tensor.array.expressions.conv_indexed_to_array import convert_indexed_to_array, _convert_indexed_to_array from sympy.testing.pytest import raises A, B = symbols("A B", cls=IndexedBase) i, j, k, l, m, n = symbols("i j k l m n") I = Identity(k) M = MatrixSymbol("M", k, k) N = MatrixSymbol("N", k, k) P = MatrixSymbol("P", k, k) Q = MatrixSymbol("Q", k, k) a = MatrixSymbol("a", k, 1) b = MatrixSymbol("b", k, 1) c = MatrixSymbol("c", k, 1) d = MatrixSymbol("d", k, 1) def test_arrayexpr_convert_index_to_array_support_function(): expr = M[i, j] assert _convert_indexed_to_array(expr) == (M, (i, j)) expr = M[i, j]*N[k, l] assert _convert_indexed_to_array(expr) == (ArrayTensorProduct(M, N), (i, j, k, l)) expr = M[i, j]*N[j, k] assert _convert_indexed_to_array(expr) == (ArrayDiagonal(ArrayTensorProduct(M, N), (1, 2)), (i, k, j)) expr = Sum(M[i, j]*N[j, k], (j, 0, k-1)) assert _convert_indexed_to_array(expr) == (ArrayContraction(ArrayTensorProduct(M, N), (1, 2)), (i, k)) expr = M[i, j] + N[i, j] assert _convert_indexed_to_array(expr) == (ArrayAdd(M, N), (i, j)) expr = M[i, j] + N[j, i] assert _convert_indexed_to_array(expr) == (ArrayAdd(M, PermuteDims(N, Permutation([1, 0]))), (i, j)) expr = M[i, j] + M[j, i] assert _convert_indexed_to_array(expr) == (ArrayAdd(M, PermuteDims(M, Permutation([1, 0]))), (i, j)) expr = (M*N*P)[i, j] assert _convert_indexed_to_array(expr) == (ArrayContraction(ArrayTensorProduct(M, N, P), (1, 2), (3, 4)), (i, j)) expr = expr.function # Disregard summation in previous expression ret1, ret2 = _convert_indexed_to_array(expr) assert ret1 == ArrayDiagonal(ArrayTensorProduct(M, N, P), (1, 2), (3, 4)) assert str(ret2) == "(i, j, _i_1, _i_2)" expr = KroneckerDelta(i, j)*M[i, k] assert _convert_indexed_to_array(expr) == (M, ({i, j}, k)) expr = KroneckerDelta(i, j)*KroneckerDelta(j, k)*M[i, l] assert _convert_indexed_to_array(expr) == (M, ({i, j, k}, l)) expr = KroneckerDelta(j, k)*(M[i, j]*N[k, l] + N[i, j]*M[k, l]) assert _convert_indexed_to_array(expr) == (ArrayDiagonal(ArrayAdd( ArrayTensorProduct(M, N), PermuteDims(ArrayTensorProduct(M, N), Permutation(0, 2)(1, 3)) ), (1, 2)), (i, l, frozenset({j, k}))) expr = KroneckerDelta(j, m)*KroneckerDelta(m, k)*(M[i, j]*N[k, l] + N[i, j]*M[k, l]) assert _convert_indexed_to_array(expr) == (ArrayDiagonal(ArrayAdd( ArrayTensorProduct(M, N), PermuteDims(ArrayTensorProduct(M, N), Permutation(0, 2)(1, 3)) ), (1, 2)), (i, l, frozenset({j, m, k}))) expr = KroneckerDelta(i, j)*KroneckerDelta(j, k)*KroneckerDelta(k,m)*M[i, 0]*KroneckerDelta(m, n) assert _convert_indexed_to_array(expr) == (M, ({i, j, k, m, n}, 0)) expr = M[i, i] assert _convert_indexed_to_array(expr) == (ArrayDiagonal(M, (0, 1)), (i,)) def test_arrayexpr_convert_indexed_to_array_expression(): s = Sum(A[i]*B[i], (i, 0, 3)) cg = convert_indexed_to_array(s) assert cg == ArrayContraction(ArrayTensorProduct(A, B), (0, 1)) expr = M*N result = ArrayContraction(ArrayTensorProduct(M, N), (1, 2)) elem = expr[i, j] assert convert_indexed_to_array(elem) == result expr = M*N*M elem = expr[i, j] result = ArrayContraction(ArrayTensorProduct(M, M, N), (1, 4), (2, 5)) cg = convert_indexed_to_array(elem) assert cg == result cg = convert_indexed_to_array((M * N * P)[i, j]) assert cg == ArrayContraction(ArrayTensorProduct(M, N, P), (1, 2), (3, 4)) cg = convert_indexed_to_array((M * N.T * P)[i, j]) assert cg == ArrayContraction(ArrayTensorProduct(M, N, P), (1, 3), (2, 4)) expr = -2*M*N elem = expr[i, j] cg = convert_indexed_to_array(elem) assert cg == ArrayContraction(ArrayTensorProduct(-2, M, N), (1, 2)) def test_arrayexpr_convert_indexed_to_array_and_back_to_matrix(): expr = a.T*b elem = expr[0, 0] cg = convert_indexed_to_array(elem) assert cg == ArrayContraction(ArrayTensorProduct(a, b), (0, 2)) expr = M[i,j] + N[i,j] p1, p2 = _convert_indexed_to_array(expr) assert convert_array_to_matrix(p1) == M + N expr = M[i,j] + N[j,i] p1, p2 = _convert_indexed_to_array(expr) assert convert_array_to_matrix(p1) == M + N.T expr = M[i,j]*N[k,l] + N[i,j]*M[k,l] p1, p2 = _convert_indexed_to_array(expr) assert convert_array_to_matrix(p1) == ArrayAdd( ArrayTensorProduct(M, N), ArrayTensorProduct(N, M)) expr = (M*N*P)[i, j] p1, p2 = _convert_indexed_to_array(expr) assert convert_array_to_matrix(p1) == M * N * P expr = Sum(M[i,j]*(N*P)[j,m], (j, 0, k-1)) p1, p2 = _convert_indexed_to_array(expr) assert convert_array_to_matrix(p1) == M * N * P expr = Sum((P[j, m] + P[m, j])*(M[i,j]*N[m,n] + N[i,j]*M[m,n]), (j, 0, k-1), (m, 0, k-1)) p1, p2 = _convert_indexed_to_array(expr) assert convert_array_to_matrix(p1) == M * P * N + M * P.T * N + N * P * M + N * P.T * M def test_arrayexpr_convert_indexed_to_array_out_of_bounds(): expr = Sum(M[i, i], (i, 0, 4)) raises(ValueError, lambda: convert_indexed_to_array(expr)) expr = Sum(M[i, i], (i, 0, k)) raises(ValueError, lambda: convert_indexed_to_array(expr)) expr = Sum(M[i, i], (i, 1, k-1)) raises(ValueError, lambda: convert_indexed_to_array(expr)) expr = Sum(M[i, j]*N[j,m], (j, 0, 4)) raises(ValueError, lambda: convert_indexed_to_array(expr)) expr = Sum(M[i, j]*N[j,m], (j, 0, k)) raises(ValueError, lambda: convert_indexed_to_array(expr)) expr = Sum(M[i, j]*N[j,m], (j, 1, k-1)) raises(ValueError, lambda: convert_indexed_to_array(expr))
364e2373f49b93951523eaa74513c4d3ef5473692c40d426ce3b4f1b4d0008a6
from sympy import MatrixSymbol, Transpose, Inverse, Trace, HadamardProduct, HadamardPower, MatPow, symbols, Identity from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct, ArrayContraction, \ PermuteDims, ArrayDiagonal from sympy.tensor.array.expressions.conv_array_to_matrix import convert_array_to_matrix from sympy.tensor.array.expressions.conv_matrix_to_array import convert_matrix_to_array i, j, k, l, m, n = symbols("i j k l m n") I = Identity(k) M = MatrixSymbol("M", k, k) N = MatrixSymbol("N", k, k) P = MatrixSymbol("P", k, k) Q = MatrixSymbol("Q", k, k) A = MatrixSymbol("A", k, k) B = MatrixSymbol("B", k, k) C = MatrixSymbol("C", k, k) D = MatrixSymbol("D", k, k) X = MatrixSymbol("X", k, k) Y = MatrixSymbol("Y", k, k) a = MatrixSymbol("a", k, 1) b = MatrixSymbol("b", k, 1) c = MatrixSymbol("c", k, 1) d = MatrixSymbol("d", k, 1) def test_arrayexpr_convert_matrix_to_array(): expr = M*N result = ArrayContraction(ArrayTensorProduct(M, N), (1, 2)) assert convert_matrix_to_array(expr) == result expr = M*N*M result = ArrayContraction(ArrayTensorProduct(M, N, M), (1, 2), (3, 4)) assert convert_matrix_to_array(expr) == result expr = Transpose(M) assert convert_matrix_to_array(expr) == PermuteDims(M, [1, 0]) expr = M*Transpose(N) assert convert_matrix_to_array(expr) == ArrayContraction(ArrayTensorProduct(M, PermuteDims(N, [1, 0])), (1, 2)) expr = 3*M*N res = convert_matrix_to_array(expr) rexpr = convert_array_to_matrix(res) assert expr == rexpr expr = 3*M + N*M.T*M + 4*k*N res = convert_matrix_to_array(expr) rexpr = convert_array_to_matrix(res) assert expr == rexpr expr = Inverse(M)*N rexpr = convert_array_to_matrix(convert_matrix_to_array(expr)) assert expr == rexpr expr = M**2 rexpr = convert_array_to_matrix(convert_matrix_to_array(expr)) assert expr == rexpr expr = M*(2*N + 3*M) res = convert_matrix_to_array(expr) rexpr = convert_array_to_matrix(res) assert expr == rexpr expr = Trace(M) result = ArrayContraction(M, (0, 1)) assert convert_matrix_to_array(expr) == result expr = 3*Trace(M) result = ArrayContraction(ArrayTensorProduct(3, M), (0, 1)) assert convert_matrix_to_array(expr) == result expr = 3*Trace(Trace(M) * M) result = ArrayContraction(ArrayTensorProduct(3, M, M), (0, 1), (2, 3)) assert convert_matrix_to_array(expr) == result expr = 3*Trace(M)**2 result = ArrayContraction(ArrayTensorProduct(3, M, M), (0, 1), (2, 3)) assert convert_matrix_to_array(expr) == result expr = HadamardProduct(M, N) result = ArrayDiagonal(ArrayTensorProduct(M, N), (0, 2), (1, 3)) assert convert_matrix_to_array(expr) == result expr = HadamardProduct(M*N, N*M) result = ArrayDiagonal(ArrayContraction(ArrayTensorProduct(M, N, N, M), (1, 2), (5, 6)), (0, 2), (1, 3)) assert convert_matrix_to_array(expr) == result expr = HadamardPower(M, 2) result = ArrayDiagonal(ArrayTensorProduct(M, M), (0, 2), (1, 3)) assert convert_matrix_to_array(expr) == result expr = HadamardPower(M*N, 2) result = ArrayDiagonal(ArrayContraction(ArrayTensorProduct(M, N, M, N), (1, 2), (5, 6)), (0, 2), (1, 3)) assert convert_matrix_to_array(expr) == result expr = M**2 assert isinstance(expr, MatPow) assert convert_matrix_to_array(expr) == ArrayContraction(ArrayTensorProduct(M, M), (1, 2)) expr = a.T*b cg = convert_matrix_to_array(expr) assert cg == ArrayContraction(ArrayTensorProduct(a, b), (0, 2))
efadfcef79b93fe1375d53f9798ba63372e8e1eb1bba5401fd664e9b7c363c82
import random from sympy import symbols, ImmutableDenseNDimArray, tensorproduct, tensorcontraction, permutedims, MatrixSymbol, \ ZeroMatrix, sin, cos, DiagMatrix from sympy.combinatorics import Permutation from sympy.tensor.array.expressions.array_expressions import ZeroArray, OneArray, ArraySymbol, ArrayElement, \ PermuteDims, ArrayContraction, ArrayTensorProduct, ArrayDiagonal, \ ArrayAdd, nest_permutation, ArrayElementwiseApplyFunc from sympy.testing.pytest import raises i, j, k, l, m, n = symbols("i j k l m n") M = ArraySymbol("M", k, k) N = ArraySymbol("N", k, k) P = ArraySymbol("P", k, k) Q = ArraySymbol("Q", k, k) A = ArraySymbol("A", k, k) B = ArraySymbol("B", k, k) C = ArraySymbol("C", k, k) D = ArraySymbol("D", k, k) X = ArraySymbol("X", k, k) Y = ArraySymbol("Y", k, k) a = ArraySymbol("a", k, 1) b = ArraySymbol("b", k, 1) c = ArraySymbol("c", k, 1) d = ArraySymbol("d", k, 1) def test_array_symbol_and_element(): A = ArraySymbol("A", 2) A0 = ArrayElement(A, (0,)) A1 = ArrayElement(A, (1,)) assert A.as_explicit() == ImmutableDenseNDimArray([A0, A1]) A2 = tensorproduct(A, A) assert A2.shape == (2, 2) # TODO: not yet supported: # assert A2.as_explicit() == Array([[A[0]*A[0], A[1]*A[0]], [A[0]*A[1], A[1]*A[1]]]) A3 = tensorcontraction(A2, (0, 1)) assert A3.shape == () # TODO: not yet supported: # assert A3.as_explicit() == Array([]) A = ArraySymbol("A", 2, 3, 4) Ae = A.as_explicit() assert Ae == ImmutableDenseNDimArray( [[[ArrayElement(A, (i, j, k)) for k in range(4)] for j in range(3)] for i in range(2)]) p = permutedims(A, Permutation(0, 2, 1)) assert isinstance(p, PermuteDims) def test_zero_array(): assert ZeroArray() == 0 assert ZeroArray().is_Integer za = ZeroArray(3, 2, 4) assert za.shape == (3, 2, 4) za_e = za.as_explicit() assert za_e.shape == (3, 2, 4) m, n, k = symbols("m n k") za = ZeroArray(m, n, k, 2) assert za.shape == (m, n, k, 2) raises(ValueError, lambda: za.as_explicit()) def test_one_array(): assert OneArray() == 1 assert OneArray().is_Integer oa = OneArray(3, 2, 4) assert oa.shape == (3, 2, 4) oa_e = oa.as_explicit() assert oa_e.shape == (3, 2, 4) m, n, k = symbols("m n k") oa = OneArray(m, n, k, 2) assert oa.shape == (m, n, k, 2) raises(ValueError, lambda: oa.as_explicit()) def test_arrayexpr_contraction_construction(): cg = ArrayContraction(A) assert cg == A cg = ArrayContraction(ArrayTensorProduct(A, B), (1, 0)) assert cg == ArrayContraction(ArrayTensorProduct(A, B), (0, 1)) cg = ArrayContraction(ArrayTensorProduct(M, N), (0, 1)) indtup = cg._get_contraction_tuples() assert indtup == [[(0, 0), (0, 1)]] assert cg._contraction_tuples_to_contraction_indices(cg.expr, indtup) == [(0, 1)] cg = ArrayContraction(ArrayTensorProduct(M, N), (1, 2)) indtup = cg._get_contraction_tuples() assert indtup == [[(0, 1), (1, 0)]] assert cg._contraction_tuples_to_contraction_indices(cg.expr, indtup) == [(1, 2)] cg = ArrayContraction(ArrayTensorProduct(M, M, N), (1, 4), (2, 5)) indtup = cg._get_contraction_tuples() assert indtup == [[(0, 0), (1, 1)], [(0, 1), (2, 0)]] assert cg._contraction_tuples_to_contraction_indices(cg.expr, indtup) == [(0, 3), (1, 4)] def test_arrayexpr_array_flatten(): # Flatten nested ArrayTensorProduct objects: expr1 = ArrayTensorProduct(M, N) expr2 = ArrayTensorProduct(P, Q) expr = ArrayTensorProduct(expr1, expr2) assert expr == ArrayTensorProduct(M, N, P, Q) assert expr.args == (M, N, P, Q) # Flatten mixed ArrayTensorProduct and ArrayContraction objects: cg1 = ArrayContraction(expr1, (1, 2)) cg2 = ArrayContraction(expr2, (0, 3)) expr = ArrayTensorProduct(cg1, cg2) assert expr == ArrayContraction(ArrayTensorProduct(M, N, P, Q), (1, 2), (4, 7)) expr = ArrayTensorProduct(M, cg1) assert expr == ArrayContraction(ArrayTensorProduct(M, M, N), (3, 4)) # Flatten nested ArrayContraction objects: cgnested = ArrayContraction(cg1, (0, 1)) assert cgnested == ArrayContraction(ArrayTensorProduct(M, N), (0, 3), (1, 2)) cgnested = ArrayContraction(ArrayTensorProduct(cg1, cg2), (0, 3)) assert cgnested == ArrayContraction(ArrayTensorProduct(M, N, P, Q), (0, 6), (1, 2), (4, 7)) cg3 = ArrayContraction(ArrayTensorProduct(M, N, P, Q), (1, 3), (2, 4)) cgnested = ArrayContraction(cg3, (0, 1)) assert cgnested == ArrayContraction(ArrayTensorProduct(M, N, P, Q), (0, 5), (1, 3), (2, 4)) cgnested = ArrayContraction(cg3, (0, 3), (1, 2)) assert cgnested == ArrayContraction(ArrayTensorProduct(M, N, P, Q), (0, 7), (1, 3), (2, 4), (5, 6)) cg4 = ArrayContraction(ArrayTensorProduct(M, N, P, Q), (1, 5), (3, 7)) cgnested = ArrayContraction(cg4, (0, 1)) assert cgnested == ArrayContraction(ArrayTensorProduct(M, N, P, Q), (0, 2), (1, 5), (3, 7)) cgnested = ArrayContraction(cg4, (0, 1), (2, 3)) assert cgnested == ArrayContraction(ArrayTensorProduct(M, N, P, Q), (0, 2), (1, 5), (3, 7), (4, 6)) cg = ArrayDiagonal(cg4) assert cg == cg4 assert isinstance(cg, type(cg4)) # Flatten nested ArrayDiagonal objects: cg1 = ArrayDiagonal(expr1, (1, 2)) cg2 = ArrayDiagonal(expr2, (0, 3)) cg3 = ArrayDiagonal(ArrayTensorProduct(M, N, P, Q), (1, 3), (2, 4)) cg4 = ArrayDiagonal(ArrayTensorProduct(M, N, P, Q), (1, 5), (3, 7)) cgnested = ArrayDiagonal(cg1, (0, 1)) assert cgnested == ArrayDiagonal(ArrayTensorProduct(M, N), (1, 2), (0, 3)) cgnested = ArrayDiagonal(cg3, (1, 2)) assert cgnested == ArrayDiagonal(ArrayTensorProduct(M, N, P, Q), (1, 3), (2, 4), (5, 6)) cgnested = ArrayDiagonal(cg4, (1, 2)) assert cgnested == ArrayDiagonal(ArrayTensorProduct(M, N, P, Q), (1, 5), (3, 7), (2, 4)) cg = ArrayAdd(M, N) cg2 = ArrayAdd(cg, P) assert isinstance(cg2, ArrayAdd) assert cg2.args == (M, N, P) assert cg2.shape == (k, k) expr = ArrayTensorProduct(ArrayDiagonal(X, (0, 1)), ArrayDiagonal(A, (0, 1))) assert expr == ArrayDiagonal(ArrayTensorProduct(X, A), (0, 1), (2, 3)) expr1 = ArrayDiagonal(ArrayTensorProduct(X, A), (1, 2)) expr2 = ArrayTensorProduct(expr1, a) assert expr2 == PermuteDims(ArrayDiagonal(ArrayTensorProduct(X, A, a), (1, 2)), [0, 1, 3, 4, 2]) expr1 = ArrayContraction(ArrayTensorProduct(X, A), (1, 2)) expr2 = ArrayTensorProduct(expr1, a) assert isinstance(expr2, ArrayContraction) assert isinstance(expr2.expr, ArrayTensorProduct) def test_arrayexpr_array_diagonal(): cg = ArrayDiagonal(M, (1, 0)) assert cg == ArrayDiagonal(M, (0, 1)) cg = ArrayDiagonal(ArrayTensorProduct(M, N, P), (4, 1), (2, 0)) assert cg == ArrayDiagonal(ArrayTensorProduct(M, N, P), (1, 4), (0, 2)) def test_arrayexpr_array_shape(): expr = ArrayTensorProduct(M, N, P, Q) assert expr.shape == (k, k, k, k, k, k, k, k) Z = MatrixSymbol("Z", m, n) expr = ArrayTensorProduct(M, Z) assert expr.shape == (k, k, m, n) expr2 = ArrayContraction(expr, (0, 1)) assert expr2.shape == (m, n) expr2 = ArrayDiagonal(expr, (0, 1)) assert expr2.shape == (m, n, k) exprp = PermuteDims(expr, [2, 1, 3, 0]) assert exprp.shape == (m, k, n, k) expr3 = ArrayTensorProduct(N, Z) expr2 = ArrayAdd(expr, expr3) assert expr2.shape == (k, k, m, n) # Contraction along axes with discordant dimensions: raises(ValueError, lambda: ArrayContraction(expr, (1, 2))) # Also diagonal needs the same dimensions: raises(ValueError, lambda: ArrayDiagonal(expr, (1, 2))) # Diagonal requires at least to axes to compute the diagonal: raises(ValueError, lambda: ArrayDiagonal(expr, (1,))) def test_arrayexpr_permutedims_sink(): cg = PermuteDims(ArrayTensorProduct(M, N), [0, 1, 3, 2], nest_permutation=False) sunk = nest_permutation(cg) assert sunk == ArrayTensorProduct(M, PermuteDims(N, [1, 0])) cg = PermuteDims(ArrayTensorProduct(M, N), [1, 0, 3, 2], nest_permutation=False) sunk = nest_permutation(cg) assert sunk == ArrayTensorProduct(PermuteDims(M, [1, 0]), PermuteDims(N, [1, 0])) cg = PermuteDims(ArrayTensorProduct(M, N), [3, 2, 1, 0], nest_permutation=False) sunk = nest_permutation(cg) assert sunk == ArrayTensorProduct(PermuteDims(N, [1, 0]), PermuteDims(M, [1, 0])) cg = PermuteDims(ArrayContraction(ArrayTensorProduct(M, N), (1, 2)), [1, 0], nest_permutation=False) sunk = nest_permutation(cg) assert sunk == ArrayContraction(PermuteDims(ArrayTensorProduct(M, N), [[0, 3]]), (1, 2)) cg = PermuteDims(ArrayTensorProduct(M, N), [1, 0, 3, 2], nest_permutation=False) sunk = nest_permutation(cg) assert sunk == ArrayTensorProduct(PermuteDims(M, [1, 0]), PermuteDims(N, [1, 0])) cg = PermuteDims(ArrayContraction(ArrayTensorProduct(M, N, P), (1, 2), (3, 4)), [1, 0], nest_permutation=False) sunk = nest_permutation(cg) assert sunk == ArrayContraction(PermuteDims(ArrayTensorProduct(M, N, P), [[0, 5]]), (1, 2), (3, 4)) def test_arrayexpr_push_indices_up_and_down(): indices = list(range(12)) contr_diag_indices = [(0, 6), (2, 8)] assert ArrayContraction._push_indices_down(contr_diag_indices, indices) == (1, 3, 4, 5, 7, 9, 10, 11, 12, 13, 14, 15) assert ArrayContraction._push_indices_up(contr_diag_indices, indices) == (None, 0, None, 1, 2, 3, None, 4, None, 5, 6, 7) assert ArrayDiagonal._push_indices_down(contr_diag_indices, indices, 10) == (1, 3, 4, 5, 7, 9, (0, 6), (2, 8), None, None, None, None) assert ArrayDiagonal._push_indices_up(contr_diag_indices, indices, 10) == (6, 0, 7, 1, 2, 3, 6, 4, 7, 5, None, None) contr_diag_indices = [(1, 2), (7, 8)] assert ArrayContraction._push_indices_down(contr_diag_indices, indices) == (0, 3, 4, 5, 6, 9, 10, 11, 12, 13, 14, 15) assert ArrayContraction._push_indices_up(contr_diag_indices, indices) == (0, None, None, 1, 2, 3, 4, None, None, 5, 6, 7) assert ArrayDiagonal._push_indices_down(contr_diag_indices, indices, 10) == (0, 3, 4, 5, 6, 9, (1, 2), (7, 8), None, None, None, None) assert ArrayDiagonal._push_indices_up(contr_diag_indices, indices, 10) == (0, 6, 6, 1, 2, 3, 4, 7, 7, 5, None, None) def test_arrayexpr_split_multiple_contractions(): a = MatrixSymbol("a", k, 1) b = MatrixSymbol("b", k, 1) A = MatrixSymbol("A", k, k) B = MatrixSymbol("B", k, k) C = MatrixSymbol("C", k, k) X = MatrixSymbol("X", k, k) cg = ArrayContraction(ArrayTensorProduct(A.T, a, b, b.T, (A*X*b).applyfunc(cos)), (1, 2, 8), (5, 6, 9)) assert cg.split_multiple_contractions().dummy_eq(ArrayContraction(ArrayTensorProduct(DiagMatrix(a), (A*X*b).applyfunc(cos), A.T, b, b.T), (0, 2), (1, 5), (3, 7, 8))) # assert recognize_matrix_expression(cg) # Check no overlap of lines: cg = ArrayContraction(ArrayTensorProduct(A, a, C, a, B), (1, 2, 4), (5, 6, 8), (3, 7)) assert cg.split_multiple_contractions() == cg cg = ArrayContraction(ArrayTensorProduct(a, b, A), (0, 2, 4), (1, 3)) assert cg.split_multiple_contractions() == cg def test_arrayexpr_nested_permutations(): cg = PermuteDims(PermuteDims(M, (1, 0)), (1, 0)) assert cg == M times = 3 plist1 = [list(range(6)) for i in range(times)] plist2 = [list(range(6)) for i in range(times)] for i in range(times): random.shuffle(plist1[i]) random.shuffle(plist2[i]) plist1.append([2, 5, 4, 1, 0, 3]) plist2.append([3, 5, 0, 4, 1, 2]) plist1.append([2, 5, 4, 0, 3, 1]) plist2.append([3, 0, 5, 1, 2, 4]) plist1.append([5, 4, 2, 0, 3, 1]) plist2.append([4, 5, 0, 2, 3, 1]) Me = M.subs(k, 3).as_explicit() Ne = N.subs(k, 3).as_explicit() Pe = P.subs(k, 3).as_explicit() cge = tensorproduct(Me, Ne, Pe) for permutation_array1, permutation_array2 in zip(plist1, plist2): p1 = Permutation(permutation_array1) p2 = Permutation(permutation_array2) cg = PermuteDims( PermuteDims( ArrayTensorProduct(M, N, P), p1), p2 ) result = PermuteDims( ArrayTensorProduct(M, N, P), p2*p1 ) assert cg == result # Check that `permutedims` behaves the same way with explicit-component arrays: result1 = permutedims(permutedims(cge, p1), p2) result2 = permutedims(cge, p2*p1) assert result1 == result2 def test_arrayexpr_contraction_permutation_mix(): Me = M.subs(k, 3).as_explicit() Ne = N.subs(k, 3).as_explicit() cg1 = ArrayContraction(PermuteDims(ArrayTensorProduct(M, N), Permutation([0, 2, 1, 3])), (2, 3)) cg2 = ArrayContraction(ArrayTensorProduct(M, N), (1, 3)) assert cg1 == cg2 cge1 = tensorcontraction(permutedims(tensorproduct(Me, Ne), Permutation([0, 2, 1, 3])), (2, 3)) cge2 = tensorcontraction(tensorproduct(Me, Ne), (1, 3)) assert cge1 == cge2 cg1 = PermuteDims(ArrayTensorProduct(M, N), Permutation([0, 1, 3, 2])) cg2 = ArrayTensorProduct(M, PermuteDims(N, Permutation([1, 0]))) assert cg1 == cg2 cg1 = ArrayContraction( PermuteDims( ArrayTensorProduct(M, N, P, Q), Permutation([0, 2, 3, 1, 4, 5, 7, 6])), (1, 2), (3, 5) ) cg2 = ArrayContraction( ArrayTensorProduct(M, N, P, PermuteDims(Q, Permutation([1, 0]))), (1, 5), (2, 3) ) assert cg1 == cg2 cg1 = ArrayContraction( PermuteDims( ArrayTensorProduct(M, N, P, Q), Permutation([1, 0, 4, 6, 2, 7, 5, 3])), (0, 1), (2, 6), (3, 7) ) cg2 = PermuteDims( ArrayContraction( ArrayTensorProduct(M, P, Q, N), (0, 1), (2, 3), (4, 7)), [1, 0] ) assert cg1 == cg2 cg1 = ArrayContraction( PermuteDims( ArrayTensorProduct(M, N, P, Q), Permutation([1, 0, 4, 6, 7, 2, 5, 3])), (0, 1), (2, 6), (3, 7) ) cg2 = PermuteDims( ArrayContraction( ArrayTensorProduct(PermuteDims(M, [1, 0]), N, P, Q), (0, 1), (3, 6), (4, 5) ), Permutation([1, 0]) ) assert cg1 == cg2 def test_arrayexpr_permute_tensor_product(): cg1 = PermuteDims(ArrayTensorProduct(M, N, P, Q), Permutation([2, 3, 1, 0, 5, 4, 6, 7])) cg2 = ArrayTensorProduct(N, PermuteDims(M, [1, 0]), PermuteDims(P, [1, 0]), Q) assert cg1 == cg2 # TODO: reverse operation starting with `PermuteDims` and getting down to `bb`... cg1 = PermuteDims(ArrayTensorProduct(M, N, P, Q), Permutation([2, 3, 4, 5, 0, 1, 6, 7])) cg2 = ArrayTensorProduct(N, P, M, Q) assert cg1 == cg2 cg1 = PermuteDims(ArrayTensorProduct(M, N, P, Q), Permutation([2, 3, 4, 6, 5, 7, 0, 1])) assert cg1.expr == ArrayTensorProduct(N, P, Q, M) assert cg1.permutation == Permutation([0, 1, 2, 4, 3, 5, 6, 7]) cg1 = ArrayContraction( PermuteDims( ArrayTensorProduct(N, Q, Q, M), [2, 1, 5, 4, 0, 3, 6, 7]), [1, 2, 6]) cg2 = PermuteDims(ArrayContraction(ArrayTensorProduct(Q, Q, N, M), (3, 5, 6)), [0, 2, 3, 1, 4]) assert cg1 == cg2 cg1 = ArrayContraction( ArrayContraction( ArrayContraction( ArrayContraction( PermuteDims( ArrayTensorProduct(N, Q, Q, M), [2, 1, 5, 4, 0, 3, 6, 7]), [1, 2, 6]), [1, 3, 4]), [1]), [0]) cg2 = ArrayContraction(ArrayTensorProduct(M, N, Q, Q), (0, 3, 5), (1, 4, 7), (2,), (6,)) assert cg1 == cg2 def test_arrayexpr_normalize_diagonal_permutedims(): tp = ArrayTensorProduct(M, Q, N, P) expr = ArrayDiagonal( PermuteDims(tp, [0, 1, 2, 4, 7, 6, 3, 5]), (2, 4, 5), (6, 7), (0, 3)) result = ArrayDiagonal(tp, (2, 6, 7), (3, 5), (0, 4)) assert expr == result tp = ArrayTensorProduct(M, N, P, Q) expr = ArrayDiagonal(PermuteDims(tp, [0, 5, 2, 4, 1, 6, 3, 7]), (1, 2, 6), (3, 4)) result = ArrayDiagonal(ArrayTensorProduct(M, P, N, Q), (3, 4, 5), (1, 2)) assert expr == result def test_arrayexpr_normalize_diagonal_contraction(): tp = ArrayTensorProduct(M, N, P, Q) expr = ArrayContraction(ArrayDiagonal(tp, (1, 3, 4)), (0, 3)) result = ArrayDiagonal(ArrayContraction(ArrayTensorProduct(M, N, P, Q), (0, 6)), (0, 2, 3)) assert expr == result expr = ArrayContraction(ArrayDiagonal(tp, (0, 1, 2, 3, 7)), (1, 2, 3)) result = ArrayContraction(ArrayTensorProduct(M, N, P, Q), (0, 1, 2, 3, 5, 6, 7)) assert expr == result expr = ArrayContraction(ArrayDiagonal(tp, (0, 2, 6, 7)), (1, 2, 3)) result = ArrayDiagonal(ArrayContraction(tp, (3, 4, 5)), (0, 2, 3, 4)) assert expr == result td = ArrayDiagonal(ArrayTensorProduct(M, N, P, Q), (0, 3)) expr = ArrayContraction(td, (2, 1), (0, 4, 6, 5, 3)) result = ArrayContraction(ArrayTensorProduct(M, N, P, Q), (0, 1, 3, 5, 6, 7), (2, 4)) assert expr == result def test_arrayexpr_array_wrong_permutation_size(): cg = ArrayTensorProduct(M, N) raises(ValueError, lambda: PermuteDims(cg, [1, 0])) raises(ValueError, lambda: PermuteDims(cg, [1, 0, 2, 3, 5, 4])) def test_arrayexpr_nested_array_elementwise_add(): cg = ArrayContraction(ArrayAdd( ArrayTensorProduct(M, N), ArrayTensorProduct(N, M) ), (1, 2)) result = ArrayAdd( ArrayContraction(ArrayTensorProduct(M, N), (1, 2)), ArrayContraction(ArrayTensorProduct(N, M), (1, 2)) ) assert cg == result cg = ArrayDiagonal(ArrayAdd( ArrayTensorProduct(M, N), ArrayTensorProduct(N, M) ), (1, 2)) result = ArrayAdd( ArrayDiagonal(ArrayTensorProduct(M, N), (1, 2)), ArrayDiagonal(ArrayTensorProduct(N, M), (1, 2)) ) assert cg == result def test_arrayexpr_array_expr_zero_array(): za1 = ZeroArray(k, l, m, n) zm1 = ZeroMatrix(m, n) za2 = ZeroArray(k, m, m, n) zm2 = ZeroMatrix(m, m) zm3 = ZeroMatrix(k, k) assert ArrayTensorProduct(M, N, za1) == ZeroArray(k, k, k, k, k, l, m, n) assert ArrayTensorProduct(M, N, zm1) == ZeroArray(k, k, k, k, m, n) assert ArrayContraction(za1, (3,)) == ZeroArray(k, l, m) assert ArrayContraction(zm1, (1,)) == ZeroArray(m) assert ArrayContraction(za2, (1, 2)) == ZeroArray(k, n) assert ArrayContraction(zm2, (0, 1)) == 0 assert ArrayDiagonal(za2, (1, 2)) == ZeroArray(k, n, m) assert ArrayDiagonal(zm2, (0, 1)) == ZeroArray(m) assert PermuteDims(za1, [2, 1, 3, 0]) == ZeroArray(m, l, n, k) assert PermuteDims(zm1, [1, 0]) == ZeroArray(n, m) assert ArrayAdd(za1) == za1 assert ArrayAdd(zm1) == ZeroArray(m, n) tp1 = ArrayTensorProduct(MatrixSymbol("A", k, l), MatrixSymbol("B", m, n)) assert ArrayAdd(tp1, za1) == tp1 tp2 = ArrayTensorProduct(MatrixSymbol("C", k, l), MatrixSymbol("D", m, n)) assert ArrayAdd(tp1, za1, tp2) == ArrayAdd(tp1, tp2) assert ArrayAdd(M, zm3) == M assert ArrayAdd(M, N, zm3) == ArrayAdd(M, N) def test_arrayexpr_array_expr_applyfunc(): A = ArraySymbol("A", 3, k, 2) aaf = ArrayElementwiseApplyFunc(sin, A) assert aaf.shape == (3, k, 2)
3dfe0ca9efd8f01376d0e84182b10d045aea61f8d70a4b19b183ad8fed115c94
from sympy import MatrixSymbol, symbols, Identity, sin, cos from sympy.matrices.expressions.applyfunc import ElementwiseApplyFunction from sympy.tensor.array.expressions.array_expressions import ArraySymbol, ArrayTensorProduct, \ PermuteDims, ArrayDiagonal, ArrayElementwiseApplyFunc, ArrayContraction from sympy.tensor.array.expressions.arrayexpr_derivatives import array_derive k = symbols("k") I = Identity(k) X = MatrixSymbol("X", k, k) x = MatrixSymbol("x", k, 1) A = MatrixSymbol("A", k, k) B = MatrixSymbol("B", k, k) C = MatrixSymbol("C", k, k) D = MatrixSymbol("D", k, k) A1 = ArraySymbol("A", 3, 2, k) def test_arrayexpr_derivatives1(): res = array_derive(X, X) assert res == PermuteDims(ArrayTensorProduct(I, I), [0, 2, 1, 3]) cg = ArrayTensorProduct(A, X, B) res = array_derive(cg, X) assert res == PermuteDims( ArrayTensorProduct(I, A, I, B), [0, 4, 2, 3, 1, 5, 6, 7]) cg = ArrayContraction(X, (0, 1)) res = array_derive(cg, X) assert res == ArrayContraction(ArrayTensorProduct(I, I), (1, 3)) cg = ArrayDiagonal(X, (0, 1)) res = array_derive(cg, X) assert res == ArrayDiagonal(ArrayTensorProduct(I, I), (1, 3)) cg = ElementwiseApplyFunction(sin, X) res = array_derive(cg, X) assert res.dummy_eq(ArrayDiagonal( ArrayTensorProduct( ElementwiseApplyFunction(cos, X), I, I ), (0, 3), (1, 5))) cg = ArrayElementwiseApplyFunc(sin, X) res = array_derive(cg, X) assert res.dummy_eq(ArrayDiagonal( ArrayTensorProduct( I, I, ArrayElementwiseApplyFunc(cos, X) ), (1, 4), (3, 5))) res = array_derive(A1, A1) assert res == PermuteDims( ArrayTensorProduct(Identity(3), Identity(2), Identity(k)), [0, 2, 4, 1, 3, 5] ) cg = ArrayElementwiseApplyFunc(sin, A1) res = array_derive(cg, A1) assert res.dummy_eq(ArrayDiagonal( ArrayTensorProduct( Identity(3), Identity(2), Identity(k), ArrayElementwiseApplyFunc(cos, A1) ), (1, 6), (3, 7), (5, 8) ))
3b8bf20b61137bd7686645138f3f181f155e77c453b03af77704d638bb83f3ea
from sympy.assumptions.ask import Q from sympy.assumptions.refine import refine from sympy.core.numbers import oo from sympy.core.relational import Equality, Eq, Ne from sympy.core.singleton import S from sympy.core.symbol import (Dummy, symbols) from sympy.functions import Piecewise from sympy.functions.elementary.miscellaneous import Max, Min from sympy.functions.elementary.trigonometric import sin from sympy.sets.sets import (EmptySet, Interval, Union) from sympy.simplify.simplify import simplify from sympy.logic.boolalg import ( And, Boolean, Equivalent, ITE, Implies, Nand, Nor, Not, Or, POSform, SOPform, Xor, Xnor, conjuncts, disjuncts, distribute_or_over_and, distribute_and_over_or, eliminate_implications, is_nnf, is_cnf, is_dnf, simplify_logic, to_nnf, to_cnf, to_dnf, to_int_repr, bool_map, true, false, BooleanAtom, is_literal, term_to_integer, integer_to_term, truth_table, as_Boolean, to_anf, is_anf, distribute_xor_over_and, anf_coeffs, ANFform, bool_minterm, bool_maxterm, bool_monomial, _check_pair, _convert_to_varsSOP, _convert_to_varsPOS) from sympy.assumptions.cnf import CNF from sympy.testing.pytest import raises, XFAIL, slow from sympy.utilities.iterables import cartes from itertools import combinations, permutations A, B, C, D = symbols('A:D') a, b, c, d, e, w, x, y, z = symbols('a:e w:z') def test_overloading(): """Test that |, & are overloaded as expected""" assert A & B == And(A, B) assert A | B == Or(A, B) assert (A & B) | C == Or(And(A, B), C) assert A >> B == Implies(A, B) assert A << B == Implies(B, A) assert ~A == Not(A) assert A ^ B == Xor(A, B) def test_And(): assert And() is true assert And(A) == A assert And(True) is true assert And(False) is false assert And(True, True) is true assert And(True, False) is false assert And(False, False) is false assert And(True, A) == A assert And(False, A) is false assert And(True, True, True) is true assert And(True, True, A) == A assert And(True, False, A) is false assert And(1, A) == A raises(TypeError, lambda: And(2, A)) raises(TypeError, lambda: And(A < 2, A)) assert And(A < 1, A >= 1) is false e = A > 1 assert And(e, e.canonical) == e.canonical g, l, ge, le = A > B, B < A, A >= B, B <= A assert And(g, l, ge, le) == And(ge, g) assert {And(*i) for i in permutations((l,g,le,ge))} == {And(ge, g)} assert And(And(Eq(a, 0), Eq(b, 0)), And(Ne(a, 0), Eq(c, 0))) is false def test_Or(): assert Or() is false assert Or(A) == A assert Or(True) is true assert Or(False) is false assert Or(True, True) is true assert Or(True, False) is true assert Or(False, False) is false assert Or(True, A) is true assert Or(False, A) == A assert Or(True, False, False) is true assert Or(True, False, A) is true assert Or(False, False, A) == A assert Or(1, A) is true raises(TypeError, lambda: Or(2, A)) raises(TypeError, lambda: Or(A < 2, A)) assert Or(A < 1, A >= 1) is true e = A > 1 assert Or(e, e.canonical) == e g, l, ge, le = A > B, B < A, A >= B, B <= A assert Or(g, l, ge, le) == Or(g, ge) def test_Xor(): assert Xor() is false assert Xor(A) == A assert Xor(A, A) is false assert Xor(True, A, A) is true assert Xor(A, A, A, A, A) == A assert Xor(True, False, False, A, B) == ~Xor(A, B) assert Xor(True) is true assert Xor(False) is false assert Xor(True, True) is false assert Xor(True, False) is true assert Xor(False, False) is false assert Xor(True, A) == ~A assert Xor(False, A) == A assert Xor(True, False, False) is true assert Xor(True, False, A) == ~A assert Xor(False, False, A) == A assert isinstance(Xor(A, B), Xor) assert Xor(A, B, Xor(C, D)) == Xor(A, B, C, D) assert Xor(A, B, Xor(B, C)) == Xor(A, C) assert Xor(A < 1, A >= 1, B) == Xor(0, 1, B) == Xor(1, 0, B) e = A > 1 assert Xor(e, e.canonical) == Xor(0, 0) == Xor(1, 1) def test_rewrite_as_And(): expr = x ^ y assert expr.rewrite(And) == (x | y) & (~x | ~y) def test_rewrite_as_Or(): expr = x ^ y assert expr.rewrite(Or) == (x & ~y) | (y & ~x) def test_rewrite_as_Nand(): expr = (y & z) | (z & ~w) assert expr.rewrite(Nand) == ~(~(y & z) & ~(z & ~w)) def test_rewrite_as_Nor(): expr = z & (y | ~w) assert expr.rewrite(Nor) == ~(~z | ~(y | ~w)) def test_Not(): raises(TypeError, lambda: Not(True, False)) assert Not(True) is false assert Not(False) is true assert Not(0) is true assert Not(1) is false assert Not(2) is false def test_Nand(): assert Nand() is false assert Nand(A) == ~A assert Nand(True) is false assert Nand(False) is true assert Nand(True, True) is false assert Nand(True, False) is true assert Nand(False, False) is true assert Nand(True, A) == ~A assert Nand(False, A) is true assert Nand(True, True, True) is false assert Nand(True, True, A) == ~A assert Nand(True, False, A) is true def test_Nor(): assert Nor() is true assert Nor(A) == ~A assert Nor(True) is false assert Nor(False) is true assert Nor(True, True) is false assert Nor(True, False) is false assert Nor(False, False) is true assert Nor(True, A) is false assert Nor(False, A) == ~A assert Nor(True, True, True) is false assert Nor(True, True, A) is false assert Nor(True, False, A) is false def test_Xnor(): assert Xnor() is true assert Xnor(A) == ~A assert Xnor(A, A) is true assert Xnor(True, A, A) is false assert Xnor(A, A, A, A, A) == ~A assert Xnor(True) is false assert Xnor(False) is true assert Xnor(True, True) is true assert Xnor(True, False) is false assert Xnor(False, False) is true assert Xnor(True, A) == A assert Xnor(False, A) == ~A assert Xnor(True, False, False) is false assert Xnor(True, False, A) == A assert Xnor(False, False, A) == ~A def test_Implies(): raises(ValueError, lambda: Implies(A, B, C)) assert Implies(True, True) is true assert Implies(True, False) is false assert Implies(False, True) is true assert Implies(False, False) is true assert Implies(0, A) is true assert Implies(1, 1) is true assert Implies(1, 0) is false assert A >> B == B << A assert (A < 1) >> (A >= 1) == (A >= 1) assert (A < 1) >> (S.One > A) is true assert A >> A is true def test_Equivalent(): assert Equivalent(A, B) == Equivalent(B, A) == Equivalent(A, B, A) assert Equivalent() is true assert Equivalent(A, A) == Equivalent(A) is true assert Equivalent(True, True) == Equivalent(False, False) is true assert Equivalent(True, False) == Equivalent(False, True) is false assert Equivalent(A, True) == A assert Equivalent(A, False) == Not(A) assert Equivalent(A, B, True) == A & B assert Equivalent(A, B, False) == ~A & ~B assert Equivalent(1, A) == A assert Equivalent(0, A) == Not(A) assert Equivalent(A, Equivalent(B, C)) != Equivalent(Equivalent(A, B), C) assert Equivalent(A < 1, A >= 1) is false assert Equivalent(A < 1, A >= 1, 0) is false assert Equivalent(A < 1, A >= 1, 1) is false assert Equivalent(A < 1, S.One > A) == Equivalent(1, 1) == Equivalent(0, 0) assert Equivalent(Equality(A, B), Equality(B, A)) is true def test_equals(): assert Not(Or(A, B)).equals(And(Not(A), Not(B))) is True assert Equivalent(A, B).equals((A >> B) & (B >> A)) is True assert ((A | ~B) & (~A | B)).equals((~A & ~B) | (A & B)) is True assert (A >> B).equals(~A >> ~B) is False assert (A >> (B >> A)).equals(A >> (C >> A)) is False raises(NotImplementedError, lambda: (A & B).equals(A > B)) def test_simplification(): """ Test working of simplification methods. """ set1 = [[0, 0, 1], [0, 1, 1], [1, 0, 0], [1, 1, 0]] set2 = [[0, 0, 0], [0, 1, 0], [1, 0, 1], [1, 1, 1]] assert SOPform([x, y, z], set1) == Or(And(Not(x), z), And(Not(z), x)) assert Not(SOPform([x, y, z], set2)) == \ Not(Or(And(Not(x), Not(z)), And(x, z))) assert POSform([x, y, z], set1 + set2) is true assert SOPform([x, y, z], set1 + set2) is true assert SOPform([Dummy(), Dummy(), Dummy()], set1 + set2) is true minterms = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 1], [1, 0, 1, 1], [1, 1, 1, 1]] dontcares = [[0, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 1]] assert ( SOPform([w, x, y, z], minterms, dontcares) == Or(And(y, z), And(Not(w), Not(x)))) assert POSform([w, x, y, z], minterms, dontcares) == And(Or(Not(w), y), z) minterms = [1, 3, 7, 11, 15] dontcares = [0, 2, 5] assert ( SOPform([w, x, y, z], minterms, dontcares) == Or(And(y, z), And(Not(w), Not(x)))) assert POSform([w, x, y, z], minterms, dontcares) == And(Or(Not(w), y), z) minterms = [1, [0, 0, 1, 1], 7, [1, 0, 1, 1], [1, 1, 1, 1]] dontcares = [0, [0, 0, 1, 0], 5] assert ( SOPform([w, x, y, z], minterms, dontcares) == Or(And(y, z), And(Not(w), Not(x)))) assert POSform([w, x, y, z], minterms, dontcares) == And(Or(Not(w), y), z) minterms = [1, {y: 1, z: 1}] dontcares = [0, [0, 0, 1, 0], 5] assert ( SOPform([w, x, y, z], minterms, dontcares) == Or(And(y, z), And(Not(w), Not(x)))) assert POSform([w, x, y, z], minterms, dontcares) == And(Or(Not(w), y), z) minterms = [{y: 1, z: 1}, 1] dontcares = [[0, 0, 0, 0]] minterms = [[0, 0, 0]] raises(ValueError, lambda: SOPform([w, x, y, z], minterms)) raises(ValueError, lambda: POSform([w, x, y, z], minterms)) raises(TypeError, lambda: POSform([w, x, y, z], ["abcdefg"])) # test simplification ans = And(A, Or(B, C)) assert simplify_logic(A & (B | C)) == ans assert simplify_logic((A & B) | (A & C)) == ans assert simplify_logic(Implies(A, B)) == Or(Not(A), B) assert simplify_logic(Equivalent(A, B)) == \ Or(And(A, B), And(Not(A), Not(B))) assert simplify_logic(And(Equality(A, 2), C)) == And(Equality(A, 2), C) assert simplify_logic(And(Equality(A, 2), A)) is S.false assert simplify_logic(And(Equality(A, 2), A)) == And(Equality(A, 2), A) assert simplify_logic(And(Equality(A, B), C)) == And(Equality(A, B), C) assert simplify_logic(Or(And(Equality(A, 3), B), And(Equality(A, 3), C))) \ == And(Equality(A, 3), Or(B, C)) b = (~x & ~y & ~z) | (~x & ~y & z) e = And(A, b) assert simplify_logic(e) == A & ~x & ~y raises(ValueError, lambda: simplify_logic(A & (B | C), form='blabla')) # Check that expressions with nine variables or more are not simplified # (without the force-flag) a, b, c, d, e, f, g, h, j = symbols('a b c d e f g h j') expr = a & b & c & d & e & f & g & h & j | \ a & b & c & d & e & f & g & h & ~j # This expression can be simplified to get rid of the j variables assert simplify_logic(expr) == expr # check input ans = SOPform([x, y], [[1, 0]]) assert SOPform([x, y], [[1, 0]]) == ans assert POSform([x, y], [[1, 0]]) == ans raises(ValueError, lambda: SOPform([x], [[1]], [[1]])) assert SOPform([x], [[1]], [[0]]) is true assert SOPform([x], [[0]], [[1]]) is true assert SOPform([x], [], []) is false raises(ValueError, lambda: POSform([x], [[1]], [[1]])) assert POSform([x], [[1]], [[0]]) is true assert POSform([x], [[0]], [[1]]) is true assert POSform([x], [], []) is false # check working of simplify assert simplify((A & B) | (A & C)) == And(A, Or(B, C)) assert simplify(And(x, Not(x))) == False assert simplify(Or(x, Not(x))) == True assert simplify(And(Eq(x, 0), Eq(x, y))) == And(Eq(x, 0), Eq(y, 0)) assert And(Eq(x - 1, 0), Eq(x, y)).simplify() == And(Eq(x, 1), Eq(y, 1)) assert And(Ne(x - 1, 0), Ne(x, y)).simplify() == And(Ne(x, 1), Ne(x, y)) assert And(Eq(x - 1, 0), Ne(x, y)).simplify() == And(Eq(x, 1), Ne(y, 1)) assert And(Eq(x - 1, 0), Eq(x, z + y), Eq(y + x, 0)).simplify( ) == And(Eq(x, 1), Eq(y, -1), Eq(z, 2)) assert And(Eq(x - 1, 0), Eq(x + 2, 3)).simplify() == Eq(x, 1) assert And(Ne(x - 1, 0), Ne(x + 2, 3)).simplify() == Ne(x, 1) assert And(Eq(x - 1, 0), Eq(x + 2, 2)).simplify() == False assert And(Ne(x - 1, 0), Ne(x + 2, 2)).simplify( ) == And(Ne(x, 1), Ne(x, 0)) def test_bool_map(): """ Test working of bool_map function. """ minterms = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 1], [1, 0, 1, 1], [1, 1, 1, 1]] assert bool_map(Not(Not(a)), a) == (a, {a: a}) assert bool_map(SOPform([w, x, y, z], minterms), POSform([w, x, y, z], minterms)) == \ (And(Or(Not(w), y), Or(Not(x), y), z), {x: x, w: w, z: z, y: y}) assert bool_map(SOPform([x, z, y], [[1, 0, 1]]), SOPform([a, b, c], [[1, 0, 1]])) != False function1 = SOPform([x, z, y], [[1, 0, 1], [0, 0, 1]]) function2 = SOPform([a, b, c], [[1, 0, 1], [1, 0, 0]]) assert bool_map(function1, function2) == \ (function1, {y: a, z: b}) assert bool_map(Xor(x, y), ~Xor(x, y)) == False assert bool_map(And(x, y), Or(x, y)) is None assert bool_map(And(x, y), And(x, y, z)) is None # issue 16179 assert bool_map(Xor(x, y, z), ~Xor(x, y, z)) == False assert bool_map(Xor(a, x, y, z), ~Xor(a, x, y, z)) == False def test_bool_symbol(): """Test that mixing symbols with boolean values works as expected""" assert And(A, True) == A assert And(A, True, True) == A assert And(A, False) is false assert And(A, True, False) is false assert Or(A, True) is true assert Or(A, False) == A def test_is_boolean(): assert isinstance(True, Boolean) is False assert isinstance(true, Boolean) is True assert 1 == True assert 1 != true assert (1 == true) is False assert 0 == False assert 0 != false assert (0 == false) is False assert true.is_Boolean is True assert (A & B).is_Boolean assert (A | B).is_Boolean assert (~A).is_Boolean assert (A ^ B).is_Boolean assert A.is_Boolean != isinstance(A, Boolean) assert isinstance(A, Boolean) def test_subs(): assert (A & B).subs(A, True) == B assert (A & B).subs(A, False) is false assert (A & B).subs(B, True) == A assert (A & B).subs(B, False) is false assert (A & B).subs({A: True, B: True}) is true assert (A | B).subs(A, True) is true assert (A | B).subs(A, False) == B assert (A | B).subs(B, True) is true assert (A | B).subs(B, False) == A assert (A | B).subs({A: True, B: True}) is true """ we test for axioms of boolean algebra see https://en.wikipedia.org/wiki/Boolean_algebra_(structure) """ def test_commutative(): """Test for commutativity of And and Or""" A, B = map(Boolean, symbols('A,B')) assert A & B == B & A assert A | B == B | A def test_and_associativity(): """Test for associativity of And""" assert (A & B) & C == A & (B & C) def test_or_assicativity(): assert ((A | B) | C) == (A | (B | C)) def test_double_negation(): a = Boolean() assert ~(~a) == a # test methods def test_eliminate_implications(): assert eliminate_implications(Implies(A, B, evaluate=False)) == (~A) | B assert eliminate_implications( A >> (C >> Not(B))) == Or(Or(Not(B), Not(C)), Not(A)) assert eliminate_implications(Equivalent(A, B, C, D)) == \ (~A | B) & (~B | C) & (~C | D) & (~D | A) def test_conjuncts(): assert conjuncts(A & B & C) == {A, B, C} assert conjuncts((A | B) & C) == {A | B, C} assert conjuncts(A) == {A} assert conjuncts(True) == {True} assert conjuncts(False) == {False} def test_disjuncts(): assert disjuncts(A | B | C) == {A, B, C} assert disjuncts((A | B) & C) == {(A | B) & C} assert disjuncts(A) == {A} assert disjuncts(True) == {True} assert disjuncts(False) == {False} def test_distribute(): assert distribute_and_over_or(Or(And(A, B), C)) == And(Or(A, C), Or(B, C)) assert distribute_or_over_and(And(A, Or(B, C))) == Or(And(A, B), And(A, C)) assert distribute_xor_over_and(And(A, Xor(B, C))) == Xor(And(A, B), And(A, C)) def test_to_anf(): x, y, z = symbols('x,y,z') assert to_anf(And(x, y)) == And(x, y) assert to_anf(Or(x, y)) == Xor(x, y, And(x, y)) assert to_anf(Or(Implies(x, y), And(x, y), y)) == \ Xor(x, True, x & y, remove_true=False) assert to_anf(Or(Nand(x, y), Nor(x, y), Xnor(x, y), Implies(x, y))) == True assert to_anf(Or(x, Not(y), Nor(x,z), And(x, y), Nand(y, z))) == \ Xor(True, And(y, z), And(x, y, z), remove_true=False) assert to_anf(Xor(x, y)) == Xor(x, y) assert to_anf(Not(x)) == Xor(x, True, remove_true=False) assert to_anf(Nand(x, y)) == Xor(True, And(x, y), remove_true=False) assert to_anf(Nor(x, y)) == Xor(x, y, True, And(x, y), remove_true=False) assert to_anf(Implies(x, y)) == Xor(x, True, And(x, y), remove_true=False) assert to_anf(Equivalent(x, y)) == Xor(x, y, True, remove_true=False) assert to_anf(Nand(x | y, x >> y), deep=False) == \ Xor(True, And(Or(x, y), Implies(x, y)), remove_true=False) assert to_anf(Nor(x ^ y, x & y), deep=False) == \ Xor(True, Or(Xor(x, y), And(x, y)), remove_true=False) def test_to_nnf(): assert to_nnf(true) is true assert to_nnf(false) is false assert to_nnf(A) == A assert to_nnf(A | ~A | B) is true assert to_nnf(A & ~A & B) is false assert to_nnf(A >> B) == ~A | B assert to_nnf(Equivalent(A, B, C)) == (~A | B) & (~B | C) & (~C | A) assert to_nnf(A ^ B ^ C) == \ (A | B | C) & (~A | ~B | C) & (A | ~B | ~C) & (~A | B | ~C) assert to_nnf(ITE(A, B, C)) == (~A | B) & (A | C) assert to_nnf(Not(A | B | C)) == ~A & ~B & ~C assert to_nnf(Not(A & B & C)) == ~A | ~B | ~C assert to_nnf(Not(A >> B)) == A & ~B assert to_nnf(Not(Equivalent(A, B, C))) == And(Or(A, B, C), Or(~A, ~B, ~C)) assert to_nnf(Not(A ^ B ^ C)) == \ (~A | B | C) & (A | ~B | C) & (A | B | ~C) & (~A | ~B | ~C) assert to_nnf(Not(ITE(A, B, C))) == (~A | ~B) & (A | ~C) assert to_nnf((A >> B) ^ (B >> A)) == (A & ~B) | (~A & B) assert to_nnf((A >> B) ^ (B >> A), False) == \ (~A | ~B | A | B) & ((A & ~B) | (~A & B)) assert ITE(A, 1, 0).to_nnf() == A assert ITE(A, 0, 1).to_nnf() == ~A # although ITE can hold non-Boolean, it will complain if # an attempt is made to convert the ITE to Boolean nnf raises(TypeError, lambda: ITE(A < 1, [1], B).to_nnf()) def test_to_cnf(): assert to_cnf(~(B | C)) == And(Not(B), Not(C)) assert to_cnf((A & B) | C) == And(Or(A, C), Or(B, C)) assert to_cnf(A >> B) == (~A) | B assert to_cnf(A >> (B & C)) == (~A | B) & (~A | C) assert to_cnf(A & (B | C) | ~A & (B | C), True) == B | C assert to_cnf(A & B) == And(A, B) assert to_cnf(Equivalent(A, B)) == And(Or(A, Not(B)), Or(B, Not(A))) assert to_cnf(Equivalent(A, B & C)) == \ (~A | B) & (~A | C) & (~B | ~C | A) assert to_cnf(Equivalent(A, B | C), True) == \ And(Or(Not(B), A), Or(Not(C), A), Or(B, C, Not(A))) assert to_cnf(A + 1) == A + 1 def test_issue_18904(): x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15 = symbols('x1:16') eq = (( x1 & x2 & x3 & x4 & x5 & x6 & x7 & x8 & x9 ) | ( x1 & x2 & x3 & x4 & x5 & x6 & x7 & x10 & x9 ) | ( x1 & x11 & x3 & x12 & x5 & x13 & x14 & x15 & x9 )) assert is_cnf(to_cnf(eq)) raises(ValueError, lambda: to_cnf(eq, simplify=True)) for f, t in zip((And, Or), (to_cnf, to_dnf)): eq = f(x1, x2, x3, x4, x5, x6, x7, x8, x9) raises(ValueError, lambda: to_cnf(eq, simplify=True)) assert t(eq, simplify=True, force=True) == eq def test_issue_9949(): assert is_cnf(to_cnf((b > -5) | (a > 2) & (a < 4))) def test_to_CNF(): assert CNF.CNF_to_cnf(CNF.to_CNF(~(B | C))) == to_cnf(~(B | C)) assert CNF.CNF_to_cnf(CNF.to_CNF((A & B) | C)) == to_cnf((A & B) | C) assert CNF.CNF_to_cnf(CNF.to_CNF(A >> B)) == to_cnf(A >> B) assert CNF.CNF_to_cnf(CNF.to_CNF(A >> (B & C))) == to_cnf(A >> (B & C)) assert CNF.CNF_to_cnf(CNF.to_CNF(A & (B | C) | ~A & (B | C))) == to_cnf(A & (B | C) | ~A & (B | C)) assert CNF.CNF_to_cnf(CNF.to_CNF(A & B)) == to_cnf(A & B) def test_to_dnf(): assert to_dnf(~(B | C)) == And(Not(B), Not(C)) assert to_dnf(A & (B | C)) == Or(And(A, B), And(A, C)) assert to_dnf(A >> B) == (~A) | B assert to_dnf(A >> (B & C)) == (~A) | (B & C) assert to_dnf(A | B) == A | B assert to_dnf(Equivalent(A, B), True) == \ Or(And(A, B), And(Not(A), Not(B))) assert to_dnf(Equivalent(A, B & C), True) == \ Or(And(A, B, C), And(Not(A), Not(B)), And(Not(A), Not(C))) assert to_dnf(A + 1) == A + 1 def test_to_int_repr(): x, y, z = map(Boolean, symbols('x,y,z')) def sorted_recursive(arg): try: return sorted(sorted_recursive(x) for x in arg) except TypeError: # arg is not a sequence return arg assert sorted_recursive(to_int_repr([x | y, z | x], [x, y, z])) == \ sorted_recursive([[1, 2], [1, 3]]) assert sorted_recursive(to_int_repr([x | y, z | ~x], [x, y, z])) == \ sorted_recursive([[1, 2], [3, -1]]) def test_is_anf(): x, y = symbols('x,y') assert is_anf(true) is True assert is_anf(false) is True assert is_anf(x) is True assert is_anf(And(x, y)) is True assert is_anf(Xor(x, y, And(x, y))) is True assert is_anf(Xor(x, y, Or(x, y))) is False assert is_anf(Xor(Not(x), y)) is False def test_is_nnf(): assert is_nnf(true) is True assert is_nnf(A) is True assert is_nnf(~A) is True assert is_nnf(A & B) is True assert is_nnf((A & B) | (~A & A) | (~B & B) | (~A & ~B), False) is True assert is_nnf((A | B) & (~A | ~B)) is True assert is_nnf(Not(Or(A, B))) is False assert is_nnf(A ^ B) is False assert is_nnf((A & B) | (~A & A) | (~B & B) | (~A & ~B), True) is False def test_is_cnf(): assert is_cnf(x) is True assert is_cnf(x | y | z) is True assert is_cnf(x & y & z) is True assert is_cnf((x | y) & z) is True assert is_cnf((x & y) | z) is False assert is_cnf(~(x & y) | z) is False def test_is_dnf(): assert is_dnf(x) is True assert is_dnf(x | y | z) is True assert is_dnf(x & y & z) is True assert is_dnf((x & y) | z) is True assert is_dnf((x | y) & z) is False assert is_dnf(~(x | y) & z) is False def test_ITE(): A, B, C = symbols('A:C') assert ITE(True, False, True) is false assert ITE(True, True, False) is true assert ITE(False, True, False) is false assert ITE(False, False, True) is true assert isinstance(ITE(A, B, C), ITE) A = True assert ITE(A, B, C) == B A = False assert ITE(A, B, C) == C B = True assert ITE(And(A, B), B, C) == C assert ITE(Or(A, False), And(B, True), False) is false assert ITE(x, A, B) == Not(x) assert ITE(x, B, A) == x assert ITE(1, x, y) == x assert ITE(0, x, y) == y raises(TypeError, lambda: ITE(2, x, y)) raises(TypeError, lambda: ITE(1, [], y)) raises(TypeError, lambda: ITE(1, (), y)) raises(TypeError, lambda: ITE(1, y, [])) assert ITE(1, 1, 1) is S.true assert isinstance(ITE(1, 1, 1, evaluate=False), ITE) raises(TypeError, lambda: ITE(x > 1, y, x)) assert ITE(Eq(x, True), y, x) == ITE(x, y, x) assert ITE(Eq(x, False), y, x) == ITE(~x, y, x) assert ITE(Ne(x, True), y, x) == ITE(~x, y, x) assert ITE(Ne(x, False), y, x) == ITE(x, y, x) assert ITE(Eq(S. true, x), y, x) == ITE(x, y, x) assert ITE(Eq(S.false, x), y, x) == ITE(~x, y, x) assert ITE(Ne(S.true, x), y, x) == ITE(~x, y, x) assert ITE(Ne(S.false, x), y, x) == ITE(x, y, x) # 0 and 1 in the context are not treated as True/False # so the equality must always be False since dissimilar # objects cannot be equal assert ITE(Eq(x, 0), y, x) == x assert ITE(Eq(x, 1), y, x) == x assert ITE(Ne(x, 0), y, x) == y assert ITE(Ne(x, 1), y, x) == y assert ITE(Eq(x, 0), y, z).subs(x, 0) == y assert ITE(Eq(x, 0), y, z).subs(x, 1) == z raises(ValueError, lambda: ITE(x > 1, y, x, z)) def test_is_literal(): assert is_literal(True) is True assert is_literal(False) is True assert is_literal(A) is True assert is_literal(~A) is True assert is_literal(Or(A, B)) is False assert is_literal(Q.zero(A)) is True assert is_literal(Not(Q.zero(A))) is True assert is_literal(Or(A, B)) is False assert is_literal(And(Q.zero(A), Q.zero(B))) is False assert is_literal(x < 3) assert not is_literal(x + y < 3) def test_operators(): # Mostly test __and__, __rand__, and so on assert True & A == A & True == A assert False & A == A & False == False assert A & B == And(A, B) assert True | A == A | True == True assert False | A == A | False == A assert A | B == Or(A, B) assert ~A == Not(A) assert True >> A == A << True == A assert False >> A == A << False == True assert A >> True == True << A == True assert A >> False == False << A == ~A assert A >> B == B << A == Implies(A, B) assert True ^ A == A ^ True == ~A assert False ^ A == A ^ False == A assert A ^ B == Xor(A, B) def test_true_false(): assert true is S.true assert false is S.false assert true is not True assert false is not False assert true assert not false assert true == True assert false == False assert not (true == False) assert not (false == True) assert not (true == false) assert hash(true) == hash(True) assert hash(false) == hash(False) assert len({true, True}) == len({false, False}) == 1 assert isinstance(true, BooleanAtom) assert isinstance(false, BooleanAtom) # We don't want to subclass from bool, because bool subclasses from # int. But operators like &, |, ^, <<, >>, and ~ act differently on 0 and # 1 then we want them to on true and false. See the docstrings of the # various And, Or, etc. functions for examples. assert not isinstance(true, bool) assert not isinstance(false, bool) # Note: using 'is' comparison is important here. We want these to return # true and false, not True and False assert Not(true) is false assert Not(True) is false assert Not(false) is true assert Not(False) is true assert ~true is false assert ~false is true for T, F in cartes([True, true], [False, false]): assert And(T, F) is false assert And(F, T) is false assert And(F, F) is false assert And(T, T) is true assert And(T, x) == x assert And(F, x) is false if not (T is True and F is False): assert T & F is false assert F & T is false if F is not False: assert F & F is false if T is not True: assert T & T is true assert Or(T, F) is true assert Or(F, T) is true assert Or(F, F) is false assert Or(T, T) is true assert Or(T, x) is true assert Or(F, x) == x if not (T is True and F is False): assert T | F is true assert F | T is true if F is not False: assert F | F is false if T is not True: assert T | T is true assert Xor(T, F) is true assert Xor(F, T) is true assert Xor(F, F) is false assert Xor(T, T) is false assert Xor(T, x) == ~x assert Xor(F, x) == x if not (T is True and F is False): assert T ^ F is true assert F ^ T is true if F is not False: assert F ^ F is false if T is not True: assert T ^ T is false assert Nand(T, F) is true assert Nand(F, T) is true assert Nand(F, F) is true assert Nand(T, T) is false assert Nand(T, x) == ~x assert Nand(F, x) is true assert Nor(T, F) is false assert Nor(F, T) is false assert Nor(F, F) is true assert Nor(T, T) is false assert Nor(T, x) is false assert Nor(F, x) == ~x assert Implies(T, F) is false assert Implies(F, T) is true assert Implies(F, F) is true assert Implies(T, T) is true assert Implies(T, x) == x assert Implies(F, x) is true assert Implies(x, T) is true assert Implies(x, F) == ~x if not (T is True and F is False): assert T >> F is false assert F << T is false assert F >> T is true assert T << F is true if F is not False: assert F >> F is true assert F << F is true if T is not True: assert T >> T is true assert T << T is true assert Equivalent(T, F) is false assert Equivalent(F, T) is false assert Equivalent(F, F) is true assert Equivalent(T, T) is true assert Equivalent(T, x) == x assert Equivalent(F, x) == ~x assert Equivalent(x, T) == x assert Equivalent(x, F) == ~x assert ITE(T, T, T) is true assert ITE(T, T, F) is true assert ITE(T, F, T) is false assert ITE(T, F, F) is false assert ITE(F, T, T) is true assert ITE(F, T, F) is false assert ITE(F, F, T) is true assert ITE(F, F, F) is false assert all(i.simplify(1, 2) is i for i in (S.true, S.false)) def test_bool_as_set(): assert ITE(y <= 0, False, y >= 1).as_set() == Interval(1, oo) assert And(x <= 2, x >= -2).as_set() == Interval(-2, 2) assert Or(x >= 2, x <= -2).as_set() == Interval(-oo, -2) + Interval(2, oo) assert Not(x > 2).as_set() == Interval(-oo, 2) # issue 10240 assert Not(And(x > 2, x < 3)).as_set() == \ Union(Interval(-oo, 2), Interval(3, oo)) assert true.as_set() == S.UniversalSet assert false.as_set() == EmptySet() assert x.as_set() == S.UniversalSet assert And(Or(x < 1, x > 3), x < 2).as_set() == Interval.open(-oo, 1) assert And(x < 1, sin(x) < 3).as_set() == (x < 1).as_set() raises(NotImplementedError, lambda: (sin(x) < 1).as_set()) @XFAIL def test_multivariate_bool_as_set(): x, y = symbols('x,y') assert And(x >= 0, y >= 0).as_set() == Interval(0, oo)*Interval(0, oo) assert Or(x >= 0, y >= 0).as_set() == S.Reals*S.Reals - \ Interval(-oo, 0, True, True)*Interval(-oo, 0, True, True) def test_all_or_nothing(): x = symbols('x', extended_real=True) args = x >= -oo, x <= oo v = And(*args) if v.func is And: assert len(v.args) == len(args) - args.count(S.true) else: assert v == True v = Or(*args) if v.func is Or: assert len(v.args) == 2 else: assert v == True def test_canonical_atoms(): assert true.canonical == true assert false.canonical == false def test_negated_atoms(): assert true.negated == false assert false.negated == true def test_issue_8777(): assert And(x > 2, x < oo).as_set() == Interval(2, oo, left_open=True) assert And(x >= 1, x < oo).as_set() == Interval(1, oo) assert (x < oo).as_set() == Interval(-oo, oo) assert (x > -oo).as_set() == Interval(-oo, oo) def test_issue_8975(): assert Or(And(-oo < x, x <= -2), And(2 <= x, x < oo)).as_set() == \ Interval(-oo, -2) + Interval(2, oo) def test_term_to_integer(): assert term_to_integer([1, 0, 1, 0, 0, 1, 0]) == 82 assert term_to_integer('0010101000111001') == 10809 def test_integer_to_term(): assert integer_to_term(777) == [1, 1, 0, 0, 0, 0, 1, 0, 0, 1] assert integer_to_term(123, 3) == [1, 1, 1, 1, 0, 1, 1] assert integer_to_term(456, 16) == [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0] def test_truth_table(): assert list(truth_table(And(x, y), [x, y], input=False)) == \ [False, False, False, True] assert list(truth_table(x | y, [x, y], input=False)) == \ [False, True, True, True] assert list(truth_table(x >> y, [x, y], input=False)) == \ [True, True, False, True] assert list(truth_table(And(x, y), [x, y])) == \ [([0, 0], False), ([0, 1], False), ([1, 0], False), ([1, 1], True)] def test_issue_8571(): for t in (S.true, S.false): raises(TypeError, lambda: +t) raises(TypeError, lambda: -t) raises(TypeError, lambda: abs(t)) # use int(bool(t)) to get 0 or 1 raises(TypeError, lambda: int(t)) for o in [S.Zero, S.One, x]: for _ in range(2): raises(TypeError, lambda: o + t) raises(TypeError, lambda: o - t) raises(TypeError, lambda: o % t) raises(TypeError, lambda: o*t) raises(TypeError, lambda: o/t) raises(TypeError, lambda: o**t) o, t = t, o # do again in reversed order def test_expand_relational(): n = symbols('n', negative=True) p, q = symbols('p q', positive=True) r = ((n + q*(-n/q + 1))/(q*(-n/q + 1)) < 0) assert r is not S.false assert r.expand() is S.false assert (q > 0).expand() is S.true def test_issue_12717(): assert S.true.is_Atom == True assert S.false.is_Atom == True def test_as_Boolean(): nz = symbols('nz', nonzero=True) assert all(as_Boolean(i) is S.true for i in (True, S.true, 1, nz)) z = symbols('z', zero=True) assert all(as_Boolean(i) is S.false for i in (False, S.false, 0, z)) assert all(as_Boolean(i) == i for i in (x, x < 0)) for i in (2, S(2), x + 1, []): raises(TypeError, lambda: as_Boolean(i)) def test_binary_symbols(): assert ITE(x < 1, y, z).binary_symbols == {y, z} for f in (Eq, Ne): assert f(x, 1).binary_symbols == set() assert f(x, True).binary_symbols == {x} assert f(x, False).binary_symbols == {x} assert S.true.binary_symbols == set() assert S.false.binary_symbols == set() assert x.binary_symbols == {x} assert And(x, Eq(y, False), Eq(z, 1)).binary_symbols == {x, y} assert Q.prime(x).binary_symbols == set() assert Q.lt(x, 1).binary_symbols == set() assert Q.is_true(x).binary_symbols == {x} assert Q.eq(x, True).binary_symbols == {x} assert Q.prime(x).binary_symbols == set() def test_BooleanFunction_diff(): assert And(x, y).diff(x) == Piecewise((0, Eq(y, False)), (1, True)) def test_issue_14700(): A, B, C, D, E, F, G, H = symbols('A B C D E F G H') q = ((B & D & H & ~F) | (B & H & ~C & ~D) | (B & H & ~C & ~F) | (B & H & ~D & ~G) | (B & H & ~F & ~G) | (C & G & ~B & ~D) | (C & G & ~D & ~H) | (C & G & ~F & ~H) | (D & F & H & ~B) | (D & F & ~G & ~H) | (B & D & F & ~C & ~H) | (D & E & F & ~B & ~C) | (D & F & ~A & ~B & ~C) | (D & F & ~A & ~C & ~H) | (A & B & D & F & ~E & ~H)) soldnf = ((B & D & H & ~F) | (D & F & H & ~B) | (B & H & ~C & ~D) | (B & H & ~D & ~G) | (C & G & ~B & ~D) | (C & G & ~D & ~H) | (C & G & ~F & ~H) | (D & F & ~G & ~H) | (D & E & F & ~C & ~H) | (D & F & ~A & ~C & ~H) | (A & B & D & F & ~E & ~H)) solcnf = ((B | C | D) & (B | D | G) & (C | D | H) & (C | F | H) & (D | G | H) & (F | G | H) & (B | F | ~D | ~H) & (~B | ~D | ~F | ~H) & (D | ~B | ~C | ~G | ~H) & (A | H | ~C | ~D | ~F | ~G) & (H | ~C | ~D | ~E | ~F | ~G) & (B | E | H | ~A | ~D | ~F | ~G)) assert simplify_logic(q, "dnf") == soldnf assert simplify_logic(q, "cnf") == solcnf minterms = [[0, 1, 0, 0], [0, 1, 0, 1], [0, 1, 1, 0], [0, 1, 1, 1], [0, 0, 1, 1], [1, 0, 1, 1]] dontcares = [[1, 0, 0, 0], [1, 0, 0, 1], [1, 1, 0, 0], [1, 1, 0, 1]] assert SOPform([w, x, y, z], minterms) == (x & ~w) | (y & z & ~x) # Should not be more complicated with don't cares assert SOPform([w, x, y, z], minterms, dontcares) == \ (x & ~w) | (y & z & ~x) def test_relational_simplification(): w, x, y, z = symbols('w x y z', real=True) d, e = symbols('d e', real=False) # Test all combinations or sign and order assert Or(x >= y, x < y).simplify() == S.true assert Or(x >= y, y > x).simplify() == S.true assert Or(x >= y, -x > -y).simplify() == S.true assert Or(x >= y, -y < -x).simplify() == S.true assert Or(-x <= -y, x < y).simplify() == S.true assert Or(-x <= -y, -x > -y).simplify() == S.true assert Or(-x <= -y, y > x).simplify() == S.true assert Or(-x <= -y, -y < -x).simplify() == S.true assert Or(y <= x, x < y).simplify() == S.true assert Or(y <= x, y > x).simplify() == S.true assert Or(y <= x, -x > -y).simplify() == S.true assert Or(y <= x, -y < -x).simplify() == S.true assert Or(-y >= -x, x < y).simplify() == S.true assert Or(-y >= -x, y > x).simplify() == S.true assert Or(-y >= -x, -x > -y).simplify() == S.true assert Or(-y >= -x, -y < -x).simplify() == S.true assert Or(x < y, x >= y).simplify() == S.true assert Or(y > x, x >= y).simplify() == S.true assert Or(-x > -y, x >= y).simplify() == S.true assert Or(-y < -x, x >= y).simplify() == S.true assert Or(x < y, -x <= -y).simplify() == S.true assert Or(-x > -y, -x <= -y).simplify() == S.true assert Or(y > x, -x <= -y).simplify() == S.true assert Or(-y < -x, -x <= -y).simplify() == S.true assert Or(x < y, y <= x).simplify() == S.true assert Or(y > x, y <= x).simplify() == S.true assert Or(-x > -y, y <= x).simplify() == S.true assert Or(-y < -x, y <= x).simplify() == S.true assert Or(x < y, -y >= -x).simplify() == S.true assert Or(y > x, -y >= -x).simplify() == S.true assert Or(-x > -y, -y >= -x).simplify() == S.true assert Or(-y < -x, -y >= -x).simplify() == S.true # Some other tests assert Or(x >= y, w < z, x <= y).simplify() == S.true assert And(x >= y, x < y).simplify() == S.false assert Or(x >= y, Eq(y, x)).simplify() == (x >= y) assert And(x >= y, Eq(y, x)).simplify() == Eq(x, y) assert Or(Eq(x, y), x >= y, w < y, z < y).simplify() == \ Or(x >= y, y > Min(w, z)) assert And(Eq(x, y), x >= y, w < y, y >= z, z < y).simplify() == \ And(Eq(x, y), y > Max(w, z)) assert Or(Eq(x, y), x >= 1, 2 < y, y >= 5, z < y).simplify() == \ (Eq(x, y) | (x >= 1) | (y > Min(2, z))) assert And(Eq(x, y), x >= 1, 2 < y, y >= 5, z < y).simplify() == \ (Eq(x, y) & (x >= 1) & (y >= 5) & (y > z)) assert (Eq(x, y) & Eq(d, e) & (x >= y) & (d >= e)).simplify() == \ (Eq(x, y) & Eq(d, e) & (d >= e)) assert And(Eq(x, y), Eq(x, -y)).simplify() == And(Eq(x, 0), Eq(y, 0)) assert Xor(x >= y, x <= y).simplify() == Ne(x, y) @slow def test_relational_simplification_numerically(): def test_simplification_numerically_function(original, simplified): symb = original.free_symbols n = len(symb) valuelist = list(set(list(combinations(list(range(-(n-1), n))*n, n)))) for values in valuelist: sublist = dict(zip(symb, values)) originalvalue = original.subs(sublist) simplifiedvalue = simplified.subs(sublist) assert originalvalue == simplifiedvalue, "Original: {}\nand"\ " simplified: {}\ndo not evaluate to the same value for {}"\ "".format(original, simplified, sublist) w, x, y, z = symbols('w x y z', real=True) d, e = symbols('d e', real=False) expressions = (And(Eq(x, y), x >= y, w < y, y >= z, z < y), And(Eq(x, y), x >= 1, 2 < y, y >= 5, z < y), Or(Eq(x, y), x >= 1, 2 < y, y >= 5, z < y), And(x >= y, Eq(y, x)), Or(And(Eq(x, y), x >= y, w < y, Or(y >= z, z < y)), And(Eq(x, y), x >= 1, 2 < y, y >= -1, z < y)), (Eq(x, y) & Eq(d, e) & (x >= y) & (d >= e)), ) for expression in expressions: test_simplification_numerically_function(expression, expression.simplify()) def test_relational_simplification_patterns_numerically(): from sympy.core import Wild from sympy.logic.boolalg import simplify_patterns_and, \ simplify_patterns_or, simplify_patterns_xor a = Wild('a') b = Wild('b') c = Wild('c') symb = [a, b, c] patternlists = [simplify_patterns_and(), simplify_patterns_or(), simplify_patterns_xor()] for patternlist in patternlists: for pattern in patternlist: original = pattern[0] simplified = pattern[1] valuelist = list(set(list(combinations(list(range(-2, 2))*3, 3)))) for values in valuelist: sublist = dict(zip(symb, values)) originalvalue = original.subs(sublist) simplifiedvalue = simplified.subs(sublist) assert originalvalue == simplifiedvalue, "Original: {}\nand"\ " simplified: {}\ndo not evaluate to the same value for"\ "{}".format(original, simplified, sublist) def test_issue_16803(): n = symbols('n') # No simplification done, but should not raise an exception assert ((n > 3) | (n < 0) | ((n > 0) & (n < 3))).simplify() == \ ((n > 3) | (n < 0) | ((n > 0) & (n < 3))) def test_issue_17530(): r = {x: oo, y: oo} assert Or(x + y > 0, x - y < 0).subs(r) assert not And(x + y < 0, x - y < 0).subs(r) raises(TypeError, lambda: Or(x + y < 0, x - y < 0).subs(r)) raises(TypeError, lambda: And(x + y > 0, x - y < 0).subs(r)) raises(TypeError, lambda: And(x + y > 0, x - y < 0).subs(r)) def test_anf_coeffs(): assert anf_coeffs([1, 0]) == [1, 1] assert anf_coeffs([0, 0, 0, 1]) == [0, 0, 0, 1] assert anf_coeffs([0, 1, 1, 1]) == [0, 1, 1, 1] assert anf_coeffs([1, 1, 1, 0]) == [1, 0, 0, 1] assert anf_coeffs([1, 0, 0, 0]) == [1, 1, 1, 1] assert anf_coeffs([1, 0, 0, 1]) == [1, 1, 1, 0] assert anf_coeffs([1, 1, 0, 1]) == [1, 0, 1, 1] def test_ANFform(): x, y = symbols('x,y') assert ANFform([x], [1, 1]) == True assert ANFform([x], [0, 0]) == False assert ANFform([x], [1, 0]) == Xor(x, True, remove_true=False) assert ANFform([x, y], [1, 1, 1, 0]) == \ Xor(True, And(x, y), remove_true=False) def test_bool_minterm(): x, y = symbols('x,y') assert bool_minterm(3, [x, y]) == And(x, y) assert bool_minterm([1, 0], [x, y]) == And(Not(y), x) def test_bool_maxterm(): x, y = symbols('x,y') assert bool_maxterm(2, [x, y]) == Or(Not(x), y) assert bool_maxterm([0, 1], [x, y]) == Or(Not(y), x) def test_bool_monomial(): x, y = symbols('x,y') assert bool_monomial(1, [x, y]) == y assert bool_monomial([1, 1], [x, y]) == And(x, y) def test_check_pair(): assert _check_pair([0, 1, 0], [0, 1, 1]) == 2 assert _check_pair([0, 1, 0], [1, 1, 1]) == -1 def test_convert_to_varsSOP(): assert _convert_to_varsSOP([0, 1, 0], [x, y, z]) == And(Not(x), y, Not(z)) assert _convert_to_varsSOP([3, 1, 0], [x, y, z]) == And(y, Not(z)) def test_convert_to_varsPOS(): assert _convert_to_varsPOS([0, 1, 0], [x, y, z]) == Or(x, Not(y), z) assert _convert_to_varsPOS([3, 1, 0], [x, y, z]) == Or(Not(y), z) def test_refine(): # relational assert not refine(x < 0, ~(x < 0)) assert refine(x < 0, (x < 0)) assert refine(x < 0, (0 > x)) is S.true assert refine(x < 0, (y < 0)) == (x < 0) assert not refine(x <= 0, ~(x <= 0)) assert refine(x <= 0, (x <= 0)) assert refine(x <= 0, (0 >= x)) is S.true assert refine(x <= 0, (y <= 0)) == (x <= 0) assert not refine(x > 0, ~(x > 0)) assert refine(x > 0, (x > 0)) assert refine(x > 0, (0 < x)) is S.true assert refine(x > 0, (y > 0)) == (x > 0) assert not refine(x >= 0, ~(x >= 0)) assert refine(x >= 0, (x >= 0)) assert refine(x >= 0, (0 <= x)) is S.true assert refine(x >= 0, (y >= 0)) == (x >= 0) assert not refine(Eq(x, 0), ~(Eq(x, 0))) assert refine(Eq(x, 0), (Eq(x, 0))) assert refine(Eq(x, 0), (Eq(0, x))) is S.true assert refine(Eq(x, 0), (Eq(y, 0))) == Eq(x, 0) assert not refine(Ne(x, 0), ~(Ne(x, 0))) assert refine(Ne(x, 0), (Ne(0, x))) is S.true assert refine(Ne(x, 0), (Ne(x, 0))) assert refine(Ne(x, 0), (Ne(y, 0))) == (Ne(x, 0)) # boolean functions assert refine(And(x > 0, y > 0), (x > 0)) == (y > 0) assert refine(And(x > 0, y > 0), (x > 0) & (y > 0)) is S.true # predicates assert refine(Q.positive(x), Q.positive(x)) is S.true assert refine(Q.positive(x), Q.negative(x)) is S.false assert refine(Q.positive(x), Q.real(x)) == Q.positive(x)
722e58875b9ad2cb6959d1b7e77aa19a877b18a90f4e486ac6f140949892e789
from sympy.assumptions import Q from sympy.core.expr import Expr from sympy.core.add import Add from sympy.core.function import Function from sympy.core.numbers import I, Integer, oo, pi, Rational from sympy.core.singleton import S from sympy.core.symbol import Symbol, symbols from sympy.functions.elementary.complexes import Abs from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import cos, sin from sympy.matrices.common import (ShapeError, NonSquareMatrixError, _MinimalMatrix, _CastableMatrix, MatrixShaping, MatrixProperties, MatrixOperations, MatrixArithmetic, MatrixSpecial) from sympy.matrices.matrices import MatrixCalculus from sympy.matrices import (Matrix, diag, eye, matrix_multiply_elementwise, ones, zeros, SparseMatrix, banded, MutableDenseMatrix, MutableSparseMatrix, ImmutableDenseMatrix, ImmutableSparseMatrix) from sympy.polys.polytools import Poly from sympy.utilities.iterables import flatten from sympy.testing.pytest import raises, XFAIL, warns_deprecated_sympy from sympy import Array from sympy.abc import x, y, z # classes to test the basic matrix classes class ShapingOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixShaping): pass def eye_Shaping(n): return ShapingOnlyMatrix(n, n, lambda i, j: int(i == j)) def zeros_Shaping(n): return ShapingOnlyMatrix(n, n, lambda i, j: 0) class PropertiesOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixProperties): pass def eye_Properties(n): return PropertiesOnlyMatrix(n, n, lambda i, j: int(i == j)) def zeros_Properties(n): return PropertiesOnlyMatrix(n, n, lambda i, j: 0) class OperationsOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixOperations): pass def eye_Operations(n): return OperationsOnlyMatrix(n, n, lambda i, j: int(i == j)) def zeros_Operations(n): return OperationsOnlyMatrix(n, n, lambda i, j: 0) class ArithmeticOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixArithmetic): pass def eye_Arithmetic(n): return ArithmeticOnlyMatrix(n, n, lambda i, j: int(i == j)) def zeros_Arithmetic(n): return ArithmeticOnlyMatrix(n, n, lambda i, j: 0) class SpecialOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixSpecial): pass class CalculusOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixCalculus): pass def test__MinimalMatrix(): x = _MinimalMatrix(2, 3, [1, 2, 3, 4, 5, 6]) assert x.rows == 2 assert x.cols == 3 assert x[2] == 3 assert x[1, 1] == 5 assert list(x) == [1, 2, 3, 4, 5, 6] assert list(x[1, :]) == [4, 5, 6] assert list(x[:, 1]) == [2, 5] assert list(x[:, :]) == list(x) assert x[:, :] == x assert _MinimalMatrix(x) == x assert _MinimalMatrix([[1, 2, 3], [4, 5, 6]]) == x assert _MinimalMatrix(([1, 2, 3], [4, 5, 6])) == x assert _MinimalMatrix([(1, 2, 3), (4, 5, 6)]) == x assert _MinimalMatrix(((1, 2, 3), (4, 5, 6))) == x assert not (_MinimalMatrix([[1, 2], [3, 4], [5, 6]]) == x) # ShapingOnlyMatrix tests def test_vec(): m = ShapingOnlyMatrix(2, 2, [1, 3, 2, 4]) m_vec = m.vec() assert m_vec.cols == 1 for i in range(4): assert m_vec[i] == i + 1 def test_todok(): a, b, c, d = symbols('a:d') m1 = MutableDenseMatrix([[a, b], [c, d]]) m2 = ImmutableDenseMatrix([[a, b], [c, d]]) m3 = MutableSparseMatrix([[a, b], [c, d]]) m4 = ImmutableSparseMatrix([[a, b], [c, d]]) assert m1.todok() == m2.todok() == m3.todok() == m4.todok() == \ {(0, 0): a, (0, 1): b, (1, 0): c, (1, 1): d} def test_tolist(): lst = [[S.One, S.Half, x*y, S.Zero], [x, y, z, x**2], [y, -S.One, z*x, 3]] flat_lst = [S.One, S.Half, x*y, S.Zero, x, y, z, x**2, y, -S.One, z*x, 3] m = ShapingOnlyMatrix(3, 4, flat_lst) assert m.tolist() == lst def test_row_col_del(): e = ShapingOnlyMatrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9]) raises(IndexError, lambda: e.row_del(5)) raises(IndexError, lambda: e.row_del(-5)) raises(IndexError, lambda: e.col_del(5)) raises(IndexError, lambda: e.col_del(-5)) assert e.row_del(2) == e.row_del(-1) == Matrix([[1, 2, 3], [4, 5, 6]]) assert e.col_del(2) == e.col_del(-1) == Matrix([[1, 2], [4, 5], [7, 8]]) assert e.row_del(1) == e.row_del(-2) == Matrix([[1, 2, 3], [7, 8, 9]]) assert e.col_del(1) == e.col_del(-2) == Matrix([[1, 3], [4, 6], [7, 9]]) def test_get_diag_blocks1(): a = Matrix([[1, 2], [2, 3]]) b = Matrix([[3, x], [y, 3]]) c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]]) assert a.get_diag_blocks() == [a] assert b.get_diag_blocks() == [b] assert c.get_diag_blocks() == [c] def test_get_diag_blocks2(): a = Matrix([[1, 2], [2, 3]]) b = Matrix([[3, x], [y, 3]]) c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]]) A, B, C, D = diag(a, b, b), diag(a, b, c), diag(a, c, b), diag(c, c, b) A = ShapingOnlyMatrix(A.rows, A.cols, A) B = ShapingOnlyMatrix(B.rows, B.cols, B) C = ShapingOnlyMatrix(C.rows, C.cols, C) D = ShapingOnlyMatrix(D.rows, D.cols, D) assert A.get_diag_blocks() == [a, b, b] assert B.get_diag_blocks() == [a, b, c] assert C.get_diag_blocks() == [a, c, b] assert D.get_diag_blocks() == [c, c, b] def test_shape(): m = ShapingOnlyMatrix(1, 2, [0, 0]) m.shape == (1, 2) def test_reshape(): m0 = eye_Shaping(3) assert m0.reshape(1, 9) == Matrix(1, 9, (1, 0, 0, 0, 1, 0, 0, 0, 1)) m1 = ShapingOnlyMatrix(3, 4, lambda i, j: i + j) assert m1.reshape( 4, 3) == Matrix(((0, 1, 2), (3, 1, 2), (3, 4, 2), (3, 4, 5))) assert m1.reshape(2, 6) == Matrix(((0, 1, 2, 3, 1, 2), (3, 4, 2, 3, 4, 5))) def test_row_col(): m = ShapingOnlyMatrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9]) assert m.row(0) == Matrix(1, 3, [1, 2, 3]) assert m.col(0) == Matrix(3, 1, [1, 4, 7]) def test_row_join(): assert eye_Shaping(3).row_join(Matrix([7, 7, 7])) == \ Matrix([[1, 0, 0, 7], [0, 1, 0, 7], [0, 0, 1, 7]]) def test_col_join(): assert eye_Shaping(3).col_join(Matrix([[7, 7, 7]])) == \ Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1], [7, 7, 7]]) def test_row_insert(): r4 = Matrix([[4, 4, 4]]) for i in range(-4, 5): l = [1, 0, 0] l.insert(i, 4) assert flatten(eye_Shaping(3).row_insert(i, r4).col(0).tolist()) == l def test_col_insert(): c4 = Matrix([4, 4, 4]) for i in range(-4, 5): l = [0, 0, 0] l.insert(i, 4) assert flatten(zeros_Shaping(3).col_insert(i, c4).row(0).tolist()) == l # issue 13643 assert eye_Shaping(6).col_insert(3, Matrix([[2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2]])) == \ Matrix([[1, 0, 0, 2, 2, 0, 0, 0], [0, 1, 0, 2, 2, 0, 0, 0], [0, 0, 1, 2, 2, 0, 0, 0], [0, 0, 0, 2, 2, 1, 0, 0], [0, 0, 0, 2, 2, 0, 1, 0], [0, 0, 0, 2, 2, 0, 0, 1]]) def test_extract(): m = ShapingOnlyMatrix(4, 3, lambda i, j: i*3 + j) assert m.extract([0, 1, 3], [0, 1]) == Matrix(3, 2, [0, 1, 3, 4, 9, 10]) assert m.extract([0, 3], [0, 0, 2]) == Matrix(2, 3, [0, 0, 2, 9, 9, 11]) assert m.extract(range(4), range(3)) == m raises(IndexError, lambda: m.extract([4], [0])) raises(IndexError, lambda: m.extract([0], [3])) def test_hstack(): m = ShapingOnlyMatrix(4, 3, lambda i, j: i*3 + j) m2 = ShapingOnlyMatrix(3, 4, lambda i, j: i*3 + j) assert m == m.hstack(m) assert m.hstack(m, m, m) == ShapingOnlyMatrix.hstack(m, m, m) == Matrix([ [0, 1, 2, 0, 1, 2, 0, 1, 2], [3, 4, 5, 3, 4, 5, 3, 4, 5], [6, 7, 8, 6, 7, 8, 6, 7, 8], [9, 10, 11, 9, 10, 11, 9, 10, 11]]) raises(ShapeError, lambda: m.hstack(m, m2)) assert Matrix.hstack() == Matrix() # test regression #12938 M1 = Matrix.zeros(0, 0) M2 = Matrix.zeros(0, 1) M3 = Matrix.zeros(0, 2) M4 = Matrix.zeros(0, 3) m = ShapingOnlyMatrix.hstack(M1, M2, M3, M4) assert m.rows == 0 and m.cols == 6 def test_vstack(): m = ShapingOnlyMatrix(4, 3, lambda i, j: i*3 + j) m2 = ShapingOnlyMatrix(3, 4, lambda i, j: i*3 + j) assert m == m.vstack(m) assert m.vstack(m, m, m) == ShapingOnlyMatrix.vstack(m, m, m) == Matrix([ [0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]) raises(ShapeError, lambda: m.vstack(m, m2)) assert Matrix.vstack() == Matrix() # PropertiesOnlyMatrix tests def test_atoms(): m = PropertiesOnlyMatrix(2, 2, [1, 2, x, 1 - 1/x]) assert m.atoms() == {S.One, S(2), S.NegativeOne, x} assert m.atoms(Symbol) == {x} def test_free_symbols(): assert PropertiesOnlyMatrix([[x], [0]]).free_symbols == {x} def test_has(): A = PropertiesOnlyMatrix(((x, y), (2, 3))) assert A.has(x) assert not A.has(z) assert A.has(Symbol) A = PropertiesOnlyMatrix(((2, y), (2, 3))) assert not A.has(x) def test_is_anti_symmetric(): x = symbols('x') assert PropertiesOnlyMatrix(2, 1, [1, 2]).is_anti_symmetric() is False m = PropertiesOnlyMatrix(3, 3, [0, x**2 + 2*x + 1, y, -(x + 1)**2, 0, x*y, -y, -x*y, 0]) assert m.is_anti_symmetric() is True assert m.is_anti_symmetric(simplify=False) is False assert m.is_anti_symmetric(simplify=lambda x: x) is False m = PropertiesOnlyMatrix(3, 3, [x.expand() for x in m]) assert m.is_anti_symmetric(simplify=False) is True m = PropertiesOnlyMatrix(3, 3, [x.expand() for x in [S.One] + list(m)[1:]]) assert m.is_anti_symmetric() is False def test_diagonal_symmetrical(): m = PropertiesOnlyMatrix(2, 2, [0, 1, 1, 0]) assert not m.is_diagonal() assert m.is_symmetric() assert m.is_symmetric(simplify=False) m = PropertiesOnlyMatrix(2, 2, [1, 0, 0, 1]) assert m.is_diagonal() m = PropertiesOnlyMatrix(3, 3, diag(1, 2, 3)) assert m.is_diagonal() assert m.is_symmetric() m = PropertiesOnlyMatrix(3, 3, [1, 0, 0, 0, 2, 0, 0, 0, 3]) assert m == diag(1, 2, 3) m = PropertiesOnlyMatrix(2, 3, zeros(2, 3)) assert not m.is_symmetric() assert m.is_diagonal() m = PropertiesOnlyMatrix(((5, 0), (0, 6), (0, 0))) assert m.is_diagonal() m = PropertiesOnlyMatrix(((5, 0, 0), (0, 6, 0))) assert m.is_diagonal() m = Matrix(3, 3, [1, x**2 + 2*x + 1, y, (x + 1)**2, 2, 0, y, 0, 3]) assert m.is_symmetric() assert not m.is_symmetric(simplify=False) assert m.expand().is_symmetric(simplify=False) def test_is_hermitian(): a = PropertiesOnlyMatrix([[1, I], [-I, 1]]) assert a.is_hermitian a = PropertiesOnlyMatrix([[2*I, I], [-I, 1]]) assert a.is_hermitian is False a = PropertiesOnlyMatrix([[x, I], [-I, 1]]) assert a.is_hermitian is None a = PropertiesOnlyMatrix([[x, 1], [-I, 1]]) assert a.is_hermitian is False def test_is_Identity(): assert eye_Properties(3).is_Identity assert not PropertiesOnlyMatrix(zeros(3)).is_Identity assert not PropertiesOnlyMatrix(ones(3)).is_Identity # issue 6242 assert not PropertiesOnlyMatrix([[1, 0, 0]]).is_Identity def test_is_symbolic(): a = PropertiesOnlyMatrix([[x, x], [x, x]]) assert a.is_symbolic() is True a = PropertiesOnlyMatrix([[1, 2, 3, 4], [5, 6, 7, 8]]) assert a.is_symbolic() is False a = PropertiesOnlyMatrix([[1, 2, 3, 4], [5, 6, x, 8]]) assert a.is_symbolic() is True a = PropertiesOnlyMatrix([[1, x, 3]]) assert a.is_symbolic() is True a = PropertiesOnlyMatrix([[1, 2, 3]]) assert a.is_symbolic() is False a = PropertiesOnlyMatrix([[1], [x], [3]]) assert a.is_symbolic() is True a = PropertiesOnlyMatrix([[1], [2], [3]]) assert a.is_symbolic() is False def test_is_upper(): a = PropertiesOnlyMatrix([[1, 2, 3]]) assert a.is_upper is True a = PropertiesOnlyMatrix([[1], [2], [3]]) assert a.is_upper is False def test_is_lower(): a = PropertiesOnlyMatrix([[1, 2, 3]]) assert a.is_lower is False a = PropertiesOnlyMatrix([[1], [2], [3]]) assert a.is_lower is True def test_is_square(): m = PropertiesOnlyMatrix([[1], [1]]) m2 = PropertiesOnlyMatrix([[2, 2], [2, 2]]) assert not m.is_square assert m2.is_square def test_is_symmetric(): m = PropertiesOnlyMatrix(2, 2, [0, 1, 1, 0]) assert m.is_symmetric() m = PropertiesOnlyMatrix(2, 2, [0, 1, 0, 1]) assert not m.is_symmetric() def test_is_hessenberg(): A = PropertiesOnlyMatrix([[3, 4, 1], [2, 4, 5], [0, 1, 2]]) assert A.is_upper_hessenberg A = PropertiesOnlyMatrix(3, 3, [3, 2, 0, 4, 4, 1, 1, 5, 2]) assert A.is_lower_hessenberg A = PropertiesOnlyMatrix(3, 3, [3, 2, -1, 4, 4, 1, 1, 5, 2]) assert A.is_lower_hessenberg is False assert A.is_upper_hessenberg is False A = PropertiesOnlyMatrix([[3, 4, 1], [2, 4, 5], [3, 1, 2]]) assert not A.is_upper_hessenberg def test_is_zero(): assert PropertiesOnlyMatrix(0, 0, []).is_zero_matrix assert PropertiesOnlyMatrix([[0, 0], [0, 0]]).is_zero_matrix assert PropertiesOnlyMatrix(zeros(3, 4)).is_zero_matrix assert not PropertiesOnlyMatrix(eye(3)).is_zero_matrix assert PropertiesOnlyMatrix([[x, 0], [0, 0]]).is_zero_matrix == None assert PropertiesOnlyMatrix([[x, 1], [0, 0]]).is_zero_matrix == False a = Symbol('a', nonzero=True) assert PropertiesOnlyMatrix([[a, 0], [0, 0]]).is_zero_matrix == False def test_values(): assert set(PropertiesOnlyMatrix(2, 2, [0, 1, 2, 3] ).values()) == {1, 2, 3} x = Symbol('x', real=True) assert set(PropertiesOnlyMatrix(2, 2, [x, 0, 0, 1] ).values()) == {x, 1} # OperationsOnlyMatrix tests def test_applyfunc(): m0 = OperationsOnlyMatrix(eye(3)) assert m0.applyfunc(lambda x: 2*x) == eye(3)*2 assert m0.applyfunc(lambda x: 0) == zeros(3) assert m0.applyfunc(lambda x: 1) == ones(3) def test_adjoint(): dat = [[0, I], [1, 0]] ans = OperationsOnlyMatrix([[0, 1], [-I, 0]]) assert ans.adjoint() == Matrix(dat) def test_as_real_imag(): m1 = OperationsOnlyMatrix(2, 2, [1, 2, 3, 4]) m3 = OperationsOnlyMatrix(2, 2, [1 + S.ImaginaryUnit, 2 + 2*S.ImaginaryUnit, 3 + 3*S.ImaginaryUnit, 4 + 4*S.ImaginaryUnit]) a, b = m3.as_real_imag() assert a == m1 assert b == m1 def test_conjugate(): M = OperationsOnlyMatrix([[0, I, 5], [1, 2, 0]]) assert M.T == Matrix([[0, 1], [I, 2], [5, 0]]) assert M.C == Matrix([[0, -I, 5], [1, 2, 0]]) assert M.C == M.conjugate() assert M.H == M.T.C assert M.H == Matrix([[ 0, 1], [-I, 2], [ 5, 0]]) def test_doit(): a = OperationsOnlyMatrix([[Add(x, x, evaluate=False)]]) assert a[0] != 2*x assert a.doit() == Matrix([[2*x]]) def test_evalf(): a = OperationsOnlyMatrix(2, 1, [sqrt(5), 6]) assert all(a.evalf()[i] == a[i].evalf() for i in range(2)) assert all(a.evalf(2)[i] == a[i].evalf(2) for i in range(2)) assert all(a.n(2)[i] == a[i].n(2) for i in range(2)) def test_expand(): m0 = OperationsOnlyMatrix([[x*(x + y), 2], [((x + y)*y)*x, x*(y + x*(x + y))]]) # Test if expand() returns a matrix m1 = m0.expand() assert m1 == Matrix( [[x*y + x**2, 2], [x*y**2 + y*x**2, x*y + y*x**2 + x**3]]) a = Symbol('a', real=True) assert OperationsOnlyMatrix(1, 1, [exp(I*a)]).expand(complex=True) == \ Matrix([cos(a) + I*sin(a)]) def test_refine(): m0 = OperationsOnlyMatrix([[Abs(x)**2, sqrt(x**2)], [sqrt(x**2)*Abs(y)**2, sqrt(y**2)*Abs(x)**2]]) m1 = m0.refine(Q.real(x) & Q.real(y)) assert m1 == Matrix([[x**2, Abs(x)], [y**2*Abs(x), x**2*Abs(y)]]) m1 = m0.refine(Q.positive(x) & Q.positive(y)) assert m1 == Matrix([[x**2, x], [x*y**2, x**2*y]]) m1 = m0.refine(Q.negative(x) & Q.negative(y)) assert m1 == Matrix([[x**2, -x], [-x*y**2, -x**2*y]]) def test_replace(): F, G = symbols('F, G', cls=Function) K = OperationsOnlyMatrix(2, 2, lambda i, j: G(i+j)) M = OperationsOnlyMatrix(2, 2, lambda i, j: F(i+j)) N = M.replace(F, G) assert N == K def test_replace_map(): F, G = symbols('F, G', cls=Function) K = OperationsOnlyMatrix(2, 2, [(G(0), {F(0): G(0)}), (G(1), {F(1): G(1)}), (G(1), {F(1) \ : G(1)}), (G(2), {F(2): G(2)})]) M = OperationsOnlyMatrix(2, 2, lambda i, j: F(i+j)) N = M.replace(F, G, True) assert N == K def test_rot90(): A = Matrix([[1, 2], [3, 4]]) assert A == A.rot90(0) == A.rot90(4) assert A.rot90(2) == A.rot90(-2) == A.rot90(6) == Matrix(((4, 3), (2, 1))) assert A.rot90(3) == A.rot90(-1) == A.rot90(7) == Matrix(((2, 4), (1, 3))) assert A.rot90() == A.rot90(-7) == A.rot90(-3) == Matrix(((3, 1), (4, 2))) def test_simplify(): n = Symbol('n') f = Function('f') M = OperationsOnlyMatrix([[ 1/x + 1/y, (x + x*y) / x ], [ (f(x) + y*f(x))/f(x), 2 * (1/n - cos(n * pi)/n) / pi ]]) assert M.simplify() == Matrix([[ (x + y)/(x * y), 1 + y ], [ 1 + y, 2*((1 - 1*cos(pi*n))/(pi*n)) ]]) eq = (1 + x)**2 M = OperationsOnlyMatrix([[eq]]) assert M.simplify() == Matrix([[eq]]) assert M.simplify(ratio=oo) == Matrix([[eq.simplify(ratio=oo)]]) def test_subs(): assert OperationsOnlyMatrix([[1, x], [x, 4]]).subs(x, 5) == Matrix([[1, 5], [5, 4]]) assert OperationsOnlyMatrix([[x, 2], [x + y, 4]]).subs([[x, -1], [y, -2]]) == \ Matrix([[-1, 2], [-3, 4]]) assert OperationsOnlyMatrix([[x, 2], [x + y, 4]]).subs([(x, -1), (y, -2)]) == \ Matrix([[-1, 2], [-3, 4]]) assert OperationsOnlyMatrix([[x, 2], [x + y, 4]]).subs({x: -1, y: -2}) == \ Matrix([[-1, 2], [-3, 4]]) assert OperationsOnlyMatrix([[x*y]]).subs({x: y - 1, y: x - 1}, simultaneous=True) == \ Matrix([[(x - 1)*(y - 1)]]) def test_trace(): M = OperationsOnlyMatrix([[1, 0, 0], [0, 5, 0], [0, 0, 8]]) assert M.trace() == 14 def test_xreplace(): assert OperationsOnlyMatrix([[1, x], [x, 4]]).xreplace({x: 5}) == \ Matrix([[1, 5], [5, 4]]) assert OperationsOnlyMatrix([[x, 2], [x + y, 4]]).xreplace({x: -1, y: -2}) == \ Matrix([[-1, 2], [-3, 4]]) def test_permute(): a = OperationsOnlyMatrix(3, 4, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) raises(IndexError, lambda: a.permute([[0, 5]])) raises(ValueError, lambda: a.permute(Symbol('x'))) b = a.permute_rows([[0, 2], [0, 1]]) assert a.permute([[0, 2], [0, 1]]) == b == Matrix([ [5, 6, 7, 8], [9, 10, 11, 12], [1, 2, 3, 4]]) b = a.permute_cols([[0, 2], [0, 1]]) assert a.permute([[0, 2], [0, 1]], orientation='cols') == b ==\ Matrix([ [ 2, 3, 1, 4], [ 6, 7, 5, 8], [10, 11, 9, 12]]) b = a.permute_cols([[0, 2], [0, 1]], direction='backward') assert a.permute([[0, 2], [0, 1]], orientation='cols', direction='backward') == b ==\ Matrix([ [ 3, 1, 2, 4], [ 7, 5, 6, 8], [11, 9, 10, 12]]) assert a.permute([1, 2, 0, 3]) == Matrix([ [5, 6, 7, 8], [9, 10, 11, 12], [1, 2, 3, 4]]) from sympy.combinatorics import Permutation assert a.permute(Permutation([1, 2, 0, 3])) == Matrix([ [5, 6, 7, 8], [9, 10, 11, 12], [1, 2, 3, 4]]) def test_upper_triangular(): A = OperationsOnlyMatrix([ [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1] ]) R = A.upper_triangular(2) assert R == OperationsOnlyMatrix([ [0, 0, 1, 1], [0, 0, 0, 1], [0, 0, 0, 0], [0, 0, 0, 0] ]) R = A.upper_triangular(-2) assert R == OperationsOnlyMatrix([ [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 1] ]) R = A.upper_triangular() assert R == OperationsOnlyMatrix([ [1, 1, 1, 1], [0, 1, 1, 1], [0, 0, 1, 1], [0, 0, 0, 1] ]) def test_lower_triangular(): A = OperationsOnlyMatrix([ [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1] ]) L = A.lower_triangular() assert L == ArithmeticOnlyMatrix([ [1, 0, 0, 0], [1, 1, 0, 0], [1, 1, 1, 0], [1, 1, 1, 1]]) L = A.lower_triangular(2) assert L == ArithmeticOnlyMatrix([ [1, 1, 1, 0], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1] ]) L = A.lower_triangular(-2) assert L == ArithmeticOnlyMatrix([ [0, 0, 0, 0], [0, 0, 0, 0], [1, 0, 0, 0], [1, 1, 0, 0] ]) # ArithmeticOnlyMatrix tests def test_abs(): m = ArithmeticOnlyMatrix([[1, -2], [x, y]]) assert abs(m) == ArithmeticOnlyMatrix([[1, 2], [Abs(x), Abs(y)]]) def test_add(): m = ArithmeticOnlyMatrix([[1, 2, 3], [x, y, x], [2*y, -50, z*x]]) assert m + m == ArithmeticOnlyMatrix([[2, 4, 6], [2*x, 2*y, 2*x], [4*y, -100, 2*z*x]]) n = ArithmeticOnlyMatrix(1, 2, [1, 2]) raises(ShapeError, lambda: m + n) def test_multiplication(): a = ArithmeticOnlyMatrix(( (1, 2), (3, 1), (0, 6), )) b = ArithmeticOnlyMatrix(( (1, 2), (3, 0), )) raises(ShapeError, lambda: b*a) raises(TypeError, lambda: a*{}) c = a*b assert c[0, 0] == 7 assert c[0, 1] == 2 assert c[1, 0] == 6 assert c[1, 1] == 6 assert c[2, 0] == 18 assert c[2, 1] == 0 try: eval('c = a @ b') except SyntaxError: pass else: assert c[0, 0] == 7 assert c[0, 1] == 2 assert c[1, 0] == 6 assert c[1, 1] == 6 assert c[2, 0] == 18 assert c[2, 1] == 0 h = a.multiply_elementwise(c) assert h == matrix_multiply_elementwise(a, c) assert h[0, 0] == 7 assert h[0, 1] == 4 assert h[1, 0] == 18 assert h[1, 1] == 6 assert h[2, 0] == 0 assert h[2, 1] == 0 raises(ShapeError, lambda: a.multiply_elementwise(b)) c = b * Symbol("x") assert isinstance(c, ArithmeticOnlyMatrix) assert c[0, 0] == x assert c[0, 1] == 2*x assert c[1, 0] == 3*x assert c[1, 1] == 0 c2 = x * b assert c == c2 c = 5 * b assert isinstance(c, ArithmeticOnlyMatrix) assert c[0, 0] == 5 assert c[0, 1] == 2*5 assert c[1, 0] == 3*5 assert c[1, 1] == 0 try: eval('c = 5 @ b') except SyntaxError: pass else: assert isinstance(c, ArithmeticOnlyMatrix) assert c[0, 0] == 5 assert c[0, 1] == 2*5 assert c[1, 0] == 3*5 assert c[1, 1] == 0 def test_matmul(): a = Matrix([[1, 2], [3, 4]]) assert a.__matmul__(2) == NotImplemented assert a.__rmatmul__(2) == NotImplemented #This is done this way because @ is only supported in Python 3.5+ #To check 2@a case try: eval('2 @ a') except SyntaxError: pass except TypeError: #TypeError is raised in case of NotImplemented is returned pass #Check a@2 case try: eval('a @ 2') except SyntaxError: pass except TypeError: #TypeError is raised in case of NotImplemented is returned pass def test_non_matmul(): """ Test that if explicitly specified as non-matrix, mul reverts to scalar multiplication. """ class foo(Expr): is_Matrix=False is_MatrixLike=False shape = (1, 1) A = Matrix([[1, 2], [3, 4]]) b = foo() assert b*A == Matrix([[b, 2*b], [3*b, 4*b]]) assert A*b == Matrix([[b, 2*b], [3*b, 4*b]]) def test_power(): raises(NonSquareMatrixError, lambda: Matrix((1, 2))**2) A = ArithmeticOnlyMatrix([[2, 3], [4, 5]]) assert (A**5)[:] == (6140, 8097, 10796, 14237) A = ArithmeticOnlyMatrix([[2, 1, 3], [4, 2, 4], [6, 12, 1]]) assert (A**3)[:] == (290, 262, 251, 448, 440, 368, 702, 954, 433) assert A**0 == eye(3) assert A**1 == A assert (ArithmeticOnlyMatrix([[2]]) ** 100)[0, 0] == 2**100 assert ArithmeticOnlyMatrix([[1, 2], [3, 4]])**Integer(2) == ArithmeticOnlyMatrix([[7, 10], [15, 22]]) A = Matrix([[1,2],[4,5]]) assert A.pow(20, method='cayley') == A.pow(20, method='multiply') def test_neg(): n = ArithmeticOnlyMatrix(1, 2, [1, 2]) assert -n == ArithmeticOnlyMatrix(1, 2, [-1, -2]) def test_sub(): n = ArithmeticOnlyMatrix(1, 2, [1, 2]) assert n - n == ArithmeticOnlyMatrix(1, 2, [0, 0]) def test_div(): n = ArithmeticOnlyMatrix(1, 2, [1, 2]) assert n/2 == ArithmeticOnlyMatrix(1, 2, [S.Half, S(2)/2]) # SpecialOnlyMatrix tests def test_eye(): assert list(SpecialOnlyMatrix.eye(2, 2)) == [1, 0, 0, 1] assert list(SpecialOnlyMatrix.eye(2)) == [1, 0, 0, 1] assert type(SpecialOnlyMatrix.eye(2)) == SpecialOnlyMatrix assert type(SpecialOnlyMatrix.eye(2, cls=Matrix)) == Matrix def test_ones(): assert list(SpecialOnlyMatrix.ones(2, 2)) == [1, 1, 1, 1] assert list(SpecialOnlyMatrix.ones(2)) == [1, 1, 1, 1] assert SpecialOnlyMatrix.ones(2, 3) == Matrix([[1, 1, 1], [1, 1, 1]]) assert type(SpecialOnlyMatrix.ones(2)) == SpecialOnlyMatrix assert type(SpecialOnlyMatrix.ones(2, cls=Matrix)) == Matrix def test_zeros(): assert list(SpecialOnlyMatrix.zeros(2, 2)) == [0, 0, 0, 0] assert list(SpecialOnlyMatrix.zeros(2)) == [0, 0, 0, 0] assert SpecialOnlyMatrix.zeros(2, 3) == Matrix([[0, 0, 0], [0, 0, 0]]) assert type(SpecialOnlyMatrix.zeros(2)) == SpecialOnlyMatrix assert type(SpecialOnlyMatrix.zeros(2, cls=Matrix)) == Matrix def test_diag_make(): diag = SpecialOnlyMatrix.diag a = Matrix([[1, 2], [2, 3]]) b = Matrix([[3, x], [y, 3]]) c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]]) assert diag(a, b, b) == Matrix([ [1, 2, 0, 0, 0, 0], [2, 3, 0, 0, 0, 0], [0, 0, 3, x, 0, 0], [0, 0, y, 3, 0, 0], [0, 0, 0, 0, 3, x], [0, 0, 0, 0, y, 3], ]) assert diag(a, b, c) == Matrix([ [1, 2, 0, 0, 0, 0, 0], [2, 3, 0, 0, 0, 0, 0], [0, 0, 3, x, 0, 0, 0], [0, 0, y, 3, 0, 0, 0], [0, 0, 0, 0, 3, x, 3], [0, 0, 0, 0, y, 3, z], [0, 0, 0, 0, x, y, z], ]) assert diag(a, c, b) == Matrix([ [1, 2, 0, 0, 0, 0, 0], [2, 3, 0, 0, 0, 0, 0], [0, 0, 3, x, 3, 0, 0], [0, 0, y, 3, z, 0, 0], [0, 0, x, y, z, 0, 0], [0, 0, 0, 0, 0, 3, x], [0, 0, 0, 0, 0, y, 3], ]) a = Matrix([x, y, z]) b = Matrix([[1, 2], [3, 4]]) c = Matrix([[5, 6]]) # this "wandering diagonal" is what makes this # a block diagonal where each block is independent # of the others assert diag(a, 7, b, c) == Matrix([ [x, 0, 0, 0, 0, 0], [y, 0, 0, 0, 0, 0], [z, 0, 0, 0, 0, 0], [0, 7, 0, 0, 0, 0], [0, 0, 1, 2, 0, 0], [0, 0, 3, 4, 0, 0], [0, 0, 0, 0, 5, 6]]) raises(ValueError, lambda: diag(a, 7, b, c, rows=5)) assert diag(1) == Matrix([[1]]) assert diag(1, rows=2) == Matrix([[1, 0], [0, 0]]) assert diag(1, cols=2) == Matrix([[1, 0], [0, 0]]) assert diag(1, rows=3, cols=2) == Matrix([[1, 0], [0, 0], [0, 0]]) assert diag(*[2, 3]) == Matrix([ [2, 0], [0, 3]]) assert diag(Matrix([2, 3])) == Matrix([ [2], [3]]) assert diag([1, [2, 3], 4], unpack=False) == \ diag([[1], [2, 3], [4]], unpack=False) == Matrix([ [1, 0], [2, 3], [4, 0]]) assert type(diag(1)) == SpecialOnlyMatrix assert type(diag(1, cls=Matrix)) == Matrix assert Matrix.diag([1, 2, 3]) == Matrix.diag(1, 2, 3) assert Matrix.diag([1, 2, 3], unpack=False).shape == (3, 1) assert Matrix.diag([[1, 2, 3]]).shape == (3, 1) assert Matrix.diag([[1, 2, 3]], unpack=False).shape == (1, 3) assert Matrix.diag([[[1, 2, 3]]]).shape == (1, 3) # kerning can be used to move the starting point assert Matrix.diag(ones(0, 2), 1, 2) == Matrix([ [0, 0, 1, 0], [0, 0, 0, 2]]) assert Matrix.diag(ones(2, 0), 1, 2) == Matrix([ [0, 0], [0, 0], [1, 0], [0, 2]]) def test_diagonal(): m = Matrix(3, 3, range(9)) d = m.diagonal() assert d == m.diagonal(0) assert tuple(d) == (0, 4, 8) assert tuple(m.diagonal(1)) == (1, 5) assert tuple(m.diagonal(-1)) == (3, 7) assert tuple(m.diagonal(2)) == (2,) assert type(m.diagonal()) == type(m) s = SparseMatrix(3, 3, {(1, 1): 1}) assert type(s.diagonal()) == type(s) assert type(m) != type(s) raises(ValueError, lambda: m.diagonal(3)) raises(ValueError, lambda: m.diagonal(-3)) raises(ValueError, lambda: m.diagonal(pi)) M = ones(2, 3) assert banded({i: list(M.diagonal(i)) for i in range(1-M.rows, M.cols)}) == M def test_jordan_block(): assert SpecialOnlyMatrix.jordan_block(3, 2) == SpecialOnlyMatrix.jordan_block(3, eigenvalue=2) \ == SpecialOnlyMatrix.jordan_block(size=3, eigenvalue=2) \ == SpecialOnlyMatrix.jordan_block(3, 2, band='upper') \ == SpecialOnlyMatrix.jordan_block( size=3, eigenval=2, eigenvalue=2) \ == Matrix([ [2, 1, 0], [0, 2, 1], [0, 0, 2]]) assert SpecialOnlyMatrix.jordan_block(3, 2, band='lower') == Matrix([ [2, 0, 0], [1, 2, 0], [0, 1, 2]]) # missing eigenvalue raises(ValueError, lambda: SpecialOnlyMatrix.jordan_block(2)) # non-integral size raises(ValueError, lambda: SpecialOnlyMatrix.jordan_block(3.5, 2)) # size not specified raises(ValueError, lambda: SpecialOnlyMatrix.jordan_block(eigenvalue=2)) # inconsistent eigenvalue raises(ValueError, lambda: SpecialOnlyMatrix.jordan_block( eigenvalue=2, eigenval=4)) # Deprecated feature with warns_deprecated_sympy(): assert (SpecialOnlyMatrix.jordan_block(cols=3, eigenvalue=2) == SpecialOnlyMatrix(3, 3, (2, 1, 0, 0, 2, 1, 0, 0, 2))) with warns_deprecated_sympy(): assert (SpecialOnlyMatrix.jordan_block(rows=3, eigenvalue=2) == SpecialOnlyMatrix(3, 3, (2, 1, 0, 0, 2, 1, 0, 0, 2))) with warns_deprecated_sympy(): assert SpecialOnlyMatrix.jordan_block(3, 2) == \ SpecialOnlyMatrix.jordan_block(cols=3, eigenvalue=2) == \ SpecialOnlyMatrix.jordan_block(rows=3, eigenvalue=2) with warns_deprecated_sympy(): assert SpecialOnlyMatrix.jordan_block( rows=4, cols=3, eigenvalue=2) == \ Matrix([ [2, 1, 0], [0, 2, 1], [0, 0, 2], [0, 0, 0]]) # Using alias keyword assert SpecialOnlyMatrix.jordan_block(size=3, eigenvalue=2) == \ SpecialOnlyMatrix.jordan_block(size=3, eigenval=2) def test_orthogonalize(): m = Matrix([[1, 2], [3, 4]]) assert m.orthogonalize(Matrix([[2], [1]])) == [Matrix([[2], [1]])] assert m.orthogonalize(Matrix([[2], [1]]), normalize=True) == \ [Matrix([[2*sqrt(5)/5], [sqrt(5)/5]])] assert m.orthogonalize(Matrix([[1], [2]]), Matrix([[-1], [4]])) == \ [Matrix([[1], [2]]), Matrix([[Rational(-12, 5)], [Rational(6, 5)]])] assert m.orthogonalize(Matrix([[0], [0]]), Matrix([[-1], [4]])) == \ [Matrix([[-1], [4]])] assert m.orthogonalize(Matrix([[0], [0]])) == [] n = Matrix([[9, 1, 9], [3, 6, 10], [8, 5, 2]]) vecs = [Matrix([[-5], [1]]), Matrix([[-5], [2]]), Matrix([[-5], [-2]])] assert n.orthogonalize(*vecs) == \ [Matrix([[-5], [1]]), Matrix([[Rational(5, 26)], [Rational(25, 26)]])] vecs = [Matrix([0, 0, 0]), Matrix([1, 2, 3]), Matrix([1, 4, 5])] raises(ValueError, lambda: Matrix.orthogonalize(*vecs, rankcheck=True)) vecs = [Matrix([1, 2, 3]), Matrix([4, 5, 6]), Matrix([7, 8, 9])] raises(ValueError, lambda: Matrix.orthogonalize(*vecs, rankcheck=True)) def test_wilkinson(): wminus, wplus = Matrix.wilkinson(1) assert wminus == Matrix([ [-1, 1, 0], [1, 0, 1], [0, 1, 1]]) assert wplus == Matrix([ [1, 1, 0], [1, 0, 1], [0, 1, 1]]) wminus, wplus = Matrix.wilkinson(3) assert wminus == Matrix([ [-3, 1, 0, 0, 0, 0, 0], [1, -2, 1, 0, 0, 0, 0], [0, 1, -1, 1, 0, 0, 0], [0, 0, 1, 0, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0], [0, 0, 0, 0, 1, 2, 1], [0, 0, 0, 0, 0, 1, 3]]) assert wplus == Matrix([ [3, 1, 0, 0, 0, 0, 0], [1, 2, 1, 0, 0, 0, 0], [0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 0, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0], [0, 0, 0, 0, 1, 2, 1], [0, 0, 0, 0, 0, 1, 3]]) # CalculusOnlyMatrix tests @XFAIL def test_diff(): x, y = symbols('x y') m = CalculusOnlyMatrix(2, 1, [x, y]) # TODO: currently not working as ``_MinimalMatrix`` cannot be sympified: assert m.diff(x) == Matrix(2, 1, [1, 0]) def test_integrate(): x, y = symbols('x y') m = CalculusOnlyMatrix(2, 1, [x, y]) assert m.integrate(x) == Matrix(2, 1, [x**2/2, y*x]) def test_jacobian2(): rho, phi = symbols("rho,phi") X = CalculusOnlyMatrix(3, 1, [rho*cos(phi), rho*sin(phi), rho**2]) Y = CalculusOnlyMatrix(2, 1, [rho, phi]) J = Matrix([ [cos(phi), -rho*sin(phi)], [sin(phi), rho*cos(phi)], [ 2*rho, 0], ]) assert X.jacobian(Y) == J m = CalculusOnlyMatrix(2, 2, [1, 2, 3, 4]) m2 = CalculusOnlyMatrix(4, 1, [1, 2, 3, 4]) raises(TypeError, lambda: m.jacobian(Matrix([1, 2]))) raises(TypeError, lambda: m2.jacobian(m)) def test_limit(): x, y = symbols('x y') m = CalculusOnlyMatrix(2, 1, [1/x, y]) assert m.limit(x, 5) == Matrix(2, 1, [Rational(1, 5), y]) def test_issue_13774(): M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) v = [1, 1, 1] raises(TypeError, lambda: M*v) raises(TypeError, lambda: v*M) def test_companion(): x = Symbol('x') y = Symbol('y') raises(ValueError, lambda: Matrix.companion(1)) raises(ValueError, lambda: Matrix.companion(Poly([1], x))) raises(ValueError, lambda: Matrix.companion(Poly([2, 1], x))) raises(ValueError, lambda: Matrix.companion(Poly(x*y, [x, y]))) c0, c1, c2 = symbols('c0:3') assert Matrix.companion(Poly([1, c0], x)) == Matrix([-c0]) assert Matrix.companion(Poly([1, c1, c0], x)) == \ Matrix([[0, -c0], [1, -c1]]) assert Matrix.companion(Poly([1, c2, c1, c0], x)) == \ Matrix([[0, 0, -c0], [1, 0, -c1], [0, 1, -c2]]) def test_issue_10589(): x, y, z = symbols("x, y z") M1 = Matrix([x, y, z]) M1 = M1.subs(zip([x, y, z], [1, 2, 3])) assert M1 == Matrix([[1], [2], [3]]) M2 = Matrix([[x, x, x, x, x], [x, x, x, x, x], [x, x, x, x, x]]) M2 = M2.subs(zip([x], [1])) assert M2 == Matrix([[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]) def test_rmul_pr19860(): class Foo(ImmutableDenseMatrix): _op_priority = MutableDenseMatrix._op_priority + 0.01 a = Matrix(2, 2, [1, 2, 3, 4]) b = Foo(2, 2, [1, 2, 3, 4]) # This would throw a RecursionError: maximum recursion depth # since b always has higher priority even after a.as_mutable() c = a*b assert isinstance(c, Foo) assert c == Matrix([[7, 10], [15, 22]]) def test_issue_18956(): A = Array([[1, 2], [3, 4]]) B = Matrix([[1,2],[3,4]]) raises(TypeError, lambda: B + A) raises(TypeError, lambda: A + B)
4d55a7d056158e79b05f4839b3b119f2aa1d129213c9d19f8ee7296975e831f8
import random from sympy.core.numbers import I from sympy import symbols, Symbol, Rational, sqrt, Poly from sympy.matrices import Matrix, eye, ones from sympy.abc import x, y, z from sympy.testing.pytest import raises from sympy.matrices.matrices import MatrixDeterminant from sympy.matrices.common import NonSquareMatrixError, _MinimalMatrix, _CastableMatrix from sympy.functions.combinatorial.factorials import factorial, subfactorial class DeterminantOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixDeterminant): pass def test_determinant(): for M in [Matrix(), Matrix([[1]])]: assert ( M.det() == M._eval_det_bareiss() == M._eval_det_berkowitz() == M._eval_det_lu() == 1) M = Matrix(( (-3, 2), ( 8, -5) )) assert M.det(method="domain-ge") == -1 assert M.det(method="bareiss") == -1 assert M.det(method="berkowitz") == -1 assert M.det(method="lu") == -1 M = Matrix(( (x, 1), (y, 2*y) )) assert M.det(method="domain-ge") == 2*x*y - y assert M.det(method="bareiss") == 2*x*y - y assert M.det(method="berkowitz") == 2*x*y - y assert M.det(method="lu") == 2*x*y - y M = Matrix(( (1, 1, 1), (1, 2, 3), (1, 3, 6) )) assert M.det(method="domain-ge") == 1 assert M.det(method="bareiss") == 1 assert M.det(method="berkowitz") == 1 assert M.det(method="lu") == 1 M = Matrix(( ( 3, -2, 0, 5), (-2, 1, -2, 2), ( 0, -2, 5, 0), ( 5, 0, 3, 4) )) assert M.det(method="domain-ge") == -289 assert M.det(method="bareiss") == -289 assert M.det(method="berkowitz") == -289 assert M.det(method="lu") == -289 M = Matrix(( ( 1, 2, 3, 4), ( 5, 6, 7, 8), ( 9, 10, 11, 12), (13, 14, 15, 16) )) assert M.det(method="domain-ge") == 0 assert M.det(method="bareiss") == 0 assert M.det(method="berkowitz") == 0 assert M.det(method="lu") == 0 M = Matrix(( (3, 2, 0, 0, 0), (0, 3, 2, 0, 0), (0, 0, 3, 2, 0), (0, 0, 0, 3, 2), (2, 0, 0, 0, 3) )) assert M.det(method="domain-ge") == 275 assert M.det(method="bareiss") == 275 assert M.det(method="berkowitz") == 275 assert M.det(method="lu") == 275 M = Matrix(( ( 3, 0, 0, 0), (-2, 1, 0, 0), ( 0, -2, 5, 0), ( 5, 0, 3, 4) )) assert M.det(method="domain-ge") == 60 assert M.det(method="bareiss") == 60 assert M.det(method="berkowitz") == 60 assert M.det(method="lu") == 60 M = Matrix(( ( 1, 0, 0, 0), ( 5, 0, 0, 0), ( 9, 10, 11, 0), (13, 14, 15, 16) )) assert M.det(method="domain-ge") == 0 assert M.det(method="bareiss") == 0 assert M.det(method="berkowitz") == 0 assert M.det(method="lu") == 0 M = Matrix(( (3, 2, 0, 0, 0), (0, 3, 2, 0, 0), (0, 0, 3, 2, 0), (0, 0, 0, 3, 2), (0, 0, 0, 0, 3) )) assert M.det(method="domain-ge") == 243 assert M.det(method="bareiss") == 243 assert M.det(method="berkowitz") == 243 assert M.det(method="lu") == 243 M = Matrix(( (1, 0, 1, 2, 12), (2, 0, 1, 1, 4), (2, 1, 1, -1, 3), (3, 2, -1, 1, 8), (1, 1, 1, 0, 6) )) assert M.det(method="domain-ge") == -55 assert M.det(method="bareiss") == -55 assert M.det(method="berkowitz") == -55 assert M.det(method="lu") == -55 M = Matrix(( (-5, 2, 3, 4, 5), ( 1, -4, 3, 4, 5), ( 1, 2, -3, 4, 5), ( 1, 2, 3, -2, 5), ( 1, 2, 3, 4, -1) )) assert M.det(method="domain-ge") == 11664 assert M.det(method="bareiss") == 11664 assert M.det(method="berkowitz") == 11664 assert M.det(method="lu") == 11664 M = Matrix(( ( 2, 7, -1, 3, 2), ( 0, 0, 1, 0, 1), (-2, 0, 7, 0, 2), (-3, -2, 4, 5, 3), ( 1, 0, 0, 0, 1) )) assert M.det(method="domain-ge") == 123 assert M.det(method="bareiss") == 123 assert M.det(method="berkowitz") == 123 assert M.det(method="lu") == 123 M = Matrix(( (x, y, z), (1, 0, 0), (y, z, x) )) assert M.det(method="domain-ge") == z**2 - x*y assert M.det(method="bareiss") == z**2 - x*y assert M.det(method="berkowitz") == z**2 - x*y assert M.det(method="lu") == z**2 - x*y # issue 13835 a = symbols('a') M = lambda n: Matrix([[i + a*j for i in range(n)] for j in range(n)]) assert M(5).det() == 0 assert M(6).det() == 0 assert M(7).det() == 0 def test_issue_14517(): M = Matrix([ [ 0, 10*I, 10*I, 0], [10*I, 0, 0, 10*I], [10*I, 0, 5 + 2*I, 10*I], [ 0, 10*I, 10*I, 5 + 2*I]]) ev = M.eigenvals() # test one random eigenvalue, the computation is a little slow test_ev = random.choice(list(ev.keys())) assert (M - test_ev*eye(4)).det() == 0 def test_legacy_det(): # Minimal support for legacy keys for 'method' in det() # Partially copied from test_determinant() M = Matrix(( ( 3, -2, 0, 5), (-2, 1, -2, 2), ( 0, -2, 5, 0), ( 5, 0, 3, 4) )) assert M.det(method="bareis") == -289 assert M.det(method="det_lu") == -289 assert M.det(method="det_LU") == -289 M = Matrix(( (3, 2, 0, 0, 0), (0, 3, 2, 0, 0), (0, 0, 3, 2, 0), (0, 0, 0, 3, 2), (2, 0, 0, 0, 3) )) assert M.det(method="bareis") == 275 assert M.det(method="det_lu") == 275 assert M.det(method="Bareis") == 275 M = Matrix(( (1, 0, 1, 2, 12), (2, 0, 1, 1, 4), (2, 1, 1, -1, 3), (3, 2, -1, 1, 8), (1, 1, 1, 0, 6) )) assert M.det(method="bareis") == -55 assert M.det(method="det_lu") == -55 assert M.det(method="BAREISS") == -55 M = Matrix(( ( 3, 0, 0, 0), (-2, 1, 0, 0), ( 0, -2, 5, 0), ( 5, 0, 3, 4) )) assert M.det(method="bareiss") == 60 assert M.det(method="berkowitz") == 60 assert M.det(method="lu") == 60 M = Matrix(( ( 1, 0, 0, 0), ( 5, 0, 0, 0), ( 9, 10, 11, 0), (13, 14, 15, 16) )) assert M.det(method="bareiss") == 0 assert M.det(method="berkowitz") == 0 assert M.det(method="lu") == 0 M = Matrix(( (3, 2, 0, 0, 0), (0, 3, 2, 0, 0), (0, 0, 3, 2, 0), (0, 0, 0, 3, 2), (0, 0, 0, 0, 3) )) assert M.det(method="bareiss") == 243 assert M.det(method="berkowitz") == 243 assert M.det(method="lu") == 243 M = Matrix(( (-5, 2, 3, 4, 5), ( 1, -4, 3, 4, 5), ( 1, 2, -3, 4, 5), ( 1, 2, 3, -2, 5), ( 1, 2, 3, 4, -1) )) assert M.det(method="bareis") == 11664 assert M.det(method="det_lu") == 11664 assert M.det(method="BERKOWITZ") == 11664 M = Matrix(( ( 2, 7, -1, 3, 2), ( 0, 0, 1, 0, 1), (-2, 0, 7, 0, 2), (-3, -2, 4, 5, 3), ( 1, 0, 0, 0, 1) )) assert M.det(method="bareis") == 123 assert M.det(method="det_lu") == 123 assert M.det(method="LU") == 123 def eye_Determinant(n): return DeterminantOnlyMatrix(n, n, lambda i, j: int(i == j)) def zeros_Determinant(n): return DeterminantOnlyMatrix(n, n, lambda i, j: 0) def test_det(): a = DeterminantOnlyMatrix(2, 3, [1, 2, 3, 4, 5, 6]) raises(NonSquareMatrixError, lambda: a.det()) z = zeros_Determinant(2) ey = eye_Determinant(2) assert z.det() == 0 assert ey.det() == 1 x = Symbol('x') a = DeterminantOnlyMatrix(0, 0, []) b = DeterminantOnlyMatrix(1, 1, [5]) c = DeterminantOnlyMatrix(2, 2, [1, 2, 3, 4]) d = DeterminantOnlyMatrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 8]) e = DeterminantOnlyMatrix(4, 4, [x, 1, 2, 3, 4, 5, 6, 7, 2, 9, 10, 11, 12, 13, 14, 14]) from sympy.abc import i, j, k, l, m, n f = DeterminantOnlyMatrix(3, 3, [i, l, m, 0, j, n, 0, 0, k]) g = DeterminantOnlyMatrix(3, 3, [i, 0, 0, l, j, 0, m, n, k]) h = DeterminantOnlyMatrix(3, 3, [x**3, 0, 0, i, x**-1, 0, j, k, x**-2]) # the method keyword for `det` doesn't kick in until 4x4 matrices, # so there is no need to test all methods on smaller ones assert a.det() == 1 assert b.det() == 5 assert c.det() == -2 assert d.det() == 3 assert e.det() == 4*x - 24 assert e.det(method="domain-ge") == 4*x - 24 assert e.det(method='bareiss') == 4*x - 24 assert e.det(method='berkowitz') == 4*x - 24 assert f.det() == i*j*k assert g.det() == i*j*k assert h.det() == 1 raises(ValueError, lambda: e.det(iszerofunc="test")) def test_permanent(): M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) assert M.per() == 450 for i in range(1, 12): assert ones(i, i).per() == ones(i, i).T.per() == factorial(i) assert (ones(i, i)-eye(i)).per() == (ones(i, i)-eye(i)).T.per() == subfactorial(i) a1, a2, a3, a4, a5 = symbols('a_1 a_2 a_3 a_4 a_5') M = Matrix([a1, a2, a3, a4, a5]) assert M.per() == M.T.per() == a1 + a2 + a3 + a4 + a5 def test_adjugate(): x = Symbol('x') e = DeterminantOnlyMatrix(4, 4, [x, 1, 2, 3, 4, 5, 6, 7, 2, 9, 10, 11, 12, 13, 14, 14]) adj = Matrix([ [ 4, -8, 4, 0], [ 76, -14*x - 68, 14*x - 8, -4*x + 24], [-122, 17*x + 142, -21*x + 4, 8*x - 48], [ 48, -4*x - 72, 8*x, -4*x + 24]]) assert e.adjugate() == adj assert e.adjugate(method='bareiss') == adj assert e.adjugate(method='berkowitz') == adj a = DeterminantOnlyMatrix(2, 3, [1, 2, 3, 4, 5, 6]) raises(NonSquareMatrixError, lambda: a.adjugate()) def test_util(): R = Rational v1 = Matrix(1, 3, [1, 2, 3]) v2 = Matrix(1, 3, [3, 4, 5]) assert v1.norm() == sqrt(14) assert v1.project(v2) == Matrix(1, 3, [R(39)/25, R(52)/25, R(13)/5]) assert Matrix.zeros(1, 2) == Matrix(1, 2, [0, 0]) assert ones(1, 2) == Matrix(1, 2, [1, 1]) assert v1.copy() == v1 # cofactor assert eye(3) == eye(3).cofactor_matrix() test = Matrix([[1, 3, 2], [2, 6, 3], [2, 3, 6]]) assert test.cofactor_matrix() == \ Matrix([[27, -6, -6], [-12, 2, 3], [-3, 1, 0]]) test = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) assert test.cofactor_matrix() == \ Matrix([[-3, 6, -3], [6, -12, 6], [-3, 6, -3]]) def test_cofactor_and_minors(): x = Symbol('x') e = DeterminantOnlyMatrix(4, 4, [x, 1, 2, 3, 4, 5, 6, 7, 2, 9, 10, 11, 12, 13, 14, 14]) m = Matrix([ [ x, 1, 3], [ 2, 9, 11], [12, 13, 14]]) cm = Matrix([ [ 4, 76, -122, 48], [-8, -14*x - 68, 17*x + 142, -4*x - 72], [ 4, 14*x - 8, -21*x + 4, 8*x], [ 0, -4*x + 24, 8*x - 48, -4*x + 24]]) sub = Matrix([ [x, 1, 2], [4, 5, 6], [2, 9, 10]]) assert e.minor_submatrix(1, 2) == m assert e.minor_submatrix(-1, -1) == sub assert e.minor(1, 2) == -17*x - 142 assert e.cofactor(1, 2) == 17*x + 142 assert e.cofactor_matrix() == cm assert e.cofactor_matrix(method="bareiss") == cm assert e.cofactor_matrix(method="berkowitz") == cm raises(ValueError, lambda: e.cofactor(4, 5)) raises(ValueError, lambda: e.minor(4, 5)) raises(ValueError, lambda: e.minor_submatrix(4, 5)) a = DeterminantOnlyMatrix(2, 3, [1, 2, 3, 4, 5, 6]) assert a.minor_submatrix(0, 0) == Matrix([[5, 6]]) raises(ValueError, lambda: DeterminantOnlyMatrix(0, 0, []).minor_submatrix(0, 0)) raises(NonSquareMatrixError, lambda: a.cofactor(0, 0)) raises(NonSquareMatrixError, lambda: a.minor(0, 0)) raises(NonSquareMatrixError, lambda: a.cofactor_matrix()) def test_charpoly(): x, y = Symbol('x'), Symbol('y') z, t = Symbol('z'), Symbol('t') from sympy.abc import a,b,c m = DeterminantOnlyMatrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9]) assert eye_Determinant(3).charpoly(x) == Poly((x - 1)**3, x) assert eye_Determinant(3).charpoly(y) == Poly((y - 1)**3, y) assert m.charpoly() == Poly(x**3 - 15*x**2 - 18*x, x) raises(NonSquareMatrixError, lambda: Matrix([[1], [2]]).charpoly()) n = DeterminantOnlyMatrix(4, 4, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) assert n.charpoly() == Poly(x**4, x) n = DeterminantOnlyMatrix(4, 4, [45, 0, 0, 0, 0, 23, 0, 0, 0, 0, 87, 0, 0, 0, 0, 12]) assert n.charpoly() == Poly(x**4 - 167*x**3 + 8811*x**2 - 173457*x + 1080540, x) n = DeterminantOnlyMatrix(3, 3, [x, 0, 0, a, y, 0, b, c, z]) assert n.charpoly() == Poly(t**3 - (x+y+z)*t**2 + t*(x*y+y*z+x*z) - x*y*z , t)
b5cc6cbc2ddfaedf49a0d374b80ddf9d3e683b5a8929b50bb9619831fc4f1c4f
from sympy.matrices.expressions import MatrixExpr from sympy import MatrixBase, Dummy, Lambda, Function, FunctionClass from sympy.core.sympify import sympify, _sympify class ElementwiseApplyFunction(MatrixExpr): r""" Apply function to a matrix elementwise without evaluating. Examples ======== It can be created by calling ``.applyfunc(<function>)`` on a matrix expression: >>> from sympy.matrices.expressions import MatrixSymbol >>> from sympy.matrices.expressions.applyfunc import ElementwiseApplyFunction >>> from sympy import exp >>> X = MatrixSymbol("X", 3, 3) >>> X.applyfunc(exp) Lambda(_d, exp(_d)).(X) Otherwise using the class constructor: >>> from sympy import eye >>> expr = ElementwiseApplyFunction(exp, eye(3)) >>> expr Lambda(_d, exp(_d)).(Matrix([ [1, 0, 0], [0, 1, 0], [0, 0, 1]])) >>> expr.doit() Matrix([ [E, 1, 1], [1, E, 1], [1, 1, E]]) Notice the difference with the real mathematical functions: >>> exp(eye(3)) Matrix([ [E, 0, 0], [0, E, 0], [0, 0, E]]) """ def __new__(cls, function, expr): expr = _sympify(expr) if not expr.is_Matrix: raise ValueError("{} must be a matrix instance.".format(expr)) if not isinstance(function, (FunctionClass, Lambda)): d = Dummy('d') function = Lambda(d, function(d)) function = sympify(function) if not isinstance(function, (FunctionClass, Lambda)): raise ValueError( "{} should be compatible with SymPy function classes." .format(function)) if 1 not in function.nargs: raise ValueError( '{} should be able to accept 1 arguments.'.format(function)) if not isinstance(function, Lambda): d = Dummy('d') function = Lambda(d, function(d)) obj = MatrixExpr.__new__(cls, function, expr) return obj @property def function(self): return self.args[0] @property def expr(self): return self.args[1] @property def shape(self): return self.expr.shape def doit(self, **kwargs): deep = kwargs.get("deep", True) expr = self.expr if deep: expr = expr.doit(**kwargs) function = self.function if isinstance(function, Lambda) and function.is_identity: # This is a Lambda containing the identity function. return expr if isinstance(expr, MatrixBase): return expr.applyfunc(self.function) elif isinstance(expr, ElementwiseApplyFunction): return ElementwiseApplyFunction( lambda x: self.function(expr.function(x)), expr.expr ).doit() else: return self def _entry(self, i, j, **kwargs): return self.function(self.expr._entry(i, j, **kwargs)) def _get_function_fdiff(self): d = Dummy("d") function = self.function(d) fdiff = function.diff(d) if isinstance(fdiff, Function): fdiff = type(fdiff) else: fdiff = Lambda(d, fdiff) return fdiff def _eval_derivative(self, x): from sympy import hadamard_product dexpr = self.expr.diff(x) fdiff = self._get_function_fdiff() return hadamard_product( dexpr, ElementwiseApplyFunction(fdiff, self.expr) ) def _eval_derivative_matrix_lines(self, x): from sympy import Identity from sympy.tensor.array.expressions.array_expressions import ArrayContraction from sympy.tensor.array.expressions.array_expressions import ArrayDiagonal from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct from sympy.core.expr import ExprBuilder fdiff = self._get_function_fdiff() lr = self.expr._eval_derivative_matrix_lines(x) ewdiff = ElementwiseApplyFunction(fdiff, self.expr) if 1 in x.shape: # Vector: iscolumn = self.shape[1] == 1 for i in lr: if iscolumn: ptr1 = i.first_pointer ptr2 = Identity(self.shape[1]) else: ptr1 = Identity(self.shape[0]) ptr2 = i.second_pointer subexpr = ExprBuilder( ArrayDiagonal, [ ExprBuilder( ArrayTensorProduct, [ ewdiff, ptr1, ptr2, ] ), (0, 2) if iscolumn else (1, 4) ], validator=ArrayDiagonal._validate ) i._lines = [subexpr] i._first_pointer_parent = subexpr.args[0].args i._first_pointer_index = 1 i._second_pointer_parent = subexpr.args[0].args i._second_pointer_index = 2 else: # Matrix case: for i in lr: ptr1 = i.first_pointer ptr2 = i.second_pointer newptr1 = Identity(ptr1.shape[1]) newptr2 = Identity(ptr2.shape[1]) subexpr = ExprBuilder( ArrayContraction, [ ExprBuilder( ArrayTensorProduct, [ptr1, newptr1, ewdiff, ptr2, newptr2] ), (1, 2, 4), (5, 7, 8), ], validator=ArrayContraction._validate ) i._first_pointer_parent = subexpr.args[0].args i._first_pointer_index = 1 i._second_pointer_parent = subexpr.args[0].args i._second_pointer_index = 4 i._lines = [subexpr] return lr def _eval_transpose(self): from sympy import Transpose return self.func(self.function, Transpose(self.expr).doit())
fcc6710454cd42e9f42633cf2e81912c095d63fd3a1f2c5f1b5da9edcb0376ce
from sympy import Number from sympy.core import Mul, Basic, sympify, S from sympy.core.mul import mul from sympy.functions import adjoint from sympy.strategies import (rm_id, unpack, typed, flatten, exhaust, do_one, new) from sympy.matrices.common import ShapeError, NonInvertibleMatrixError from sympy.matrices.matrices import MatrixBase from .inverse import Inverse from .matexpr import MatrixExpr from .matpow import MatPow from .transpose import transpose from .permutation import PermutationMatrix from .special import ZeroMatrix, Identity, GenericIdentity, OneMatrix # XXX: MatMul should perhaps not subclass directly from Mul class MatMul(MatrixExpr, Mul): """ A product of matrix expressions Examples ======== >>> from sympy import MatMul, MatrixSymbol >>> A = MatrixSymbol('A', 5, 4) >>> B = MatrixSymbol('B', 4, 3) >>> C = MatrixSymbol('C', 3, 6) >>> MatMul(A, B, C) A*B*C """ is_MatMul = True identity = GenericIdentity() def __new__(cls, *args, evaluate=False, check=True, _sympify=True): if not args: return cls.identity # This must be removed aggressively in the constructor to avoid # TypeErrors from GenericIdentity().shape args = list(filter(lambda i: cls.identity != i, args)) if _sympify: args = list(map(sympify, args)) obj = Basic.__new__(cls, *args) factor, matrices = obj.as_coeff_matrices() if check: validate(*matrices) if not matrices: # Should it be # # return Basic.__neq__(cls, factor, GenericIdentity()) ? return factor if evaluate: return canonicalize(obj) return obj @property def shape(self): matrices = [arg for arg in self.args if arg.is_Matrix] return (matrices[0].rows, matrices[-1].cols) def _entry(self, i, j, expand=True, **kwargs): from sympy import Dummy, Sum, Mul, ImmutableMatrix, Integer coeff, matrices = self.as_coeff_matrices() if len(matrices) == 1: # situation like 2*X, matmul is just X return coeff * matrices[0][i, j] indices = [None]*(len(matrices) + 1) ind_ranges = [None]*(len(matrices) - 1) indices[0] = i indices[-1] = j def f(): counter = 1 while True: yield Dummy("i_%i" % counter) counter += 1 dummy_generator = kwargs.get("dummy_generator", f()) for i in range(1, len(matrices)): indices[i] = next(dummy_generator) for i, arg in enumerate(matrices[:-1]): ind_ranges[i] = arg.shape[1] - 1 matrices = [arg._entry(indices[i], indices[i+1], dummy_generator=dummy_generator) for i, arg in enumerate(matrices)] expr_in_sum = Mul.fromiter(matrices) if any(v.has(ImmutableMatrix) for v in matrices): expand = True result = coeff*Sum( expr_in_sum, *zip(indices[1:-1], [0]*len(ind_ranges), ind_ranges) ) # Don't waste time in result.doit() if the sum bounds are symbolic if not any(isinstance(v, (Integer, int)) for v in ind_ranges): expand = False return result.doit() if expand else result def as_coeff_matrices(self): scalars = [x for x in self.args if not x.is_Matrix] matrices = [x for x in self.args if x.is_Matrix] coeff = Mul(*scalars) if coeff.is_commutative is False: raise NotImplementedError("noncommutative scalars in MatMul are not supported.") return coeff, matrices def as_coeff_mmul(self): coeff, matrices = self.as_coeff_matrices() return coeff, MatMul(*matrices) def _eval_transpose(self): """Transposition of matrix multiplication. Notes ===== The following rules are applied. Transposition for matrix multiplied with another matrix: `\\left(A B\\right)^{T} = B^{T} A^{T}` Transposition for matrix multiplied with scalar: `\\left(c A\\right)^{T} = c A^{T}` References ========== .. [1] https://en.wikipedia.org/wiki/Transpose """ coeff, matrices = self.as_coeff_matrices() return MatMul( coeff, *[transpose(arg) for arg in matrices[::-1]]).doit() def _eval_adjoint(self): return MatMul(*[adjoint(arg) for arg in self.args[::-1]]).doit() def _eval_trace(self): factor, mmul = self.as_coeff_mmul() if factor != 1: from .trace import trace return factor * trace(mmul.doit()) else: raise NotImplementedError("Can't simplify any further") def _eval_determinant(self): from sympy.matrices.expressions.determinant import Determinant factor, matrices = self.as_coeff_matrices() square_matrices = only_squares(*matrices) return factor**self.rows * Mul(*list(map(Determinant, square_matrices))) def _eval_inverse(self): try: return MatMul(*[ arg.inverse() if isinstance(arg, MatrixExpr) else arg**-1 for arg in self.args[::-1]]).doit() except ShapeError: return Inverse(self) def doit(self, **kwargs): deep = kwargs.get('deep', True) if deep: args = [arg.doit(**kwargs) for arg in self.args] else: args = self.args # treat scalar*MatrixSymbol or scalar*MatPow separately expr = canonicalize(MatMul(*args)) return expr # Needed for partial compatibility with Mul def args_cnc(self, **kwargs): coeff_c = [x for x in self.args if x.is_commutative] coeff_nc = [x for x in self.args if not x.is_commutative] return [coeff_c, coeff_nc] def _eval_derivative_matrix_lines(self, x): from .transpose import Transpose with_x_ind = [i for i, arg in enumerate(self.args) if arg.has(x)] lines = [] for ind in with_x_ind: left_args = self.args[:ind] right_args = self.args[ind+1:] if right_args: right_mat = MatMul.fromiter(right_args) else: right_mat = Identity(self.shape[1]) if left_args: left_rev = MatMul.fromiter([Transpose(i).doit() if i.is_Matrix else i for i in reversed(left_args)]) else: left_rev = Identity(self.shape[0]) d = self.args[ind]._eval_derivative_matrix_lines(x) for i in d: i.append_first(left_rev) i.append_second(right_mat) lines.append(i) return lines mul.register_handlerclass((Mul, MatMul), MatMul) def validate(*matrices): """ Checks for valid shapes for args of MatMul """ for i in range(len(matrices)-1): A, B = matrices[i:i+2] if A.cols != B.rows: raise ShapeError("Matrices %s and %s are not aligned"%(A, B)) # Rules def newmul(*args): if args[0] == 1: args = args[1:] return new(MatMul, *args) def any_zeros(mul): if any([arg.is_zero or (arg.is_Matrix and arg.is_ZeroMatrix) for arg in mul.args]): matrices = [arg for arg in mul.args if arg.is_Matrix] return ZeroMatrix(matrices[0].rows, matrices[-1].cols) return mul def merge_explicit(matmul): """ Merge explicit MatrixBase arguments >>> from sympy import MatrixSymbol, Matrix, MatMul, pprint >>> from sympy.matrices.expressions.matmul import merge_explicit >>> A = MatrixSymbol('A', 2, 2) >>> B = Matrix([[1, 1], [1, 1]]) >>> C = Matrix([[1, 2], [3, 4]]) >>> X = MatMul(A, B, C) >>> pprint(X) [1 1] [1 2] A*[ ]*[ ] [1 1] [3 4] >>> pprint(merge_explicit(X)) [4 6] A*[ ] [4 6] >>> X = MatMul(B, A, C) >>> pprint(X) [1 1] [1 2] [ ]*A*[ ] [1 1] [3 4] >>> pprint(merge_explicit(X)) [1 1] [1 2] [ ]*A*[ ] [1 1] [3 4] """ if not any(isinstance(arg, MatrixBase) for arg in matmul.args): return matmul newargs = [] last = matmul.args[0] for arg in matmul.args[1:]: if isinstance(arg, (MatrixBase, Number)) and isinstance(last, (MatrixBase, Number)): last = last * arg else: newargs.append(last) last = arg newargs.append(last) return MatMul(*newargs) def remove_ids(mul): """ Remove Identities from a MatMul This is a modified version of sympy.strategies.rm_id. This is necesssary because MatMul may contain both MatrixExprs and Exprs as args. See Also ======== sympy.strategies.rm_id """ # Separate Exprs from MatrixExprs in args factor, mmul = mul.as_coeff_mmul() # Apply standard rm_id for MatMuls result = rm_id(lambda x: x.is_Identity is True)(mmul) if result != mmul: return newmul(factor, *result.args) # Recombine and return else: return mul def factor_in_front(mul): factor, matrices = mul.as_coeff_matrices() if factor != 1: return newmul(factor, *matrices) return mul def combine_powers(mul): """Combine consecutive powers with the same base into one e.g. A*A**2 -> A**3 This also cancels out the possible matrix inverses using the knowledgebase of ``Inverse``. e.g. Y * X * X.I -> Y """ factor, args = mul.as_coeff_matrices() new_args = [args[0]] for B in args[1:]: A = new_args[-1] if A.is_square == False or B.is_square == False: new_args.append(B) continue if isinstance(A, MatPow): A_base, A_exp = A.args else: A_base, A_exp = A, S.One if isinstance(B, MatPow): B_base, B_exp = B.args else: B_base, B_exp = B, S.One if A_base == B_base: new_exp = A_exp + B_exp new_args[-1] = MatPow(A_base, new_exp).doit(deep=False) continue elif not isinstance(B_base, MatrixBase): try: B_base_inv = B_base.inverse() except NonInvertibleMatrixError: B_base_inv = None if B_base_inv is not None and A_base == B_base_inv: new_exp = A_exp - B_exp new_args[-1] = MatPow(A_base, new_exp).doit(deep=False) continue new_args.append(B) return newmul(factor, *new_args) def combine_permutations(mul): """Refine products of permutation matrices as the products of cycles. """ args = mul.args l = len(args) if l < 2: return mul result = [args[0]] for i in range(1, l): A = result[-1] B = args[i] if isinstance(A, PermutationMatrix) and \ isinstance(B, PermutationMatrix): cycle_1 = A.args[0] cycle_2 = B.args[0] result[-1] = PermutationMatrix(cycle_1 * cycle_2) else: result.append(B) return MatMul(*result) def combine_one_matrices(mul): """ Combine products of OneMatrix e.g. OneMatrix(2, 3) * OneMatrix(3, 4) -> 3 * OneMatrix(2, 4) """ factor, args = mul.as_coeff_matrices() new_args = [args[0]] for B in args[1:]: A = new_args[-1] if not isinstance(A, OneMatrix) or not isinstance(B, OneMatrix): new_args.append(B) continue new_args.pop() new_args.append(OneMatrix(A.shape[0], B.shape[1])) factor *= A.shape[1] return newmul(factor, *new_args) def distribute_monom(mul): """ Simplify MatMul expressions but distributing rational term to MatMul. e.g. 2*(A+B) -> 2*A + 2*B """ args = mul.args if len(args) == 2: from .matadd import MatAdd if args[0].is_MatAdd and args[1].is_Rational: return MatAdd(*[MatMul(mat, args[1]).doit() for mat in args[0].args]) if args[1].is_MatAdd and args[0].is_Rational: return MatAdd(*[MatMul(args[0], mat).doit() for mat in args[1].args]) return mul rules = ( distribute_monom, any_zeros, remove_ids, combine_one_matrices, combine_powers, unpack, rm_id(lambda x: x == 1), merge_explicit, factor_in_front, flatten, combine_permutations) canonicalize = exhaust(typed({MatMul: do_one(*rules)})) def only_squares(*matrices): """factor matrices only if they are square""" if matrices[0].rows != matrices[-1].cols: raise RuntimeError("Invalid matrices being multiplied") out = [] start = 0 for i, M in enumerate(matrices): if M.cols == matrices[start].rows: out.append(MatMul(*matrices[start:i+1]).doit()) start = i+1 return out from sympy.assumptions.ask import ask, Q from sympy.assumptions.refine import handlers_dict 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
e39ea8ef53498da10e0975603f10da642aa8dd2d3429d1424c1a070ed8a08f70
from sympy.matrices.common import NonSquareMatrixError from .matexpr import MatrixExpr from .special import Identity from sympy.core import S from sympy.core.sympify import _sympify from sympy.matrices import MatrixBase class MatPow(MatrixExpr): def __new__(cls, base, exp, evaluate=False, **options): base = _sympify(base) if not base.is_Matrix: raise TypeError("MatPow base should be a matrix") if not base.is_square: raise NonSquareMatrixError("Power of non-square matrix %s" % base) exp = _sympify(exp) obj = super().__new__(cls, base, exp) if evaluate: obj = obj.doit(deep=False) return obj @property def base(self): return self.args[0] @property def exp(self): return self.args[1] @property def shape(self): return self.base.shape def _entry(self, i, j, **kwargs): from sympy.matrices.expressions import MatMul A = self.doit() if isinstance(A, MatPow): # We still have a MatPow, make an explicit MatMul out of it. if A.exp.is_Integer and A.exp.is_positive: A = MatMul(*[A.base for k in range(A.exp)]) #elif A.exp.is_Integer and self.exp.is_negative: # Note: possible future improvement: in principle we can take # positive powers of the inverse, but carefully avoid recursion, # perhaps by adding `_entry` to Inverse (as it is our subclass). # T = A.base.as_explicit().inverse() # A = MatMul(*[T for k in range(-A.exp)]) else: # Leave the expression unevaluated: from sympy.matrices.expressions.matexpr import MatrixElement return MatrixElement(self, i, j) return A[i, j] def doit(self, **kwargs): if kwargs.get('deep', True): base, exp = [arg.doit(**kwargs) for arg in self.args] else: base, exp = self.args # combine all powers, e.g. (A ** 2) ** 3 -> A ** 6 while isinstance(base, MatPow): exp *= base.args[1] base = base.args[0] if isinstance(base, MatrixBase): # Delegate return base ** exp # Handle simple cases so that _eval_power() in MatrixExpr sub-classes can ignore them if exp == S.One: return base if exp == S.Zero: return Identity(base.rows) if exp == S.NegativeOne: from sympy.matrices.expressions import Inverse return Inverse(base).doit(**kwargs) eval_power = getattr(base, '_eval_power', None) if eval_power is not None: return eval_power(exp) return MatPow(base, exp) def _eval_transpose(self): base, exp = self.args return MatPow(base.T, exp) def _eval_derivative(self, x): from sympy import Pow return Pow._eval_derivative(self, x) def _eval_derivative_matrix_lines(self, x): from sympy.core.expr import ExprBuilder from sympy.tensor.array.expressions.array_expressions import ArrayContraction from ...tensor.array.expressions.array_expressions import ArrayTensorProduct from .matmul import MatMul from .inverse import Inverse exp = self.exp if self.base.shape == (1, 1) and not exp.has(x): lr = self.base._eval_derivative_matrix_lines(x) for i in lr: subexpr = ExprBuilder( ArrayContraction, [ ExprBuilder( ArrayTensorProduct, [ Identity(1), i._lines[0], exp*self.base**(exp-1), i._lines[1], Identity(1), ] ), (0, 3, 4), (5, 7, 8) ], validator=ArrayContraction._validate ) i._first_pointer_parent = subexpr.args[0].args i._first_pointer_index = 0 i._second_pointer_parent = subexpr.args[0].args i._second_pointer_index = 4 i._lines = [subexpr] return lr if (exp > 0) == True: newexpr = MatMul.fromiter([self.base for i in range(exp)]) elif (exp == -1) == True: return Inverse(self.base)._eval_derivative_matrix_lines(x) elif (exp < 0) == True: newexpr = MatMul.fromiter([Inverse(self.base) for i in range(-exp)]) elif (exp == 0) == True: return self.doit()._eval_derivative_matrix_lines(x) else: raise NotImplementedError("cannot evaluate %s derived by %s" % (self, x)) return newexpr._eval_derivative_matrix_lines(x) def _eval_inverse(self): return MatPow(self.base, -self.exp)
806e2e4d7e889b105f502c654efba789564b5f24b64640c21b8f6bc006066ba9
from typing import Tuple as tTuple from sympy.core.logic import FuzzyBool from functools import wraps, reduce import collections from sympy.core import S, Symbol, Integer, Basic, Expr, Mul, Add from sympy.core.decorators import call_highest_priority from sympy.core.compatibility import SYMPY_INTS, default_sort_key from sympy.core.symbol import Str from sympy.core.sympify import SympifyError, _sympify from sympy.functions import conjugate, adjoint from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.matrices.common import NonSquareMatrixError from sympy.simplify import simplify from sympy.matrices.matrices import MatrixKind from sympy.utilities.misc import filldedent from sympy.multipledispatch import dispatch def _sympifyit(arg, retval=None): # This version of _sympifyit sympifies MutableMatrix objects def deco(func): @wraps(func) def __sympifyit_wrapper(a, b): try: b = _sympify(b) return func(a, b) except SympifyError: return retval return __sympifyit_wrapper return deco class MatrixExpr(Expr): """Superclass for Matrix Expressions MatrixExprs represent abstract matrices, linear transformations represented within a particular basis. Examples ======== >>> from sympy import MatrixSymbol >>> A = MatrixSymbol('A', 3, 3) >>> y = MatrixSymbol('y', 3, 1) >>> x = (A.T*A).I * A * y See Also ======== MatrixSymbol, MatAdd, MatMul, Transpose, Inverse """ # Should not be considered iterable by the # sympy.core.compatibility.iterable function. Subclass that actually are # iterable (i.e., explicit matrices) should set this to True. _iterable = False _op_priority = 11.0 is_Matrix = True # type: bool is_MatrixExpr = True # type: bool is_Identity = None # type: FuzzyBool is_Inverse = False is_Transpose = False is_ZeroMatrix = False is_MatAdd = False is_MatMul = False is_commutative = False is_number = False is_symbol = False is_scalar = False kind = MatrixKind() def __new__(cls, *args, **kwargs): args = map(_sympify, args) return Basic.__new__(cls, *args, **kwargs) # The following is adapted from the core Expr object @property def shape(self) -> tTuple[Expr, Expr]: raise NotImplementedError @property def _add_handler(self): return MatAdd @property def _mul_handler(self): return MatMul def __neg__(self): return MatMul(S.NegativeOne, self).doit() def __abs__(self): raise NotImplementedError @_sympifyit('other', NotImplemented) @call_highest_priority('__radd__') def __add__(self, other): return MatAdd(self, other, check=True).doit() @_sympifyit('other', NotImplemented) @call_highest_priority('__add__') def __radd__(self, other): return MatAdd(other, self, check=True).doit() @_sympifyit('other', NotImplemented) @call_highest_priority('__rsub__') def __sub__(self, other): return MatAdd(self, -other, check=True).doit() @_sympifyit('other', NotImplemented) @call_highest_priority('__sub__') def __rsub__(self, other): return MatAdd(other, -self, check=True).doit() @_sympifyit('other', NotImplemented) @call_highest_priority('__rmul__') def __mul__(self, other): return MatMul(self, other).doit() @_sympifyit('other', NotImplemented) @call_highest_priority('__rmul__') def __matmul__(self, other): return MatMul(self, other).doit() @_sympifyit('other', NotImplemented) @call_highest_priority('__mul__') def __rmul__(self, other): return MatMul(other, self).doit() @_sympifyit('other', NotImplemented) @call_highest_priority('__mul__') def __rmatmul__(self, other): return MatMul(other, self).doit() @_sympifyit('other', NotImplemented) @call_highest_priority('__rpow__') def __pow__(self, other): return MatPow(self, other).doit() @_sympifyit('other', NotImplemented) @call_highest_priority('__pow__') def __rpow__(self, other): raise NotImplementedError("Matrix Power not defined") @_sympifyit('other', NotImplemented) @call_highest_priority('__rtruediv__') def __truediv__(self, other): return self * other**S.NegativeOne @_sympifyit('other', NotImplemented) @call_highest_priority('__truediv__') def __rtruediv__(self, other): raise NotImplementedError() #return MatMul(other, Pow(self, S.NegativeOne)) @property def rows(self): return self.shape[0] @property def cols(self): return self.shape[1] @property def is_square(self): return self.rows == self.cols def _eval_conjugate(self): from sympy.matrices.expressions.adjoint import Adjoint from sympy.matrices.expressions.transpose import Transpose return Adjoint(Transpose(self)) def as_real_imag(self, deep=True, **hints): from sympy import I real = S.Half * (self + self._eval_conjugate()) im = (self - self._eval_conjugate())/(2*I) return (real, im) def _eval_inverse(self): from sympy.matrices.expressions.inverse import Inverse return Inverse(self) def _eval_transpose(self): return Transpose(self) def _eval_power(self, exp): """ Override this in sub-classes to implement simplification of powers. The cases where the exponent is -1, 0, 1 are already covered in MatPow.doit(), so implementations can exclude these cases. """ return MatPow(self, exp) def _eval_simplify(self, **kwargs): if self.is_Atom: return self else: return self.func(*[simplify(x, **kwargs) for x in self.args]) def _eval_adjoint(self): from sympy.matrices.expressions.adjoint import Adjoint return Adjoint(self) def _eval_derivative_n_times(self, x, n): return Basic._eval_derivative_n_times(self, x, n) def _eval_derivative(self, x): # `x` is a scalar: if self.has(x): # See if there are other methods using it: return super()._eval_derivative(x) else: return ZeroMatrix(*self.shape) @classmethod def _check_dim(cls, dim): """Helper function to check invalid matrix dimensions""" from sympy.core.assumptions import check_assumptions ok = check_assumptions(dim, integer=True, nonnegative=True) if ok is False: raise ValueError( "The dimension specification {} should be " "a nonnegative integer.".format(dim)) def _entry(self, i, j, **kwargs): raise NotImplementedError( "Indexing not implemented for %s" % self.__class__.__name__) def adjoint(self): return adjoint(self) def as_coeff_Mul(self, rational=False): """Efficiently extract the coefficient of a product. """ return S.One, self def conjugate(self): return conjugate(self) def transpose(self): from sympy.matrices.expressions.transpose import transpose return transpose(self) @property def T(self): '''Matrix transposition''' return self.transpose() def inverse(self): if not self.is_square: raise NonSquareMatrixError('Inverse of non-square matrix') return self._eval_inverse() def inv(self): return self.inverse() @property def I(self): return self.inverse() def valid_index(self, i, j): def is_valid(idx): return isinstance(idx, (int, Integer, Symbol, Expr)) return (is_valid(i) and is_valid(j) and (self.rows is None or (0 <= i) != False and (i < self.rows) != False) and (0 <= j) != False and (j < self.cols) != False) def __getitem__(self, key): if not isinstance(key, tuple) and isinstance(key, slice): from sympy.matrices.expressions.slice import MatrixSlice return MatrixSlice(self, key, (0, None, 1)) if isinstance(key, tuple) and len(key) == 2: i, j = key if isinstance(i, slice) or isinstance(j, slice): from sympy.matrices.expressions.slice import MatrixSlice return MatrixSlice(self, i, j) i, j = _sympify(i), _sympify(j) if self.valid_index(i, j) != False: return self._entry(i, j) else: raise IndexError("Invalid indices (%s, %s)" % (i, j)) elif isinstance(key, (SYMPY_INTS, Integer)): # row-wise decomposition of matrix rows, cols = self.shape # allow single indexing if number of columns is known if not isinstance(cols, Integer): raise IndexError(filldedent(''' Single indexing is only supported when the number of columns is known.''')) key = _sympify(key) i = key // cols j = key % cols if self.valid_index(i, j) != False: return self._entry(i, j) else: raise IndexError("Invalid index %s" % key) elif isinstance(key, (Symbol, Expr)): raise IndexError(filldedent(''' Only integers may be used when addressing the matrix with a single index.''')) raise IndexError("Invalid index, wanted %s[i,j]" % self) def as_explicit(self): """ Returns a dense Matrix with elements represented explicitly Returns an object of type ImmutableDenseMatrix. Examples ======== >>> from sympy import Identity >>> I = Identity(3) >>> I I >>> I.as_explicit() Matrix([ [1, 0, 0], [0, 1, 0], [0, 0, 1]]) See Also ======== as_mutable: returns mutable Matrix type """ if (not isinstance(self.rows, (SYMPY_INTS, Integer)) or not isinstance(self.cols, (SYMPY_INTS, Integer))): raise ValueError( 'Matrix with symbolic shape ' 'cannot be represented explicitly.') from sympy.matrices.immutable import ImmutableDenseMatrix return ImmutableDenseMatrix([[self[i, j] for j in range(self.cols)] for i in range(self.rows)]) def as_mutable(self): """ Returns a dense, mutable matrix with elements represented explicitly Examples ======== >>> from sympy import Identity >>> I = Identity(3) >>> I I >>> I.shape (3, 3) >>> I.as_mutable() Matrix([ [1, 0, 0], [0, 1, 0], [0, 0, 1]]) See Also ======== as_explicit: returns ImmutableDenseMatrix """ return self.as_explicit().as_mutable() def __array__(self): from numpy import empty a = empty(self.shape, dtype=object) for i in range(self.rows): for j in range(self.cols): a[i, j] = self[i, j] return a def equals(self, other): """ Test elementwise equality between matrices, potentially of different types >>> from sympy import Identity, eye >>> Identity(3).equals(eye(3)) True """ return self.as_explicit().equals(other) def canonicalize(self): return self def as_coeff_mmul(self): return 1, MatMul(self) @staticmethod def from_index_summation(expr, first_index=None, last_index=None, dimensions=None): r""" Parse expression of matrices with explicitly summed indices into a matrix expression without indices, if possible. This transformation expressed in mathematical notation: `\sum_{j=0}^{N-1} A_{i,j} B_{j,k} \Longrightarrow \mathbf{A}\cdot \mathbf{B}` Optional parameter ``first_index``: specify which free index to use as the index starting the expression. Examples ======== >>> from sympy import MatrixSymbol, MatrixExpr, Sum >>> from sympy.abc import i, j, k, l, N >>> A = MatrixSymbol("A", N, N) >>> B = MatrixSymbol("B", N, N) >>> expr = Sum(A[i, j]*B[j, k], (j, 0, N-1)) >>> MatrixExpr.from_index_summation(expr) A*B Transposition is detected: >>> expr = Sum(A[j, i]*B[j, k], (j, 0, N-1)) >>> MatrixExpr.from_index_summation(expr) A.T*B Detect the trace: >>> expr = Sum(A[i, i], (i, 0, N-1)) >>> MatrixExpr.from_index_summation(expr) Trace(A) More complicated expressions: >>> expr = Sum(A[i, j]*B[k, j]*A[l, k], (j, 0, N-1), (k, 0, N-1)) >>> MatrixExpr.from_index_summation(expr) A*B.T*A.T """ from sympy import Sum, Mul, Add, MatMul, transpose, trace from sympy.strategies.traverse import bottom_up def remove_matelement(expr, i1, i2): def repl_match(pos): def func(x): if not isinstance(x, MatrixElement): return False if x.args[pos] != i1: return False if x.args[3-pos] == 0: if x.args[0].shape[2-pos] == 1: return True else: return False return True return func expr = expr.replace(repl_match(1), lambda x: x.args[0]) expr = expr.replace(repl_match(2), lambda x: transpose(x.args[0])) # Make sure that all Mul are transformed to MatMul and that they # are flattened: rule = bottom_up(lambda x: reduce(lambda a, b: a*b, x.args) if isinstance(x, (Mul, MatMul)) else x) return rule(expr) def recurse_expr(expr, index_ranges={}): if expr.is_Mul: nonmatargs = [] pos_arg = [] pos_ind = [] dlinks = {} link_ind = [] counter = 0 args_ind = [] for arg in expr.args: retvals = recurse_expr(arg, index_ranges) assert isinstance(retvals, list) if isinstance(retvals, list): for i in retvals: args_ind.append(i) else: args_ind.append(retvals) for arg_symbol, arg_indices in args_ind: if arg_indices is None: nonmatargs.append(arg_symbol) continue if isinstance(arg_symbol, MatrixElement): arg_symbol = arg_symbol.args[0] pos_arg.append(arg_symbol) pos_ind.append(arg_indices) link_ind.append([None]*len(arg_indices)) for i, ind in enumerate(arg_indices): if ind in dlinks: other_i = dlinks[ind] link_ind[counter][i] = other_i link_ind[other_i[0]][other_i[1]] = (counter, i) dlinks[ind] = (counter, i) counter += 1 counter2 = 0 lines = {} while counter2 < len(link_ind): for i, e in enumerate(link_ind): if None in e: line_start_index = (i, e.index(None)) break cur_ind_pos = line_start_index cur_line = [] index1 = pos_ind[cur_ind_pos[0]][cur_ind_pos[1]] while True: d, r = cur_ind_pos if pos_arg[d] != 1: if r % 2 == 1: cur_line.append(transpose(pos_arg[d])) else: cur_line.append(pos_arg[d]) next_ind_pos = link_ind[d][1-r] counter2 += 1 # Mark as visited, there will be no `None` anymore: link_ind[d] = (-1, -1) if next_ind_pos is None: index2 = pos_ind[d][1-r] lines[(index1, index2)] = cur_line break cur_ind_pos = next_ind_pos lines = {k: MatMul.fromiter(v) if len(v) != 1 else v[0] for k, v in lines.items()} return [(Mul.fromiter(nonmatargs), None)] + [ (MatrixElement(a, i, j), (i, j)) for (i, j), a in lines.items() ] elif expr.is_Add: res = [recurse_expr(i) for i in expr.args] d = collections.defaultdict(list) for res_addend in res: scalar = 1 for elem, indices in res_addend: if indices is None: scalar = elem continue indices = tuple(sorted(indices, key=default_sort_key)) d[indices].append(scalar*remove_matelement(elem, *indices)) scalar = 1 return [(MatrixElement(Add.fromiter(v), *k), k) for k, v in d.items()] elif isinstance(expr, KroneckerDelta): i1, i2 = expr.args if dimensions is not None: identity = Identity(dimensions[0]) else: identity = S.One return [(MatrixElement(identity, i1, i2), (i1, i2))] elif isinstance(expr, MatrixElement): matrix_symbol, i1, i2 = expr.args if i1 in index_ranges: r1, r2 = index_ranges[i1] if r1 != 0 or matrix_symbol.shape[0] != r2+1: raise ValueError("index range mismatch: {} vs. (0, {})".format( (r1, r2), matrix_symbol.shape[0])) if i2 in index_ranges: r1, r2 = index_ranges[i2] if r1 != 0 or matrix_symbol.shape[1] != r2+1: raise ValueError("index range mismatch: {} vs. (0, {})".format( (r1, r2), matrix_symbol.shape[1])) if (i1 == i2) and (i1 in index_ranges): return [(trace(matrix_symbol), None)] return [(MatrixElement(matrix_symbol, i1, i2), (i1, i2))] elif isinstance(expr, Sum): return recurse_expr( expr.args[0], index_ranges={i[0]: i[1:] for i in expr.args[1:]} ) else: return [(expr, None)] retvals = recurse_expr(expr) factors, indices = zip(*retvals) retexpr = Mul.fromiter(factors) if len(indices) == 0 or list(set(indices)) == [None]: return retexpr if first_index is None: for i in indices: if i is not None: ind0 = i break return remove_matelement(retexpr, *ind0) else: return remove_matelement(retexpr, first_index, last_index) def applyfunc(self, func): from .applyfunc import ElementwiseApplyFunction return ElementwiseApplyFunction(func, self) @dispatch(MatrixExpr, Expr) def _eval_is_eq(lhs, rhs): # noqa:F811 return False @dispatch(MatrixExpr, MatrixExpr) # type: ignore def _eval_is_eq(lhs, rhs): # noqa:F811 if lhs.shape != rhs.shape: return False if (lhs - rhs).is_ZeroMatrix: return True def get_postprocessor(cls): def _postprocessor(expr): # To avoid circular imports, we can't have MatMul/MatAdd on the top level mat_class = {Mul: MatMul, Add: MatAdd}[cls] nonmatrices = [] matrices = [] for term in expr.args: if isinstance(term, MatrixExpr): matrices.append(term) else: nonmatrices.append(term) if not matrices: return cls._from_args(nonmatrices) if nonmatrices: if cls == Mul: for i in range(len(matrices)): if not matrices[i].is_MatrixExpr: # If one of the matrices explicit, absorb the scalar into it # (doit will combine all explicit matrices into one, so it # doesn't matter which) matrices[i] = matrices[i].__mul__(cls._from_args(nonmatrices)) nonmatrices = [] break else: # Maintain the ability to create Add(scalar, matrix) without # raising an exception. That way different algorithms can # replace matrix expressions with non-commutative symbols to # manipulate them like non-commutative scalars. return cls._from_args(nonmatrices + [mat_class(*matrices).doit(deep=False)]) if mat_class == MatAdd: return mat_class(*matrices).doit(deep=False) return mat_class(cls._from_args(nonmatrices), *matrices).doit(deep=False) return _postprocessor Basic._constructor_postprocessor_mapping[MatrixExpr] = { "Mul": [get_postprocessor(Mul)], "Add": [get_postprocessor(Add)], } def _matrix_derivative(expr, x): from sympy.tensor.array.array_derivatives import ArrayDerivative lines = expr._eval_derivative_matrix_lines(x) parts = [i.build() for i in lines] from sympy.tensor.array.expressions.conv_array_to_matrix import convert_array_to_matrix parts = [[convert_array_to_matrix(j) for j in i] for i in parts] def _get_shape(elem): if isinstance(elem, MatrixExpr): return elem.shape return 1, 1 def get_rank(parts): return sum([j not in (1, None) for i in parts for j in _get_shape(i)]) ranks = [get_rank(i) for i in parts] rank = ranks[0] def contract_one_dims(parts): if len(parts) == 1: return parts[0] else: p1, p2 = parts[:2] if p2.is_Matrix: p2 = p2.T if p1 == Identity(1): pbase = p2 elif p2 == Identity(1): pbase = p1 else: pbase = p1*p2 if len(parts) == 2: return pbase else: # len(parts) > 2 if pbase.is_Matrix: raise ValueError("") return pbase*Mul.fromiter(parts[2:]) if rank <= 2: return Add.fromiter([contract_one_dims(i) for i in parts]) return ArrayDerivative(expr, x) class MatrixElement(Expr): parent = property(lambda self: self.args[0]) i = property(lambda self: self.args[1]) j = property(lambda self: self.args[2]) _diff_wrt = True is_symbol = True is_commutative = True def __new__(cls, name, n, m): n, m = map(_sympify, (n, m)) from sympy import MatrixBase if isinstance(name, (MatrixBase,)): if n.is_Integer and m.is_Integer: return name[n, m] if isinstance(name, str): name = Symbol(name) name = _sympify(name) obj = Expr.__new__(cls, name, n, m) return obj def doit(self, **kwargs): deep = kwargs.get('deep', True) if deep: args = [arg.doit(**kwargs) for arg in self.args] else: args = self.args return args[0][args[1], args[2]] @property def indices(self): return self.args[1:] def _eval_derivative(self, v): from sympy import Sum, symbols, Dummy if not isinstance(v, MatrixElement): from sympy import MatrixBase if isinstance(self.parent, MatrixBase): return self.parent.diff(v)[self.i, self.j] return S.Zero M = self.args[0] m, n = self.parent.shape if M == v.args[0]: return KroneckerDelta(self.args[1], v.args[1], (0, m-1)) * \ KroneckerDelta(self.args[2], v.args[2], (0, n-1)) if isinstance(M, Inverse): i, j = self.args[1:] i1, i2 = symbols("z1, z2", cls=Dummy) Y = M.args[0] r1, r2 = Y.shape return -Sum(M[i, i1]*Y[i1, i2].diff(v)*M[i2, j], (i1, 0, r1-1), (i2, 0, r2-1)) if self.has(v.args[0]): return None return S.Zero class MatrixSymbol(MatrixExpr): """Symbolic representation of a Matrix object Creates a SymPy Symbol to represent a Matrix. This matrix has a shape and can be included in Matrix Expressions Examples ======== >>> from sympy import MatrixSymbol, Identity >>> A = MatrixSymbol('A', 3, 4) # A 3 by 4 Matrix >>> B = MatrixSymbol('B', 4, 3) # A 4 by 3 Matrix >>> A.shape (3, 4) >>> 2*A*B + Identity(3) I + 2*A*B """ is_commutative = False is_symbol = True _diff_wrt = True def __new__(cls, name, n, m): n, m = _sympify(n), _sympify(m) cls._check_dim(m) cls._check_dim(n) if isinstance(name, str): name = Str(name) obj = Basic.__new__(cls, name, n, m) return obj @property def shape(self): return self.args[1], self.args[2] @property def name(self): return self.args[0].name def _entry(self, i, j, **kwargs): return MatrixElement(self, i, j) @property def free_symbols(self): return {self} def _eval_simplify(self, **kwargs): return self def _eval_derivative(self, x): # x is a scalar: return ZeroMatrix(self.shape[0], self.shape[1]) def _eval_derivative_matrix_lines(self, x): if self != x: first = ZeroMatrix(x.shape[0], self.shape[0]) if self.shape[0] != 1 else S.Zero second = ZeroMatrix(x.shape[1], self.shape[1]) if self.shape[1] != 1 else S.Zero return [_LeftRightArgs( [first, second], )] else: first = Identity(self.shape[0]) if self.shape[0] != 1 else S.One second = Identity(self.shape[1]) if self.shape[1] != 1 else S.One return [_LeftRightArgs( [first, second], )] def matrix_symbols(expr): return [sym for sym in expr.free_symbols if sym.is_Matrix] class _LeftRightArgs: r""" Helper class to compute matrix derivatives. The logic: when an expression is derived by a matrix `X_{mn}`, two lines of matrix multiplications are created: the one contracted to `m` (first line), and the one contracted to `n` (second line). Transposition flips the side by which new matrices are connected to the lines. The trace connects the end of the two lines. """ def __init__(self, lines, higher=S.One): self._lines = [i for i in lines] self._first_pointer_parent = self._lines self._first_pointer_index = 0 self._first_line_index = 0 self._second_pointer_parent = self._lines self._second_pointer_index = 1 self._second_line_index = 1 self.higher = higher @property def first_pointer(self): return self._first_pointer_parent[self._first_pointer_index] @first_pointer.setter def first_pointer(self, value): self._first_pointer_parent[self._first_pointer_index] = value @property def second_pointer(self): return self._second_pointer_parent[self._second_pointer_index] @second_pointer.setter def second_pointer(self, value): self._second_pointer_parent[self._second_pointer_index] = value def __repr__(self): built = [self._build(i) for i in self._lines] return "_LeftRightArgs(lines=%s, higher=%s)" % ( built, self.higher, ) def transpose(self): self._first_pointer_parent, self._second_pointer_parent = self._second_pointer_parent, self._first_pointer_parent self._first_pointer_index, self._second_pointer_index = self._second_pointer_index, self._first_pointer_index self._first_line_index, self._second_line_index = self._second_line_index, self._first_line_index return self @staticmethod def _build(expr): from sympy.core.expr import ExprBuilder if isinstance(expr, ExprBuilder): return expr.build() if isinstance(expr, list): if len(expr) == 1: return expr[0] else: return expr[0](*[_LeftRightArgs._build(i) for i in expr[1]]) else: return expr def build(self): data = [self._build(i) for i in self._lines] if self.higher != 1: data += [self._build(self.higher)] data = [i for i in data] return data def matrix_form(self): if self.first != 1 and self.higher != 1: raise ValueError("higher dimensional array cannot be represented") def _get_shape(elem): if isinstance(elem, MatrixExpr): return elem.shape return (None, None) if _get_shape(self.first)[1] != _get_shape(self.second)[1]: # Remove one-dimensional identity matrices: # (this is needed by `a.diff(a)` where `a` is a vector) if _get_shape(self.second) == (1, 1): return self.first*self.second[0, 0] if _get_shape(self.first) == (1, 1): return self.first[1, 1]*self.second.T raise ValueError("incompatible shapes") if self.first != 1: return self.first*self.second.T else: return self.higher def rank(self): """ Number of dimensions different from trivial (warning: not related to matrix rank). """ rank = 0 if self.first != 1: rank += sum([i != 1 for i in self.first.shape]) if self.second != 1: rank += sum([i != 1 for i in self.second.shape]) if self.higher != 1: rank += 2 return rank def _multiply_pointer(self, pointer, other): from sympy.core.expr import ExprBuilder from ...tensor.array.expressions.array_expressions import ArrayTensorProduct from ...tensor.array.expressions.array_expressions import ArrayContraction subexpr = ExprBuilder( ArrayContraction, [ ExprBuilder( ArrayTensorProduct, [ pointer, other ] ), (1, 2) ], validator=ArrayContraction._validate ) return subexpr def append_first(self, other): self.first_pointer *= other def append_second(self, other): self.second_pointer *= other def _make_matrix(x): from sympy import ImmutableDenseMatrix if isinstance(x, MatrixExpr): return x return ImmutableDenseMatrix([[x]]) from .matmul import MatMul from .matadd import MatAdd from .matpow import MatPow from .transpose import Transpose from .inverse import Inverse from .special import ZeroMatrix, Identity
6a3603845e8e2523bc7c956de6d3ac15d8d8b97140d2cb217116746d76076afb
from sympy import Basic, Expr, sympify, S from sympy.matrices.matrices import MatrixBase from sympy.matrices.common import NonSquareMatrixError class Trace(Expr): """Matrix Trace Represents the trace of a matrix expression. Examples ======== >>> from sympy import MatrixSymbol, Trace, eye >>> A = MatrixSymbol('A', 3, 3) >>> Trace(A) Trace(A) >>> Trace(eye(3)) Trace(Matrix([ [1, 0, 0], [0, 1, 0], [0, 0, 1]])) >>> Trace(eye(3)).simplify() 3 """ is_Trace = True is_commutative = True def __new__(cls, mat): mat = sympify(mat) if not mat.is_Matrix: raise TypeError("input to Trace, %s, is not a matrix" % str(mat)) if not mat.is_square: raise NonSquareMatrixError("Trace of a non-square matrix") return Basic.__new__(cls, mat) def _eval_transpose(self): return self def _eval_derivative(self, v): from sympy import Sum from .matexpr import MatrixElement if isinstance(v, MatrixElement): return self.rewrite(Sum).diff(v) expr = self.doit() if isinstance(expr, Trace): # Avoid looping infinitely: raise NotImplementedError return expr._eval_derivative(v) def _eval_derivative_matrix_lines(self, x): from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct, ArrayContraction from sympy.core.expr import ExprBuilder r = self.args[0]._eval_derivative_matrix_lines(x) for lr in r: if lr.higher == 1: lr.higher = ExprBuilder( ArrayContraction, [ ExprBuilder( ArrayTensorProduct, [ lr._lines[0], lr._lines[1], ] ), (1, 3), ], validator=ArrayContraction._validate ) else: # This is not a matrix line: lr.higher = ExprBuilder( ArrayContraction, [ ExprBuilder( ArrayTensorProduct, [ lr._lines[0], lr._lines[1], lr.higher, ] ), (1, 3), (0, 2) ] ) lr._lines = [S.One, S.One] lr._first_pointer_parent = lr._lines lr._second_pointer_parent = lr._lines lr._first_pointer_index = 0 lr._second_pointer_index = 1 return r @property def arg(self): return self.args[0] def doit(self, **kwargs): if kwargs.get('deep', True): arg = self.arg.doit(**kwargs) try: return arg._eval_trace() except (AttributeError, NotImplementedError): return Trace(arg) else: # _eval_trace would go too deep here if isinstance(self.arg, MatrixBase): return trace(self.arg) else: return Trace(self.arg) def _normalize(self): # Normalization of trace of matrix products. Use transposition and # cyclic properties of traces to make sure the arguments of the matrix # product are sorted and the first argument is not a trasposition. from sympy import MatMul, Transpose, default_sort_key trace_arg = self.arg if isinstance(trace_arg, MatMul): indmin = min(range(len(trace_arg.args)), key=lambda x: default_sort_key(trace_arg.args[x])) if isinstance(trace_arg.args[indmin], Transpose): trace_arg = Transpose(trace_arg).doit() indmin = min(range(len(trace_arg.args)), key=lambda x: default_sort_key(trace_arg.args[x])) trace_arg = MatMul.fromiter(trace_arg.args[indmin:] + trace_arg.args[:indmin]) return Trace(trace_arg) return self def _eval_rewrite_as_Sum(self, expr, **kwargs): from sympy import Sum, Dummy i = Dummy('i') return Sum(self.arg[i, i], (i, 0, self.arg.rows-1)).doit() def trace(expr): """Trace of a Matrix. Sum of the diagonal elements. Examples ======== >>> from sympy import trace, Symbol, MatrixSymbol, eye >>> n = Symbol('n') >>> X = MatrixSymbol('X', n, n) # A square matrix >>> trace(2*X) 2*Trace(X) >>> trace(eye(3)) 3 """ return Trace(expr).doit()
31f8bd45ee55154f8c5abf7e8947bd6da756b09e4df325c8e1b6a0fc53963750
from sympy.core import Mul, sympify from sympy.matrices.common import ShapeError from sympy.matrices.expressions.matexpr import MatrixExpr from sympy.matrices.expressions.special import ZeroMatrix, OneMatrix from sympy.strategies import ( unpack, flatten, condition, exhaust, rm_id, sort ) def hadamard_product(*matrices): """ Return the elementwise (aka Hadamard) product of matrices. Examples ======== >>> from sympy.matrices import hadamard_product, MatrixSymbol >>> A = MatrixSymbol('A', 2, 3) >>> B = MatrixSymbol('B', 2, 3) >>> hadamard_product(A) A >>> hadamard_product(A, B) HadamardProduct(A, B) >>> hadamard_product(A, B)[0, 1] A[0, 1]*B[0, 1] """ if not matrices: raise TypeError("Empty Hadamard product is undefined") validate(*matrices) if len(matrices) == 1: return matrices[0] else: matrices = [i for i in matrices if not i.is_Identity] return HadamardProduct(*matrices).doit() class HadamardProduct(MatrixExpr): """ Elementwise product of matrix expressions Examples ======== Hadamard product for matrix symbols: >>> from sympy.matrices import hadamard_product, HadamardProduct, MatrixSymbol >>> A = MatrixSymbol('A', 5, 5) >>> B = MatrixSymbol('B', 5, 5) >>> isinstance(hadamard_product(A, B), HadamardProduct) True Notes ===== This is a symbolic object that simply stores its argument without evaluating it. To actually compute the product, use the function ``hadamard_product()`` or ``HadamardProduct.doit`` """ is_HadamardProduct = True def __new__(cls, *args, evaluate=False, check=True): args = list(map(sympify, args)) if check: validate(*args) obj = super().__new__(cls, *args) if evaluate: obj = obj.doit(deep=False) return obj @property def shape(self): return self.args[0].shape def _entry(self, i, j, **kwargs): return Mul(*[arg._entry(i, j, **kwargs) for arg in self.args]) def _eval_transpose(self): from sympy.matrices.expressions.transpose import transpose return HadamardProduct(*list(map(transpose, self.args))) def doit(self, **ignored): expr = self.func(*[i.doit(**ignored) for i in self.args]) # Check for explicit matrices: from sympy import MatrixBase from sympy.matrices.immutable import ImmutableMatrix explicit = [i for i in expr.args if isinstance(i, MatrixBase)] if explicit: remainder = [i for i in expr.args if i not in explicit] expl_mat = ImmutableMatrix([ Mul.fromiter(i) for i in zip(*explicit) ]).reshape(*self.shape) expr = HadamardProduct(*([expl_mat] + remainder)) return canonicalize(expr) def _eval_derivative(self, x): from sympy import Add terms = [] args = list(self.args) for i in range(len(args)): factors = args[:i] + [args[i].diff(x)] + args[i+1:] terms.append(hadamard_product(*factors)) return Add.fromiter(terms) def _eval_derivative_matrix_lines(self, x): from sympy.core.expr import ExprBuilder from sympy.tensor.array.expressions.array_expressions import ArrayDiagonal from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct from sympy.matrices.expressions.matexpr import _make_matrix with_x_ind = [i for i, arg in enumerate(self.args) if arg.has(x)] lines = [] for ind in with_x_ind: left_args = self.args[:ind] right_args = self.args[ind+1:] d = self.args[ind]._eval_derivative_matrix_lines(x) hadam = hadamard_product(*(right_args + left_args)) diagonal = [(0, 2), (3, 4)] diagonal = [e for j, e in enumerate(diagonal) if self.shape[j] != 1] for i in d: l1 = i._lines[i._first_line_index] l2 = i._lines[i._second_line_index] subexpr = ExprBuilder( ArrayDiagonal, [ ExprBuilder( ArrayTensorProduct, [ ExprBuilder(_make_matrix, [l1]), hadam, ExprBuilder(_make_matrix, [l2]), ] ), *diagonal], ) i._first_pointer_parent = subexpr.args[0].args[0].args i._first_pointer_index = 0 i._second_pointer_parent = subexpr.args[0].args[2].args i._second_pointer_index = 0 i._lines = [subexpr] lines.append(i) return lines def validate(*args): if not all(arg.is_Matrix for arg in args): raise TypeError("Mix of Matrix and Scalar symbols") A = args[0] for B in args[1:]: if A.shape != B.shape: raise ShapeError("Matrices %s and %s are not aligned" % (A, B)) # TODO Implement algorithm for rewriting Hadamard product as diagonal matrix # if matmul identy matrix is multiplied. def canonicalize(x): """Canonicalize the Hadamard product ``x`` with mathematical properties. Examples ======== >>> from sympy.matrices.expressions import MatrixSymbol, HadamardProduct >>> from sympy.matrices.expressions import OneMatrix, ZeroMatrix >>> from sympy.matrices.expressions.hadamard import canonicalize >>> from sympy import init_printing >>> init_printing(use_unicode=False) >>> A = MatrixSymbol('A', 2, 2) >>> B = MatrixSymbol('B', 2, 2) >>> C = MatrixSymbol('C', 2, 2) Hadamard product associativity: >>> X = HadamardProduct(A, HadamardProduct(B, C)) >>> X A.*(B.*C) >>> canonicalize(X) A.*B.*C Hadamard product commutativity: >>> X = HadamardProduct(A, B) >>> Y = HadamardProduct(B, A) >>> X A.*B >>> Y B.*A >>> canonicalize(X) A.*B >>> canonicalize(Y) A.*B Hadamard product identity: >>> X = HadamardProduct(A, OneMatrix(2, 2)) >>> X A.*1 >>> canonicalize(X) A Absorbing element of Hadamard product: >>> X = HadamardProduct(A, ZeroMatrix(2, 2)) >>> X A.*0 >>> canonicalize(X) 0 Rewriting to Hadamard Power >>> X = HadamardProduct(A, A, A) >>> X A.*A.*A >>> canonicalize(X) .3 A Notes ===== As the Hadamard product is associative, nested products can be flattened. The Hadamard product is commutative so that factors can be sorted for canonical form. A matrix of only ones is an identity for Hadamard product, so every matrices of only ones can be removed. Any zero matrix will make the whole product a zero matrix. Duplicate elements can be collected and rewritten as HadamardPower References ========== .. [1] https://en.wikipedia.org/wiki/Hadamard_product_(matrices) """ from sympy.core.compatibility import default_sort_key # Associativity rule = condition( lambda x: isinstance(x, HadamardProduct), flatten ) fun = exhaust(rule) x = fun(x) # Identity fun = condition( lambda x: isinstance(x, HadamardProduct), rm_id(lambda x: isinstance(x, OneMatrix)) ) x = fun(x) # Absorbing by Zero Matrix def absorb(x): if any(isinstance(c, ZeroMatrix) for c in x.args): return ZeroMatrix(*x.shape) else: return x fun = condition( lambda x: isinstance(x, HadamardProduct), absorb ) x = fun(x) # Rewriting with HadamardPower if isinstance(x, HadamardProduct): from collections import Counter tally = Counter(x.args) new_arg = [] for base, exp in tally.items(): if exp == 1: new_arg.append(base) else: new_arg.append(HadamardPower(base, exp)) x = HadamardProduct(*new_arg) # Commutativity fun = condition( lambda x: isinstance(x, HadamardProduct), sort(default_sort_key) ) x = fun(x) # Unpacking x = unpack(x) return x def hadamard_power(base, exp): base = sympify(base) exp = sympify(exp) if exp == 1: return base if not base.is_Matrix: return base**exp if exp.is_Matrix: raise ValueError("cannot raise expression to a matrix") return HadamardPower(base, exp) class HadamardPower(MatrixExpr): r""" Elementwise power of matrix expressions Parameters ========== base : scalar or matrix exp : scalar or matrix Notes ===== There are four definitions for the hadamard power which can be used. Let's consider `A, B` as `(m, n)` matrices, and `a, b` as scalars. Matrix raised to a scalar exponent: .. math:: A^{\circ b} = \begin{bmatrix} A_{0, 0}^b & A_{0, 1}^b & \cdots & A_{0, n-1}^b \\ A_{1, 0}^b & A_{1, 1}^b & \cdots & A_{1, n-1}^b \\ \vdots & \vdots & \ddots & \vdots \\ A_{m-1, 0}^b & A_{m-1, 1}^b & \cdots & A_{m-1, n-1}^b \end{bmatrix} Scalar raised to a matrix exponent: .. math:: a^{\circ B} = \begin{bmatrix} a^{B_{0, 0}} & a^{B_{0, 1}} & \cdots & a^{B_{0, n-1}} \\ a^{B_{1, 0}} & a^{B_{1, 1}} & \cdots & a^{B_{1, n-1}} \\ \vdots & \vdots & \ddots & \vdots \\ a^{B_{m-1, 0}} & a^{B_{m-1, 1}} & \cdots & a^{B_{m-1, n-1}} \end{bmatrix} Matrix raised to a matrix exponent: .. math:: A^{\circ B} = \begin{bmatrix} A_{0, 0}^{B_{0, 0}} & A_{0, 1}^{B_{0, 1}} & \cdots & A_{0, n-1}^{B_{0, n-1}} \\ A_{1, 0}^{B_{1, 0}} & A_{1, 1}^{B_{1, 1}} & \cdots & A_{1, n-1}^{B_{1, n-1}} \\ \vdots & \vdots & \ddots & \vdots \\ A_{m-1, 0}^{B_{m-1, 0}} & A_{m-1, 1}^{B_{m-1, 1}} & \cdots & A_{m-1, n-1}^{B_{m-1, n-1}} \end{bmatrix} Scalar raised to a scalar exponent: .. math:: a^{\circ b} = a^b """ def __new__(cls, base, exp): base = sympify(base) exp = sympify(exp) if base.is_scalar and exp.is_scalar: return base ** exp if base.is_Matrix and exp.is_Matrix and base.shape != exp.shape: raise ValueError( 'The shape of the base {} and ' 'the shape of the exponent {} do not match.' .format(base.shape, exp.shape) ) obj = super().__new__(cls, base, exp) return obj @property def base(self): return self._args[0] @property def exp(self): return self._args[1] @property def shape(self): if self.base.is_Matrix: return self.base.shape return self.exp.shape def _entry(self, i, j, **kwargs): base = self.base exp = self.exp if base.is_Matrix: a = base._entry(i, j, **kwargs) elif base.is_scalar: a = base else: raise ValueError( 'The base {} must be a scalar or a matrix.'.format(base)) if exp.is_Matrix: b = exp._entry(i, j, **kwargs) elif exp.is_scalar: b = exp else: raise ValueError( 'The exponent {} must be a scalar or a matrix.'.format(exp)) return a ** b def _eval_transpose(self): from sympy.matrices.expressions.transpose import transpose return HadamardPower(transpose(self.base), self.exp) def _eval_derivative(self, x): from sympy import log dexp = self.exp.diff(x) logbase = self.base.applyfunc(log) dlbase = logbase.diff(x) return hadamard_product( dexp*logbase + self.exp*dlbase, self ) def _eval_derivative_matrix_lines(self, x): from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct from sympy.tensor.array.expressions.array_expressions import ArrayDiagonal from sympy.core.expr import ExprBuilder from sympy.matrices.expressions.matexpr import _make_matrix lr = self.base._eval_derivative_matrix_lines(x) for i in lr: diagonal = [(1, 2), (3, 4)] diagonal = [e for j, e in enumerate(diagonal) if self.base.shape[j] != 1] l1 = i._lines[i._first_line_index] l2 = i._lines[i._second_line_index] subexpr = ExprBuilder( ArrayDiagonal, [ ExprBuilder( ArrayTensorProduct, [ ExprBuilder(_make_matrix, [l1]), self.exp*hadamard_power(self.base, self.exp-1), ExprBuilder(_make_matrix, [l2]), ] ), *diagonal], validator=ArrayDiagonal._validate ) i._first_pointer_parent = subexpr.args[0].args[0].args i._first_pointer_index = 0 i._first_line_index = 0 i._second_pointer_parent = subexpr.args[0].args[2].args i._second_pointer_index = 0 i._second_line_index = 0 i._lines = [subexpr] return lr
d86cd8344899f36c2e160f8333075a188d26288006b3b755e23ed578be8fc8e3
""" Some examples have been taken from: http://www.math.uwaterloo.ca/~hwolkowi//matrixcookbook.pdf """ from sympy import (MatrixSymbol, Inverse, symbols, Determinant, Trace, sin, exp, cos, tan, log, S, sqrt, hadamard_product, DiagMatrix, OneMatrix, HadamardProduct, HadamardPower, KroneckerDelta, Sum, Rational) from sympy import MatAdd, Identity, MatMul, ZeroMatrix from sympy.tensor.array.array_derivatives import ArrayDerivative from sympy.matrices.expressions import hadamard_power k = symbols("k") i, j = symbols("i j") m, n = symbols("m n") X = MatrixSymbol("X", k, k) x = MatrixSymbol("x", k, 1) y = MatrixSymbol("y", k, 1) A = MatrixSymbol("A", k, k) B = MatrixSymbol("B", k, k) C = MatrixSymbol("C", k, k) D = MatrixSymbol("D", k, k) a = MatrixSymbol("a", k, 1) b = MatrixSymbol("b", k, 1) c = MatrixSymbol("c", k, 1) d = MatrixSymbol("d", k, 1) KDelta = lambda i, j: KroneckerDelta(i, j, (0, k-1)) def _check_derivative_with_explicit_matrix(expr, x, diffexpr, dim=2): # TODO: this is commented because it slows down the tests. return expr = expr.xreplace({k: dim}) x = x.xreplace({k: dim}) diffexpr = diffexpr.xreplace({k: dim}) expr = expr.as_explicit() x = x.as_explicit() diffexpr = diffexpr.as_explicit() assert expr.diff(x).reshape(*diffexpr.shape).tomatrix() == diffexpr def test_matrix_derivative_by_scalar(): assert A.diff(i) == ZeroMatrix(k, k) assert (A*(X + B)*c).diff(i) == ZeroMatrix(k, 1) assert x.diff(i) == ZeroMatrix(k, 1) assert (x.T*y).diff(i) == ZeroMatrix(1, 1) assert (x*x.T).diff(i) == ZeroMatrix(k, k) assert (x + y).diff(i) == ZeroMatrix(k, 1) assert hadamard_power(x, 2).diff(i) == ZeroMatrix(k, 1) assert hadamard_power(x, i).diff(i).dummy_eq( HadamardProduct(x.applyfunc(log), HadamardPower(x, i))) assert hadamard_product(x, y).diff(i) == ZeroMatrix(k, 1) assert hadamard_product(i*OneMatrix(k, 1), x, y).diff(i) == hadamard_product(x, y) assert (i*x).diff(i) == x assert (sin(i)*A*B*x).diff(i) == cos(i)*A*B*x assert x.applyfunc(sin).diff(i) == ZeroMatrix(k, 1) assert Trace(i**2*X).diff(i) == 2*i*Trace(X) mu = symbols("mu") expr = (2*mu*x) assert expr.diff(x) == 2*mu*Identity(k) def test_matrix_derivative_non_matrix_result(): # This is a 4-dimensional array: assert A.diff(A) == ArrayDerivative(A, A) assert A.T.diff(A) == ArrayDerivative(A.T, A) assert (2*A).diff(A) == ArrayDerivative(2*A, A) assert MatAdd(A, A).diff(A) == ArrayDerivative(MatAdd(A, A), A) assert (A + B).diff(A) == ArrayDerivative(A + B, A) # TODO: `B` can be removed. def test_matrix_derivative_trivial_cases(): # Cookbook example 33: # TODO: find a way to represent a four-dimensional zero-array: assert X.diff(A) == ArrayDerivative(X, A) def test_matrix_derivative_with_inverse(): # Cookbook example 61: expr = a.T*Inverse(X)*b assert expr.diff(X) == -Inverse(X).T*a*b.T*Inverse(X).T # Cookbook example 62: expr = Determinant(Inverse(X)) # Not implemented yet: # assert expr.diff(X) == -Determinant(X.inv())*(X.inv()).T # Cookbook example 63: expr = Trace(A*Inverse(X)*B) assert expr.diff(X) == -(X**(-1)*B*A*X**(-1)).T # Cookbook example 64: expr = Trace(Inverse(X + A)) assert expr.diff(X) == -(Inverse(X + A)).T**2 def test_matrix_derivative_vectors_and_scalars(): assert x.diff(x) == Identity(k) assert x[i, 0].diff(x[m, 0]).doit() == KDelta(m, i) assert x.T.diff(x) == Identity(k) # Cookbook example 69: expr = x.T*a assert expr.diff(x) == a assert expr[0, 0].diff(x[m, 0]).doit() == a[m, 0] expr = a.T*x assert expr.diff(x) == a # Cookbook example 70: expr = a.T*X*b assert expr.diff(X) == a*b.T # Cookbook example 71: expr = a.T*X.T*b assert expr.diff(X) == b*a.T # Cookbook example 72: expr = a.T*X*a assert expr.diff(X) == a*a.T expr = a.T*X.T*a assert expr.diff(X) == a*a.T # Cookbook example 77: expr = b.T*X.T*X*c assert expr.diff(X) == X*b*c.T + X*c*b.T # Cookbook example 78: expr = (B*x + b).T*C*(D*x + d) assert expr.diff(x) == B.T*C*(D*x + d) + D.T*C.T*(B*x + b) # Cookbook example 81: expr = x.T*B*x assert expr.diff(x) == B*x + B.T*x # Cookbook example 82: expr = b.T*X.T*D*X*c assert expr.diff(X) == D.T*X*b*c.T + D*X*c*b.T # Cookbook example 83: expr = (X*b + c).T*D*(X*b + c) assert expr.diff(X) == D*(X*b + c)*b.T + D.T*(X*b + c)*b.T assert str(expr[0, 0].diff(X[m, n]).doit()) == \ 'b[n, 0]*Sum((c[_i_1, 0] + Sum(X[_i_1, _i_3]*b[_i_3, 0], (_i_3, 0, k - 1)))*D[_i_1, m], (_i_1, 0, k - 1)) + Sum((c[_i_2, 0] + Sum(X[_i_2, _i_4]*b[_i_4, 0], (_i_4, 0, k - 1)))*D[m, _i_2]*b[n, 0], (_i_2, 0, k - 1))' def test_matrix_derivatives_of_traces(): expr = Trace(A)*A assert expr.diff(A) == ArrayDerivative(Trace(A)*A, A) assert expr[i, j].diff(A[m, n]).doit() == ( KDelta(i, m)*KDelta(j, n)*Trace(A) + KDelta(m, n)*A[i, j] ) ## First order: # Cookbook example 99: expr = Trace(X) assert expr.diff(X) == Identity(k) assert expr.rewrite(Sum).diff(X[m, n]).doit() == KDelta(m, n) # Cookbook example 100: expr = Trace(X*A) assert expr.diff(X) == A.T assert expr.rewrite(Sum).diff(X[m, n]).doit() == A[n, m] # Cookbook example 101: expr = Trace(A*X*B) assert expr.diff(X) == A.T*B.T assert expr.rewrite(Sum).diff(X[m, n]).doit().dummy_eq((A.T*B.T)[m, n]) # Cookbook example 102: expr = Trace(A*X.T*B) assert expr.diff(X) == B*A # Cookbook example 103: expr = Trace(X.T*A) assert expr.diff(X) == A # Cookbook example 104: expr = Trace(A*X.T) assert expr.diff(X) == A # Cookbook example 105: # TODO: TensorProduct is not supported #expr = Trace(TensorProduct(A, X)) #assert expr.diff(X) == Trace(A)*Identity(k) ## Second order: # Cookbook example 106: expr = Trace(X**2) assert expr.diff(X) == 2*X.T # Cookbook example 107: expr = Trace(X**2*B) assert expr.diff(X) == (X*B + B*X).T expr = Trace(MatMul(X, X, B)) assert expr.diff(X) == (X*B + B*X).T # Cookbook example 108: expr = Trace(X.T*B*X) assert expr.diff(X) == B*X + B.T*X # Cookbook example 109: expr = Trace(B*X*X.T) assert expr.diff(X) == B*X + B.T*X # Cookbook example 110: expr = Trace(X*X.T*B) assert expr.diff(X) == B*X + B.T*X # Cookbook example 111: expr = Trace(X*B*X.T) assert expr.diff(X) == X*B.T + X*B # Cookbook example 112: expr = Trace(B*X.T*X) assert expr.diff(X) == X*B.T + X*B # Cookbook example 113: expr = Trace(X.T*X*B) assert expr.diff(X) == X*B.T + X*B # Cookbook example 114: expr = Trace(A*X*B*X) assert expr.diff(X) == A.T*X.T*B.T + B.T*X.T*A.T # Cookbook example 115: expr = Trace(X.T*X) assert expr.diff(X) == 2*X expr = Trace(X*X.T) assert expr.diff(X) == 2*X # Cookbook example 116: expr = Trace(B.T*X.T*C*X*B) assert expr.diff(X) == C.T*X*B*B.T + C*X*B*B.T # Cookbook example 117: expr = Trace(X.T*B*X*C) assert expr.diff(X) == B*X*C + B.T*X*C.T # Cookbook example 118: expr = Trace(A*X*B*X.T*C) assert expr.diff(X) == A.T*C.T*X*B.T + C*A*X*B # Cookbook example 119: expr = Trace((A*X*B + C)*(A*X*B + C).T) assert expr.diff(X) == 2*A.T*(A*X*B + C)*B.T # Cookbook example 120: # TODO: no support for TensorProduct. # expr = Trace(TensorProduct(X, X)) # expr = Trace(X)*Trace(X) # expr.diff(X) == 2*Trace(X)*Identity(k) # Higher Order # Cookbook example 121: expr = Trace(X**k) #assert expr.diff(X) == k*(X**(k-1)).T # Cookbook example 122: expr = Trace(A*X**k) #assert expr.diff(X) == # Needs indices # Cookbook example 123: expr = Trace(B.T*X.T*C*X*X.T*C*X*B) assert expr.diff(X) == C*X*X.T*C*X*B*B.T + C.T*X*B*B.T*X.T*C.T*X + C*X*B*B.T*X.T*C*X + C.T*X*X.T*C.T*X*B*B.T # Other # Cookbook example 124: expr = Trace(A*X**(-1)*B) assert expr.diff(X) == -Inverse(X).T*A.T*B.T*Inverse(X).T # Cookbook example 125: expr = Trace(Inverse(X.T*C*X)*A) # Warning: result in the cookbook is equivalent if B and C are symmetric: assert expr.diff(X) == - X.inv().T*A.T*X.inv()*C.inv().T*X.inv().T - X.inv().T*A*X.inv()*C.inv()*X.inv().T # Cookbook example 126: expr = Trace((X.T*C*X).inv()*(X.T*B*X)) assert expr.diff(X) == -2*C*X*(X.T*C*X).inv()*X.T*B*X*(X.T*C*X).inv() + 2*B*X*(X.T*C*X).inv() # Cookbook example 127: expr = Trace((A + X.T*C*X).inv()*(X.T*B*X)) # Warning: result in the cookbook is equivalent if B and C are symmetric: assert expr.diff(X) == B*X*Inverse(A + X.T*C*X) - C*X*Inverse(A + X.T*C*X)*X.T*B*X*Inverse(A + X.T*C*X) - C.T*X*Inverse(A.T + (C*X).T*X)*X.T*B.T*X*Inverse(A.T + (C*X).T*X) + B.T*X*Inverse(A.T + (C*X).T*X) def test_derivatives_of_complicated_matrix_expr(): expr = a.T*(A*X*(X.T*B + X*A) + B.T*X.T*(a*b.T*(X*D*X.T + X*(X.T*B + A*X)*D*B - X.T*C.T*A)*B + B*(X*D.T + B*A*X*A.T - 3*X*D))*B + 42*X*B*X.T*A.T*(X + X.T))*b result = (B*(B*A*X*A.T - 3*X*D + X*D.T) + a*b.T*(X*(A*X + X.T*B)*D*B + X*D*X.T - X.T*C.T*A)*B)*B*b*a.T*B.T + B**2*b*a.T*B.T*X.T*a*b.T*X*D + 42*A*X*B.T*X.T*a*b.T + B*D*B**3*b*a.T*B.T*X.T*a*b.T*X + B*b*a.T*A*X + 42*a*b.T*(X + X.T)*A*X*B.T + b*a.T*X*B*a*b.T*B.T**2*X*D.T + b*a.T*X*B*a*b.T*B.T**3*D.T*(B.T*X + X.T*A.T) + 42*b*a.T*X*B*X.T*A.T + 42*A.T*(X + X.T)*b*a.T*X*B + A.T*B.T**2*X*B*a*b.T*B.T*A + A.T*a*b.T*(A.T*X.T + B.T*X) + A.T*X.T*b*a.T*X*B*a*b.T*B.T**3*D.T + B.T*X*B*a*b.T*B.T*D - 3*B.T*X*B*a*b.T*B.T*D.T - C.T*A*B**2*b*a.T*B.T*X.T*a*b.T + X.T*A.T*a*b.T*A.T assert expr.diff(X) == result def test_mixed_deriv_mixed_expressions(): expr = 3*Trace(A) assert expr.diff(A) == 3*Identity(k) expr = k deriv = expr.diff(A) assert isinstance(deriv, ZeroMatrix) assert deriv == ZeroMatrix(k, k) expr = Trace(A)**2 assert expr.diff(A) == (2*Trace(A))*Identity(k) expr = Trace(A)*A # TODO: this is not yet supported: assert expr.diff(A) == ArrayDerivative(expr, A) expr = Trace(Trace(A)*A) assert expr.diff(A) == (2*Trace(A))*Identity(k) expr = Trace(Trace(Trace(A)*A)*A) assert expr.diff(A) == (3*Trace(A)**2)*Identity(k) def test_derivatives_matrix_norms(): expr = x.T*y assert expr.diff(x) == y assert expr[0, 0].diff(x[m, 0]).doit() == y[m, 0] expr = (x.T*y)**S.Half assert expr.diff(x) == y/(2*sqrt(x.T*y)) expr = (x.T*x)**S.Half assert expr.diff(x) == x*(x.T*x)**Rational(-1, 2) expr = (c.T*a*x.T*b)**S.Half assert expr.diff(x) == b/(2*sqrt(c.T*a*x.T*b))*c.T*a expr = (c.T*a*x.T*b)**Rational(1, 3) assert expr.diff(x) == b*(c.T*a*x.T*b)**Rational(-2, 3)*c.T*a/3 expr = (a.T*X*b)**S.Half assert expr.diff(X) == a/(2*sqrt(a.T*X*b))*b.T expr = d.T*x*(a.T*X*b)**S.Half*y.T*c assert expr.diff(X) == a*d.T*x/(2*sqrt(a.T*X*b))*y.T*c*b.T def test_derivatives_elementwise_applyfunc(): from sympy.matrices.expressions.diagonal import DiagMatrix expr = x.applyfunc(tan) assert expr.diff(x).dummy_eq( DiagMatrix(x.applyfunc(lambda x: tan(x)**2 + 1))) assert expr[i, 0].diff(x[m, 0]).doit() == (tan(x[i, 0])**2 + 1)*KDelta(i, m) _check_derivative_with_explicit_matrix(expr, x, expr.diff(x)) expr = (i**2*x).applyfunc(sin) assert expr.diff(i).dummy_eq( HadamardProduct((2*i)*x, (i**2*x).applyfunc(cos))) assert expr[i, 0].diff(i).doit() == 2*i*x[i, 0]*cos(i**2*x[i, 0]) _check_derivative_with_explicit_matrix(expr, i, expr.diff(i)) expr = (log(i)*A*B).applyfunc(sin) assert expr.diff(i).dummy_eq( HadamardProduct(A*B/i, (log(i)*A*B).applyfunc(cos))) _check_derivative_with_explicit_matrix(expr, i, expr.diff(i)) expr = A*x.applyfunc(exp) # TODO: restore this result (currently returning the transpose): # assert expr.diff(x).dummy_eq(DiagMatrix(x.applyfunc(exp))*A.T) _check_derivative_with_explicit_matrix(expr, x, expr.diff(x)) expr = x.T*A*x + k*y.applyfunc(sin).T*x assert expr.diff(x).dummy_eq(A.T*x + A*x + k*y.applyfunc(sin)) _check_derivative_with_explicit_matrix(expr, x, expr.diff(x)) expr = x.applyfunc(sin).T*y # TODO: restore (currently returning the traspose): # assert expr.diff(x).dummy_eq(DiagMatrix(x.applyfunc(cos))*y) _check_derivative_with_explicit_matrix(expr, x, expr.diff(x)) expr = (a.T * X * b).applyfunc(sin) assert expr.diff(X).dummy_eq(a*(a.T*X*b).applyfunc(cos)*b.T) _check_derivative_with_explicit_matrix(expr, X, expr.diff(X)) expr = a.T * X.applyfunc(sin) * b assert expr.diff(X).dummy_eq( DiagMatrix(a)*X.applyfunc(cos)*DiagMatrix(b)) _check_derivative_with_explicit_matrix(expr, X, expr.diff(X)) expr = a.T * (A*X*B).applyfunc(sin) * b assert expr.diff(X).dummy_eq( A.T*DiagMatrix(a)*(A*X*B).applyfunc(cos)*DiagMatrix(b)*B.T) _check_derivative_with_explicit_matrix(expr, X, expr.diff(X)) expr = a.T * (A*X*b).applyfunc(sin) * b.T # TODO: not implemented #assert expr.diff(X) == ... #_check_derivative_with_explicit_matrix(expr, X, expr.diff(X)) expr = a.T*A*X.applyfunc(sin)*B*b assert expr.diff(X).dummy_eq( DiagMatrix(A.T*a)*X.applyfunc(cos)*DiagMatrix(B*b)) expr = a.T * (A*X.applyfunc(sin)*B).applyfunc(log) * b # TODO: wrong # assert expr.diff(X) == A.T*DiagMatrix(a)*(A*X.applyfunc(sin)*B).applyfunc(Lambda(k, 1/k))*DiagMatrix(b)*B.T expr = a.T * (X.applyfunc(sin)).applyfunc(log) * b # TODO: wrong # assert expr.diff(X) == DiagMatrix(a)*X.applyfunc(sin).applyfunc(Lambda(k, 1/k))*DiagMatrix(b) def test_derivatives_of_hadamard_expressions(): # Hadamard Product expr = hadamard_product(a, x, b) assert expr.diff(x) == DiagMatrix(hadamard_product(b, a)) expr = a.T*hadamard_product(A, X, B)*b assert expr.diff(X) == DiagMatrix(a)*hadamard_product(B, A)*DiagMatrix(b) # Hadamard Power expr = hadamard_power(x, 2) assert expr.diff(x).doit() == 2*DiagMatrix(x) expr = hadamard_power(x.T, 2) assert expr.diff(x).doit() == 2*DiagMatrix(x) expr = hadamard_power(x, S.Half) assert expr.diff(x) == S.Half*DiagMatrix(hadamard_power(x, Rational(-1, 2))) expr = hadamard_power(a.T*X*b, 2) assert expr.diff(X) == 2*a*a.T*X*b*b.T expr = hadamard_power(a.T*X*b, S.Half) assert expr.diff(X) == a/2*hadamard_power(a.T*X*b, Rational(-1, 2))*b.T
1fc3db4b298a7770d6dabffdfeebb965fa1b52002b165be6be1fd7bef9554510
from sympy import (KroneckerDelta, diff, Sum, Dummy, factor, expand, zeros, gcd_terms, Eq, Symbol) 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.matexpr import MatrixElement from sympy.matrices.expressions.special import ZeroMatrix, Identity from sympy.testing.pytest import raises, XFAIL n, m, l, k, p = symbols('n m l k p', integer=True) x = symbols('x') A = MatrixSymbol('A', n, m) B = MatrixSymbol('B', m, l) C = MatrixSymbol('C', n, n) D = MatrixSymbol('D', n, n) E = MatrixSymbol('E', m, n) w = MatrixSymbol('w', n, 1) def test_matrix_symbol_creation(): assert MatrixSymbol('A', 2, 2) assert MatrixSymbol('A', 0, 0) raises(ValueError, lambda: MatrixSymbol('A', -1, 2)) raises(ValueError, lambda: MatrixSymbol('A', 2.0, 2)) raises(ValueError, lambda: MatrixSymbol('A', 2j, 2)) raises(ValueError, lambda: MatrixSymbol('A', 2, -1)) raises(ValueError, lambda: MatrixSymbol('A', 2, 2.0)) raises(ValueError, lambda: MatrixSymbol('A', 2, 2j)) n = symbols('n') assert MatrixSymbol('A', n, n) n = symbols('n', integer=False) raises(ValueError, lambda: MatrixSymbol('A', n, n)) n = symbols('n', negative=True) raises(ValueError, lambda: MatrixSymbol('A', n, n)) def test_shape(): assert A.shape == (n, m) assert (A*B).shape == (n, l) raises(ShapeError, lambda: B*A) def test_matexpr(): assert (x*A).shape == A.shape assert (x*A).__class__ == MatMul assert 2*A - A - A == ZeroMatrix(*A.shape) assert (A*B).shape == (n, l) def test_subs(): A = MatrixSymbol('A', n, m) B = MatrixSymbol('B', m, l) C = MatrixSymbol('C', m, l) assert A.subs(n, m).shape == (m, m) assert (A*B).subs(B, C) == A*C assert (A*B).subs(l, n).is_square A = SparseMatrix([[1, 2], [3, 4]]) B = Matrix([[1, 2], [3, 4]]) C, D = MatrixSymbol('C', 2, 2), MatrixSymbol('D', 2, 2) assert (C*D).subs({C: A, D: B}) == MatMul(A, B) def test_addition(): A = MatrixSymbol('A', n, m) B = MatrixSymbol('B', n, m) assert isinstance(A + B, MatAdd) assert (A + B).shape == A.shape assert isinstance(A - A + 2*B, MatMul) raises(ShapeError, lambda: A + B.T) raises(TypeError, lambda: A + 1) raises(TypeError, lambda: 5 + A) raises(TypeError, lambda: 5 - A) assert A + ZeroMatrix(n, m) - A == ZeroMatrix(n, m) with raises(TypeError): ZeroMatrix(n,m) + S.Zero def test_multiplication(): A = MatrixSymbol('A', n, m) B = MatrixSymbol('B', m, l) C = MatrixSymbol('C', n, n) assert (2*A*B).shape == (n, l) assert (A*0*B) == ZeroMatrix(n, l) raises(ShapeError, lambda: B*A) assert (2*A).shape == A.shape assert A * ZeroMatrix(m, m) * B == ZeroMatrix(n, l) assert C * Identity(n) * C.I == Identity(n) assert B/2 == S.Half*B raises(NotImplementedError, lambda: 2/B) A = MatrixSymbol('A', n, n) B = MatrixSymbol('B', n, n) assert Identity(n) * (A + B) == A + B assert A**2*A == A**3 assert A**2*(A.I)**3 == A.I assert A**3*(A.I)**2 == A def test_MatPow(): A = MatrixSymbol('A', n, n) AA = MatPow(A, 2) assert AA.exp == 2 assert AA.base == A assert (A**n).exp == n assert A**0 == Identity(n) assert A**1 == A assert A**2 == AA assert A**-1 == Inverse(A) assert (A**-1)**-1 == A assert (A**2)**3 == A**6 assert A**S.Half == sqrt(A) assert A**Rational(1, 3) == cbrt(A) raises(NonSquareMatrixError, lambda: MatrixSymbol('B', 3, 2)**2) def test_MatrixSymbol(): n, m, t = symbols('n,m,t') X = MatrixSymbol('X', n, m) assert X.shape == (n, m) raises(TypeError, lambda: MatrixSymbol('X', n, m)(t)) # issue 5855 assert X.doit() == X def test_dense_conversion(): X = MatrixSymbol('X', 2, 2) assert ImmutableMatrix(X) == ImmutableMatrix(2, 2, lambda i, j: X[i, j]) assert Matrix(X) == Matrix(2, 2, lambda i, j: X[i, j]) def test_free_symbols(): assert (C*D).free_symbols == {C, D} def test_zero_matmul(): assert isinstance(S.Zero * MatrixSymbol('X', 2, 2), MatrixExpr) def test_matadd_simplify(): A = MatrixSymbol('A', 1, 1) assert simplify(MatAdd(A, ImmutableMatrix([[sin(x)**2 + cos(x)**2]]))) == \ MatAdd(A, Matrix([[1]])) def test_matmul_simplify(): A = MatrixSymbol('A', 1, 1) assert simplify(MatMul(A, ImmutableMatrix([[sin(x)**2 + cos(x)**2]]))) == \ MatMul(A, Matrix([[1]])) def test_invariants(): A = MatrixSymbol('A', n, m) B = MatrixSymbol('B', m, l) X = MatrixSymbol('X', n, n) objs = [Identity(n), ZeroMatrix(m, n), A, MatMul(A, B), MatAdd(A, A), Transpose(A), Adjoint(A), Inverse(X), MatPow(X, 2), MatPow(X, -1), MatPow(X, 0)] for obj in objs: assert obj == obj.__class__(*obj.args) def test_indexing(): A = MatrixSymbol('A', n, m) A[1, 2] A[l, k] A[l+1, k+1] def test_single_indexing(): A = MatrixSymbol('A', 2, 3) assert A[1] == A[0, 1] assert A[int(1)] == A[0, 1] assert A[3] == A[1, 0] assert list(A[:2, :2]) == [A[0, 0], A[0, 1], A[1, 0], A[1, 1]] raises(IndexError, lambda: A[6]) raises(IndexError, lambda: A[n]) B = MatrixSymbol('B', n, m) raises(IndexError, lambda: B[1]) B = MatrixSymbol('B', n, 3) assert B[3] == B[1, 0] def test_MatrixElement_commutative(): assert A[0, 1]*A[1, 0] == A[1, 0]*A[0, 1] def test_MatrixSymbol_determinant(): A = MatrixSymbol('A', 4, 4) assert A.as_explicit().det() == A[0, 0]*A[1, 1]*A[2, 2]*A[3, 3] - \ A[0, 0]*A[1, 1]*A[2, 3]*A[3, 2] - A[0, 0]*A[1, 2]*A[2, 1]*A[3, 3] + \ A[0, 0]*A[1, 2]*A[2, 3]*A[3, 1] + A[0, 0]*A[1, 3]*A[2, 1]*A[3, 2] - \ A[0, 0]*A[1, 3]*A[2, 2]*A[3, 1] - A[0, 1]*A[1, 0]*A[2, 2]*A[3, 3] + \ A[0, 1]*A[1, 0]*A[2, 3]*A[3, 2] + A[0, 1]*A[1, 2]*A[2, 0]*A[3, 3] - \ A[0, 1]*A[1, 2]*A[2, 3]*A[3, 0] - A[0, 1]*A[1, 3]*A[2, 0]*A[3, 2] + \ A[0, 1]*A[1, 3]*A[2, 2]*A[3, 0] + A[0, 2]*A[1, 0]*A[2, 1]*A[3, 3] - \ A[0, 2]*A[1, 0]*A[2, 3]*A[3, 1] - A[0, 2]*A[1, 1]*A[2, 0]*A[3, 3] + \ A[0, 2]*A[1, 1]*A[2, 3]*A[3, 0] + A[0, 2]*A[1, 3]*A[2, 0]*A[3, 1] - \ A[0, 2]*A[1, 3]*A[2, 1]*A[3, 0] - A[0, 3]*A[1, 0]*A[2, 1]*A[3, 2] + \ A[0, 3]*A[1, 0]*A[2, 2]*A[3, 1] + A[0, 3]*A[1, 1]*A[2, 0]*A[3, 2] - \ A[0, 3]*A[1, 1]*A[2, 2]*A[3, 0] - A[0, 3]*A[1, 2]*A[2, 0]*A[3, 1] + \ A[0, 3]*A[1, 2]*A[2, 1]*A[3, 0] 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 @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
16d6dda53edb9a8253fc018442417f40386908f486453a41973c5dfd4bf459d8
from sympy.core.symbol import symbols, Dummy from sympy.matrices.expressions.applyfunc import ElementwiseApplyFunction from sympy import Matrix, Lambda, MatrixSymbol, exp, MatMul, sin, simplify from sympy.testing.pytest import raises from sympy.matrices.common import ShapeError X = MatrixSymbol("X", 3, 3) Y = MatrixSymbol("Y", 3, 3) k = symbols("k") Xk = MatrixSymbol("X", k, k) Xd = X.as_explicit() x, y, z, t = symbols("x y z t") def test_applyfunc_matrix(): x = Dummy('x') double = Lambda(x, x**2) expr = ElementwiseApplyFunction(double, Xd) assert isinstance(expr, ElementwiseApplyFunction) assert expr.doit() == Xd.applyfunc(lambda x: x**2) assert expr.shape == (3, 3) assert expr.func(*expr.args) == expr assert simplify(expr) == expr assert expr[0, 0] == double(Xd[0, 0]) expr = ElementwiseApplyFunction(double, X) assert isinstance(expr, ElementwiseApplyFunction) assert isinstance(expr.doit(), ElementwiseApplyFunction) assert expr == X.applyfunc(double) assert expr.func(*expr.args) == expr expr = ElementwiseApplyFunction(exp, X*Y) assert expr.expr == X*Y assert expr.function.dummy_eq(Lambda(x, exp(x))) assert expr.dummy_eq((X*Y).applyfunc(exp)) assert expr.func(*expr.args) == expr assert isinstance(X*expr, MatMul) assert (X*expr).shape == (3, 3) Z = MatrixSymbol("Z", 2, 3) assert (Z*expr).shape == (2, 3) expr = ElementwiseApplyFunction(exp, Z.T)*ElementwiseApplyFunction(exp, Z) assert expr.shape == (3, 3) expr = ElementwiseApplyFunction(exp, Z)*ElementwiseApplyFunction(exp, Z.T) assert expr.shape == (2, 2) raises(ShapeError, lambda: ElementwiseApplyFunction(exp, Z)*ElementwiseApplyFunction(exp, Z)) M = Matrix([[x, y], [z, t]]) expr = ElementwiseApplyFunction(sin, M) assert isinstance(expr, ElementwiseApplyFunction) assert expr.function.dummy_eq(Lambda(x, sin(x))) assert expr.expr == M assert expr.doit() == M.applyfunc(sin) assert expr.doit() == Matrix([[sin(x), sin(y)], [sin(z), sin(t)]]) assert expr.func(*expr.args) == expr expr = ElementwiseApplyFunction(double, Xk) assert expr.doit() == expr assert expr.subs(k, 2).shape == (2, 2) assert (expr*expr).shape == (k, k) M = MatrixSymbol("M", k, t) expr2 = M.T*expr*M assert isinstance(expr2, MatMul) assert expr2.args[1] == expr assert expr2.shape == (t, t) expr3 = expr*M assert expr3.shape == (k, t) raises(ShapeError, lambda: M*expr) expr1 = ElementwiseApplyFunction(lambda x: x+1, Xk) expr2 = ElementwiseApplyFunction(lambda x: x, Xk) assert expr1 != expr2 def test_applyfunc_entry(): af = X.applyfunc(sin) assert af[0, 0] == sin(X[0, 0]) af = Xd.applyfunc(sin) assert af[0, 0] == sin(X[0, 0]) def test_applyfunc_as_explicit(): af = X.applyfunc(sin) assert af.as_explicit() == Matrix([ [sin(X[0, 0]), sin(X[0, 1]), sin(X[0, 2])], [sin(X[1, 0]), sin(X[1, 1]), sin(X[1, 2])], [sin(X[2, 0]), sin(X[2, 1]), sin(X[2, 2])], ]) def test_applyfunc_transpose(): af = Xk.applyfunc(sin) assert af.T.dummy_eq(Xk.T.applyfunc(sin))
9112ada911427b236840a458687d4b9c1428fd20cfa245113851506082bde804
from sympy import Set, symbols, exp, log, S, Wild, Dummy, oo, Float from sympy.core import Expr, Add from sympy.core.function import Lambda, _coeff_isneg, FunctionClass from sympy.logic.boolalg import true from sympy.multipledispatch import dispatch from sympy.sets import (imageset, Interval, FiniteSet, Union, ImageSet, EmptySet, Intersection, Range) from sympy.sets.fancysets import Integers, Naturals, Reals from sympy.functions.elementary.exponential import match_real_imag _x, _y = symbols("x y") FunctionUnion = (FunctionClass, Lambda) @dispatch(FunctionClass, Set) # type: ignore # noqa:F811 def _set_function(f, x): # noqa:F811 return None @dispatch(FunctionUnion, FiniteSet) # type: ignore # noqa:F811 def _set_function(f, x): # noqa:F811 return FiniteSet(*map(f, x)) @dispatch(Lambda, Interval) # type: ignore # noqa:F811 def _set_function(f, x): # noqa:F811 from sympy.functions.elementary.miscellaneous import Min, Max from sympy.solvers.solveset import solveset from sympy.core.function import diff, Lambda from sympy.series import limit from sympy.calculus.singularities import singularities from sympy.sets import Complement # TODO: handle functions with infinitely many solutions (eg, sin, tan) # TODO: handle multivariate functions expr = f.expr if len(expr.free_symbols) > 1 or len(f.variables) != 1: return var = f.variables[0] if not var.is_real: if expr.subs(var, Dummy(real=True)).is_real is False: return if expr.is_Piecewise: result = S.EmptySet domain_set = x for (p_expr, p_cond) in expr.args: if p_cond is true: intrvl = domain_set else: intrvl = p_cond.as_set() intrvl = Intersection(domain_set, intrvl) if p_expr.is_Number: image = FiniteSet(p_expr) else: image = imageset(Lambda(var, p_expr), intrvl) result = Union(result, image) # remove the part which has been `imaged` domain_set = Complement(domain_set, intrvl) if domain_set is S.EmptySet: break return result if not x.start.is_comparable or not x.end.is_comparable: return try: from sympy.polys.polyutils import _nsort sing = list(singularities(expr, var, x)) if len(sing) > 1: sing = _nsort(sing) except NotImplementedError: return if x.left_open: _start = limit(expr, var, x.start, dir="+") elif x.start not in sing: _start = f(x.start) if x.right_open: _end = limit(expr, var, x.end, dir="-") elif x.end not in sing: _end = f(x.end) if len(sing) == 0: soln_expr = solveset(diff(expr, var), var) if not (isinstance(soln_expr, FiniteSet) or soln_expr is EmptySet): return solns = list(soln_expr) extr = [_start, _end] + [f(i) for i in solns if i.is_real and i in x] start, end = Min(*extr), Max(*extr) left_open, right_open = False, False if _start <= _end: # the minimum or maximum value can occur simultaneously # on both the edge of the interval and in some interior # point if start == _start and start not in solns: left_open = x.left_open if end == _end and end not in solns: right_open = x.right_open else: if start == _end and start not in solns: left_open = x.right_open if end == _start and end not in solns: right_open = x.left_open return Interval(start, end, left_open, right_open) else: return imageset(f, Interval(x.start, sing[0], x.left_open, True)) + \ Union(*[imageset(f, Interval(sing[i], sing[i + 1], True, True)) for i in range(0, len(sing) - 1)]) + \ imageset(f, Interval(sing[-1], x.end, True, x.right_open)) @dispatch(FunctionClass, Interval) # type: ignore # noqa:F811 def _set_function(f, x): # noqa:F811 if f == exp: return Interval(exp(x.start), exp(x.end), x.left_open, x.right_open) elif f == log: return Interval(log(x.start), log(x.end), x.left_open, x.right_open) return ImageSet(Lambda(_x, f(_x)), x) @dispatch(FunctionUnion, Union) # type: ignore # noqa:F811 def _set_function(f, x): # noqa:F811 return Union(*(imageset(f, arg) for arg in x.args)) @dispatch(FunctionUnion, Intersection) # type: ignore # noqa:F811 def _set_function(f, x): # noqa:F811 from sympy.sets.sets import is_function_invertible_in_set # If the function is invertible, intersect the maps of the sets. if is_function_invertible_in_set(f, x): return Intersection(*(imageset(f, arg) for arg in x.args)) else: return ImageSet(Lambda(_x, f(_x)), x) @dispatch(FunctionUnion, type(EmptySet)) # type: ignore # noqa:F811 def _set_function(f, x): # noqa:F811 return x @dispatch(FunctionUnion, Set) # type: ignore # noqa:F811 def _set_function(f, x): # noqa:F811 return ImageSet(Lambda(_x, f(_x)), x) @dispatch(FunctionUnion, Range) # type: ignore # noqa:F811 def _set_function(f, self): # noqa:F811 from sympy.core.function import expand_mul if not self: return S.EmptySet if not isinstance(f.expr, Expr): return if self.size == 1: return FiniteSet(f(self[0])) if f is S.IdentityFunction: return self x = f.variables[0] expr = f.expr # handle f that is linear in f's variable if x not in expr.free_symbols or x in expr.diff(x).free_symbols: return if self.start.is_finite: F = f(self.step*x + self.start) # for i in range(len(self)) else: F = f(-self.step*x + self[-1]) F = expand_mul(F) if F != expr: return imageset(x, F, Range(self.size)) @dispatch(FunctionUnion, Integers) # type: ignore # noqa:F811 def _set_function(f, self): # noqa:F811 expr = f.expr if not isinstance(expr, Expr): return n = f.variables[0] if expr == abs(n): return S.Naturals0 # f(x) + c and f(-x) + c cover the same integers # so choose the form that has the fewest negatives c = f(0) fx = f(n) - c f_x = f(-n) - c neg_count = lambda e: sum(_coeff_isneg(_) for _ in Add.make_args(e)) if neg_count(f_x) < neg_count(fx): expr = f_x + c a = Wild('a', exclude=[n]) b = Wild('b', exclude=[n]) match = expr.match(a*n + b) if match and match[a] and ( not match[a].atoms(Float) and not match[b].atoms(Float)): # canonical shift a, b = match[a], match[b] if a in [1, -1]: # drop integer addends in b nonint = [] for bi in Add.make_args(b): if not bi.is_integer: nonint.append(bi) b = Add(*nonint) if b.is_number and a.is_real: # avoid Mod for complex numbers, #11391 br, bi = match_real_imag(b) if br and br.is_comparable and a.is_comparable: br %= a b = br + S.ImaginaryUnit*bi elif b.is_number and a.is_imaginary: br, bi = match_real_imag(b) ai = a/S.ImaginaryUnit if bi and bi.is_comparable and ai.is_comparable: bi %= ai b = br + S.ImaginaryUnit*bi expr = a*n + b if expr != f.expr: return ImageSet(Lambda(n, expr), S.Integers) @dispatch(FunctionUnion, Naturals) # type: ignore # noqa:F811 def _set_function(f, self): # noqa:F811 expr = f.expr if not isinstance(expr, Expr): return x = f.variables[0] if not expr.free_symbols - {x}: if expr == abs(x): if self is S.Naturals: return self return S.Naturals0 step = expr.coeff(x) c = expr.subs(x, 0) if c.is_Integer and step.is_Integer and expr == step*x + c: if self is S.Naturals: c += step if step > 0: if step == 1: if c == 0: return S.Naturals0 elif c == 1: return S.Naturals return Range(c, oo, step) return Range(c, -oo, step) @dispatch(FunctionUnion, Reals) # type: ignore # noqa:F811 def _set_function(f, self): # noqa:F811 expr = f.expr if not isinstance(expr, Expr): return return _set_function(f, Interval(-oo, oo))
0e3f1e1ed7fe1cb938a66243015cbecce32d02536a19960ab1d06715a9aaf89c
from sympy.core.expr import unchanged from sympy.sets.fancysets import (ImageSet, Range, normalize_theta_set, ComplexRegion) from sympy.sets.sets import (FiniteSet, Interval, imageset, Union, Intersection, ProductSet, Contains) from sympy.simplify.simplify import simplify from sympy import (S, Symbol, Lambda, symbols, cos, sin, pi, oo, Basic, Rational, sqrt, tan, log, exp, Abs, I, Tuple, eye, Dummy, floor, And, Eq) from sympy.utilities.iterables import cartes from sympy.testing.pytest import XFAIL, raises from sympy.abc import x, y, t, z from sympy.core.mod import Mod import itertools def test_naturals(): N = S.Naturals assert 5 in N assert -5 not in N assert 5.5 not in N ni = iter(N) a, b, c, d = next(ni), next(ni), next(ni), next(ni) assert (a, b, c, d) == (1, 2, 3, 4) assert isinstance(a, Basic) assert N.intersect(Interval(-5, 5)) == Range(1, 6) assert N.intersect(Interval(-5, 5, True, True)) == Range(1, 5) assert N.boundary == N assert N.is_open == False assert N.is_closed == True assert N.inf == 1 assert N.sup is oo assert not N.contains(oo) for s in (S.Naturals0, S.Naturals): assert s.intersection(S.Reals) is s assert s.is_subset(S.Reals) assert N.as_relational(x) == And(Eq(floor(x), x), x >= 1, x < oo) def test_naturals0(): N = S.Naturals0 assert 0 in N assert -1 not in N assert next(iter(N)) == 0 assert not N.contains(oo) assert N.contains(sin(x)) == Contains(sin(x), N) def test_integers(): Z = S.Integers assert 5 in Z assert -5 in Z assert 5.5 not in Z assert not Z.contains(oo) assert not Z.contains(-oo) zi = iter(Z) a, b, c, d = next(zi), next(zi), next(zi), next(zi) assert (a, b, c, d) == (0, 1, -1, 2) assert isinstance(a, Basic) assert Z.intersect(Interval(-5, 5)) == Range(-5, 6) assert Z.intersect(Interval(-5, 5, True, True)) == Range(-4, 5) assert Z.intersect(Interval(5, S.Infinity)) == Range(5, S.Infinity) assert Z.intersect(Interval.Lopen(5, S.Infinity)) == Range(6, S.Infinity) assert Z.inf is -oo assert Z.sup is oo assert Z.boundary == Z assert Z.is_open == False assert Z.is_closed == True assert Z.as_relational(x) == And(Eq(floor(x), x), -oo < x, x < oo) def test_ImageSet(): raises(ValueError, lambda: ImageSet(x, S.Integers)) assert ImageSet(Lambda(x, 1), S.Integers) == FiniteSet(1) assert ImageSet(Lambda(x, y), S.Integers) == {y} assert ImageSet(Lambda(x, 1), S.EmptySet) == S.EmptySet empty = Intersection(FiniteSet(log(2)/pi), S.Integers) assert unchanged(ImageSet, Lambda(x, 1), empty) # issue #17471 squares = ImageSet(Lambda(x, x**2), S.Naturals) assert 4 in squares assert 5 not in squares assert FiniteSet(*range(10)).intersect(squares) == FiniteSet(1, 4, 9) assert 16 not in squares.intersect(Interval(0, 10)) si = iter(squares) a, b, c, d = next(si), next(si), next(si), next(si) assert (a, b, c, d) == (1, 4, 9, 16) harmonics = ImageSet(Lambda(x, 1/x), S.Naturals) assert Rational(1, 5) in harmonics assert Rational(.25) in harmonics assert 0.25 not in harmonics assert Rational(.3) not in harmonics assert (1, 2) not in harmonics assert harmonics.is_iterable assert imageset(x, -x, Interval(0, 1)) == Interval(-1, 0) assert ImageSet(Lambda(x, x**2), Interval(0, 2)).doit() == Interval(0, 4) assert ImageSet(Lambda((x, y), 2*x), {4}, {3}).doit() == FiniteSet(8) assert (ImageSet(Lambda((x, y), x+y), {1, 2, 3}, {10, 20, 30}).doit() == FiniteSet(11, 12, 13, 21, 22, 23, 31, 32, 33)) c = Interval(1, 3) * Interval(1, 3) assert Tuple(2, 6) in ImageSet(Lambda(((x, y),), (x, 2*y)), c) assert Tuple(2, S.Half) in ImageSet(Lambda(((x, y),), (x, 1/y)), c) assert Tuple(2, -2) not in ImageSet(Lambda(((x, y),), (x, y**2)), c) assert Tuple(2, -2) in ImageSet(Lambda(((x, y),), (x, -2)), c) c3 = ProductSet(Interval(3, 7), Interval(8, 11), Interval(5, 9)) assert Tuple(8, 3, 9) in ImageSet(Lambda(((t, y, x),), (y, t, x)), c3) assert Tuple(Rational(1, 8), 3, 9) in ImageSet(Lambda(((t, y, x),), (1/y, t, x)), c3) assert 2/pi not in ImageSet(Lambda(((x, y),), 2/x), c) assert 2/S(100) not in ImageSet(Lambda(((x, y),), 2/x), c) assert Rational(2, 3) in ImageSet(Lambda(((x, y),), 2/x), c) S1 = imageset(lambda x, y: x + y, S.Integers, S.Naturals) assert S1.base_pset == ProductSet(S.Integers, S.Naturals) assert S1.base_sets == (S.Integers, S.Naturals) # Passing a set instead of a FiniteSet shouldn't raise assert unchanged(ImageSet, Lambda(x, x**2), {1, 2, 3}) S2 = ImageSet(Lambda(((x, y),), x+y), {(1, 2), (3, 4)}) assert 3 in S2.doit() # FIXME: This doesn't yet work: #assert 3 in S2 assert S2._contains(3) is None raises(TypeError, lambda: ImageSet(Lambda(x, x**2), 1)) def test_image_is_ImageSet(): assert isinstance(imageset(x, sqrt(sin(x)), Range(5)), ImageSet) def test_halfcircle(): r, th = symbols('r, theta', real=True) L = Lambda(((r, th),), (r*cos(th), r*sin(th))) halfcircle = ImageSet(L, Interval(0, 1)*Interval(0, pi)) assert (1, 0) in halfcircle assert (0, -1) not in halfcircle assert (0, 0) in halfcircle assert halfcircle._contains((r, 0)) is None # This one doesn't work: #assert (r, 2*pi) not in halfcircle assert not halfcircle.is_iterable def test_ImageSet_iterator_not_injective(): L = Lambda(x, x - x % 2) # produces 0, 2, 2, 4, 4, 6, 6, ... evens = ImageSet(L, S.Naturals) i = iter(evens) # No repeats here assert (next(i), next(i), next(i), next(i)) == (0, 2, 4, 6) def test_inf_Range_len(): raises(ValueError, lambda: len(Range(0, oo, 2))) assert Range(0, oo, 2).size is S.Infinity assert Range(0, -oo, -2).size is S.Infinity assert Range(oo, 0, -2).size is S.Infinity assert Range(-oo, 0, 2).size is S.Infinity def test_Range_set(): empty = Range(0) assert Range(5) == Range(0, 5) == Range(0, 5, 1) r = Range(10, 20, 2) assert 12 in r assert 8 not in r assert 11 not in r assert 30 not in r assert list(Range(0, 5)) == list(range(5)) assert list(Range(5, 0, -1)) == list(range(5, 0, -1)) assert Range(5, 15).sup == 14 assert Range(5, 15).inf == 5 assert Range(15, 5, -1).sup == 15 assert Range(15, 5, -1).inf == 6 assert Range(10, 67, 10).sup == 60 assert Range(60, 7, -10).inf == 10 assert len(Range(10, 38, 10)) == 3 assert Range(0, 0, 5) == empty assert Range(oo, oo, 1) == empty assert Range(oo, 1, 1) == empty assert Range(-oo, 1, -1) == empty assert Range(1, oo, -1) == empty assert Range(1, -oo, 1) == empty assert Range(1, -4, oo) == empty ip = symbols('ip', positive=True) assert Range(0, ip, -1) == empty assert Range(0, -ip, 1) == empty assert Range(1, -4, -oo) == Range(1, 2) assert Range(1, 4, oo) == Range(1, 2) assert Range(-oo, oo).size == oo assert Range(oo, -oo, -1).size == oo raises(ValueError, lambda: Range(-oo, oo, 2)) raises(ValueError, lambda: Range(x, pi, y)) raises(ValueError, lambda: Range(x, y, 0)) assert 5 in Range(0, oo, 5) assert -5 in Range(-oo, 0, 5) assert oo not in Range(0, oo) ni = symbols('ni', integer=False) assert ni not in Range(oo) u = symbols('u', integer=None) assert Range(oo).contains(u) is not False inf = symbols('inf', infinite=True) assert inf not in Range(-oo, oo) raises(ValueError, lambda: Range(0, oo, 2)[-1]) raises(ValueError, lambda: Range(0, -oo, -2)[-1]) assert Range(-oo, 1, 1)[-1] is S.Zero assert Range(oo, 1, -1)[-1] == 2 assert inf not in Range(oo) assert Range(1, 10, 1)[-1] == 9 assert all(i.is_Integer for i in Range(0, -1, 1)) it = iter(Range(-oo, 0, 2)) raises(TypeError, lambda: next(it)) assert empty.intersect(S.Integers) == empty assert Range(-1, 10, 1).intersect(S.Integers) == Range(-1, 10, 1) assert Range(-1, 10, 1).intersect(S.Naturals) == Range(1, 10, 1) assert Range(-1, 10, 1).intersect(S.Naturals0) == Range(0, 10, 1) # test slicing assert Range(1, 10, 1)[5] == 6 assert Range(1, 12, 2)[5] == 11 assert Range(1, 10, 1)[-1] == 9 assert Range(1, 10, 3)[-1] == 7 raises(ValueError, lambda: Range(oo,0,-1)[1:3:0]) raises(ValueError, lambda: Range(oo,0,-1)[:1]) raises(ValueError, lambda: Range(1, oo)[-2]) raises(ValueError, lambda: Range(-oo, 1)[2]) raises(IndexError, lambda: Range(10)[-20]) raises(IndexError, lambda: Range(10)[20]) raises(ValueError, lambda: Range(2, -oo, -2)[2:2:0]) assert Range(2, -oo, -2)[2:2:2] == empty assert Range(2, -oo, -2)[:2:2] == Range(2, -2, -4) raises(ValueError, lambda: Range(-oo, 4, 2)[:2:2]) assert Range(-oo, 4, 2)[::-2] == Range(2, -oo, -4) raises(ValueError, lambda: Range(-oo, 4, 2)[::2]) assert Range(oo, 2, -2)[::] == Range(oo, 2, -2) assert Range(-oo, 4, 2)[:-2:-2] == Range(2, 0, -4) assert Range(-oo, 4, 2)[:-2:2] == Range(-oo, 0, 4) raises(ValueError, lambda: Range(-oo, 4, 2)[:0:-2]) raises(ValueError, lambda: Range(-oo, 4, 2)[:2:-2]) assert Range(-oo, 4, 2)[-2::-2] == Range(0, -oo, -4) raises(ValueError, lambda: Range(-oo, 4, 2)[-2:0:-2]) raises(ValueError, lambda: Range(-oo, 4, 2)[0::2]) assert Range(oo, 2, -2)[0::] == Range(oo, 2, -2) raises(ValueError, lambda: Range(-oo, 4, 2)[0:-2:2]) assert Range(oo, 2, -2)[0:-2:] == Range(oo, 6, -2) raises(ValueError, lambda: Range(oo, 2, -2)[0:2:]) raises(ValueError, lambda: Range(-oo, 4, 2)[2::-1]) assert Range(-oo, 4, 2)[-2::2] == Range(0, 4, 4) assert Range(oo, 0, -2)[-10:0:2] == empty raises(ValueError, lambda: Range(oo, 0, -2)[0]) raises(ValueError, lambda: Range(oo, 0, -2)[-10:10:2]) raises(ValueError, lambda: Range(oo, 0, -2)[0::-2]) assert Range(oo, 0, -2)[0:-4:-2] == empty assert Range(oo, 0, -2)[:0:2] == empty raises(ValueError, lambda: Range(oo, 0, -2)[:1:-1]) # test empty Range assert Range(x, x, y) == empty assert empty.reversed == empty assert 0 not in empty assert list(empty) == [] assert len(empty) == 0 assert empty.size is S.Zero assert empty.intersect(FiniteSet(0)) is S.EmptySet assert bool(empty) is False raises(IndexError, lambda: empty[0]) assert empty[:0] == empty raises(NotImplementedError, lambda: empty.inf) raises(NotImplementedError, lambda: empty.sup) assert empty.as_relational(x) is S.false AB = [None] + list(range(12)) for R in [ Range(1, 10), Range(1, 10, 2), ]: r = list(R) for a, b, c in cartes(AB, AB, [-3, -1, None, 1, 3]): for reverse in range(2): r = list(reversed(r)) R = R.reversed result = list(R[a:b:c]) ans = r[a:b:c] txt = ('\n%s[%s:%s:%s] = %s -> %s' % ( R, a, b, c, result, ans)) check = ans == result assert check, txt assert Range(1, 10, 1).boundary == Range(1, 10, 1) for r in (Range(1, 10, 2), Range(1, oo, 2)): rev = r.reversed assert r.inf == rev.inf and r.sup == rev.sup assert r.step == -rev.step builtin_range = range raises(TypeError, lambda: Range(builtin_range(1))) assert S(builtin_range(10)) == Range(10) assert S(builtin_range(1000000000000)) == Range(1000000000000) # test Range.as_relational assert Range(1, 4).as_relational(x) == (x >= 1) & (x <= 3) & Eq(Mod(x, 1), 0) assert Range(oo, 1, -2).as_relational(x) == (x >= 3) & (x < oo) & Eq(Mod(x + 1, -2), 0) def test_Range_symbolic(): # symbolic Range xr = Range(x, x + 4, 5) sr = Range(x, y, t) i = Symbol('i', integer=True) ip = Symbol('i', integer=True, positive=True) ipr = Range(ip) inr = Range(0, -ip, -1) ir = Range(i, i + 19, 2) ir2 = Range(i, i*8, 3*i) i = Symbol('i', integer=True) inf = symbols('inf', infinite=True) raises(ValueError, lambda: Range(inf)) raises(ValueError, lambda: Range(inf, 0, -1)) raises(ValueError, lambda: Range(inf, inf, 1)) raises(ValueError, lambda: Range(1, 1, inf)) # args assert xr.args == (x, x + 5, 5) assert sr.args == (x, y, t) assert ir.args == (i, i + 20, 2) assert ir2.args == (i, 10*i, 3*i) # reversed raises(ValueError, lambda: xr.reversed) raises(ValueError, lambda: sr.reversed) assert ipr.reversed.args == (ip - 1, -1, -1) assert inr.reversed.args == (-ip + 1, 1, 1) assert ir.reversed.args == (i + 18, i - 2, -2) assert ir2.reversed.args == (7*i, -2*i, -3*i) # contains assert inf not in sr assert inf not in ir assert 0 in ipr assert 0 in inr raises(TypeError, lambda: 1 in ipr) raises(TypeError, lambda: -1 in inr) assert .1 not in sr assert .1 not in ir assert i + 1 not in ir assert i + 2 in ir raises(TypeError, lambda: x in xr) # XXX is this what contains is supposed to do? raises(TypeError, lambda: 1 in sr) # XXX is this what contains is supposed to do? # iter raises(ValueError, lambda: next(iter(xr))) raises(ValueError, lambda: next(iter(sr))) assert next(iter(ir)) == i assert next(iter(ir2)) == i assert sr.intersect(S.Integers) == sr assert sr.intersect(FiniteSet(x)) == Intersection({x}, sr) raises(ValueError, lambda: sr[:2]) raises(ValueError, lambda: xr[0]) raises(ValueError, lambda: sr[0]) # len assert len(ir) == ir.size == 10 assert len(ir2) == ir2.size == 3 raises(ValueError, lambda: len(xr)) raises(ValueError, lambda: xr.size) raises(ValueError, lambda: len(sr)) raises(ValueError, lambda: sr.size) # bool assert bool(Range(0)) == False assert bool(xr) assert bool(ir) assert bool(ipr) assert bool(inr) raises(ValueError, lambda: bool(sr)) raises(ValueError, lambda: bool(ir2)) # inf raises(ValueError, lambda: xr.inf) raises(ValueError, lambda: sr.inf) assert ipr.inf == 0 assert inr.inf == -ip + 1 assert ir.inf == i raises(ValueError, lambda: ir2.inf) # sup raises(ValueError, lambda: xr.sup) raises(ValueError, lambda: sr.sup) assert ipr.sup == ip - 1 assert inr.sup == 0 assert ir.inf == i raises(ValueError, lambda: ir2.sup) # getitem raises(ValueError, lambda: xr[0]) raises(ValueError, lambda: sr[0]) raises(ValueError, lambda: sr[-1]) raises(ValueError, lambda: sr[:2]) assert ir[:2] == Range(i, i + 4, 2) assert ir[0] == i assert ir[-2] == i + 16 assert ir[-1] == i + 18 assert ir2[:2] == Range(i, 7*i, 3*i) assert ir2[0] == i assert ir2[-2] == 4*i assert ir2[-1] == 7*i raises(ValueError, lambda: Range(i)[-1]) assert ipr[0] == ipr.inf == 0 assert ipr[-1] == ipr.sup == ip - 1 assert inr[0] == inr.sup == 0 assert inr[-1] == inr.inf == -ip + 1 raises(ValueError, lambda: ipr[-2]) assert ir.inf == i assert ir.sup == i + 18 raises(ValueError, lambda: Range(i).inf) # as_relational assert ir.as_relational(x) == ((x >= i) & (x <= i + 18) & Eq(Mod(-i + x, 2), 0)) assert ir2.as_relational(x) == Eq( Mod(-i + x, 3*i), 0) & (((x >= i) & (x <= 7*i) & (3*i >= 1)) | ((x <= i) & (x >= 7*i) & (3*i <= -1))) assert Range(i, i + 1).as_relational(x) == Eq(x, i) assert sr.as_relational(z) == Eq( Mod(t, 1), 0) & Eq(Mod(x, 1), 0) & Eq(Mod(-x + z, t), 0 ) & (((z >= x) & (z <= -t + y) & (t >= 1)) | ((z <= x) & (z >= -t + y) & (t <= -1))) assert xr.as_relational(z) == Eq(z, x) & Eq(Mod(x, 1), 0) # symbols can clash if user wants (but it must be integer) assert xr.as_relational(x) == Eq(Mod(x, 1), 0) # contains() for symbolic values (issue #18146) e = Symbol('e', integer=True, even=True) o = Symbol('o', integer=True, odd=True) assert Range(5).contains(i) == And(i >= 0, i <= 4) assert Range(1).contains(i) == Eq(i, 0) assert Range(-oo, 5, 1).contains(i) == (i <= 4) assert Range(-oo, oo).contains(i) == True assert Range(0, 8, 2).contains(i) == Contains(i, Range(0, 8, 2)) assert Range(0, 8, 2).contains(e) == And(e >= 0, e <= 6) assert Range(0, 8, 2).contains(2*i) == And(2*i >= 0, 2*i <= 6) assert Range(0, 8, 2).contains(o) == False assert Range(1, 9, 2).contains(e) == False assert Range(1, 9, 2).contains(o) == And(o >= 1, o <= 7) assert Range(8, 0, -2).contains(o) == False assert Range(9, 1, -2).contains(o) == And(o >= 3, o <= 9) assert Range(-oo, 8, 2).contains(i) == Contains(i, Range(-oo, 8, 2)) def test_range_range_intersection(): for a, b, r in [ (Range(0), Range(1), S.EmptySet), (Range(3), Range(4, oo), S.EmptySet), (Range(3), Range(-3, -1), S.EmptySet), (Range(1, 3), Range(0, 3), Range(1, 3)), (Range(1, 3), Range(1, 4), Range(1, 3)), (Range(1, oo, 2), Range(2, oo, 2), S.EmptySet), (Range(0, oo, 2), Range(oo), Range(0, oo, 2)), (Range(0, oo, 2), Range(100), Range(0, 100, 2)), (Range(2, oo, 2), Range(oo), Range(2, oo, 2)), (Range(0, oo, 2), Range(5, 6), S.EmptySet), (Range(2, 80, 1), Range(55, 71, 4), Range(55, 71, 4)), (Range(0, 6, 3), Range(-oo, 5, 3), S.EmptySet), (Range(0, oo, 2), Range(5, oo, 3), Range(8, oo, 6)), (Range(4, 6, 2), Range(2, 16, 7), S.EmptySet),]: assert a.intersect(b) == r assert a.intersect(b.reversed) == r assert a.reversed.intersect(b) == r assert a.reversed.intersect(b.reversed) == r a, b = b, a assert a.intersect(b) == r assert a.intersect(b.reversed) == r assert a.reversed.intersect(b) == r assert a.reversed.intersect(b.reversed) == r def test_range_interval_intersection(): p = symbols('p', positive=True) assert isinstance(Range(3).intersect(Interval(p, p + 2)), Intersection) assert Range(4).intersect(Interval(0, 3)) == Range(4) assert Range(4).intersect(Interval(-oo, oo)) == Range(4) assert Range(4).intersect(Interval(1, oo)) == Range(1, 4) assert Range(4).intersect(Interval(1.1, oo)) == Range(2, 4) assert Range(4).intersect(Interval(0.1, 3)) == Range(1, 4) assert Range(4).intersect(Interval(0.1, 3.1)) == Range(1, 4) assert Range(4).intersect(Interval.open(0, 3)) == Range(1, 3) assert Range(4).intersect(Interval.open(0.1, 0.5)) is S.EmptySet # Null Range intersections assert Range(0).intersect(Interval(0.2, 0.8)) is S.EmptySet assert Range(0).intersect(Interval(-oo, oo)) is S.EmptySet def test_range_is_finite_set(): assert Range(-100, 100).is_finite_set is True assert Range(2, oo).is_finite_set is False assert Range(-oo, 50).is_finite_set is False assert Range(-oo, oo).is_finite_set is False assert Range(oo, -oo).is_finite_set is True assert Range(0, 0).is_finite_set is True assert Range(oo, oo).is_finite_set is True assert Range(-oo, -oo).is_finite_set is True n = Symbol('n', integer=True) m = Symbol('m', integer=True) assert Range(n, n + 49).is_finite_set is True assert Range(n, 0).is_finite_set is True assert Range(-3, n + 7).is_finite_set is True assert Range(n, m).is_finite_set is True assert Range(n + m, m - n).is_finite_set is True assert Range(n, n + m + n).is_finite_set is True assert Range(n, oo).is_finite_set is False assert Range(-oo, n).is_finite_set is False # assert Range(n, -oo).is_finite_set is True # assert Range(oo, n).is_finite_set is True # Above tests fail due to a (potential) bug in sympy.sets.fancysets.Range.size (See issue #18999) def test_Integers_eval_imageset(): ans = ImageSet(Lambda(x, 2*x + Rational(3, 7)), S.Integers) im = imageset(Lambda(x, -2*x + Rational(3, 7)), S.Integers) assert im == ans im = imageset(Lambda(x, -2*x - Rational(11, 7)), S.Integers) assert im == ans y = Symbol('y') L = imageset(x, 2*x + y, S.Integers) assert y + 4 in L a, b, c = 0.092, 0.433, 0.341 assert a in imageset(x, a + c*x, S.Integers) assert b in imageset(x, b + c*x, S.Integers) _x = symbols('x', negative=True) eq = _x**2 - _x + 1 assert imageset(_x, eq, S.Integers).lamda.expr == _x**2 + _x + 1 eq = 3*_x - 1 assert imageset(_x, eq, S.Integers).lamda.expr == 3*_x + 2 assert imageset(x, (x, 1/x), S.Integers) == \ ImageSet(Lambda(x, (x, 1/x)), S.Integers) def test_Range_eval_imageset(): a, b, c = symbols('a b c') assert imageset(x, a*(x + b) + c, Range(3)) == \ imageset(x, a*x + a*b + c, Range(3)) eq = (x + 1)**2 assert imageset(x, eq, Range(3)).lamda.expr == eq eq = a*(x + b) + c r = Range(3, -3, -2) imset = imageset(x, eq, r) assert imset.lamda.expr != eq assert list(imset) == [eq.subs(x, i).expand() for i in list(r)] def test_fun(): assert (FiniteSet(*ImageSet(Lambda(x, sin(pi*x/4)), Range(-10, 11))) == FiniteSet(-1, -sqrt(2)/2, 0, sqrt(2)/2, 1)) def test_Reals(): assert 5 in S.Reals assert S.Pi in S.Reals assert -sqrt(2) in S.Reals assert (2, 5) not in S.Reals assert sqrt(-1) not in S.Reals assert S.Reals == Interval(-oo, oo) assert S.Reals != Interval(0, oo) assert S.Reals.is_subset(Interval(-oo, oo)) assert S.Reals.intersect(Range(-oo, oo)) == Range(-oo, oo) def test_Complex(): assert 5 in S.Complexes assert 5 + 4*I in S.Complexes assert S.Pi in S.Complexes assert -sqrt(2) in S.Complexes assert -I in S.Complexes assert sqrt(-1) in S.Complexes assert S.Complexes.intersect(S.Reals) == S.Reals assert S.Complexes.union(S.Reals) == S.Complexes assert S.Complexes == ComplexRegion(S.Reals*S.Reals) assert (S.Complexes == ComplexRegion(Interval(1, 2)*Interval(3, 4))) == False assert str(S.Complexes) == "S.Complexes" assert repr(S.Complexes) == "S.Complexes" def take(n, iterable): "Return first n items of the iterable as a list" return list(itertools.islice(iterable, n)) def test_intersections(): assert S.Integers.intersect(S.Reals) == S.Integers assert 5 in S.Integers.intersect(S.Reals) assert 5 in S.Integers.intersect(S.Reals) assert -5 not in S.Naturals.intersect(S.Reals) assert 5.5 not in S.Integers.intersect(S.Reals) assert 5 in S.Integers.intersect(Interval(3, oo)) assert -5 in S.Integers.intersect(Interval(-oo, 3)) assert all(x.is_Integer for x in take(10, S.Integers.intersect(Interval(3, oo)) )) def test_infinitely_indexed_set_1(): from sympy.abc import n, m, t assert imageset(Lambda(n, n), S.Integers) == imageset(Lambda(m, m), S.Integers) assert imageset(Lambda(n, 2*n), S.Integers).intersect( imageset(Lambda(m, 2*m + 1), S.Integers)) is S.EmptySet assert imageset(Lambda(n, 2*n), S.Integers).intersect( imageset(Lambda(n, 2*n + 1), S.Integers)) is S.EmptySet assert imageset(Lambda(m, 2*m), S.Integers).intersect( imageset(Lambda(n, 3*n), S.Integers)).dummy_eq( ImageSet(Lambda(t, 6*t), S.Integers)) assert imageset(x, x/2 + Rational(1, 3), S.Integers).intersect(S.Integers) is S.EmptySet assert imageset(x, x/2 + S.Half, S.Integers).intersect(S.Integers) is S.Integers # https://github.com/sympy/sympy/issues/17355 S53 = ImageSet(Lambda(n, 5*n + 3), S.Integers) assert S53.intersect(S.Integers) == S53 def test_infinitely_indexed_set_2(): from sympy.abc import n a = Symbol('a', integer=True) assert imageset(Lambda(n, n), S.Integers) == \ imageset(Lambda(n, n + a), S.Integers) assert imageset(Lambda(n, n + pi), S.Integers) == \ imageset(Lambda(n, n + a + pi), S.Integers) assert imageset(Lambda(n, n), S.Integers) == \ imageset(Lambda(n, -n + a), S.Integers) assert imageset(Lambda(n, -6*n), S.Integers) == \ ImageSet(Lambda(n, 6*n), S.Integers) assert imageset(Lambda(n, 2*n + pi), S.Integers) == \ ImageSet(Lambda(n, 2*n + pi - 2), S.Integers) def test_imageset_intersect_real(): from sympy import I from sympy.abc import n assert imageset(Lambda(n, n + (n - 1)*(n + 1)*I), S.Integers).intersect(S.Reals) == \ FiniteSet(-1, 1) s = ImageSet( Lambda(n, -I*(I*(2*pi*n - pi/4) + log(Abs(sqrt(-I))))), S.Integers) # s is unevaluated, but after intersection the result # should be canonical assert s.intersect(S.Reals) == imageset( Lambda(n, 2*n*pi - pi/4), S.Integers) == ImageSet( Lambda(n, 2*pi*n + pi*Rational(7, 4)), S.Integers) def test_imageset_intersect_interval(): from sympy.abc import n f1 = ImageSet(Lambda(n, n*pi), S.Integers) f2 = ImageSet(Lambda(n, 2*n), Interval(0, pi)) f3 = ImageSet(Lambda(n, 2*n*pi + pi/2), S.Integers) # complex expressions f4 = ImageSet(Lambda(n, n*I*pi), S.Integers) f5 = ImageSet(Lambda(n, 2*I*n*pi + pi/2), S.Integers) # non-linear expressions f6 = ImageSet(Lambda(n, log(n)), S.Integers) f7 = ImageSet(Lambda(n, n**2), S.Integers) f8 = ImageSet(Lambda(n, Abs(n)), S.Integers) f9 = ImageSet(Lambda(n, exp(n)), S.Naturals0) assert f1.intersect(Interval(-1, 1)) == FiniteSet(0) assert f1.intersect(Interval(0, 2*pi, False, True)) == FiniteSet(0, pi) assert f2.intersect(Interval(1, 2)) == Interval(1, 2) assert f3.intersect(Interval(-1, 1)) == S.EmptySet assert f3.intersect(Interval(-5, 5)) == FiniteSet(pi*Rational(-3, 2), pi/2) assert f4.intersect(Interval(-1, 1)) == FiniteSet(0) assert f4.intersect(Interval(1, 2)) == S.EmptySet assert f5.intersect(Interval(0, 1)) == S.EmptySet assert f6.intersect(Interval(0, 1)) == FiniteSet(S.Zero, log(2)) assert f7.intersect(Interval(0, 10)) == Intersection(f7, Interval(0, 10)) assert f8.intersect(Interval(0, 2)) == Intersection(f8, Interval(0, 2)) assert f9.intersect(Interval(1, 2)) == Intersection(f9, Interval(1, 2)) def test_imageset_intersect_diophantine(): from sympy.abc import m, n # Check that same lambda variable for both ImageSets is handled correctly img1 = ImageSet(Lambda(n, 2*n + 1), S.Integers) img2 = ImageSet(Lambda(n, 4*n + 1), S.Integers) assert img1.intersect(img2) == img2 # Empty solution set returned by diophantine: assert ImageSet(Lambda(n, 2*n), S.Integers).intersect( ImageSet(Lambda(n, 2*n + 1), S.Integers)) == S.EmptySet # Check intersection with S.Integers: assert ImageSet(Lambda(n, 9/n + 20*n/3), S.Integers).intersect( S.Integers) == FiniteSet(-61, -23, 23, 61) # Single solution (2, 3) for diophantine solution: assert ImageSet(Lambda(n, (n - 2)**2), S.Integers).intersect( ImageSet(Lambda(n, -(n - 3)**2), S.Integers)) == FiniteSet(0) # Single parametric solution for diophantine solution: assert ImageSet(Lambda(n, n**2 + 5), S.Integers).intersect( ImageSet(Lambda(m, 2*m), S.Integers)).dummy_eq(ImageSet( Lambda(n, 4*n**2 + 4*n + 6), S.Integers)) # 4 non-parametric solution couples for dioph. equation: assert ImageSet(Lambda(n, n**2 - 9), S.Integers).intersect( ImageSet(Lambda(m, -m**2), S.Integers)) == FiniteSet(-9, 0) # Double parametric solution for diophantine solution: assert ImageSet(Lambda(m, m**2 + 40), S.Integers).intersect( ImageSet(Lambda(n, 41*n), S.Integers)).dummy_eq(Intersection( ImageSet(Lambda(m, m**2 + 40), S.Integers), ImageSet(Lambda(n, 41*n), S.Integers))) # Check that diophantine returns *all* (8) solutions (permute=True) assert ImageSet(Lambda(n, n**4 - 2**4), S.Integers).intersect( ImageSet(Lambda(m, -m**4 + 3**4), S.Integers)) == FiniteSet(0, 65) assert ImageSet(Lambda(n, pi/12 + n*5*pi/12), S.Integers).intersect( ImageSet(Lambda(n, 7*pi/12 + n*11*pi/12), S.Integers)).dummy_eq(ImageSet( Lambda(n, 55*pi*n/12 + 17*pi/4), S.Integers)) # TypeError raised by diophantine (#18081) assert ImageSet(Lambda(n, n*log(2)), S.Integers).intersection( S.Integers).dummy_eq(Intersection(ImageSet( Lambda(n, n*log(2)), S.Integers), S.Integers)) # NotImplementedError raised by diophantine (no solver for cubic_thue) assert ImageSet(Lambda(n, n**3 + 1), S.Integers).intersect( ImageSet(Lambda(n, n**3), S.Integers)).dummy_eq(Intersection( ImageSet(Lambda(n, n**3 + 1), S.Integers), ImageSet(Lambda(n, n**3), S.Integers))) def test_infinitely_indexed_set_3(): from sympy.abc import n, m, t assert imageset(Lambda(m, 2*pi*m), S.Integers).intersect( imageset(Lambda(n, 3*pi*n), S.Integers)).dummy_eq( ImageSet(Lambda(t, 6*pi*t), S.Integers)) assert imageset(Lambda(n, 2*n + 1), S.Integers) == \ imageset(Lambda(n, 2*n - 1), S.Integers) assert imageset(Lambda(n, 3*n + 2), S.Integers) == \ imageset(Lambda(n, 3*n - 1), S.Integers) def test_ImageSet_simplification(): from sympy.abc import n, m assert imageset(Lambda(n, n), S.Integers) == S.Integers assert imageset(Lambda(n, sin(n)), imageset(Lambda(m, tan(m)), S.Integers)) == \ imageset(Lambda(m, sin(tan(m))), S.Integers) assert imageset(n, 1 + 2*n, S.Naturals) == Range(3, oo, 2) assert imageset(n, 1 + 2*n, S.Naturals0) == Range(1, oo, 2) assert imageset(n, 1 - 2*n, S.Naturals) == Range(-1, -oo, -2) def test_ImageSet_contains(): from sympy.abc import x assert (2, S.Half) in imageset(x, (x, 1/x), S.Integers) assert imageset(x, x + I*3, S.Integers).intersection(S.Reals) is S.EmptySet i = Dummy(integer=True) q = imageset(x, x + I*y, S.Integers).intersection(S.Reals) assert q.subs(y, I*i).intersection(S.Integers) is S.Integers q = imageset(x, x + I*y/x, S.Integers).intersection(S.Reals) assert q.subs(y, 0) is S.Integers assert q.subs(y, I*i*x).intersection(S.Integers) is S.Integers z = cos(1)**2 + sin(1)**2 - 1 q = imageset(x, x + I*z, S.Integers).intersection(S.Reals) assert q is not S.EmptySet def test_ComplexRegion_contains(): r = Symbol('r', real=True) # contains in ComplexRegion a = Interval(2, 3) b = Interval(4, 6) c = Interval(7, 9) c1 = ComplexRegion(a*b) c2 = ComplexRegion(Union(a*b, c*a)) assert 2.5 + 4.5*I in c1 assert 2 + 4*I in c1 assert 3 + 4*I in c1 assert 8 + 2.5*I in c2 assert 2.5 + 6.1*I not in c1 assert 4.5 + 3.2*I not in c1 assert c1.contains(x) == Contains(x, c1, evaluate=False) assert c1.contains(r) == False assert c2.contains(x) == Contains(x, c2, evaluate=False) assert c2.contains(r) == False r1 = Interval(0, 1) theta1 = Interval(0, 2*S.Pi) c3 = ComplexRegion(r1*theta1, polar=True) assert (0.5 + I*Rational(6, 10)) in c3 assert (S.Half + I*Rational(6, 10)) in c3 assert (S.Half + .6*I) in c3 assert (0.5 + .6*I) in c3 assert I in c3 assert 1 in c3 assert 0 in c3 assert 1 + I not in c3 assert 1 - I not in c3 assert c3.contains(x) == Contains(x, c3, evaluate=False) assert c3.contains(r + 2*I) == Contains( r + 2*I, c3, evaluate=False) # is in fact False assert c3.contains(1/(1 + r**2)) == Contains( 1/(1 + r**2), c3, evaluate=False) # is in fact True r2 = Interval(0, 3) theta2 = Interval(pi, 2*pi, left_open=True) c4 = ComplexRegion(r2*theta2, polar=True) assert c4.contains(0) == True assert c4.contains(2 + I) == False assert c4.contains(-2 + I) == False assert c4.contains(-2 - I) == True assert c4.contains(2 - I) == True assert c4.contains(-2) == False assert c4.contains(2) == True assert c4.contains(x) == Contains(x, c4, evaluate=False) assert c4.contains(3/(1 + r**2)) == Contains( 3/(1 + r**2), c4, evaluate=False) # is in fact True raises(ValueError, lambda: ComplexRegion(r1*theta1, polar=2)) def test_ComplexRegion_intersect(): # Polar form X_axis = ComplexRegion(Interval(0, oo)*FiniteSet(0, S.Pi), polar=True) unit_disk = ComplexRegion(Interval(0, 1)*Interval(0, 2*S.Pi), polar=True) upper_half_unit_disk = ComplexRegion(Interval(0, 1)*Interval(0, S.Pi), polar=True) upper_half_disk = ComplexRegion(Interval(0, oo)*Interval(0, S.Pi), polar=True) lower_half_disk = ComplexRegion(Interval(0, oo)*Interval(S.Pi, 2*S.Pi), polar=True) right_half_disk = ComplexRegion(Interval(0, oo)*Interval(-S.Pi/2, S.Pi/2), polar=True) first_quad_disk = ComplexRegion(Interval(0, oo)*Interval(0, S.Pi/2), polar=True) assert upper_half_disk.intersect(unit_disk) == upper_half_unit_disk assert right_half_disk.intersect(first_quad_disk) == first_quad_disk assert upper_half_disk.intersect(right_half_disk) == first_quad_disk assert upper_half_disk.intersect(lower_half_disk) == X_axis c1 = ComplexRegion(Interval(0, 4)*Interval(0, 2*S.Pi), polar=True) assert c1.intersect(Interval(1, 5)) == Interval(1, 4) assert c1.intersect(Interval(4, 9)) == FiniteSet(4) assert c1.intersect(Interval(5, 12)) is S.EmptySet # Rectangular form X_axis = ComplexRegion(Interval(-oo, oo)*FiniteSet(0)) unit_square = ComplexRegion(Interval(-1, 1)*Interval(-1, 1)) upper_half_unit_square = ComplexRegion(Interval(-1, 1)*Interval(0, 1)) upper_half_plane = ComplexRegion(Interval(-oo, oo)*Interval(0, oo)) lower_half_plane = ComplexRegion(Interval(-oo, oo)*Interval(-oo, 0)) right_half_plane = ComplexRegion(Interval(0, oo)*Interval(-oo, oo)) first_quad_plane = ComplexRegion(Interval(0, oo)*Interval(0, oo)) assert upper_half_plane.intersect(unit_square) == upper_half_unit_square assert right_half_plane.intersect(first_quad_plane) == first_quad_plane assert upper_half_plane.intersect(right_half_plane) == first_quad_plane assert upper_half_plane.intersect(lower_half_plane) == X_axis c1 = ComplexRegion(Interval(-5, 5)*Interval(-10, 10)) assert c1.intersect(Interval(2, 7)) == Interval(2, 5) assert c1.intersect(Interval(5, 7)) == FiniteSet(5) assert c1.intersect(Interval(6, 9)) is S.EmptySet # unevaluated object C1 = ComplexRegion(Interval(0, 1)*Interval(0, 2*S.Pi), polar=True) C2 = ComplexRegion(Interval(-1, 1)*Interval(-1, 1)) assert C1.intersect(C2) == Intersection(C1, C2, evaluate=False) def test_ComplexRegion_union(): # Polar form c1 = ComplexRegion(Interval(0, 1)*Interval(0, 2*S.Pi), polar=True) c2 = ComplexRegion(Interval(0, 1)*Interval(0, S.Pi), polar=True) c3 = ComplexRegion(Interval(0, oo)*Interval(0, S.Pi), polar=True) c4 = ComplexRegion(Interval(0, oo)*Interval(S.Pi, 2*S.Pi), polar=True) p1 = Union(Interval(0, 1)*Interval(0, 2*S.Pi), Interval(0, 1)*Interval(0, S.Pi)) p2 = Union(Interval(0, oo)*Interval(0, S.Pi), Interval(0, oo)*Interval(S.Pi, 2*S.Pi)) assert c1.union(c2) == ComplexRegion(p1, polar=True) assert c3.union(c4) == ComplexRegion(p2, polar=True) # Rectangular form c5 = ComplexRegion(Interval(2, 5)*Interval(6, 9)) c6 = ComplexRegion(Interval(4, 6)*Interval(10, 12)) c7 = ComplexRegion(Interval(0, 10)*Interval(-10, 0)) c8 = ComplexRegion(Interval(12, 16)*Interval(14, 20)) p3 = Union(Interval(2, 5)*Interval(6, 9), Interval(4, 6)*Interval(10, 12)) p4 = Union(Interval(0, 10)*Interval(-10, 0), Interval(12, 16)*Interval(14, 20)) assert c5.union(c6) == ComplexRegion(p3) assert c7.union(c8) == ComplexRegion(p4) assert c1.union(Interval(2, 4)) == Union(c1, Interval(2, 4), evaluate=False) assert c5.union(Interval(2, 4)) == Union(c5, ComplexRegion.from_real(Interval(2, 4))) def test_ComplexRegion_from_real(): c1 = ComplexRegion(Interval(0, 1) * Interval(0, 2 * S.Pi), polar=True) raises(ValueError, lambda: c1.from_real(c1)) assert c1.from_real(Interval(-1, 1)) == ComplexRegion(Interval(-1, 1) * FiniteSet(0), False) def test_ComplexRegion_measure(): a, b = Interval(2, 5), Interval(4, 8) theta1, theta2 = Interval(0, 2*S.Pi), Interval(0, S.Pi) c1 = ComplexRegion(a*b) c2 = ComplexRegion(Union(a*theta1, b*theta2), polar=True) assert c1.measure == 12 assert c2.measure == 9*pi def test_normalize_theta_set(): # Interval assert normalize_theta_set(Interval(pi, 2*pi)) == \ Union(FiniteSet(0), Interval.Ropen(pi, 2*pi)) assert normalize_theta_set(Interval(pi*Rational(9, 2), 5*pi)) == Interval(pi/2, pi) assert normalize_theta_set(Interval(pi*Rational(-3, 2), pi/2)) == Interval.Ropen(0, 2*pi) assert normalize_theta_set(Interval.open(pi*Rational(-3, 2), pi/2)) == \ Union(Interval.Ropen(0, pi/2), Interval.open(pi/2, 2*pi)) assert normalize_theta_set(Interval.open(pi*Rational(-7, 2), pi*Rational(-3, 2))) == \ Union(Interval.Ropen(0, pi/2), Interval.open(pi/2, 2*pi)) assert normalize_theta_set(Interval(-pi/2, pi/2)) == \ Union(Interval(0, pi/2), Interval.Ropen(pi*Rational(3, 2), 2*pi)) assert normalize_theta_set(Interval.open(-pi/2, pi/2)) == \ Union(Interval.Ropen(0, pi/2), Interval.open(pi*Rational(3, 2), 2*pi)) assert normalize_theta_set(Interval(-4*pi, 3*pi)) == Interval.Ropen(0, 2*pi) assert normalize_theta_set(Interval(pi*Rational(-3, 2), -pi/2)) == Interval(pi/2, pi*Rational(3, 2)) assert normalize_theta_set(Interval.open(0, 2*pi)) == Interval.open(0, 2*pi) assert normalize_theta_set(Interval.Ropen(-pi/2, pi/2)) == \ Union(Interval.Ropen(0, pi/2), Interval.Ropen(pi*Rational(3, 2), 2*pi)) assert normalize_theta_set(Interval.Lopen(-pi/2, pi/2)) == \ Union(Interval(0, pi/2), Interval.open(pi*Rational(3, 2), 2*pi)) assert normalize_theta_set(Interval(-pi/2, pi/2)) == \ Union(Interval(0, pi/2), Interval.Ropen(pi*Rational(3, 2), 2*pi)) assert normalize_theta_set(Interval.open(4*pi, pi*Rational(9, 2))) == Interval.open(0, pi/2) assert normalize_theta_set(Interval.Lopen(4*pi, pi*Rational(9, 2))) == Interval.Lopen(0, pi/2) assert normalize_theta_set(Interval.Ropen(4*pi, pi*Rational(9, 2))) == Interval.Ropen(0, pi/2) assert normalize_theta_set(Interval.open(3*pi, 5*pi)) == \ Union(Interval.Ropen(0, pi), Interval.open(pi, 2*pi)) # FiniteSet assert normalize_theta_set(FiniteSet(0, pi, 3*pi)) == FiniteSet(0, pi) assert normalize_theta_set(FiniteSet(0, pi/2, pi, 2*pi)) == FiniteSet(0, pi/2, pi) assert normalize_theta_set(FiniteSet(0, -pi/2, -pi, -2*pi)) == FiniteSet(0, pi, pi*Rational(3, 2)) assert normalize_theta_set(FiniteSet(pi*Rational(-3, 2), pi/2)) == \ FiniteSet(pi/2) assert normalize_theta_set(FiniteSet(2*pi)) == FiniteSet(0) # Unions assert normalize_theta_set(Union(Interval(0, pi/3), Interval(pi/2, pi))) == \ Union(Interval(0, pi/3), Interval(pi/2, pi)) assert normalize_theta_set(Union(Interval(0, pi), Interval(2*pi, pi*Rational(7, 3)))) == \ Interval(0, pi) # ValueError for non-real sets raises(ValueError, lambda: normalize_theta_set(S.Complexes)) # NotImplementedError for subset of reals raises(NotImplementedError, lambda: normalize_theta_set(Interval(0, 1))) # NotImplementedError without pi as coefficient raises(NotImplementedError, lambda: normalize_theta_set(Interval(1, 2*pi))) raises(NotImplementedError, lambda: normalize_theta_set(Interval(2*pi, 10))) raises(NotImplementedError, lambda: normalize_theta_set(FiniteSet(0, 3, 3*pi))) def test_ComplexRegion_FiniteSet(): x, y, z, a, b, c = symbols('x y z a b c') # Issue #9669 assert ComplexRegion(FiniteSet(a, b, c)*FiniteSet(x, y, z)) == \ FiniteSet(a + I*x, a + I*y, a + I*z, b + I*x, b + I*y, b + I*z, c + I*x, c + I*y, c + I*z) assert ComplexRegion(FiniteSet(2)*FiniteSet(3)) == FiniteSet(2 + 3*I) def test_union_RealSubSet(): assert (S.Complexes).union(Interval(1, 2)) == S.Complexes assert (S.Complexes).union(S.Integers) == S.Complexes def test_issue_9980(): c1 = ComplexRegion(Interval(1, 2)*Interval(2, 3)) c2 = ComplexRegion(Interval(1, 5)*Interval(1, 3)) R = Union(c1, c2) assert simplify(R) == ComplexRegion(Union(Interval(1, 2)*Interval(2, 3), \ Interval(1, 5)*Interval(1, 3)), False) assert c1.func(*c1.args) == c1 assert R.func(*R.args) == R def test_issue_11732(): interval12 = Interval(1, 2) finiteset1234 = FiniteSet(1, 2, 3, 4) pointComplex = Tuple(1, 5) assert (interval12 in S.Naturals) == False assert (interval12 in S.Naturals0) == False assert (interval12 in S.Integers) == False assert (interval12 in S.Complexes) == False assert (finiteset1234 in S.Naturals) == False assert (finiteset1234 in S.Naturals0) == False assert (finiteset1234 in S.Integers) == False assert (finiteset1234 in S.Complexes) == False assert (pointComplex in S.Naturals) == False assert (pointComplex in S.Naturals0) == False assert (pointComplex in S.Integers) == False assert (pointComplex in S.Complexes) == True def test_issue_11730(): unit = Interval(0, 1) square = ComplexRegion(unit ** 2) assert Union(S.Complexes, FiniteSet(oo)) != S.Complexes assert Union(S.Complexes, FiniteSet(eye(4))) != S.Complexes assert Union(unit, square) == square assert Intersection(S.Reals, square) == unit def test_issue_11938(): unit = Interval(0, 1) ival = Interval(1, 2) cr1 = ComplexRegion(ival * unit) assert Intersection(cr1, S.Reals) == ival assert Intersection(cr1, unit) == FiniteSet(1) arg1 = Interval(0, S.Pi) arg2 = FiniteSet(S.Pi) arg3 = Interval(S.Pi / 4, 3 * S.Pi / 4) cp1 = ComplexRegion(unit * arg1, polar=True) cp2 = ComplexRegion(unit * arg2, polar=True) cp3 = ComplexRegion(unit * arg3, polar=True) assert Intersection(cp1, S.Reals) == Interval(-1, 1) assert Intersection(cp2, S.Reals) == Interval(-1, 0) assert Intersection(cp3, S.Reals) == FiniteSet(0) def test_issue_11914(): a, b = Interval(0, 1), Interval(0, pi) c, d = Interval(2, 3), Interval(pi, 3 * pi / 2) cp1 = ComplexRegion(a * b, polar=True) cp2 = ComplexRegion(c * d, polar=True) assert -3 in cp1.union(cp2) assert -3 in cp2.union(cp1) assert -5 not in cp1.union(cp2) def test_issue_9543(): assert ImageSet(Lambda(x, x**2), S.Naturals).is_subset(S.Reals) def test_issue_16871(): assert ImageSet(Lambda(x, x), FiniteSet(1)) == {1} assert ImageSet(Lambda(x, x - 3), S.Integers ).intersection(S.Integers) is S.Integers @XFAIL def test_issue_16871b(): assert ImageSet(Lambda(x, x - 3), S.Integers).is_subset(S.Integers) def test_issue_18050(): assert imageset(Lambda(x, I*x + 1), S.Integers ) == ImageSet(Lambda(x, I*x + 1), S.Integers) assert imageset(Lambda(x, 3*I*x + 4 + 8*I), S.Integers ) == ImageSet(Lambda(x, 3*I*x + 4 + 2*I), S.Integers) # no 'Mod' for next 2 tests: assert imageset(Lambda(x, 2*x + 3*I), S.Integers ) == ImageSet(Lambda(x, 2*x + 3*I), S.Integers) r = Symbol('r', positive=True) assert imageset(Lambda(x, r*x + 10), S.Integers ) == ImageSet(Lambda(x, r*x + 10), S.Integers) # reduce real part: assert imageset(Lambda(x, 3*x + 8 + 5*I), S.Integers ) == ImageSet(Lambda(x, 3*x + 2 + 5*I), S.Integers) def test_Rationals(): assert S.Integers.is_subset(S.Rationals) assert S.Naturals.is_subset(S.Rationals) assert S.Naturals0.is_subset(S.Rationals) assert S.Rationals.is_subset(S.Reals) assert S.Rationals.inf is -oo assert S.Rationals.sup is oo it = iter(S.Rationals) assert [next(it) for i in range(12)] == [ 0, 1, -1, S.Half, 2, Rational(-1, 2), -2, Rational(1, 3), 3, Rational(-1, 3), -3, Rational(2, 3)] assert Basic() not in S.Rationals assert S.Half in S.Rationals assert S.Rationals.contains(0.5) == Contains(0.5, S.Rationals, evaluate=False) assert 2 in S.Rationals r = symbols('r', rational=True) assert r in S.Rationals raises(TypeError, lambda: x in S.Rationals) # issue #18134: assert S.Rationals.boundary == S.Reals assert S.Rationals.closure == S.Reals assert S.Rationals.is_open == False assert S.Rationals.is_closed == False def test_NZQRC_unions(): # check that all trivial number set unions are simplified: nbrsets = (S.Naturals, S.Naturals0, S.Integers, S.Rationals, S.Reals, S.Complexes) unions = (Union(a, b) for a in nbrsets for b in nbrsets) assert all(u.is_Union is False for u in unions) def test_imageset_intersection(): n = Dummy() s = ImageSet(Lambda(n, -I*(I*(2*pi*n - pi/4) + log(Abs(sqrt(-I))))), S.Integers) assert s.intersect(S.Reals) == ImageSet( Lambda(n, 2*pi*n + pi*Rational(7, 4)), S.Integers) def test_issue_17858(): assert 1 in Range(-oo, oo) assert 0 in Range(oo, -oo, -1) assert oo not in Range(-oo, oo) assert -oo not in Range(-oo, oo) def test_issue_17859(): r = Range(-oo,oo) raises(ValueError,lambda: r[::2]) raises(ValueError, lambda: r[::-2]) r = Range(oo,-oo,-1) raises(ValueError,lambda: r[::2]) raises(ValueError, lambda: r[::-2])
4858b80f5dd95d42651293a7bc0060c68960db6116e793d2e9abc4670d8d81b3
from sympy import (Symbol, Set, Union, Interval, oo, S, sympify, nan, Max, Min, Float, DisjointUnion, FiniteSet, Intersection, imageset, I, true, false, ProductSet, sqrt, Complement, EmptySet, sin, cos, Lambda, ImageSet, pi, Pow, Contains, Sum, rootof, SymmetricDifference, Piecewise, Matrix, Range, Add, symbols, zoo, Rational) from mpmath import mpi from sympy.core.expr import unchanged from sympy.core.relational import Eq, Ne, Le, Lt, LessThan from sympy.logic import And, Or, Xor from sympy.testing.pytest import raises, XFAIL, warns_deprecated_sympy from sympy.abc import x, y, z, m, n def test_imageset(): ints = S.Integers assert imageset(x, x - 1, S.Naturals) is S.Naturals0 assert imageset(x, x + 1, S.Naturals0) is S.Naturals assert imageset(x, abs(x), S.Naturals0) is S.Naturals0 assert imageset(x, abs(x), S.Naturals) is S.Naturals assert imageset(x, abs(x), S.Integers) is S.Naturals0 # issue 16878a r = symbols('r', real=True) assert imageset(x, (x, x), S.Reals)._contains((1, r)) == None assert imageset(x, (x, x), S.Reals)._contains((1, 2)) == False assert (r, r) in imageset(x, (x, x), S.Reals) assert 1 + I in imageset(x, x + I, S.Reals) assert {1} not in imageset(x, (x,), S.Reals) assert (1, 1) not in imageset(x, (x,) , S.Reals) raises(TypeError, lambda: imageset(x, ints)) raises(ValueError, lambda: imageset(x, y, z, ints)) raises(ValueError, lambda: imageset(Lambda(x, cos(x)), y)) assert (1, 2) in imageset(Lambda((x, y), (x, y)), ints, ints) raises(ValueError, lambda: imageset(Lambda(x, x), ints, ints)) assert imageset(cos, ints) == ImageSet(Lambda(x, cos(x)), ints) def f(x): return cos(x) assert imageset(f, ints) == imageset(x, cos(x), ints) f = lambda x: cos(x) assert imageset(f, ints) == ImageSet(Lambda(x, cos(x)), ints) assert imageset(x, 1, ints) == FiniteSet(1) assert imageset(x, y, ints) == {y} assert imageset((x, y), (1, z), ints, S.Reals) == {(1, z)} clash = Symbol('x', integer=true) assert (str(imageset(lambda x: x + clash, Interval(-2, 1)).lamda.expr) in ('x0 + x', 'x + x0')) x1, x2 = symbols("x1, x2") assert imageset(lambda x, y: Add(x, y), Interval(1, 2), Interval(2, 3)).dummy_eq( ImageSet(Lambda((x1, x2), x1 + x2), Interval(1, 2), Interval(2, 3))) def test_is_empty(): for s in [S.Naturals, S.Naturals0, S.Integers, S.Rationals, S.Reals, S.UniversalSet]: assert s.is_empty is False assert S.EmptySet.is_empty is True def test_is_finiteset(): for s in [S.Naturals, S.Naturals0, S.Integers, S.Rationals, S.Reals, S.UniversalSet]: assert s.is_finite_set is False assert S.EmptySet.is_finite_set is True assert FiniteSet(1, 2).is_finite_set is True assert Interval(1, 2).is_finite_set is False assert Interval(x, y).is_finite_set is None assert ProductSet(FiniteSet(1), FiniteSet(2)).is_finite_set is True assert ProductSet(FiniteSet(1), Interval(1, 2)).is_finite_set is False assert ProductSet(FiniteSet(1), Interval(x, y)).is_finite_set is None assert Union(Interval(0, 1), Interval(2, 3)).is_finite_set is False assert Union(FiniteSet(1), Interval(2, 3)).is_finite_set is False assert Union(FiniteSet(1), FiniteSet(2)).is_finite_set is True assert Union(FiniteSet(1), Interval(x, y)).is_finite_set is None assert Intersection(Interval(x, y), FiniteSet(1)).is_finite_set is True assert Intersection(Interval(x, y), Interval(1, 2)).is_finite_set is None assert Intersection(FiniteSet(x), FiniteSet(y)).is_finite_set is True assert Complement(FiniteSet(1), Interval(x, y)).is_finite_set is True assert Complement(Interval(x, y), FiniteSet(1)).is_finite_set is None assert Complement(Interval(1, 2), FiniteSet(x)).is_finite_set is False assert DisjointUnion(Interval(-5, 3), FiniteSet(x, y)).is_finite_set is False assert DisjointUnion(S.EmptySet, FiniteSet(x, y), S.EmptySet).is_finite_set is True def test_deprecated_is_EmptySet(): with warns_deprecated_sympy(): S.EmptySet.is_EmptySet def test_interval_arguments(): assert Interval(0, oo) == Interval(0, oo, False, True) assert Interval(0, oo).right_open is true assert Interval(-oo, 0) == Interval(-oo, 0, True, False) assert Interval(-oo, 0).left_open is true assert Interval(oo, -oo) == S.EmptySet assert Interval(oo, oo) == S.EmptySet assert Interval(-oo, -oo) == S.EmptySet assert Interval(oo, x) == S.EmptySet assert Interval(oo, oo) == S.EmptySet assert Interval(x, -oo) == S.EmptySet assert Interval(x, x) == {x} assert isinstance(Interval(1, 1), FiniteSet) e = Sum(x, (x, 1, 3)) assert isinstance(Interval(e, e), FiniteSet) assert Interval(1, 0) == S.EmptySet assert Interval(1, 1).measure == 0 assert Interval(1, 1, False, True) == S.EmptySet assert Interval(1, 1, True, False) == S.EmptySet assert Interval(1, 1, True, True) == S.EmptySet assert isinstance(Interval(0, Symbol('a')), Interval) assert Interval(Symbol('a', real=True, positive=True), 0) == S.EmptySet raises(ValueError, lambda: Interval(0, S.ImaginaryUnit)) raises(ValueError, lambda: Interval(0, Symbol('z', extended_real=False))) raises(ValueError, lambda: Interval(x, x + S.ImaginaryUnit)) raises(NotImplementedError, lambda: Interval(0, 1, And(x, y))) raises(NotImplementedError, lambda: Interval(0, 1, False, And(x, y))) raises(NotImplementedError, lambda: Interval(0, 1, z, And(x, y))) def test_interval_symbolic_end_points(): a = Symbol('a', real=True) assert Union(Interval(0, a), Interval(0, 3)).sup == Max(a, 3) assert Union(Interval(a, 0), Interval(-3, 0)).inf == Min(-3, a) assert Interval(0, a).contains(1) == LessThan(1, a) def test_interval_is_empty(): x, y = symbols('x, y') r = Symbol('r', real=True) p = Symbol('p', positive=True) n = Symbol('n', negative=True) nn = Symbol('nn', nonnegative=True) assert Interval(1, 2).is_empty == False assert Interval(3, 3).is_empty == False # FiniteSet assert Interval(r, r).is_empty == False # FiniteSet assert Interval(r, r + nn).is_empty == False assert Interval(x, x).is_empty == False assert Interval(1, oo).is_empty == False assert Interval(-oo, oo).is_empty == False assert Interval(-oo, 1).is_empty == False assert Interval(x, y).is_empty == None assert Interval(r, oo).is_empty == False # real implies finite assert Interval(n, 0).is_empty == False assert Interval(n, 0, left_open=True).is_empty == False assert Interval(p, 0).is_empty == True # EmptySet assert Interval(nn, 0).is_empty == None assert Interval(n, p).is_empty == False assert Interval(0, p, left_open=True).is_empty == False assert Interval(0, p, right_open=True).is_empty == False assert Interval(0, nn, left_open=True).is_empty == None assert Interval(0, nn, right_open=True).is_empty == None def test_union(): assert Union(Interval(1, 2), Interval(2, 3)) == Interval(1, 3) assert Union(Interval(1, 2), Interval(2, 3, True)) == Interval(1, 3) assert Union(Interval(1, 3), Interval(2, 4)) == Interval(1, 4) assert Union(Interval(1, 2), Interval(1, 3)) == Interval(1, 3) assert Union(Interval(1, 3), Interval(1, 2)) == Interval(1, 3) assert Union(Interval(1, 3, False, True), Interval(1, 2)) == \ Interval(1, 3, False, True) assert Union(Interval(1, 3), Interval(1, 2, False, True)) == Interval(1, 3) assert Union(Interval(1, 2, True), Interval(1, 3)) == Interval(1, 3) assert Union(Interval(1, 2, True), Interval(1, 3, True)) == \ Interval(1, 3, True) assert Union(Interval(1, 2, True), Interval(1, 3, True, True)) == \ Interval(1, 3, True, True) assert Union(Interval(1, 2, True, True), Interval(1, 3, True)) == \ Interval(1, 3, True) assert Union(Interval(1, 3), Interval(2, 3)) == Interval(1, 3) assert Union(Interval(1, 3, False, True), Interval(2, 3)) == \ Interval(1, 3) assert Union(Interval(1, 2, False, True), Interval(2, 3, True)) != \ Interval(1, 3) assert Union(Interval(1, 2), S.EmptySet) == Interval(1, 2) assert Union(S.EmptySet) == S.EmptySet assert Union(Interval(0, 1), *[FiniteSet(1.0/n) for n in range(1, 10)]) == \ Interval(0, 1) # issue #18241: x = Symbol('x') assert Union(Interval(0, 1), FiniteSet(1, x)) == Union( Interval(0, 1), FiniteSet(x)) assert unchanged(Union, Interval(0, 1), FiniteSet(2, x)) assert Interval(1, 2).union(Interval(2, 3)) == \ Interval(1, 2) + Interval(2, 3) assert Interval(1, 2).union(Interval(2, 3)) == Interval(1, 3) assert Union(Set()) == Set() assert FiniteSet(1) + FiniteSet(2) + FiniteSet(3) == FiniteSet(1, 2, 3) assert FiniteSet('ham') + FiniteSet('eggs') == FiniteSet('ham', 'eggs') assert FiniteSet(1, 2, 3) + S.EmptySet == FiniteSet(1, 2, 3) assert FiniteSet(1, 2, 3) & FiniteSet(2, 3, 4) == FiniteSet(2, 3) assert FiniteSet(1, 2, 3) | FiniteSet(2, 3, 4) == FiniteSet(1, 2, 3, 4) assert FiniteSet(1, 2, 3) & S.EmptySet == S.EmptySet assert FiniteSet(1, 2, 3) | S.EmptySet == FiniteSet(1, 2, 3) x = Symbol("x") y = Symbol("y") z = Symbol("z") assert S.EmptySet | FiniteSet(x, FiniteSet(y, z)) == \ FiniteSet(x, FiniteSet(y, z)) # Test that Intervals and FiniteSets play nicely assert Interval(1, 3) + FiniteSet(2) == Interval(1, 3) assert Interval(1, 3, True, True) + FiniteSet(3) == \ Interval(1, 3, True, False) X = Interval(1, 3) + FiniteSet(5) Y = Interval(1, 2) + FiniteSet(3) XandY = X.intersect(Y) assert 2 in X and 3 in X and 3 in XandY assert XandY.is_subset(X) and XandY.is_subset(Y) raises(TypeError, lambda: Union(1, 2, 3)) assert X.is_iterable is False # issue 7843 assert Union(S.EmptySet, FiniteSet(-sqrt(-I), sqrt(-I))) == \ FiniteSet(-sqrt(-I), sqrt(-I)) assert Union(S.Reals, S.Integers) == S.Reals def test_union_iter(): # Use Range because it is ordered u = Union(Range(3), Range(5), Range(4), evaluate=False) # Round robin assert list(u) == [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 4] def test_union_is_empty(): assert (Interval(x, y) + FiniteSet(1)).is_empty == False assert (Interval(x, y) + Interval(-x, y)).is_empty == None def test_difference(): assert Interval(1, 3) - Interval(1, 2) == Interval(2, 3, True) assert Interval(1, 3) - Interval(2, 3) == Interval(1, 2, False, True) assert Interval(1, 3, True) - Interval(2, 3) == Interval(1, 2, True, True) assert Interval(1, 3, True) - Interval(2, 3, True) == \ Interval(1, 2, True, False) assert Interval(0, 2) - FiniteSet(1) == \ Union(Interval(0, 1, False, True), Interval(1, 2, True, False)) # issue #18119 assert S.Reals - FiniteSet(I) == S.Reals assert S.Reals - FiniteSet(-I, I) == S.Reals assert Interval(0, 10) - FiniteSet(-I, I) == Interval(0, 10) assert Interval(0, 10) - FiniteSet(1, I) == Union( Interval.Ropen(0, 1), Interval.Lopen(1, 10)) assert S.Reals - FiniteSet(1, 2 + I, x, y**2) == Complement( Union(Interval.open(-oo, 1), Interval.open(1, oo)), FiniteSet(x, y**2), evaluate=False) assert FiniteSet(1, 2, 3) - FiniteSet(2) == FiniteSet(1, 3) assert FiniteSet('ham', 'eggs') - FiniteSet('eggs') == FiniteSet('ham') assert FiniteSet(1, 2, 3, 4) - Interval(2, 10, True, False) == \ FiniteSet(1, 2) assert FiniteSet(1, 2, 3, 4) - S.EmptySet == FiniteSet(1, 2, 3, 4) assert Union(Interval(0, 2), FiniteSet(2, 3, 4)) - Interval(1, 3) == \ Union(Interval(0, 1, False, True), FiniteSet(4)) assert -1 in S.Reals - S.Naturals def test_Complement(): A = FiniteSet(1, 3, 4) B = FiniteSet(3, 4) C = Interval(1, 3) D = Interval(1, 2) assert Complement(A, B, evaluate=False).is_iterable is True assert Complement(A, C, evaluate=False).is_iterable is True assert Complement(C, D, evaluate=False).is_iterable is None assert FiniteSet(*Complement(A, B, evaluate=False)) == FiniteSet(1) assert FiniteSet(*Complement(A, C, evaluate=False)) == FiniteSet(4) raises(TypeError, lambda: FiniteSet(*Complement(C, A, evaluate=False))) assert Complement(Interval(1, 3), Interval(1, 2)) == Interval(2, 3, True) assert Complement(FiniteSet(1, 3, 4), FiniteSet(3, 4)) == FiniteSet(1) assert Complement(Union(Interval(0, 2), FiniteSet(2, 3, 4)), Interval(1, 3)) == \ Union(Interval(0, 1, False, True), FiniteSet(4)) assert not 3 in Complement(Interval(0, 5), Interval(1, 4), evaluate=False) assert -1 in Complement(S.Reals, S.Naturals, evaluate=False) assert not 1 in Complement(S.Reals, S.Naturals, evaluate=False) assert Complement(S.Integers, S.UniversalSet) == EmptySet assert S.UniversalSet.complement(S.Integers) == EmptySet assert (not 0 in S.Reals.intersect(S.Integers - FiniteSet(0))) assert S.EmptySet - S.Integers == S.EmptySet assert (S.Integers - FiniteSet(0)) - FiniteSet(1) == S.Integers - FiniteSet(0, 1) assert S.Reals - Union(S.Naturals, FiniteSet(pi)) == \ Intersection(S.Reals - S.Naturals, S.Reals - FiniteSet(pi)) # issue 12712 assert Complement(FiniteSet(x, y, 2), Interval(-10, 10)) == \ Complement(FiniteSet(x, y), Interval(-10, 10)) A = FiniteSet(*symbols('a:c')) B = FiniteSet(*symbols('d:f')) assert unchanged(Complement, ProductSet(A, A), B) A2 = ProductSet(A, A) B3 = ProductSet(B, B, B) assert A2 - B3 == A2 assert B3 - A2 == B3 def test_set_operations_nonsets(): '''Tests that e.g. FiniteSet(1) * 2 raises TypeError''' ops = [ lambda a, b: a + b, lambda a, b: a - b, lambda a, b: a * b, lambda a, b: a / b, lambda a, b: a // b, lambda a, b: a | b, lambda a, b: a & b, lambda a, b: a ^ b, # FiniteSet(1) ** 2 gives a ProductSet #lambda a, b: a ** b, ] Sx = FiniteSet(x) Sy = FiniteSet(y) sets = [ {1}, FiniteSet(1), Interval(1, 2), Union(Sx, Interval(1, 2)), Intersection(Sx, Sy), Complement(Sx, Sy), ProductSet(Sx, Sy), S.EmptySet, ] nums = [0, 1, 2, S(0), S(1), S(2)] for si in sets: for ni in nums: for op in ops: raises(TypeError, lambda : op(si, ni)) raises(TypeError, lambda : op(ni, si)) raises(TypeError, lambda: si ** object()) raises(TypeError, lambda: si ** {1}) def test_complement(): assert Interval(0, 1).complement(S.Reals) == \ Union(Interval(-oo, 0, True, True), Interval(1, oo, True, True)) assert Interval(0, 1, True, False).complement(S.Reals) == \ Union(Interval(-oo, 0, True, False), Interval(1, oo, True, True)) assert Interval(0, 1, False, True).complement(S.Reals) == \ Union(Interval(-oo, 0, True, True), Interval(1, oo, False, True)) assert Interval(0, 1, True, True).complement(S.Reals) == \ Union(Interval(-oo, 0, True, False), Interval(1, oo, False, True)) assert S.UniversalSet.complement(S.EmptySet) == S.EmptySet assert S.UniversalSet.complement(S.Reals) == S.EmptySet assert S.UniversalSet.complement(S.UniversalSet) == S.EmptySet assert S.EmptySet.complement(S.Reals) == S.Reals assert Union(Interval(0, 1), Interval(2, 3)).complement(S.Reals) == \ Union(Interval(-oo, 0, True, True), Interval(1, 2, True, True), Interval(3, oo, True, True)) assert FiniteSet(0).complement(S.Reals) == \ Union(Interval(-oo, 0, True, True), Interval(0, oo, True, True)) assert (FiniteSet(5) + Interval(S.NegativeInfinity, 0)).complement(S.Reals) == \ Interval(0, 5, True, True) + Interval(5, S.Infinity, True, True) assert FiniteSet(1, 2, 3).complement(S.Reals) == \ Interval(S.NegativeInfinity, 1, True, True) + \ Interval(1, 2, True, True) + Interval(2, 3, True, True) +\ Interval(3, S.Infinity, True, True) assert FiniteSet(x).complement(S.Reals) == Complement(S.Reals, FiniteSet(x)) assert FiniteSet(0, x).complement(S.Reals) == Complement(Interval(-oo, 0, True, True) + Interval(0, oo, True, True) , FiniteSet(x), evaluate=False) square = Interval(0, 1) * Interval(0, 1) notsquare = square.complement(S.Reals*S.Reals) assert all(pt in square for pt in [(0, 0), (.5, .5), (1, 0), (1, 1)]) assert not any( pt in notsquare for pt in [(0, 0), (.5, .5), (1, 0), (1, 1)]) assert not any(pt in square for pt in [(-1, 0), (1.5, .5), (10, 10)]) assert all(pt in notsquare for pt in [(-1, 0), (1.5, .5), (10, 10)]) def test_intersect1(): assert all(S.Integers.intersection(i) is i for i in (S.Naturals, S.Naturals0)) assert all(i.intersection(S.Integers) is i for i in (S.Naturals, S.Naturals0)) s = S.Naturals0 assert S.Naturals.intersection(s) is S.Naturals assert s.intersection(S.Naturals) is S.Naturals x = Symbol('x') assert Interval(0, 2).intersect(Interval(1, 2)) == Interval(1, 2) assert Interval(0, 2).intersect(Interval(1, 2, True)) == \ Interval(1, 2, True) assert Interval(0, 2, True).intersect(Interval(1, 2)) == \ Interval(1, 2, False, False) assert Interval(0, 2, True, True).intersect(Interval(1, 2)) == \ Interval(1, 2, False, True) assert Interval(0, 2).intersect(Union(Interval(0, 1), Interval(2, 3))) == \ Union(Interval(0, 1), Interval(2, 2)) assert FiniteSet(1, 2).intersect(FiniteSet(1, 2, 3)) == FiniteSet(1, 2) assert FiniteSet(1, 2, x).intersect(FiniteSet(x)) == FiniteSet(x) assert FiniteSet('ham', 'eggs').intersect(FiniteSet('ham')) == \ FiniteSet('ham') assert FiniteSet(1, 2, 3, 4, 5).intersect(S.EmptySet) == S.EmptySet assert Interval(0, 5).intersect(FiniteSet(1, 3)) == FiniteSet(1, 3) assert Interval(0, 1, True, True).intersect(FiniteSet(1)) == S.EmptySet assert Union(Interval(0, 1), Interval(2, 3)).intersect(Interval(1, 2)) == \ Union(Interval(1, 1), Interval(2, 2)) assert Union(Interval(0, 1), Interval(2, 3)).intersect(Interval(0, 2)) == \ Union(Interval(0, 1), Interval(2, 2)) assert Union(Interval(0, 1), Interval(2, 3)).intersect(Interval(1, 2, True, True)) == \ S.EmptySet assert Union(Interval(0, 1), Interval(2, 3)).intersect(S.EmptySet) == \ S.EmptySet assert Union(Interval(0, 5), FiniteSet('ham')).intersect(FiniteSet(2, 3, 4, 5, 6)) == \ Intersection(FiniteSet(2, 3, 4, 5, 6), Union(FiniteSet('ham'), Interval(0, 5))) assert Intersection(FiniteSet(1, 2, 3), Interval(2, x), Interval(3, y)) == \ Intersection(FiniteSet(3), Interval(2, x), Interval(3, y), evaluate=False) assert Intersection(FiniteSet(1, 2), Interval(0, 3), Interval(x, y)) == \ Intersection({1, 2}, Interval(x, y), evaluate=False) assert Intersection(FiniteSet(1, 2, 4), Interval(0, 3), Interval(x, y)) == \ Intersection({1, 2}, Interval(x, y), evaluate=False) # XXX: Is the real=True necessary here? # https://github.com/sympy/sympy/issues/17532 m, n = symbols('m, n', real=True) assert Intersection(FiniteSet(m), FiniteSet(m, n), Interval(m, m+1)) == \ FiniteSet(m) # issue 8217 assert Intersection(FiniteSet(x), FiniteSet(y)) == \ Intersection(FiniteSet(x), FiniteSet(y), evaluate=False) assert FiniteSet(x).intersect(S.Reals) == \ Intersection(S.Reals, FiniteSet(x), evaluate=False) # tests for the intersection alias assert Interval(0, 5).intersection(FiniteSet(1, 3)) == FiniteSet(1, 3) assert Interval(0, 1, True, True).intersection(FiniteSet(1)) == S.EmptySet assert Union(Interval(0, 1), Interval(2, 3)).intersection(Interval(1, 2)) == \ Union(Interval(1, 1), Interval(2, 2)) def test_intersection(): # iterable i = Intersection(FiniteSet(1, 2, 3), Interval(2, 5), evaluate=False) assert i.is_iterable assert set(i) == {S(2), S(3)} # challenging intervals x = Symbol('x', real=True) i = Intersection(Interval(0, 3), Interval(x, 6)) assert (5 in i) is False raises(TypeError, lambda: 2 in i) # Singleton special cases assert Intersection(Interval(0, 1), S.EmptySet) == S.EmptySet assert Intersection(Interval(-oo, oo), Interval(-oo, x)) == Interval(-oo, x) # Products line = Interval(0, 5) i = Intersection(line**2, line**3, evaluate=False) assert (2, 2) not in i assert (2, 2, 2) not in i raises(TypeError, lambda: list(i)) a = Intersection(Intersection(S.Integers, S.Naturals, evaluate=False), S.Reals, evaluate=False) assert a._argset == frozenset([Intersection(S.Naturals, S.Integers, evaluate=False), S.Reals]) assert Intersection(S.Complexes, FiniteSet(S.ComplexInfinity)) == S.EmptySet # issue 12178 assert Intersection() == S.UniversalSet # issue 16987 assert Intersection({1}, {1}, {x}) == Intersection({1}, {x}) def test_issue_9623(): n = Symbol('n') a = S.Reals b = Interval(0, oo) c = FiniteSet(n) assert Intersection(a, b, c) == Intersection(b, c) assert Intersection(Interval(1, 2), Interval(3, 4), FiniteSet(n)) == EmptySet def test_is_disjoint(): assert Interval(0, 2).is_disjoint(Interval(1, 2)) == False assert Interval(0, 2).is_disjoint(Interval(3, 4)) == True def test_ProductSet__len__(): A = FiniteSet(1, 2) B = FiniteSet(1, 2, 3) assert ProductSet(A).__len__() == 2 assert ProductSet(A).__len__() is not S(2) assert ProductSet(A, B).__len__() == 6 assert ProductSet(A, B).__len__() is not S(6) def test_ProductSet(): # ProductSet is always a set of Tuples assert ProductSet(S.Reals) == S.Reals ** 1 assert ProductSet(S.Reals, S.Reals) == S.Reals ** 2 assert ProductSet(S.Reals, S.Reals, S.Reals) == S.Reals ** 3 assert ProductSet(S.Reals) != S.Reals assert ProductSet(S.Reals, S.Reals) == S.Reals * S.Reals assert ProductSet(S.Reals, S.Reals, S.Reals) != S.Reals * S.Reals * S.Reals assert ProductSet(S.Reals, S.Reals, S.Reals) == (S.Reals * S.Reals * S.Reals).flatten() assert 1 not in ProductSet(S.Reals) assert (1,) in ProductSet(S.Reals) assert 1 not in ProductSet(S.Reals, S.Reals) assert (1, 2) in ProductSet(S.Reals, S.Reals) assert (1, I) not in ProductSet(S.Reals, S.Reals) assert (1, 2, 3) in ProductSet(S.Reals, S.Reals, S.Reals) assert (1, 2, 3) in S.Reals ** 3 assert (1, 2, 3) not in S.Reals * S.Reals * S.Reals assert ((1, 2), 3) in S.Reals * S.Reals * S.Reals assert (1, (2, 3)) not in S.Reals * S.Reals * S.Reals assert (1, (2, 3)) in S.Reals * (S.Reals * S.Reals) assert ProductSet() == FiniteSet(()) assert ProductSet(S.Reals, S.EmptySet) == S.EmptySet # See GH-17458 for ni in range(5): Rn = ProductSet(*(S.Reals,) * ni) assert (1,) * ni in Rn assert 1 not in Rn assert (S.Reals * S.Reals) * S.Reals != S.Reals * (S.Reals * S.Reals) S1 = S.Reals S2 = S.Integers x1 = pi x2 = 3 assert x1 in S1 assert x2 in S2 assert (x1, x2) in S1 * S2 S3 = S1 * S2 x3 = (x1, x2) assert x3 in S3 assert (x3, x3) in S3 * S3 assert x3 + x3 not in S3 * S3 raises(ValueError, lambda: S.Reals**-1) with warns_deprecated_sympy(): ProductSet(FiniteSet(s) for s in range(2)) raises(TypeError, lambda: ProductSet(None)) S1 = FiniteSet(1, 2) S2 = FiniteSet(3, 4) S3 = ProductSet(S1, S2) assert (S3.as_relational(x, y) == And(S1.as_relational(x), S2.as_relational(y)) == And(Or(Eq(x, 1), Eq(x, 2)), Or(Eq(y, 3), Eq(y, 4)))) raises(ValueError, lambda: S3.as_relational(x)) raises(ValueError, lambda: S3.as_relational(x, 1)) raises(ValueError, lambda: ProductSet(Interval(0, 1)).as_relational(x, y)) Z2 = ProductSet(S.Integers, S.Integers) assert Z2.contains((1, 2)) is S.true assert Z2.contains((1,)) is S.false assert Z2.contains(x) == Contains(x, Z2, evaluate=False) assert Z2.contains(x).subs(x, 1) is S.false assert Z2.contains((x, 1)).subs(x, 2) is S.true assert Z2.contains((x, y)) == Contains((x, y), Z2, evaluate=False) assert unchanged(Contains, (x, y), Z2) assert Contains((1, 2), Z2) is S.true def test_ProductSet_of_single_arg_is_not_arg(): assert unchanged(ProductSet, Interval(0, 1)) assert unchanged(ProductSet, ProductSet(Interval(0, 1))) def test_ProductSet_is_empty(): assert ProductSet(S.Integers, S.Reals).is_empty == False assert ProductSet(Interval(x, 1), S.Reals).is_empty == None def test_interval_subs(): a = Symbol('a', real=True) assert Interval(0, a).subs(a, 2) == Interval(0, 2) assert Interval(a, 0).subs(a, 2) == S.EmptySet def test_interval_to_mpi(): assert Interval(0, 1).to_mpi() == mpi(0, 1) assert Interval(0, 1, True, False).to_mpi() == mpi(0, 1) assert type(Interval(0, 1).to_mpi()) == type(mpi(0, 1)) def test_set_evalf(): assert Interval(S(11)/64, S.Half).evalf() == Interval( Float('0.171875'), Float('0.5')) assert Interval(x, S.Half, right_open=True).evalf() == Interval( x, Float('0.5'), right_open=True) assert Interval(-oo, S.Half).evalf() == Interval(-oo, Float('0.5')) assert FiniteSet(2, x).evalf() == FiniteSet(Float('2.0'), x) def test_measure(): a = Symbol('a', real=True) assert Interval(1, 3).measure == 2 assert Interval(0, a).measure == a assert Interval(1, a).measure == a - 1 assert Union(Interval(1, 2), Interval(3, 4)).measure == 2 assert Union(Interval(1, 2), Interval(3, 4), FiniteSet(5, 6, 7)).measure \ == 2 assert FiniteSet(1, 2, oo, a, -oo, -5).measure == 0 assert S.EmptySet.measure == 0 square = Interval(0, 10) * Interval(0, 10) offsetsquare = Interval(5, 15) * Interval(5, 15) band = Interval(-oo, oo) * Interval(2, 4) assert square.measure == offsetsquare.measure == 100 assert (square + offsetsquare).measure == 175 # there is some overlap assert (square - offsetsquare).measure == 75 assert (square * FiniteSet(1, 2, 3)).measure == 0 assert (square.intersect(band)).measure == 20 assert (square + band).measure is oo assert (band * FiniteSet(1, 2, 3)).measure is nan def test_is_subset(): assert Interval(0, 1).is_subset(Interval(0, 2)) is True assert Interval(0, 3).is_subset(Interval(0, 2)) is False assert Interval(0, 1).is_subset(FiniteSet(0, 1)) is False assert FiniteSet(1, 2).is_subset(FiniteSet(1, 2, 3, 4)) assert FiniteSet(4, 5).is_subset(FiniteSet(1, 2, 3, 4)) is False assert FiniteSet(1).is_subset(Interval(0, 2)) assert FiniteSet(1, 2).is_subset(Interval(0, 2, True, True)) is False assert (Interval(1, 2) + FiniteSet(3)).is_subset( Interval(0, 2, False, True) + FiniteSet(2, 3)) assert Interval(3, 4).is_subset(Union(Interval(0, 1), Interval(2, 5))) is True assert Interval(3, 6).is_subset(Union(Interval(0, 1), Interval(2, 5))) is False assert FiniteSet(1, 2, 3, 4).is_subset(Interval(0, 5)) is True assert S.EmptySet.is_subset(FiniteSet(1, 2, 3)) is True assert Interval(0, 1).is_subset(S.EmptySet) is False assert S.EmptySet.is_subset(S.EmptySet) is True raises(ValueError, lambda: S.EmptySet.is_subset(1)) # tests for the issubset alias assert FiniteSet(1, 2, 3, 4).issubset(Interval(0, 5)) is True assert S.EmptySet.issubset(FiniteSet(1, 2, 3)) is True assert S.Naturals.is_subset(S.Integers) assert S.Naturals0.is_subset(S.Integers) assert FiniteSet(x).is_subset(FiniteSet(y)) is None assert FiniteSet(x).is_subset(FiniteSet(y).subs(y, x)) is True assert FiniteSet(x).is_subset(FiniteSet(y).subs(y, x+1)) is False assert Interval(0, 1).is_subset(Interval(0, 1, left_open=True)) is False assert Interval(-2, 3).is_subset(Union(Interval(-oo, -2), Interval(3, oo))) is False n = Symbol('n', integer=True) assert Range(-3, 4, 1).is_subset(FiniteSet(-10, 10)) is False assert Range(S(10)**100).is_subset(FiniteSet(0, 1, 2)) is False assert Range(6, 0, -2).is_subset(FiniteSet(2, 4, 6)) is True assert Range(1, oo).is_subset(FiniteSet(1, 2)) is False assert Range(-oo, 1).is_subset(FiniteSet(1)) is False assert Range(3).is_subset(FiniteSet(0, 1, n)) is None assert Range(n, n + 2).is_subset(FiniteSet(n, n + 1)) is True assert Range(5).is_subset(Interval(0, 4, right_open=True)) is False def test_is_proper_subset(): assert Interval(0, 1).is_proper_subset(Interval(0, 2)) is True assert Interval(0, 3).is_proper_subset(Interval(0, 2)) is False assert S.EmptySet.is_proper_subset(FiniteSet(1, 2, 3)) is True raises(ValueError, lambda: Interval(0, 1).is_proper_subset(0)) def test_is_superset(): assert Interval(0, 1).is_superset(Interval(0, 2)) == False assert Interval(0, 3).is_superset(Interval(0, 2)) assert FiniteSet(1, 2).is_superset(FiniteSet(1, 2, 3, 4)) == False assert FiniteSet(4, 5).is_superset(FiniteSet(1, 2, 3, 4)) == False assert FiniteSet(1).is_superset(Interval(0, 2)) == False assert FiniteSet(1, 2).is_superset(Interval(0, 2, True, True)) == False assert (Interval(1, 2) + FiniteSet(3)).is_superset( Interval(0, 2, False, True) + FiniteSet(2, 3)) == False assert Interval(3, 4).is_superset(Union(Interval(0, 1), Interval(2, 5))) == False assert FiniteSet(1, 2, 3, 4).is_superset(Interval(0, 5)) == False assert S.EmptySet.is_superset(FiniteSet(1, 2, 3)) == False assert Interval(0, 1).is_superset(S.EmptySet) == True assert S.EmptySet.is_superset(S.EmptySet) == True raises(ValueError, lambda: S.EmptySet.is_superset(1)) # tests for the issuperset alias assert Interval(0, 1).issuperset(S.EmptySet) == True assert S.EmptySet.issuperset(S.EmptySet) == True def test_is_proper_superset(): assert Interval(0, 1).is_proper_superset(Interval(0, 2)) is False assert Interval(0, 3).is_proper_superset(Interval(0, 2)) is True assert FiniteSet(1, 2, 3).is_proper_superset(S.EmptySet) is True raises(ValueError, lambda: Interval(0, 1).is_proper_superset(0)) def test_contains(): assert Interval(0, 2).contains(1) is S.true assert Interval(0, 2).contains(3) is S.false assert Interval(0, 2, True, False).contains(0) is S.false assert Interval(0, 2, True, False).contains(2) is S.true assert Interval(0, 2, False, True).contains(0) is S.true assert Interval(0, 2, False, True).contains(2) is S.false assert Interval(0, 2, True, True).contains(0) is S.false assert Interval(0, 2, True, True).contains(2) is S.false assert (Interval(0, 2) in Interval(0, 2)) is False assert FiniteSet(1, 2, 3).contains(2) is S.true assert FiniteSet(1, 2, Symbol('x')).contains(Symbol('x')) is S.true assert FiniteSet(y)._contains(x) is None raises(TypeError, lambda: x in FiniteSet(y)) assert FiniteSet({x, y})._contains({x}) is None assert FiniteSet({x, y}).subs(y, x)._contains({x}) is True assert FiniteSet({x, y}).subs(y, x+1)._contains({x}) is False # issue 8197 from sympy.abc import a, b assert isinstance(FiniteSet(b).contains(-a), Contains) assert isinstance(FiniteSet(b).contains(a), Contains) assert isinstance(FiniteSet(a).contains(1), Contains) raises(TypeError, lambda: 1 in FiniteSet(a)) # issue 8209 rad1 = Pow(Pow(2, Rational(1, 3)) - 1, Rational(1, 3)) rad2 = Pow(Rational(1, 9), Rational(1, 3)) - Pow(Rational(2, 9), Rational(1, 3)) + Pow(Rational(4, 9), Rational(1, 3)) s1 = FiniteSet(rad1) s2 = FiniteSet(rad2) assert s1 - s2 == S.EmptySet items = [1, 2, S.Infinity, S('ham'), -1.1] fset = FiniteSet(*items) assert all(item in fset for item in items) assert all(fset.contains(item) is S.true for item in items) assert Union(Interval(0, 1), Interval(2, 5)).contains(3) is S.true assert Union(Interval(0, 1), Interval(2, 5)).contains(6) is S.false assert Union(Interval(0, 1), FiniteSet(2, 5)).contains(3) is S.false assert S.EmptySet.contains(1) is S.false assert FiniteSet(rootof(x**3 + x - 1, 0)).contains(S.Infinity) is S.false assert rootof(x**5 + x**3 + 1, 0) in S.Reals assert not rootof(x**5 + x**3 + 1, 1) in S.Reals # non-bool results assert Union(Interval(1, 2), Interval(3, 4)).contains(x) == \ Or(And(S.One <= x, x <= 2), And(S(3) <= x, x <= 4)) assert Intersection(Interval(1, x), Interval(2, 3)).contains(y) == \ And(y <= 3, y <= x, S.One <= y, S(2) <= y) assert (S.Complexes).contains(S.ComplexInfinity) == S.false def test_interval_symbolic(): x = Symbol('x') e = Interval(0, 1) assert e.contains(x) == And(S.Zero <= x, x <= 1) raises(TypeError, lambda: x in e) e = Interval(0, 1, True, True) assert e.contains(x) == And(S.Zero < x, x < 1) c = Symbol('c', real=False) assert Interval(x, x + 1).contains(c) == False e = Symbol('e', extended_real=True) assert Interval(-oo, oo).contains(e) == And( S.NegativeInfinity < e, e < S.Infinity) def test_union_contains(): x = Symbol('x') i1 = Interval(0, 1) i2 = Interval(2, 3) i3 = Union(i1, i2) assert i3.as_relational(x) == Or(And(S.Zero <= x, x <= 1), And(S(2) <= x, x <= 3)) raises(TypeError, lambda: x in i3) e = i3.contains(x) assert e == i3.as_relational(x) assert e.subs(x, -0.5) is false assert e.subs(x, 0.5) is true assert e.subs(x, 1.5) is false assert e.subs(x, 2.5) is true assert e.subs(x, 3.5) is false U = Interval(0, 2, True, True) + Interval(10, oo) + FiniteSet(-1, 2, 5, 6) assert all(el not in U for el in [0, 4, -oo]) assert all(el in U for el in [2, 5, 10]) def test_is_number(): assert Interval(0, 1).is_number is False assert Set().is_number is False def test_Interval_is_left_unbounded(): assert Interval(3, 4).is_left_unbounded is False assert Interval(-oo, 3).is_left_unbounded is True assert Interval(Float("-inf"), 3).is_left_unbounded is True def test_Interval_is_right_unbounded(): assert Interval(3, 4).is_right_unbounded is False assert Interval(3, oo).is_right_unbounded is True assert Interval(3, Float("+inf")).is_right_unbounded is True def test_Interval_as_relational(): x = Symbol('x') assert Interval(-1, 2, False, False).as_relational(x) == \ And(Le(-1, x), Le(x, 2)) assert Interval(-1, 2, True, False).as_relational(x) == \ And(Lt(-1, x), Le(x, 2)) assert Interval(-1, 2, False, True).as_relational(x) == \ And(Le(-1, x), Lt(x, 2)) assert Interval(-1, 2, True, True).as_relational(x) == \ And(Lt(-1, x), Lt(x, 2)) assert Interval(-oo, 2, right_open=False).as_relational(x) == And(Lt(-oo, x), Le(x, 2)) assert Interval(-oo, 2, right_open=True).as_relational(x) == And(Lt(-oo, x), Lt(x, 2)) assert Interval(-2, oo, left_open=False).as_relational(x) == And(Le(-2, x), Lt(x, oo)) assert Interval(-2, oo, left_open=True).as_relational(x) == And(Lt(-2, x), Lt(x, oo)) assert Interval(-oo, oo).as_relational(x) == And(Lt(-oo, x), Lt(x, oo)) x = Symbol('x', real=True) y = Symbol('y', real=True) assert Interval(x, y).as_relational(x) == (x <= y) assert Interval(y, x).as_relational(x) == (y <= x) def test_Finite_as_relational(): x = Symbol('x') y = Symbol('y') assert FiniteSet(1, 2).as_relational(x) == Or(Eq(x, 1), Eq(x, 2)) assert FiniteSet(y, -5).as_relational(x) == Or(Eq(x, y), Eq(x, -5)) def test_Union_as_relational(): x = Symbol('x') assert (Interval(0, 1) + FiniteSet(2)).as_relational(x) == \ Or(And(Le(0, x), Le(x, 1)), Eq(x, 2)) assert (Interval(0, 1, True, True) + FiniteSet(1)).as_relational(x) == \ And(Lt(0, x), Le(x, 1)) assert Or(x < 0, x > 0).as_set().as_relational(x) == \ And((x > -oo), (x < oo), Ne(x, 0)) assert (Interval.Ropen(1, 3) + Interval.Lopen(3, 5) ).as_relational(x) == And((x > 1), (x < 5), Ne(x, 3)) def test_Intersection_as_relational(): x = Symbol('x') assert (Intersection(Interval(0, 1), FiniteSet(2), evaluate=False).as_relational(x) == And(And(Le(0, x), Le(x, 1)), Eq(x, 2))) def test_Complement_as_relational(): x = Symbol('x') expr = Complement(Interval(0, 1), FiniteSet(2), evaluate=False) assert expr.as_relational(x) == \ And(Le(0, x), Le(x, 1), Ne(x, 2)) @XFAIL def test_Complement_as_relational_fail(): x = Symbol('x') expr = Complement(Interval(0, 1), FiniteSet(2), evaluate=False) # XXX This example fails because 0 <= x changes to x >= 0 # during the evaluation. assert expr.as_relational(x) == \ (0 <= x) & (x <= 1) & Ne(x, 2) def test_SymmetricDifference_as_relational(): x = Symbol('x') expr = SymmetricDifference(Interval(0, 1), FiniteSet(2), evaluate=False) assert expr.as_relational(x) == Xor(Eq(x, 2), Le(0, x) & Le(x, 1)) def test_EmptySet(): assert S.EmptySet.as_relational(Symbol('x')) is S.false assert S.EmptySet.intersect(S.UniversalSet) == S.EmptySet assert S.EmptySet.boundary == S.EmptySet def test_finite_basic(): x = Symbol('x') A = FiniteSet(1, 2, 3) B = FiniteSet(3, 4, 5) AorB = Union(A, B) AandB = A.intersect(B) assert A.is_subset(AorB) and B.is_subset(AorB) assert AandB.is_subset(A) assert AandB == FiniteSet(3) assert A.inf == 1 and A.sup == 3 assert AorB.inf == 1 and AorB.sup == 5 assert FiniteSet(x, 1, 5).sup == Max(x, 5) assert FiniteSet(x, 1, 5).inf == Min(x, 1) # issue 7335 assert FiniteSet(S.EmptySet) != S.EmptySet assert FiniteSet(FiniteSet(1, 2, 3)) != FiniteSet(1, 2, 3) assert FiniteSet((1, 2, 3)) != FiniteSet(1, 2, 3) # Ensure a variety of types can exist in a FiniteSet assert FiniteSet((1, 2), Float, A, -5, x, 'eggs', x**2, Interval) assert (A > B) is False assert (A >= B) is False assert (A < B) is False assert (A <= B) is False assert AorB > A and AorB > B assert AorB >= A and AorB >= B assert A >= A and A <= A assert A >= AandB and B >= AandB assert A > AandB and B > AandB assert FiniteSet(1.0) == FiniteSet(1) def test_product_basic(): H, T = 'H', 'T' unit_line = Interval(0, 1) d6 = FiniteSet(1, 2, 3, 4, 5, 6) d4 = FiniteSet(1, 2, 3, 4) coin = FiniteSet(H, T) square = unit_line * unit_line assert (0, 0) in square assert 0 not in square assert (H, T) in coin ** 2 assert (.5, .5, .5) in (square * unit_line).flatten() assert ((.5, .5), .5) in square * unit_line assert (H, 3, 3) in (coin * d6 * d6).flatten() assert ((H, 3), 3) in coin * d6 * d6 HH, TT = sympify(H), sympify(T) assert set(coin**2) == {(HH, HH), (HH, TT), (TT, HH), (TT, TT)} assert (d4*d4).is_subset(d6*d6) assert square.complement(Interval(-oo, oo)*Interval(-oo, oo)) == Union( (Interval(-oo, 0, True, True) + Interval(1, oo, True, True))*Interval(-oo, oo), Interval(-oo, oo)*(Interval(-oo, 0, True, True) + Interval(1, oo, True, True))) assert (Interval(-5, 5)**3).is_subset(Interval(-10, 10)**3) assert not (Interval(-10, 10)**3).is_subset(Interval(-5, 5)**3) assert not (Interval(-5, 5)**2).is_subset(Interval(-10, 10)**3) assert (Interval(.2, .5)*FiniteSet(.5)).is_subset(square) # segment in square assert len(coin*coin*coin) == 8 assert len(S.EmptySet*S.EmptySet) == 0 assert len(S.EmptySet*coin) == 0 raises(TypeError, lambda: len(coin*Interval(0, 2))) def test_real(): x = Symbol('x', real=True, finite=True) I = Interval(0, 5) J = Interval(10, 20) A = FiniteSet(1, 2, 30, x, S.Pi) B = FiniteSet(-4, 0) C = FiniteSet(100) D = FiniteSet('Ham', 'Eggs') assert all(s.is_subset(S.Reals) for s in [I, J, A, B, C]) assert not D.is_subset(S.Reals) assert all((a + b).is_subset(S.Reals) for a in [I, J, A, B, C] for b in [I, J, A, B, C]) assert not any((a + D).is_subset(S.Reals) for a in [I, J, A, B, C, D]) assert not (I + A + D).is_subset(S.Reals) def test_supinf(): x = Symbol('x', real=True) y = Symbol('y', real=True) assert (Interval(0, 1) + FiniteSet(2)).sup == 2 assert (Interval(0, 1) + FiniteSet(2)).inf == 0 assert (Interval(0, 1) + FiniteSet(x)).sup == Max(1, x) assert (Interval(0, 1) + FiniteSet(x)).inf == Min(0, x) assert FiniteSet(5, 1, x).sup == Max(5, x) assert FiniteSet(5, 1, x).inf == Min(1, x) assert FiniteSet(5, 1, x, y).sup == Max(5, x, y) assert FiniteSet(5, 1, x, y).inf == Min(1, x, y) assert FiniteSet(5, 1, x, y, S.Infinity, S.NegativeInfinity).sup == \ S.Infinity assert FiniteSet(5, 1, x, y, S.Infinity, S.NegativeInfinity).inf == \ S.NegativeInfinity assert FiniteSet('Ham', 'Eggs').sup == Max('Ham', 'Eggs') def test_universalset(): U = S.UniversalSet x = Symbol('x') assert U.as_relational(x) is S.true assert U.union(Interval(2, 4)) == U assert U.intersect(Interval(2, 4)) == Interval(2, 4) assert U.measure is S.Infinity assert U.boundary == S.EmptySet assert U.contains(0) is S.true def test_Union_of_ProductSets_shares(): line = Interval(0, 2) points = FiniteSet(0, 1, 2) assert Union(line * line, line * points) == line * line def test_Interval_free_symbols(): # issue 6211 assert Interval(0, 1).free_symbols == set() x = Symbol('x', real=True) assert Interval(0, x).free_symbols == {x} def test_image_interval(): from sympy.core.numbers import Rational x = Symbol('x', real=True) a = Symbol('a', real=True) assert imageset(x, 2*x, Interval(-2, 1)) == Interval(-4, 2) assert imageset(x, 2*x, Interval(-2, 1, True, False)) == \ Interval(-4, 2, True, False) assert imageset(x, x**2, Interval(-2, 1, True, False)) == \ Interval(0, 4, False, True) assert imageset(x, x**2, Interval(-2, 1)) == Interval(0, 4) assert imageset(x, x**2, Interval(-2, 1, True, False)) == \ Interval(0, 4, False, True) assert imageset(x, x**2, Interval(-2, 1, True, True)) == \ Interval(0, 4, False, True) assert imageset(x, (x - 2)**2, Interval(1, 3)) == Interval(0, 1) assert imageset(x, 3*x**4 - 26*x**3 + 78*x**2 - 90*x, Interval(0, 4)) == \ Interval(-35, 0) # Multiple Maxima assert imageset(x, x + 1/x, Interval(-oo, oo)) == Interval(-oo, -2) \ + Interval(2, oo) # Single Infinite discontinuity assert imageset(x, 1/x + 1/(x-1)**2, Interval(0, 2, True, False)) == \ Interval(Rational(3, 2), oo, False) # Multiple Infinite discontinuities # Test for Python lambda assert imageset(lambda x: 2*x, Interval(-2, 1)) == Interval(-4, 2) assert imageset(Lambda(x, a*x), Interval(0, 1)) == \ ImageSet(Lambda(x, a*x), Interval(0, 1)) assert imageset(Lambda(x, sin(cos(x))), Interval(0, 1)) == \ ImageSet(Lambda(x, sin(cos(x))), Interval(0, 1)) def test_image_piecewise(): f = Piecewise((x, x <= -1), (1/x**2, x <= 5), (x**3, True)) f1 = Piecewise((0, x <= 1), (1, x <= 2), (2, True)) assert imageset(x, f, Interval(-5, 5)) == Union(Interval(-5, -1), Interval(Rational(1, 25), oo)) assert imageset(x, f1, Interval(1, 2)) == FiniteSet(0, 1) @XFAIL # See: https://github.com/sympy/sympy/pull/2723#discussion_r8659826 def test_image_Intersection(): x = Symbol('x', real=True) y = Symbol('y', real=True) assert imageset(x, x**2, Interval(-2, 0).intersect(Interval(x, y))) == \ Interval(0, 4).intersect(Interval(Min(x**2, y**2), Max(x**2, y**2))) def test_image_FiniteSet(): x = Symbol('x', real=True) assert imageset(x, 2*x, FiniteSet(1, 2, 3)) == FiniteSet(2, 4, 6) def test_image_Union(): x = Symbol('x', real=True) assert imageset(x, x**2, Interval(-2, 0) + FiniteSet(1, 2, 3)) == \ (Interval(0, 4) + FiniteSet(9)) def test_image_EmptySet(): x = Symbol('x', real=True) assert imageset(x, 2*x, S.EmptySet) == S.EmptySet def test_issue_5724_7680(): assert I not in S.Reals # issue 7680 assert Interval(-oo, oo).contains(I) is S.false def test_boundary(): assert FiniteSet(1).boundary == FiniteSet(1) assert all(Interval(0, 1, left_open, right_open).boundary == FiniteSet(0, 1) for left_open in (true, false) for right_open in (true, false)) def test_boundary_Union(): assert (Interval(0, 1) + Interval(2, 3)).boundary == FiniteSet(0, 1, 2, 3) assert ((Interval(0, 1, False, True) + Interval(1, 2, True, False)).boundary == FiniteSet(0, 1, 2)) assert (Interval(0, 1) + FiniteSet(2)).boundary == FiniteSet(0, 1, 2) assert Union(Interval(0, 10), Interval(5, 15), evaluate=False).boundary \ == FiniteSet(0, 15) assert Union(Interval(0, 10), Interval(0, 1), evaluate=False).boundary \ == FiniteSet(0, 10) assert Union(Interval(0, 10, True, True), Interval(10, 15, True, True), evaluate=False).boundary \ == FiniteSet(0, 10, 15) @XFAIL def test_union_boundary_of_joining_sets(): """ Testing the boundary of unions is a hard problem """ assert Union(Interval(0, 10), Interval(10, 15), evaluate=False).boundary \ == FiniteSet(0, 15) def test_boundary_ProductSet(): open_square = Interval(0, 1, True, True) ** 2 assert open_square.boundary == (FiniteSet(0, 1) * Interval(0, 1) + Interval(0, 1) * FiniteSet(0, 1)) second_square = Interval(1, 2, True, True) * Interval(0, 1, True, True) assert (open_square + second_square).boundary == ( FiniteSet(0, 1) * Interval(0, 1) + FiniteSet(1, 2) * Interval(0, 1) + Interval(0, 1) * FiniteSet(0, 1) + Interval(1, 2) * FiniteSet(0, 1)) def test_boundary_ProductSet_line(): line_in_r2 = Interval(0, 1) * FiniteSet(0) assert line_in_r2.boundary == line_in_r2 def test_is_open(): assert Interval(0, 1, False, False).is_open is False assert Interval(0, 1, True, False).is_open is False assert Interval(0, 1, True, True).is_open is True assert FiniteSet(1, 2, 3).is_open is False def test_is_closed(): assert Interval(0, 1, False, False).is_closed is True assert Interval(0, 1, True, False).is_closed is False assert FiniteSet(1, 2, 3).is_closed is True def test_closure(): assert Interval(0, 1, False, True).closure == Interval(0, 1, False, False) def test_interior(): assert Interval(0, 1, False, True).interior == Interval(0, 1, True, True) def test_issue_7841(): raises(TypeError, lambda: x in S.Reals) def test_Eq(): assert Eq(Interval(0, 1), Interval(0, 1)) assert Eq(Interval(0, 1), Interval(0, 2)) == False s1 = FiniteSet(0, 1) s2 = FiniteSet(1, 2) assert Eq(s1, s1) assert Eq(s1, s2) == False assert Eq(s1*s2, s1*s2) assert Eq(s1*s2, s2*s1) == False assert unchanged(Eq, FiniteSet({x, y}), FiniteSet({x})) assert Eq(FiniteSet({x, y}).subs(y, x), FiniteSet({x})) is S.true assert Eq(FiniteSet({x, y}), FiniteSet({x})).subs(y, x) is S.true assert Eq(FiniteSet({x, y}).subs(y, x+1), FiniteSet({x})) is S.false assert Eq(FiniteSet({x, y}), FiniteSet({x})).subs(y, x+1) is S.false assert Eq(ProductSet({1}, {2}), Interval(1, 2)) is S.false assert Eq(ProductSet({1}), ProductSet({1}, {2})) is S.false assert Eq(FiniteSet(()), FiniteSet(1)) is S.false assert Eq(ProductSet(), FiniteSet(1)) is S.false i1 = Interval(0, 1) i2 = Interval(x, y) assert unchanged(Eq, ProductSet(i1, i1), ProductSet(i2, i2)) def test_SymmetricDifference(): A = FiniteSet(0, 1, 2, 3, 4, 5) B = FiniteSet(2, 4, 6, 8, 10) C = Interval(8, 10) assert SymmetricDifference(A, B, evaluate=False).is_iterable is True assert SymmetricDifference(A, C, evaluate=False).is_iterable is None assert FiniteSet(*SymmetricDifference(A, B, evaluate=False)) == \ FiniteSet(0, 1, 3, 5, 6, 8, 10) raises(TypeError, lambda: FiniteSet(*SymmetricDifference(A, C, evaluate=False))) assert SymmetricDifference(FiniteSet(0, 1, 2, 3, 4, 5), \ FiniteSet(2, 4, 6, 8, 10)) == FiniteSet(0, 1, 3, 5, 6, 8, 10) assert SymmetricDifference(FiniteSet(2, 3, 4), FiniteSet(2, 3 , 4 , 5)) \ == FiniteSet(5) assert FiniteSet(1, 2, 3, 4, 5) ^ FiniteSet(1, 2, 5, 6) == \ FiniteSet(3, 4, 6) assert Set(S(1), S(2) , S(3)) ^ Set(S(2), S(3), S(4)) == Union(Set(S(1), S(2), S(3)) - Set(S(2), S(3), S(4)), \ Set(S(2), S(3), S(4)) - Set(S(1), S(2), S(3))) assert Interval(0, 4) ^ Interval(2, 5) == Union(Interval(0, 4) - \ Interval(2, 5), Interval(2, 5) - Interval(0, 4)) def test_issue_9536(): from sympy.functions.elementary.exponential import log a = Symbol('a', real=True) assert FiniteSet(log(a)).intersect(S.Reals) == Intersection(S.Reals, FiniteSet(log(a))) def test_issue_9637(): n = Symbol('n') a = FiniteSet(n) b = FiniteSet(2, n) assert Complement(S.Reals, a) == Complement(S.Reals, a, evaluate=False) assert Complement(Interval(1, 3), a) == Complement(Interval(1, 3), a, evaluate=False) assert Complement(Interval(1, 3), b) == \ Complement(Union(Interval(1, 2, False, True), Interval(2, 3, True, False)), a) assert Complement(a, S.Reals) == Complement(a, S.Reals, evaluate=False) assert Complement(a, Interval(1, 3)) == Complement(a, Interval(1, 3), evaluate=False) def test_issue_9808(): # See https://github.com/sympy/sympy/issues/16342 assert Complement(FiniteSet(y), FiniteSet(1)) == Complement(FiniteSet(y), FiniteSet(1), evaluate=False) assert Complement(FiniteSet(1, 2, x), FiniteSet(x, y, 2, 3)) == \ Complement(FiniteSet(1), FiniteSet(y), evaluate=False) def test_issue_9956(): assert Union(Interval(-oo, oo), FiniteSet(1)) == Interval(-oo, oo) assert Interval(-oo, oo).contains(1) is S.true def test_issue_Symbol_inter(): i = Interval(0, oo) r = S.Reals mat = Matrix([0, 0, 0]) assert Intersection(r, i, FiniteSet(m), FiniteSet(m, n)) == \ Intersection(i, FiniteSet(m)) assert Intersection(FiniteSet(1, m, n), FiniteSet(m, n, 2), i) == \ Intersection(i, FiniteSet(m, n)) assert Intersection(FiniteSet(m, n, x), FiniteSet(m, z), r) == \ Intersection(Intersection({m, z}, {m, n, x}), r) assert Intersection(FiniteSet(m, n, 3), FiniteSet(m, n, x), r) == \ Intersection(FiniteSet(3, m, n), FiniteSet(m, n, x), r, evaluate=False) assert Intersection(FiniteSet(m, n, 3), FiniteSet(m, n, 2, 3), r) == \ Intersection(FiniteSet(3, m, n), r) assert Intersection(r, FiniteSet(mat, 2, n), FiniteSet(0, mat, n)) == \ Intersection(r, FiniteSet(n)) assert Intersection(FiniteSet(sin(x), cos(x)), FiniteSet(sin(x), cos(x), 1), r) == \ Intersection(r, FiniteSet(sin(x), cos(x))) assert Intersection(FiniteSet(x**2, 1, sin(x)), FiniteSet(x**2, 2, sin(x)), r) == \ Intersection(r, FiniteSet(x**2, sin(x))) def test_issue_11827(): assert S.Naturals0**4 def test_issue_10113(): f = x**2/(x**2 - 4) assert imageset(x, f, S.Reals) == Union(Interval(-oo, 0), Interval(1, oo, True, True)) assert imageset(x, f, Interval(-2, 2)) == Interval(-oo, 0) assert imageset(x, f, Interval(-2, 3)) == Union(Interval(-oo, 0), Interval(Rational(9, 5), oo)) def test_issue_10248(): raises( TypeError, lambda: list(Intersection(S.Reals, FiniteSet(x))) ) A = Symbol('A', real=True) assert list(Intersection(S.Reals, FiniteSet(A))) == [A] def test_issue_9447(): a = Interval(0, 1) + Interval(2, 3) assert Complement(S.UniversalSet, a) == Complement( S.UniversalSet, Union(Interval(0, 1), Interval(2, 3)), evaluate=False) assert Complement(S.Naturals, a) == Complement( S.Naturals, Union(Interval(0, 1), Interval(2, 3)), evaluate=False) def test_issue_10337(): assert (FiniteSet(2) == 3) is False assert (FiniteSet(2) != 3) is True raises(TypeError, lambda: FiniteSet(2) < 3) raises(TypeError, lambda: FiniteSet(2) <= 3) raises(TypeError, lambda: FiniteSet(2) > 3) raises(TypeError, lambda: FiniteSet(2) >= 3) def test_issue_10326(): bad = [ EmptySet, FiniteSet(1), Interval(1, 2), S.ComplexInfinity, S.ImaginaryUnit, S.Infinity, S.NaN, S.NegativeInfinity, ] interval = Interval(0, 5) for i in bad: assert i not in interval x = Symbol('x', real=True) nr = Symbol('nr', extended_real=False) assert x + 1 in Interval(x, x + 4) assert nr not in Interval(x, x + 4) assert Interval(1, 2) in FiniteSet(Interval(0, 5), Interval(1, 2)) assert Interval(-oo, oo).contains(oo) is S.false assert Interval(-oo, oo).contains(-oo) is S.false def test_issue_2799(): U = S.UniversalSet a = Symbol('a', real=True) inf_interval = Interval(a, oo) R = S.Reals assert U + inf_interval == inf_interval + U assert U + R == R + U assert R + inf_interval == inf_interval + R def test_issue_9706(): assert Interval(-oo, 0).closure == Interval(-oo, 0, True, False) assert Interval(0, oo).closure == Interval(0, oo, False, True) assert Interval(-oo, oo).closure == Interval(-oo, oo) def test_issue_8257(): reals_plus_infinity = Union(Interval(-oo, oo), FiniteSet(oo)) reals_plus_negativeinfinity = Union(Interval(-oo, oo), FiniteSet(-oo)) assert Interval(-oo, oo) + FiniteSet(oo) == reals_plus_infinity assert FiniteSet(oo) + Interval(-oo, oo) == reals_plus_infinity assert Interval(-oo, oo) + FiniteSet(-oo) == reals_plus_negativeinfinity assert FiniteSet(-oo) + Interval(-oo, oo) == reals_plus_negativeinfinity def test_issue_10931(): assert S.Integers - S.Integers == EmptySet assert S.Integers - S.Reals == EmptySet def test_issue_11174(): soln = Intersection(Interval(-oo, oo), FiniteSet(-x), evaluate=False) assert Intersection(FiniteSet(-x), S.Reals) == soln soln = Intersection(S.Reals, FiniteSet(x), evaluate=False) assert Intersection(FiniteSet(x), S.Reals) == soln def test_issue_18505(): assert ImageSet(Lambda(n, sqrt(pi*n/2 - 1 + pi/2)), S.Integers).contains(0) == \ Contains(0, ImageSet(Lambda(n, sqrt(pi*n/2 - 1 + pi/2)), S.Integers)) def test_finite_set_intersection(): # The following should not produce recursion errors # Note: some of these are not completely correct. See # https://github.com/sympy/sympy/issues/16342. assert Intersection(FiniteSet(-oo, x), FiniteSet(x)) == FiniteSet(x) assert Intersection._handle_finite_sets([FiniteSet(-oo, x), FiniteSet(0, x)]) == FiniteSet(x) assert Intersection._handle_finite_sets([FiniteSet(-oo, x), FiniteSet(x)]) == FiniteSet(x) assert Intersection._handle_finite_sets([FiniteSet(2, 3, x, y), FiniteSet(1, 2, x)]) == \ Intersection._handle_finite_sets([FiniteSet(1, 2, x), FiniteSet(2, 3, x, y)]) == \ Intersection(FiniteSet(1, 2, x), FiniteSet(2, 3, x, y)) == \ Intersection(FiniteSet(1, 2, x), FiniteSet(2, x, y)) assert FiniteSet(1+x-y) & FiniteSet(1) == \ FiniteSet(1) & FiniteSet(1+x-y) == \ Intersection(FiniteSet(1+x-y), FiniteSet(1), evaluate=False) assert FiniteSet(1) & FiniteSet(x) == FiniteSet(x) & FiniteSet(1) == \ Intersection(FiniteSet(1), FiniteSet(x), evaluate=False) assert FiniteSet({x}) & FiniteSet({x, y}) == \ Intersection(FiniteSet({x}), FiniteSet({x, y}), evaluate=False) def test_union_intersection_constructor(): # The actual exception does not matter here, so long as these fail sets = [FiniteSet(1), FiniteSet(2)] raises(Exception, lambda: Union(sets)) raises(Exception, lambda: Intersection(sets)) raises(Exception, lambda: Union(tuple(sets))) raises(Exception, lambda: Intersection(tuple(sets))) raises(Exception, lambda: Union(i for i in sets)) raises(Exception, lambda: Intersection(i for i in sets)) # Python sets are treated the same as FiniteSet # The union of a single set (of sets) is the set (of sets) itself assert Union(set(sets)) == FiniteSet(*sets) assert Intersection(set(sets)) == FiniteSet(*sets) assert Union({1}, {2}) == FiniteSet(1, 2) assert Intersection({1, 2}, {2, 3}) == FiniteSet(2) def test_Union_contains(): assert zoo not in Union( Interval.open(-oo, 0), Interval.open(0, oo)) @XFAIL def test_issue_16878b(): # in intersection_sets for (ImageSet, Set) there is no code # that handles the base_set of S.Reals like there is # for Integers assert imageset(x, (x, x), S.Reals).is_subset(S.Reals**2) is True def test_DisjointUnion(): assert DisjointUnion(FiniteSet(1, 2, 3), FiniteSet(1, 2, 3), FiniteSet(1, 2, 3)).rewrite(Union) == (FiniteSet(1, 2, 3) * FiniteSet(0, 1, 2)) assert DisjointUnion(Interval(1, 3), Interval(2, 4)).rewrite(Union) == Union(Interval(1, 3) * FiniteSet(0), Interval(2, 4) * FiniteSet(1)) assert DisjointUnion(Interval(0, 5), Interval(0, 5)).rewrite(Union) == Union(Interval(0, 5) * FiniteSet(0), Interval(0, 5) * FiniteSet(1)) assert DisjointUnion(Interval(-1, 2), S.EmptySet, S.EmptySet).rewrite(Union) == Interval(-1, 2) * FiniteSet(0) assert DisjointUnion(Interval(-1, 2)).rewrite(Union) == Interval(-1, 2) * FiniteSet(0) assert DisjointUnion(S.EmptySet, Interval(-1, 2), S.EmptySet).rewrite(Union) == Interval(-1, 2) * FiniteSet(1) assert DisjointUnion(Interval(-oo, oo)).rewrite(Union) == Interval(-oo, oo) * FiniteSet(0) assert DisjointUnion(S.EmptySet).rewrite(Union) == S.EmptySet assert DisjointUnion().rewrite(Union) == S.EmptySet raises(TypeError, lambda: DisjointUnion(Symbol('n'))) x = Symbol("x") y = Symbol("y") z = Symbol("z") assert DisjointUnion(FiniteSet(x), FiniteSet(y, z)).rewrite(Union) == (FiniteSet(x) * FiniteSet(0)) + (FiniteSet(y, z) * FiniteSet(1)) def test_DisjointUnion_is_empty(): assert DisjointUnion(S.EmptySet).is_empty is True assert DisjointUnion(S.EmptySet, S.EmptySet).is_empty is True assert DisjointUnion(S.EmptySet, FiniteSet(1, 2, 3)).is_empty is False def test_DisjointUnion_is_iterable(): assert DisjointUnion(S.Integers, S.Naturals, S.Rationals).is_iterable is True assert DisjointUnion(S.EmptySet, S.Reals).is_iterable is False assert DisjointUnion(FiniteSet(1, 2, 3), S.EmptySet, FiniteSet(x, y)).is_iterable is True assert DisjointUnion(S.EmptySet, S.EmptySet).is_iterable is False def test_DisjointUnion_contains(): assert (0, 0) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2)) assert (0, 1) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2)) assert (0, 2) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2)) assert (1, 0) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2)) assert (1, 1) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2)) assert (1, 2) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2)) assert (2, 0) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2)) assert (2, 1) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2)) assert (2, 2) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2)) assert (0, 1, 2) not in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2)) assert (0, 0.5) not in DisjointUnion(FiniteSet(0.5)) assert (0, 5) not in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2)) assert (x, 0) in DisjointUnion(FiniteSet(x, y, z), S.EmptySet, FiniteSet(y)) assert (y, 0) in DisjointUnion(FiniteSet(x, y, z), S.EmptySet, FiniteSet(y)) assert (z, 0) in DisjointUnion(FiniteSet(x, y, z), S.EmptySet, FiniteSet(y)) assert (y, 2) in DisjointUnion(FiniteSet(x, y, z), S.EmptySet, FiniteSet(y)) assert (0.5, 0) in DisjointUnion(Interval(0, 1), Interval(0, 2)) assert (0.5, 1) in DisjointUnion(Interval(0, 1), Interval(0, 2)) assert (1.5, 0) not in DisjointUnion(Interval(0, 1), Interval(0, 2)) assert (1.5, 1) in DisjointUnion(Interval(0, 1), Interval(0, 2)) def test_DisjointUnion_iter(): D = DisjointUnion(FiniteSet(3, 5, 7, 9), FiniteSet(x, y, z)) it = iter(D) L1 = [(x, 1), (y, 1), (z, 1)] L2 = [(3, 0), (5, 0), (7, 0), (9, 0)] nxt = next(it) assert nxt in L2 L2.remove(nxt) nxt = next(it) assert nxt in L1 L1.remove(nxt) nxt = next(it) assert nxt in L2 L2.remove(nxt) nxt = next(it) assert nxt in L1 L1.remove(nxt) nxt = next(it) assert nxt in L2 L2.remove(nxt) nxt = next(it) assert nxt in L1 L1.remove(nxt) nxt = next(it) assert nxt in L2 L2.remove(nxt) raises(StopIteration, lambda: next(it)) raises(ValueError, lambda: iter(DisjointUnion(Interval(0, 1), S.EmptySet))) def test_DisjointUnion_len(): assert len(DisjointUnion(FiniteSet(3, 5, 7, 9), FiniteSet(x, y, z))) == 7 assert len(DisjointUnion(S.EmptySet, S.EmptySet, FiniteSet(x, y, z), S.EmptySet)) == 3 raises(ValueError, lambda: len(DisjointUnion(Interval(0, 1), S.EmptySet))) def test_issue_20089(): B = FiniteSet(FiniteSet(1, 2), FiniteSet(1)) assert not 1 in B assert not 1.0 in B assert not Eq(1, FiniteSet(1, 2)) assert FiniteSet(1) in B A = FiniteSet(1, 2) assert A in B assert B.issubset(B) assert not A.issubset(B) assert 1 in A C = FiniteSet(FiniteSet(1, 2), FiniteSet(1), 1, 2) assert A.issubset(C) assert B.issubset(C) def test_issue_19378(): a = FiniteSet(1, 2) b = ProductSet(a, a) c = FiniteSet((1, 1), (1, 2), (2, 1), (2, 2)) assert b.is_subset(c) is True d = FiniteSet(1) assert b.is_subset(d) is False assert Eq(c, b).simplify() is S.true assert Eq(a, c).simplify() is S.false assert Eq({1}, {x}).simplify() == Eq({1}, {x}) def test_issue_20379(): #https://github.com/sympy/sympy/issues/20379 x = pi - 3.14159265358979 assert FiniteSet(x).evalf(2) == FiniteSet(Float('3.23108914886517e-15', 2)) def test_finiteset_simplify(): S = FiniteSet(1, cos(1)**2 + sin(1)**2) assert S.simplify() == {1}
e92afef2aa1c2f3e5a46b3aa9c303091b0a3891d812168e81b44c9f49125b7f5
import os from tempfile import TemporaryDirectory from sympy import ( pi, sin, cos, Symbol, Integral, Sum, sqrt, log, exp, Ne, oo, LambertW, I, meijerg, exp_polar, Piecewise, And, real_root) from sympy.core.singleton import S from sympy.core.sympify import sympify from sympy.external import import_module from sympy.plotting.plot import ( Plot, plot, plot_parametric, plot3d_parametric_line, plot3d, plot3d_parametric_surface) from sympy.plotting.plot import ( unset_show, plot_contour, PlotGrid, DefaultBackend, MatplotlibBackend, TextBackend, BaseBackend) from sympy.testing.pytest import skip, raises, warns from sympy.utilities import lambdify as lambdify_ unset_show() matplotlib = import_module( 'matplotlib', min_module_version='1.1.0', catch=(RuntimeError,)) class DummyBackendNotOk(BaseBackend): """ Used to verify if users can create their own backends. This backend is meant to raise NotImplementedError for methods `show`, `save`, `close`. """ pass class DummyBackendOk(BaseBackend): """ Used to verify if users can create their own backends. This backend is meant to pass all tests. """ def show(self): pass def save(self): pass def close(self): pass def test_plot_and_save_1(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') y = Symbol('y') with TemporaryDirectory(prefix='sympy_') as tmpdir: ### # Examples from the 'introduction' notebook ### p = plot(x, legend=True, label='f1') p = plot(x*sin(x), x*cos(x), label='f2') p.extend(p) p[0].line_color = lambda a: a p[1].line_color = 'b' p.title = 'Big title' p.xlabel = 'the x axis' p[1].label = 'straight line' p.legend = True p.aspect_ratio = (1, 1) p.xlim = (-15, 20) filename = 'test_basic_options_and_colors.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p.extend(plot(x + 1)) p.append(plot(x + 3, x**2)[1]) filename = 'test_plot_extend_append.png' p.save(os.path.join(tmpdir, filename)) p[2] = plot(x**2, (x, -2, 3)) filename = 'test_plot_setitem.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p = plot(sin(x), (x, -2*pi, 4*pi)) filename = 'test_line_explicit.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p = plot(sin(x)) filename = 'test_line_default_range.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p = plot((x**2, (x, -5, 5)), (x**3, (x, -3, 3))) filename = 'test_line_multiple_range.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() raises(ValueError, lambda: plot(x, y)) #Piecewise plots p = plot(Piecewise((1, x > 0), (0, True)), (x, -1, 1)) filename = 'test_plot_piecewise.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p = plot(Piecewise((x, x < 1), (x**2, True)), (x, -3, 3)) filename = 'test_plot_piecewise_2.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() # test issue 7471 p1 = plot(x) p2 = plot(3) p1.extend(p2) filename = 'test_horizontal_line.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() # test issue 10925 f = Piecewise((-1, x < -1), (x, And(-1 <= x, x < 0)), \ (x**2, And(0 <= x, x < 1)), (x**3, x >= 1)) p = plot(f, (x, -3, 3)) filename = 'test_plot_piecewise_3.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() def test_plot_and_save_2(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') y = Symbol('y') z = Symbol('z') with TemporaryDirectory(prefix='sympy_') as tmpdir: #parametric 2d plots. #Single plot with default range. p = plot_parametric(sin(x), cos(x)) filename = 'test_parametric.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() #Single plot with range. p = plot_parametric( sin(x), cos(x), (x, -5, 5), legend=True, label='parametric_plot') filename = 'test_parametric_range.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() #Multiple plots with same range. p = plot_parametric((sin(x), cos(x)), (x, sin(x))) filename = 'test_parametric_multiple.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() #Multiple plots with different ranges. p = plot_parametric( (sin(x), cos(x), (x, -3, 3)), (x, sin(x), (x, -5, 5))) filename = 'test_parametric_multiple_ranges.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() #depth of recursion specified. p = plot_parametric(x, sin(x), depth=13) filename = 'test_recursion_depth.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() #No adaptive sampling. p = plot_parametric(cos(x), sin(x), adaptive=False, nb_of_points=500) filename = 'test_adaptive.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() #3d parametric plots p = plot3d_parametric_line( sin(x), cos(x), x, legend=True, label='3d_parametric_plot') filename = 'test_3d_line.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p = plot3d_parametric_line( (sin(x), cos(x), x, (x, -5, 5)), (cos(x), sin(x), x, (x, -3, 3))) filename = 'test_3d_line_multiple.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p = plot3d_parametric_line(sin(x), cos(x), x, nb_of_points=30) filename = 'test_3d_line_points.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() # 3d surface single plot. p = plot3d(x * y) filename = 'test_surface.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() # Multiple 3D plots with same range. p = plot3d(-x * y, x * y, (x, -5, 5)) filename = 'test_surface_multiple.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() # Multiple 3D plots with different ranges. p = plot3d( (x * y, (x, -3, 3), (y, -3, 3)), (-x * y, (x, -3, 3), (y, -3, 3))) filename = 'test_surface_multiple_ranges.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() # Single Parametric 3D plot p = plot3d_parametric_surface(sin(x + y), cos(x - y), x - y) filename = 'test_parametric_surface.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() # Multiple Parametric 3D plots. p = plot3d_parametric_surface( (x*sin(z), x*cos(z), z, (x, -5, 5), (z, -5, 5)), (sin(x + y), cos(x - y), x - y, (x, -5, 5), (y, -5, 5))) filename = 'test_parametric_surface.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() # Single Contour plot. p = plot_contour(sin(x)*sin(y), (x, -5, 5), (y, -5, 5)) filename = 'test_contour_plot.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() # Multiple Contour plots with same range. p = plot_contour(x**2 + y**2, x**3 + y**3, (x, -5, 5), (y, -5, 5)) filename = 'test_contour_plot.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() # Multiple Contour plots with different range. p = plot_contour( (x**2 + y**2, (x, -5, 5), (y, -5, 5)), (x**3 + y**3, (x, -3, 3), (y, -3, 3))) filename = 'test_contour_plot.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() def test_plot_and_save_3(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') y = Symbol('y') z = Symbol('z') with TemporaryDirectory(prefix='sympy_') as tmpdir: ### # Examples from the 'colors' notebook ### p = plot(sin(x)) p[0].line_color = lambda a: a filename = 'test_colors_line_arity1.png' p.save(os.path.join(tmpdir, filename)) p[0].line_color = lambda a, b: b filename = 'test_colors_line_arity2.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p = plot(x*sin(x), x*cos(x), (x, 0, 10)) p[0].line_color = lambda a: a filename = 'test_colors_param_line_arity1.png' p.save(os.path.join(tmpdir, filename)) p[0].line_color = lambda a, b: a filename = 'test_colors_param_line_arity1.png' p.save(os.path.join(tmpdir, filename)) p[0].line_color = lambda a, b: b filename = 'test_colors_param_line_arity2b.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p = plot3d_parametric_line(sin(x) + 0.1*sin(x)*cos(7*x), cos(x) + 0.1*cos(x)*cos(7*x), 0.1*sin(7*x), (x, 0, 2*pi)) p[0].line_color = lambdify_(x, sin(4*x)) filename = 'test_colors_3d_line_arity1.png' p.save(os.path.join(tmpdir, filename)) p[0].line_color = lambda a, b: b filename = 'test_colors_3d_line_arity2.png' p.save(os.path.join(tmpdir, filename)) p[0].line_color = lambda a, b, c: c filename = 'test_colors_3d_line_arity3.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p = plot3d(sin(x)*y, (x, 0, 6*pi), (y, -5, 5)) p[0].surface_color = lambda a: a filename = 'test_colors_surface_arity1.png' p.save(os.path.join(tmpdir, filename)) p[0].surface_color = lambda a, b: b filename = 'test_colors_surface_arity2.png' p.save(os.path.join(tmpdir, filename)) p[0].surface_color = lambda a, b, c: c filename = 'test_colors_surface_arity3a.png' p.save(os.path.join(tmpdir, filename)) p[0].surface_color = lambdify_((x, y, z), sqrt((x - 3*pi)**2 + y**2)) filename = 'test_colors_surface_arity3b.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p = plot3d_parametric_surface(x * cos(4 * y), x * sin(4 * y), y, (x, -1, 1), (y, -1, 1)) p[0].surface_color = lambda a: a filename = 'test_colors_param_surf_arity1.png' p.save(os.path.join(tmpdir, filename)) p[0].surface_color = lambda a, b: a*b filename = 'test_colors_param_surf_arity2.png' p.save(os.path.join(tmpdir, filename)) p[0].surface_color = lambdify_((x, y, z), sqrt(x**2 + y**2 + z**2)) filename = 'test_colors_param_surf_arity3.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() def test_plot_and_save_4(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') y = Symbol('y') ### # Examples from the 'advanced' notebook ### # XXX: This raises the warning "The evaluation of the expression is # problematic. We are trying a failback method that may still work. Please # report this as a bug." It has to use the fallback because using evalf() # is the only way to evaluate the integral. We should perhaps just remove # that warning. with TemporaryDirectory(prefix='sympy_') as tmpdir: with warns( UserWarning, match="The evaluation of the expression is problematic"): i = Integral(log((sin(x)**2 + 1)*sqrt(x**2 + 1)), (x, 0, y)) p = plot(i, (y, 1, 5)) filename = 'test_advanced_integral.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() def test_plot_and_save_5(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') y = Symbol('y') with TemporaryDirectory(prefix='sympy_') as tmpdir: s = Sum(1/x**y, (x, 1, oo)) p = plot(s, (y, 2, 10)) filename = 'test_advanced_inf_sum.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p = plot(Sum(1/x, (x, 1, y)), (y, 2, 10), show=False) p[0].only_integers = True p[0].steps = True filename = 'test_advanced_fin_sum.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() def test_plot_and_save_6(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') with TemporaryDirectory(prefix='sympy_') as tmpdir: filename = 'test.png' ### # Test expressions that can not be translated to np and generate complex # results. ### p = plot(sin(x) + I*cos(x)) p.save(os.path.join(tmpdir, filename)) p = plot(sqrt(sqrt(-x))) p.save(os.path.join(tmpdir, filename)) p = plot(LambertW(x)) p.save(os.path.join(tmpdir, filename)) p = plot(sqrt(LambertW(x))) p.save(os.path.join(tmpdir, filename)) #Characteristic function of a StudentT distribution with nu=10 x1 = 5 * x**2 * exp_polar(-I*pi)/2 m1 = meijerg(((1 / 2,), ()), ((5, 0, 1 / 2), ()), x1) x2 = 5*x**2 * exp_polar(I*pi)/2 m2 = meijerg(((1/2,), ()), ((5, 0, 1/2), ()), x2) expr = (m1 + m2) / (48 * pi) p = plot(expr, (x, 1e-6, 1e-2)) p.save(os.path.join(tmpdir, filename)) def test_plotgrid_and_save(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') y = Symbol('y') with TemporaryDirectory(prefix='sympy_') as tmpdir: p1 = plot(x) p2 = plot_parametric((sin(x), cos(x)), (x, sin(x)), show=False) p3 = plot_parametric( cos(x), sin(x), adaptive=False, nb_of_points=500, show=False) p4 = plot3d_parametric_line(sin(x), cos(x), x, show=False) # symmetric grid p = PlotGrid(2, 2, p1, p2, p3, p4) filename = 'test_grid1.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() # grid size greater than the number of subplots p = PlotGrid(3, 4, p1, p2, p3, p4) filename = 'test_grid2.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p5 = plot(cos(x),(x, -pi, pi), show=False) p5[0].line_color = lambda a: a p6 = plot(Piecewise((1, x > 0), (0, True)), (x, -1, 1), show=False) p7 = plot_contour( (x**2 + y**2, (x, -5, 5), (y, -5, 5)), (x**3 + y**3, (x, -3, 3), (y, -3, 3)), show=False) # unsymmetric grid (subplots in one line) p = PlotGrid(1, 3, p5, p6, p7) filename = 'test_grid3.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() def test_append_issue_7140(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') p1 = plot(x) p2 = plot(x**2) plot(x + 2) # append a series p2.append(p1[0]) assert len(p2._series) == 2 with raises(TypeError): p1.append(p2) with raises(TypeError): p1.append(p2._series) def test_issue_15265(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') eqn = sin(x) p = plot(eqn, xlim=(-S.Pi, S.Pi), ylim=(-1, 1)) p._backend.close() p = plot(eqn, xlim=(-1, 1), ylim=(-S.Pi, S.Pi)) p._backend.close() p = plot(eqn, xlim=(-1, 1), ylim=(sympify('-3.14'), sympify('3.14'))) p._backend.close() p = plot(eqn, xlim=(sympify('-3.14'), sympify('3.14')), ylim=(-1, 1)) p._backend.close() raises(ValueError, lambda: plot(eqn, xlim=(-S.ImaginaryUnit, 1), ylim=(-1, 1))) raises(ValueError, lambda: plot(eqn, xlim=(-1, 1), ylim=(-1, S.ImaginaryUnit))) raises(ValueError, lambda: plot(eqn, xlim=(S.NegativeInfinity, 1), ylim=(-1, 1))) raises(ValueError, lambda: plot(eqn, xlim=(-1, 1), ylim=(-1, S.Infinity))) def test_empty_Plot(): if not matplotlib: skip("Matplotlib not the default backend") # No exception showing an empty plot plot() p = Plot() p.show() def test_issue_17405(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') f = x**0.3 - 10*x**3 + x**2 p = plot(f, (x, -10, 10), show=False) # Random number of segments, probably more than 100, but we want to see # that there are segments generated, as opposed to when the bug was present assert len(p[0].get_data()[0]) >= 30 def test_logplot_PR_16796(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') p = plot(x, (x, .001, 100), xscale='log', show=False) # Random number of segments, probably more than 100, but we want to see # that there are segments generated, as opposed to when the bug was present assert len(p[0].get_data()[0]) >= 30 assert p[0].end == 100.0 assert p[0].start == .001 def test_issue_16572(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') p = plot(LambertW(x), show=False) # Random number of segments, probably more than 50, but we want to see # that there are segments generated, as opposed to when the bug was present assert len(p[0].get_data()[0]) >= 30 def test_issue_11865(): if not matplotlib: skip("Matplotlib not the default backend") k = Symbol('k', integer=True) f = Piecewise((-I*exp(I*pi*k)/k + I*exp(-I*pi*k)/k, Ne(k, 0)), (2*pi, True)) p = plot(f, show=False) # Random number of segments, probably more than 100, but we want to see # that there are segments generated, as opposed to when the bug was present # and that there are no exceptions. assert len(p[0].get_data()[0]) >= 30 def test_issue_11461(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') p = plot(real_root((log(x/(x-2))), 3), show=False) # Random number of segments, probably more than 100, but we want to see # that there are segments generated, as opposed to when the bug was present # and that there are no exceptions. assert len(p[0].get_data()[0]) >= 30 def test_issue_11764(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') p = plot_parametric(cos(x), sin(x), (x, 0, 2 * pi), aspect_ratio=(1,1), show=False) p.aspect_ratio == (1, 1) # Random number of segments, probably more than 100, but we want to see # that there are segments generated, as opposed to when the bug was present assert len(p[0].get_data()[0]) >= 30 def test_issue_13516(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') pm = plot(sin(x), backend="matplotlib", show=False) assert pm.backend == MatplotlibBackend assert len(pm[0].get_data()[0]) >= 30 pt = plot(sin(x), backend="text", show=False) assert pt.backend == TextBackend assert len(pt[0].get_data()[0]) >= 30 pd = plot(sin(x), backend="default", show=False) assert pd.backend == DefaultBackend assert len(pd[0].get_data()[0]) >= 30 p = plot(sin(x), show=False) assert p.backend == DefaultBackend assert len(p[0].get_data()[0]) >= 30 def test_plot_limits(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') p = plot(x, x**2, (x, -10, 10)) backend = p._backend xmin, xmax = backend.ax[0].get_xlim() assert abs(xmin + 10) < 2 assert abs(xmax - 10) < 2 ymin, ymax = backend.ax[0].get_ylim() assert abs(ymin + 10) < 10 assert abs(ymax - 100) < 10 def test_plot3d_parametric_line_limits(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') v1 = (2*cos(x), 2*sin(x), 2*x, (x, -5, 5)) v2 = (sin(x), cos(x), x, (x, -5, 5)) p = plot3d_parametric_line(v1, v2) backend = p._backend xmin, xmax = backend.ax[0].get_xlim() assert abs(xmin + 2) < 1e-2 assert abs(xmax - 2) < 1e-2 ymin, ymax = backend.ax[0].get_ylim() assert abs(ymin + 2) < 1e-2 assert abs(ymax - 2) < 1e-2 zmin, zmax = backend.ax[0].get_zlim() assert abs(zmin + 10) < 1e-2 assert abs(zmax - 10) < 1e-2 p = plot3d_parametric_line(v2, v1) backend = p._backend xmin, xmax = backend.ax[0].get_xlim() assert abs(xmin + 2) < 1e-2 assert abs(xmax - 2) < 1e-2 ymin, ymax = backend.ax[0].get_ylim() assert abs(ymin + 2) < 1e-2 assert abs(ymax - 2) < 1e-2 zmin, zmax = backend.ax[0].get_zlim() assert abs(zmin + 10) < 1e-2 assert abs(zmax - 10) < 1e-2 def test_plot_size(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') p1 = plot(sin(x), backend="matplotlib", size=(8, 4)) s1 = p1._backend.fig.get_size_inches() assert (s1[0] == 8) and (s1[1] == 4) p2 = plot(sin(x), backend="matplotlib", size=(5, 10)) s2 = p2._backend.fig.get_size_inches() assert (s2[0] == 5) and (s2[1] == 10) p3 = PlotGrid(2, 1, p1, p2, size=(6, 2)) s3 = p3._backend.fig.get_size_inches() assert (s3[0] == 6) and (s3[1] == 2) with raises(ValueError): plot(sin(x), backend="matplotlib", size=(-1, 3)) def test_issue_20113(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') # verify the capability to use custom backends with raises(TypeError): plot(sin(x), backend=Plot, show=False) p2 = plot(sin(x), backend=MatplotlibBackend, show=False) assert p2.backend == MatplotlibBackend assert len(p2[0].get_data()[0]) >= 30 p3 = plot(sin(x), backend=DummyBackendOk, show=False) assert p3.backend == DummyBackendOk assert len(p3[0].get_data()[0]) >= 30 # test for an improper coded backend p4 = plot(sin(x), backend=DummyBackendNotOk, show=False) assert p4.backend == DummyBackendNotOk assert len(p4[0].get_data()[0]) >= 30 with raises(NotImplementedError): p4.show() with raises(NotImplementedError): p4.save("test/path") with raises(NotImplementedError): p4._backend.close() def test_custom_coloring(): x = Symbol('x') y = Symbol('y') plot(cos(x), line_color=lambda a: a) plot(cos(x), line_color=1) plot(cos(x), line_color="r") plot_parametric(cos(x), sin(x), line_color=lambda a: a) plot_parametric(cos(x), sin(x), line_color=1) plot_parametric(cos(x), sin(x), line_color="r") plot3d_parametric_line(cos(x), sin(x), x, line_color=lambda a: a) plot3d_parametric_line(cos(x), sin(x), x, line_color=1) plot3d_parametric_line(cos(x), sin(x), x, line_color="r") plot3d_parametric_surface(cos(x + y), sin(x - y), x - y, (x, -5, 5), (y, -5, 5), surface_color=lambda a, b: a**2 + b**2) plot3d_parametric_surface(cos(x + y), sin(x - y), x - y, (x, -5, 5), (y, -5, 5), surface_color=1) plot3d_parametric_surface(cos(x + y), sin(x - y), x - y, (x, -5, 5), (y, -5, 5), surface_color="r") plot3d(x*y, (x, -5, 5), (y, -5, 5), surface_color=lambda a, b: a**2 + b**2) plot3d(x*y, (x, -5, 5), (y, -5, 5), surface_color=1) plot3d(x*y, (x, -5, 5), (y, -5, 5), surface_color="r")
03e08c41d7d90378b41fb2c35c558ed281e9760db26a09c4c6fa40a9a62a2668
#!/usr/bin/env python """ Test that from sympy import * doesn't import anything other than SymPy, it's hard dependencies (mpmath), and hard optional dependencies (gmpy2). Importing unnecessary libraries can accidentally add hard dependencies to SymPy in the worst case, or at best slow down the SymPy import time when they are installed. Note, for this test to be effective, every external library that could potentially be imported by SymPy must be installed. TODO: Monkeypatch the importer to detect non-standard library imports even when they aren't installed. Based on code from https://stackoverflow.com/questions/22195382/how-to-check-if-a-module-library-package-is-part-of-the-python-standard-library. """ # These libraries will always be imported with SymPy hard_dependencies = ['mpmath'] # These libraries are optional, but are always imported at SymPy import time # when they are installed. External libraries should only be added to this # list if they are required for core SymPy functionality. hard_optional_dependencies = ['gmpy', 'gmpy2', 'pycosat', 'python-sat'] import sys import os def is_stdlib(p): return ((p.startswith(sys.prefix) or p.startswith(sys.base_prefix)) and 'site-packages' not in p) stdlib = {p for p in sys.path if is_stdlib(p)} existing_modules = list(sys.modules.keys()) # hook in-tree SymPy into Python path, if possible this_path = os.path.abspath(__file__) this_dir = os.path.dirname(this_path) sympy_top = os.path.split(this_dir)[0] sympy_dir = os.path.join(sympy_top, 'sympy') if os.path.isdir(sympy_dir): sys.path.insert(0, sympy_top) def test_external_imports(): exec("from sympy import *", {}) bad = [] for mod in sys.modules: if '.' in mod and mod.split('.')[0] in sys.modules: # Only worry about the top-level modules continue if mod in existing_modules: continue if any(mod == i or mod.startswith(i + '.') for i in ['sympy'] + hard_dependencies + hard_optional_dependencies): continue if mod in sys.builtin_module_names: continue fname = getattr(sys.modules[mod], "__file__", None) if fname is None: bad.append(mod) continue if fname.endswith(('__init__.py', '__init__.pyc', '__init__.pyo')): fname = os.path.dirname(fname) if os.path.dirname(fname) in stdlib: continue bad.append(mod) if bad: raise RuntimeError("""Unexpected external modules found when running 'from sympy import *': """ + '\n '.join(bad)) print("No unexpected external modules were imported with 'from sympy import *'!") if __name__ == '__main__': test_external_imports()
da56bc53a156daed9aa1530f298b5f8b3cda5df377dda470e6cc65163a294916
#!/usr/bin/env python """ Update the ``ask_generated.py`` file. This must be run each time ``known_facts()`` in ``assumptions.facts`` module is changed. Should be run from sympy root directory. $ python bin/ask_update.py """ # hook in-tree SymPy into Python path, if possible import os import sys isympy_path = os.path.abspath(__file__) isympy_dir = os.path.dirname(isympy_path) sympy_top = os.path.split(isympy_dir)[0] sympy_dir = os.path.join(sympy_top, 'sympy') if os.path.isdir(sympy_dir): sys.path.insert(0, sympy_top) from sympy.assumptions.cnf import CNF, Literal from sympy.assumptions.facts import (get_known_facts, generate_known_facts_dict, get_known_facts_keys) from sympy.core import Symbol def generate_code(): from textwrap import dedent, wrap LINE = ",\n " HANG = ' '*8 code_string = dedent('''\ """ Do NOT manually edit this file. Instead, run ./bin/ask_update.py. """ from sympy.assumptions.ask import Q from sympy.assumptions.cnf import Literal from sympy.core.cache import cacheit @cacheit def get_all_known_facts(): """ Known facts between unary predicates as CNF clauses. """ return { %s } @cacheit def get_known_facts_dict(): """ Logical relations between unary predicates as dictionary. Each key is a predicate, and item is two groups of predicates. First group contains the predicates which are implied by the key, and second group contains the predicates which are rejected by the key. """ return { %s } ''') x = Symbol('x') fact = get_known_facts(x) # Generate CNF of facts between known unary predicates cnf = CNF.to_CNF(fact) p = LINE.join(sorted([ 'frozenset((' + ', '.join(str(Literal(lit.arg.function, lit.is_Not)) for lit in sorted(clause, key=str)) + '))' for clause in cnf.clauses])) # Generate dictionary of facts between known unary predicates keys = [pred(x) for pred in get_known_facts_keys()] mapping = generate_known_facts_dict(keys, fact) items = sorted(mapping.items(), key=str) keys = [str(i[0]) for i in items] values = ['(set(%s), set(%s))' % (sorted(i[1][0], key=str), sorted(i[1][1], key=str)) for i in items] m = LINE.join(['\n'.join( wrap("{}: {}".format(k, v), subsequent_indent=HANG, break_long_words=False)) for k, v in zip(keys, values)]) + ',' return code_string % (p, m) with open('sympy/assumptions/ask_generated.py', 'w') as f: code = generate_code() f.write(code)
6ba4ffba65ae8a95846ce3e1836729eb6c1e54ea652aeb4fc52910211f0d367a
""" This module exports all latin and greek letters as Symbols, so you can conveniently do >>> from sympy.abc import x, y instead of the slightly more clunky-looking >>> from sympy import symbols >>> x, y = symbols('x y') Caveats ======= 1. As of the time of writing this, the names ``O``, ``S``, ``I``, ``N``, ``E``, and ``Q`` are colliding with names defined in SymPy. If you import them from both ``sympy.abc`` and ``sympy``, the second import will "win". This is an issue only for * imports, which should only be used for short-lived code such as interactive sessions and throwaway scripts that do not survive until the next SymPy upgrade, where ``sympy`` may contain a different set of names. 2. This module does not define symbol names on demand, i.e. ``from sympy.abc import foo`` will be reported as an error because ``sympy.abc`` does not contain the name ``foo``. To get a symbol named ``foo``, you still need to use ``Symbol('foo')`` or ``symbols('foo')``. You can freely mix usage of ``sympy.abc`` and ``Symbol``/``symbols``, though sticking with one and only one way to get the symbols does tend to make the code more readable. The module also defines some special names to help detect which names clash with the default SymPy namespace. ``_clash1`` defines all the single letter variables that clash with SymPy objects; ``_clash2`` defines the multi-letter clashing symbols; and ``_clash`` is the union of both. These can be passed for ``locals`` during sympification if one desires Symbols rather than the non-Symbol objects for those names. Examples ======== >>> from sympy import S >>> from sympy.abc import _clash1, _clash2, _clash >>> S("Q & C", locals=_clash1) C & Q >>> S('pi(x)', locals=_clash2) pi(x) >>> S('pi(C, Q)', locals=_clash) pi(C, Q) """ from typing import Any, Dict import string from .core import Symbol, symbols from .core.alphabets import greeks ##### Symbol definitions ##### # Implementation note: The easiest way to avoid typos in the symbols() # parameter is to copy it from the left-hand side of the assignment. a, b, c, d, e, f, g, h, i, j = symbols('a, b, c, d, e, f, g, h, i, j') k, l, m, n, o, p, q, r, s, t = symbols('k, l, m, n, o, p, q, r, s, t') u, v, w, x, y, z = symbols('u, v, w, x, y, z') A, B, C, D, E, F, G, H, I, J = symbols('A, B, C, D, E, F, G, H, I, J') K, L, M, N, O, P, Q, R, S, T = symbols('K, L, M, N, O, P, Q, R, S, T') U, V, W, X, Y, Z = symbols('U, V, W, X, Y, Z') alpha, beta, gamma, delta = symbols('alpha, beta, gamma, delta') epsilon, zeta, eta, theta = symbols('epsilon, zeta, eta, theta') iota, kappa, lamda, mu = symbols('iota, kappa, lamda, mu') nu, xi, omicron, pi = symbols('nu, xi, omicron, pi') rho, sigma, tau, upsilon = symbols('rho, sigma, tau, upsilon') phi, chi, psi, omega = symbols('phi, chi, psi, omega') ##### Clashing-symbols diagnostics ##### # We want to know which names in SymPy collide with those in here. # This is mostly for diagnosing SymPy's namespace during SymPy development. _latin = list(string.ascii_letters) # OSINEQ should not be imported as they clash; gamma, pi and zeta clash, too _greek = list(greeks) # make a copy, so we can mutate it # Note: We import lamda since lambda is a reserved keyword in Python _greek.remove("lambda") _greek.append("lamda") ns = {} # type: Dict[str, Any] exec('from sympy import *', ns) _clash1 = {} _clash2 = {} while ns: _k, _ = ns.popitem() if _k in _greek: _clash2[_k] = None _greek.remove(_k) elif _k in _latin: _clash1[_k] = None _latin.remove(_k) _clash = {} _clash.update(_clash1) _clash.update(_clash2) del _latin, _greek, Symbol, _k
c9de18437fc320445f244969f2153afb86f086fe2c2066f13314839df0cd11f9
""" Continuous Random Variables - Prebuilt variables Contains ======== Arcsin Benini Beta BetaNoncentral BetaPrime BoundedPareto Cauchy Chi ChiNoncentral ChiSquared Dagum Erlang ExGaussian Exponential ExponentialPower FDistribution FisherZ Frechet Gamma GammaInverse Gumbel Gompertz Kumaraswamy Laplace Levy LogCauchy Logistic LogLogistic LogitNormal LogNormal Lomax Maxwell Moyal Nakagami Normal Pareto PowerFunction QuadraticU RaisedCosine Rayleigh Reciprocal ShiftedGompertz StudentT Trapezoidal Triangular Uniform UniformSum VonMises Wald Weibull WignerSemicircle """ from sympy import beta as beta_fn from sympy import cos, sin, tan, atan, exp, besseli, besselj, besselk from sympy import (log, sqrt, pi, S, Dummy, Interval, sympify, gamma, sign, Piecewise, And, Eq, binomial, factorial, Sum, floor, Abs, Lambda, Basic, lowergamma, erf, erfc, erfi, erfinv, I, asin, hyper, uppergamma, sinh, Ne, expint, Rational, integrate) from sympy.matrices import MatrixBase, MatrixExpr from sympy.stats.crv import SingleContinuousPSpace, SingleContinuousDistribution from sympy.stats.rv import _value_check, is_random oo = S.Infinity __all__ = ['ContinuousRV', 'Arcsin', 'Benini', 'Beta', 'BetaNoncentral', 'BetaPrime', 'BoundedPareto', 'Cauchy', 'Chi', 'ChiNoncentral', 'ChiSquared', 'Dagum', 'Erlang', 'ExGaussian', 'Exponential', 'ExponentialPower', 'FDistribution', 'FisherZ', 'Frechet', 'Gamma', 'GammaInverse', 'Gompertz', 'Gumbel', 'Kumaraswamy', 'Laplace', 'Levy', 'LogCauchy', 'Logistic', 'LogLogistic', 'LogitNormal', 'LogNormal', 'Lomax', 'Maxwell', 'Moyal', 'Nakagami', 'Normal', 'GaussianInverse', 'Pareto', 'PowerFunction', 'QuadraticU', 'RaisedCosine', 'Rayleigh', 'Reciprocal', 'StudentT', 'ShiftedGompertz', 'Trapezoidal', 'Triangular', 'Uniform', 'UniformSum', 'VonMises', 'Wald', 'Weibull', 'WignerSemicircle', ] @is_random.register(MatrixBase) def _(x): return any([is_random(i) for i in x]) def rv(symbol, cls, args, **kwargs): args = list(map(sympify, args)) dist = cls(*args) if kwargs.pop('check', True): dist.check(*args) pspace = SingleContinuousPSpace(symbol, dist) if any(is_random(arg) for arg in args): from sympy.stats.compound_rv import CompoundPSpace, CompoundDistribution pspace = CompoundPSpace(symbol, CompoundDistribution(dist)) return pspace.value class ContinuousDistributionHandmade(SingleContinuousDistribution): _argnames = ('pdf',) def __new__(cls, pdf, set=Interval(-oo, oo)): return Basic.__new__(cls, pdf, set) @property def set(self): return self.args[1] @staticmethod def check(pdf, set): x = Dummy('x') val = integrate(pdf(x), (x, set)) _value_check(Eq(val, 1) != S.false, "The pdf on the given set is incorrect.") def ContinuousRV(symbol, density, set=Interval(-oo, oo), **kwargs): """ Create a Continuous Random Variable given the following: Parameters ========== symbol : Symbol Represents name of the random variable. density : Expression containing symbol Represents probability density function. set : set/Interval Represents the region where the pdf is valid, by default is real line. check : bool If True, it will check whether the given density integrates to 1 over the given set. If False, it will not perform this check. Default is False. Returns ======= RandomSymbol Many common continuous random variable types are already implemented. This function should be necessary only very rarely. Examples ======== >>> from sympy import Symbol, sqrt, exp, pi >>> from sympy.stats import ContinuousRV, P, E >>> x = Symbol("x") >>> pdf = sqrt(2)*exp(-x**2/2)/(2*sqrt(pi)) # Normal distribution >>> X = ContinuousRV(x, pdf) >>> E(X) 0 >>> P(X>0) 1/2 """ pdf = Piecewise((density, set.as_relational(symbol)), (0, True)) pdf = Lambda(symbol, pdf) # have a default of False while `rv` should have a default of True kwargs['check'] = kwargs.pop('check', False) return rv(symbol.name, ContinuousDistributionHandmade, (pdf, set), **kwargs) ######################################## # Continuous Probability Distributions # ######################################## #------------------------------------------------------------------------------- # Arcsin distribution ---------------------------------------------------------- class ArcsinDistribution(SingleContinuousDistribution): _argnames = ('a', 'b') @property def set(self): return Interval(self.a, self.b) def pdf(self, x): a, b = self.a, self.b return 1/(pi*sqrt((x - a)*(b - x))) def _cdf(self, x): a, b = self.a, self.b return Piecewise( (S.Zero, x < a), (2*asin(sqrt((x - a)/(b - a)))/pi, x <= b), (S.One, True)) def Arcsin(name, a=0, b=1): r""" Create a Continuous Random Variable with an arcsin distribution. The density of the arcsin distribution is given by .. math:: f(x) := \frac{1}{\pi\sqrt{(x-a)(b-x)}} with :math:`x \in (a,b)`. It must hold that :math:`-\infty < a < b < \infty`. Parameters ========== a : Real number, the left interval boundary b : Real number, the right interval boundary Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Arcsin, density, cdf >>> from sympy import Symbol >>> a = Symbol("a", real=True) >>> b = Symbol("b", real=True) >>> z = Symbol("z") >>> X = Arcsin("x", a, b) >>> density(X)(z) 1/(pi*sqrt((-a + z)*(b - z))) >>> cdf(X)(z) Piecewise((0, a > z), (2*asin(sqrt((-a + z)/(-a + b)))/pi, b >= z), (1, True)) References ========== .. [1] https://en.wikipedia.org/wiki/Arcsine_distribution """ return rv(name, ArcsinDistribution, (a, b)) #------------------------------------------------------------------------------- # Benini distribution ---------------------------------------------------------- class BeniniDistribution(SingleContinuousDistribution): _argnames = ('alpha', 'beta', 'sigma') @staticmethod def check(alpha, beta, sigma): _value_check(alpha > 0, "Shape parameter Alpha must be positive.") _value_check(beta > 0, "Shape parameter Beta must be positive.") _value_check(sigma > 0, "Scale parameter Sigma must be positive.") @property def set(self): return Interval(self.sigma, oo) def pdf(self, x): alpha, beta, sigma = self.alpha, self.beta, self.sigma return (exp(-alpha*log(x/sigma) - beta*log(x/sigma)**2) *(alpha/x + 2*beta*log(x/sigma)/x)) def _moment_generating_function(self, t): raise NotImplementedError('The moment generating function of the ' 'Benini distribution does not exist.') def Benini(name, alpha, beta, sigma): r""" Create a Continuous Random Variable with a Benini distribution. The density of the Benini distribution is given by .. math:: f(x) := e^{-\alpha\log{\frac{x}{\sigma}} -\beta\log^2\left[{\frac{x}{\sigma}}\right]} \left(\frac{\alpha}{x}+\frac{2\beta\log{\frac{x}{\sigma}}}{x}\right) This is a heavy-tailed distribution and is also known as the log-Rayleigh distribution. Parameters ========== alpha : Real number, `\alpha > 0`, a shape beta : Real number, `\beta > 0`, a shape sigma : Real number, `\sigma > 0`, a scale Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Benini, density, cdf >>> from sympy import Symbol, pprint >>> alpha = Symbol("alpha", positive=True) >>> beta = Symbol("beta", positive=True) >>> sigma = Symbol("sigma", positive=True) >>> z = Symbol("z") >>> X = Benini("x", alpha, beta, sigma) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) / / z \\ / z \ 2/ z \ | 2*beta*log|-----|| - alpha*log|-----| - beta*log |-----| |alpha \sigma/| \sigma/ \sigma/ |----- + -----------------|*e \ z z / >>> cdf(X)(z) Piecewise((1 - exp(-alpha*log(z/sigma) - beta*log(z/sigma)**2), sigma <= z), (0, True)) References ========== .. [1] https://en.wikipedia.org/wiki/Benini_distribution .. [2] http://reference.wolfram.com/legacy/v8/ref/BeniniDistribution.html """ return rv(name, BeniniDistribution, (alpha, beta, sigma)) #------------------------------------------------------------------------------- # Beta distribution ------------------------------------------------------------ class BetaDistribution(SingleContinuousDistribution): _argnames = ('alpha', 'beta') set = Interval(0, 1) @staticmethod def check(alpha, beta): _value_check(alpha > 0, "Shape parameter Alpha must be positive.") _value_check(beta > 0, "Shape parameter Beta must be positive.") def pdf(self, x): alpha, beta = self.alpha, self.beta return x**(alpha - 1) * (1 - x)**(beta - 1) / beta_fn(alpha, beta) def _characteristic_function(self, t): return hyper((self.alpha,), (self.alpha + self.beta,), I*t) def _moment_generating_function(self, t): return hyper((self.alpha,), (self.alpha + self.beta,), t) def Beta(name, alpha, beta): r""" Create a Continuous Random Variable with a Beta distribution. The density of the Beta distribution is given by .. math:: f(x) := \frac{x^{\alpha-1}(1-x)^{\beta-1}} {\mathrm{B}(\alpha,\beta)} with :math:`x \in [0,1]`. Parameters ========== alpha : Real number, `\alpha > 0`, a shape beta : Real number, `\beta > 0`, a shape Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Beta, density, E, variance >>> from sympy import Symbol, simplify, pprint, factor >>> alpha = Symbol("alpha", positive=True) >>> beta = Symbol("beta", positive=True) >>> z = Symbol("z") >>> X = Beta("x", alpha, beta) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) alpha - 1 beta - 1 z *(1 - z) -------------------------- B(alpha, beta) >>> simplify(E(X)) alpha/(alpha + beta) >>> factor(simplify(variance(X))) alpha*beta/((alpha + beta)**2*(alpha + beta + 1)) References ========== .. [1] https://en.wikipedia.org/wiki/Beta_distribution .. [2] http://mathworld.wolfram.com/BetaDistribution.html """ return rv(name, BetaDistribution, (alpha, beta)) #------------------------------------------------------------------------------- # Noncentral Beta distribution ------------------------------------------------------------ class BetaNoncentralDistribution(SingleContinuousDistribution): _argnames = ('alpha', 'beta', 'lamda') set = Interval(0, 1) @staticmethod def check(alpha, beta, lamda): _value_check(alpha > 0, "Shape parameter Alpha must be positive.") _value_check(beta > 0, "Shape parameter Beta must be positive.") _value_check(lamda >= 0, "Noncentrality parameter Lambda must be positive") def pdf(self, x): alpha, beta, lamda = self.alpha, self.beta, self.lamda k = Dummy("k") return Sum(exp(-lamda / 2) * (lamda / 2)**k * x**(alpha + k - 1) *( 1 - x)**(beta - 1) / (factorial(k) * beta_fn(alpha + k, beta)), (k, 0, oo)) def BetaNoncentral(name, alpha, beta, lamda): r""" Create a Continuous Random Variable with a Type I Noncentral Beta distribution. The density of the Noncentral Beta distribution is given by .. math:: f(x) := \sum_{k=0}^\infty e^{-\lambda/2}\frac{(\lambda/2)^k}{k!} \frac{x^{\alpha+k-1}(1-x)^{\beta-1}}{\mathrm{B}(\alpha+k,\beta)} with :math:`x \in [0,1]`. Parameters ========== alpha : Real number, `\alpha > 0`, a shape beta : Real number, `\beta > 0`, a shape lamda: Real number, `\lambda >= 0`, noncentrality parameter Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import BetaNoncentral, density, cdf >>> from sympy import Symbol, pprint >>> alpha = Symbol("alpha", positive=True) >>> beta = Symbol("beta", positive=True) >>> lamda = Symbol("lamda", nonnegative=True) >>> z = Symbol("z") >>> X = BetaNoncentral("x", alpha, beta, lamda) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) oo _____ \ ` \ -lamda \ k ------- \ k + alpha - 1 /lamda\ beta - 1 2 ) z *|-----| *(1 - z) *e / \ 2 / / ------------------------------------------------ / B(k + alpha, beta)*k! /____, k = 0 Compute cdf with specific 'x', 'alpha', 'beta' and 'lamda' values as follows : >>> cdf(BetaNoncentral("x", 1, 1, 1), evaluate=False)(2).doit() 2*exp(1/2) The argument evaluate=False prevents an attempt at evaluation of the sum for general x, before the argument 2 is passed. References ========== .. [1] https://en.wikipedia.org/wiki/Noncentral_beta_distribution .. [2] https://reference.wolfram.com/language/ref/NoncentralBetaDistribution.html """ return rv(name, BetaNoncentralDistribution, (alpha, beta, lamda)) #------------------------------------------------------------------------------- # Beta prime distribution ------------------------------------------------------ class BetaPrimeDistribution(SingleContinuousDistribution): _argnames = ('alpha', 'beta') @staticmethod def check(alpha, beta): _value_check(alpha > 0, "Shape parameter Alpha must be positive.") _value_check(beta > 0, "Shape parameter Beta must be positive.") set = Interval(0, oo) def pdf(self, x): alpha, beta = self.alpha, self.beta return x**(alpha - 1)*(1 + x)**(-alpha - beta)/beta_fn(alpha, beta) def BetaPrime(name, alpha, beta): r""" Create a continuous random variable with a Beta prime distribution. The density of the Beta prime distribution is given by .. math:: f(x) := \frac{x^{\alpha-1} (1+x)^{-\alpha -\beta}}{B(\alpha,\beta)} with :math:`x > 0`. Parameters ========== alpha : Real number, `\alpha > 0`, a shape beta : Real number, `\beta > 0`, a shape Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import BetaPrime, density >>> from sympy import Symbol, pprint >>> alpha = Symbol("alpha", positive=True) >>> beta = Symbol("beta", positive=True) >>> z = Symbol("z") >>> X = BetaPrime("x", alpha, beta) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) alpha - 1 -alpha - beta z *(z + 1) ------------------------------- B(alpha, beta) References ========== .. [1] https://en.wikipedia.org/wiki/Beta_prime_distribution .. [2] http://mathworld.wolfram.com/BetaPrimeDistribution.html """ return rv(name, BetaPrimeDistribution, (alpha, beta)) #------------------------------------------------------------------------------- # Bounded Pareto Distribution -------------------------------------------------- class BoundedParetoDistribution(SingleContinuousDistribution): _argnames = ('alpha', 'left', 'right') @property def set(self): return Interval(self.left , self.right) @staticmethod def check(alpha, left, right): _value_check (alpha.is_positive, "Shape must be positive.") _value_check (left.is_positive, "Left value should be positive.") _value_check (right > left, "Right should be greater than left.") def pdf(self, x): alpha, left, right = self.alpha, self.left, self.right num = alpha * (left**alpha) * x**(- alpha -1) den = 1 - (left/right)**alpha return num/den def BoundedPareto(name, alpha, left, right): r""" Create a continuous random variable with a Bounded Pareto distribution. The density of the Bounded Pareto distribution is given by .. math:: f(x) := \frac{\alpha L^{\alpha}x^{-\alpha-1}}{1-(\frac{L}{H})^{\alpha}} Parameters ========== alpha : Real Number, `alpha > 0` Shape parameter left : Real Number, `left > 0` Location parameter right : Real Number, `right > left` Location parameter Examples ======== >>> from sympy.stats import BoundedPareto, density, cdf, E >>> from sympy import symbols >>> L, H = symbols('L, H', positive=True) >>> X = BoundedPareto('X', 2, L, H) >>> x = symbols('x') >>> density(X)(x) 2*L**2/(x**3*(1 - L**2/H**2)) >>> cdf(X)(x) Piecewise((-H**2*L**2/(x**2*(H**2 - L**2)) + H**2/(H**2 - L**2), L <= x), (0, True)) >>> E(X).simplify() 2*H*L/(H + L) Returns ======= RandomSymbol References ========== .. [1] https://en.wikipedia.org/wiki/Pareto_distribution#Bounded_Pareto_distribution """ return rv (name, BoundedParetoDistribution, (alpha, left, right)) # ------------------------------------------------------------------------------ # Cauchy distribution ---------------------------------------------------------- class CauchyDistribution(SingleContinuousDistribution): _argnames = ('x0', 'gamma') @staticmethod def check(x0, gamma): _value_check(gamma > 0, "Scale parameter Gamma must be positive.") _value_check(x0.is_real, "Location parameter must be real.") def pdf(self, x): return 1/(pi*self.gamma*(1 + ((x - self.x0)/self.gamma)**2)) def _cdf(self, x): x0, gamma = self.x0, self.gamma return (1/pi)*atan((x - x0)/gamma) + S.Half def _characteristic_function(self, t): return exp(self.x0 * I * t - self.gamma * Abs(t)) def _moment_generating_function(self, t): raise NotImplementedError("The moment generating function for the " "Cauchy distribution does not exist.") def _quantile(self, p): return self.x0 + self.gamma*tan(pi*(p - S.Half)) def Cauchy(name, x0, gamma): r""" Create a continuous random variable with a Cauchy distribution. The density of the Cauchy distribution is given by .. math:: f(x) := \frac{1}{\pi \gamma [1 + {(\frac{x-x_0}{\gamma})}^2]} Parameters ========== x0 : Real number, the location gamma : Real number, `\gamma > 0`, a scale Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Cauchy, density >>> from sympy import Symbol >>> x0 = Symbol("x0") >>> gamma = Symbol("gamma", positive=True) >>> z = Symbol("z") >>> X = Cauchy("x", x0, gamma) >>> density(X)(z) 1/(pi*gamma*(1 + (-x0 + z)**2/gamma**2)) References ========== .. [1] https://en.wikipedia.org/wiki/Cauchy_distribution .. [2] http://mathworld.wolfram.com/CauchyDistribution.html """ return rv(name, CauchyDistribution, (x0, gamma)) #------------------------------------------------------------------------------- # Chi distribution ------------------------------------------------------------- class ChiDistribution(SingleContinuousDistribution): _argnames = ('k',) @staticmethod def check(k): _value_check(k > 0, "Number of degrees of freedom (k) must be positive.") _value_check(k.is_integer, "Number of degrees of freedom (k) must be an integer.") set = Interval(0, oo) def pdf(self, x): return 2**(1 - self.k/2)*x**(self.k - 1)*exp(-x**2/2)/gamma(self.k/2) def _characteristic_function(self, t): k = self.k part_1 = hyper((k/2,), (S.Half,), -t**2/2) part_2 = I*t*sqrt(2)*gamma((k+1)/2)/gamma(k/2) part_3 = hyper(((k+1)/2,), (Rational(3, 2),), -t**2/2) return part_1 + part_2*part_3 def _moment_generating_function(self, t): k = self.k part_1 = hyper((k / 2,), (S.Half,), t ** 2 / 2) part_2 = t * sqrt(2) * gamma((k + 1) / 2) / gamma(k / 2) part_3 = hyper(((k + 1) / 2,), (S(3) / 2,), t ** 2 / 2) return part_1 + part_2 * part_3 def Chi(name, k): r""" Create a continuous random variable with a Chi distribution. The density of the Chi distribution is given by .. math:: f(x) := \frac{2^{1-k/2}x^{k-1}e^{-x^2/2}}{\Gamma(k/2)} with :math:`x \geq 0`. Parameters ========== k : Positive integer, The number of degrees of freedom Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Chi, density, E >>> from sympy import Symbol, simplify >>> k = Symbol("k", integer=True) >>> z = Symbol("z") >>> X = Chi("x", k) >>> density(X)(z) 2**(1 - k/2)*z**(k - 1)*exp(-z**2/2)/gamma(k/2) >>> simplify(E(X)) sqrt(2)*gamma(k/2 + 1/2)/gamma(k/2) References ========== .. [1] https://en.wikipedia.org/wiki/Chi_distribution .. [2] http://mathworld.wolfram.com/ChiDistribution.html """ return rv(name, ChiDistribution, (k,)) #------------------------------------------------------------------------------- # Non-central Chi distribution ------------------------------------------------- class ChiNoncentralDistribution(SingleContinuousDistribution): _argnames = ('k', 'l') @staticmethod def check(k, l): _value_check(k > 0, "Number of degrees of freedom (k) must be positive.") _value_check(k.is_integer, "Number of degrees of freedom (k) must be an integer.") _value_check(l > 0, "Shift parameter Lambda must be positive.") set = Interval(0, oo) def pdf(self, x): k, l = self.k, self.l return exp(-(x**2+l**2)/2)*x**k*l / (l*x)**(k/2) * besseli(k/2-1, l*x) def ChiNoncentral(name, k, l): r""" Create a continuous random variable with a non-central Chi distribution. Explanation =========== The density of the non-central Chi distribution is given by .. math:: f(x) := \frac{e^{-(x^2+\lambda^2)/2} x^k\lambda} {(\lambda x)^{k/2}} I_{k/2-1}(\lambda x) with `x \geq 0`. Here, `I_\nu (x)` is the :ref:`modified Bessel function of the first kind <besseli>`. Parameters ========== k : A positive Integer, $k > 0$ The number of degrees of freedom. lambda : Real number, `\lambda > 0` Shift parameter. Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import ChiNoncentral, density >>> from sympy import Symbol >>> k = Symbol("k", integer=True) >>> l = Symbol("l") >>> z = Symbol("z") >>> X = ChiNoncentral("x", k, l) >>> density(X)(z) l*z**k*exp(-l**2/2 - z**2/2)*besseli(k/2 - 1, l*z)/(l*z)**(k/2) References ========== .. [1] https://en.wikipedia.org/wiki/Noncentral_chi_distribution """ return rv(name, ChiNoncentralDistribution, (k, l)) #------------------------------------------------------------------------------- # Chi squared distribution ----------------------------------------------------- class ChiSquaredDistribution(SingleContinuousDistribution): _argnames = ('k',) @staticmethod def check(k): _value_check(k > 0, "Number of degrees of freedom (k) must be positive.") _value_check(k.is_integer, "Number of degrees of freedom (k) must be an integer.") set = Interval(0, oo) def pdf(self, x): k = self.k return 1/(2**(k/2)*gamma(k/2))*x**(k/2 - 1)*exp(-x/2) def _cdf(self, x): k = self.k return Piecewise( (S.One/gamma(k/2)*lowergamma(k/2, x/2), x >= 0), (0, True) ) def _characteristic_function(self, t): return (1 - 2*I*t)**(-self.k/2) def _moment_generating_function(self, t): return (1 - 2*t)**(-self.k/2) def ChiSquared(name, k): r""" Create a continuous random variable with a Chi-squared distribution. Explanation =========== The density of the Chi-squared distribution is given by .. math:: f(x) := \frac{1}{2^{\frac{k}{2}}\Gamma\left(\frac{k}{2}\right)} x^{\frac{k}{2}-1} e^{-\frac{x}{2}} with :math:`x \geq 0`. Parameters ========== k : Positive integer The number of degrees of freedom. Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import ChiSquared, density, E, variance, moment >>> from sympy import Symbol >>> k = Symbol("k", integer=True, positive=True) >>> z = Symbol("z") >>> X = ChiSquared("x", k) >>> density(X)(z) z**(k/2 - 1)*exp(-z/2)/(2**(k/2)*gamma(k/2)) >>> E(X) k >>> variance(X) 2*k >>> moment(X, 3) k**3 + 6*k**2 + 8*k References ========== .. [1] https://en.wikipedia.org/wiki/Chi_squared_distribution .. [2] http://mathworld.wolfram.com/Chi-SquaredDistribution.html """ return rv(name, ChiSquaredDistribution, (k, )) #------------------------------------------------------------------------------- # Dagum distribution ----------------------------------------------------------- class DagumDistribution(SingleContinuousDistribution): _argnames = ('p', 'a', 'b') set = Interval(0, oo) @staticmethod def check(p, a, b): _value_check(p > 0, "Shape parameter p must be positive.") _value_check(a > 0, "Shape parameter a must be positive.") _value_check(b > 0, "Scale parameter b must be positive.") def pdf(self, x): p, a, b = self.p, self.a, self.b return a*p/x*((x/b)**(a*p)/(((x/b)**a + 1)**(p + 1))) def _cdf(self, x): p, a, b = self.p, self.a, self.b return Piecewise(((S.One + (S(x)/b)**-a)**-p, x>=0), (S.Zero, True)) def Dagum(name, p, a, b): r""" Create a continuous random variable with a Dagum distribution. Explanation =========== The density of the Dagum distribution is given by .. math:: f(x) := \frac{a p}{x} \left( \frac{\left(\tfrac{x}{b}\right)^{a p}} {\left(\left(\tfrac{x}{b}\right)^a + 1 \right)^{p+1}} \right) with :math:`x > 0`. Parameters ========== p : Real number ``p > 0``, a shape. a : Real number ``a > 0``, a shape. b : Real number ``b > 0``, a scale. Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Dagum, density, cdf >>> from sympy import Symbol >>> p = Symbol("p", positive=True) >>> a = Symbol("a", positive=True) >>> b = Symbol("b", positive=True) >>> z = Symbol("z") >>> X = Dagum("x", p, a, b) >>> density(X)(z) a*p*(z/b)**(a*p)*((z/b)**a + 1)**(-p - 1)/z >>> cdf(X)(z) Piecewise(((1 + (z/b)**(-a))**(-p), z >= 0), (0, True)) References ========== .. [1] https://en.wikipedia.org/wiki/Dagum_distribution """ return rv(name, DagumDistribution, (p, a, b)) #------------------------------------------------------------------------------- # Erlang distribution ---------------------------------------------------------- def Erlang(name, k, l): r""" Create a continuous random variable with an Erlang distribution. Explanation =========== The density of the Erlang distribution is given by .. math:: f(x) := \frac{\lambda^k x^{k-1} e^{-\lambda x}}{(k-1)!} with :math:`x \in [0,\infty]`. Parameters ========== k : Positive integer l : Real number, `\lambda > 0`, the rate Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Erlang, density, cdf, E, variance >>> from sympy import Symbol, simplify, pprint >>> k = Symbol("k", integer=True, positive=True) >>> l = Symbol("l", positive=True) >>> z = Symbol("z") >>> X = Erlang("x", k, l) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) k k - 1 -l*z l *z *e --------------- Gamma(k) >>> C = cdf(X)(z) >>> pprint(C, use_unicode=False) /lowergamma(k, l*z) |------------------ for z > 0 < Gamma(k) | \ 0 otherwise >>> E(X) k/l >>> simplify(variance(X)) k/l**2 References ========== .. [1] https://en.wikipedia.org/wiki/Erlang_distribution .. [2] http://mathworld.wolfram.com/ErlangDistribution.html """ return rv(name, GammaDistribution, (k, S.One/l)) # ------------------------------------------------------------------------------- # ExGaussian distribution ----------------------------------------------------- class ExGaussianDistribution(SingleContinuousDistribution): _argnames = ('mean', 'std', 'rate') set = Interval(-oo, oo) @staticmethod def check(mean, std, rate): _value_check( std > 0, "Standard deviation of ExGaussian must be positive.") _value_check(rate > 0, "Rate of ExGaussian must be positive.") def pdf(self, x): mean, std, rate = self.mean, self.std, self.rate term1 = rate/2 term2 = exp(rate * (2 * mean + rate * std**2 - 2*x)/2) term3 = erfc((mean + rate*std**2 - x)/(sqrt(2)*std)) return term1*term2*term3 def _cdf(self, x): from sympy.stats import cdf mean, std, rate = self.mean, self.std, self.rate u = rate*(x - mean) v = rate*std GaussianCDF1 = cdf(Normal('x', 0, v))(u) GaussianCDF2 = cdf(Normal('x', v**2, v))(u) return GaussianCDF1 - exp(-u + (v**2/2) + log(GaussianCDF2)) def _characteristic_function(self, t): mean, std, rate = self.mean, self.std, self.rate term1 = (1 - I*t/rate)**(-1) term2 = exp(I*mean*t - std**2*t**2/2) return term1 * term2 def _moment_generating_function(self, t): mean, std, rate = self.mean, self.std, self.rate term1 = (1 - t/rate)**(-1) term2 = exp(mean*t + std**2*t**2/2) return term1*term2 def ExGaussian(name, mean, std, rate): r""" Create a continuous random variable with an Exponentially modified Gaussian (EMG) distribution. Explanation =========== The density of the exponentially modified Gaussian distribution is given by .. math:: f(x) := \frac{\lambda}{2}e^{\frac{\lambda}{2}(2\mu+\lambda\sigma^2-2x)} \text{erfc}(\frac{\mu + \lambda\sigma^2 - x}{\sqrt{2}\sigma}) with $x > 0$. Note that the expected value is `1/\lambda`. Parameters ========== mu : A Real number, the mean of Gaussian component std: A positive Real number, :math: `\sigma^2 > 0` the variance of Gaussian component lambda: A positive Real number, :math: `\lambda > 0` the rate of Exponential component Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import ExGaussian, density, cdf, E >>> from sympy.stats import variance, skewness >>> from sympy import Symbol, pprint, simplify >>> mean = Symbol("mu") >>> std = Symbol("sigma", positive=True) >>> rate = Symbol("lamda", positive=True) >>> z = Symbol("z") >>> X = ExGaussian("x", mean, std, rate) >>> pprint(density(X)(z), use_unicode=False) / 2 \ lamda*\lamda*sigma + 2*mu - 2*z/ --------------------------------- / ___ / 2 \\ 2 |\/ 2 *\lamda*sigma + mu - z/| lamda*e *erfc|-----------------------------| \ 2*sigma / ---------------------------------------------------------------------------- 2 >>> cdf(X)(z) -(erf(sqrt(2)*(-lamda**2*sigma**2 + lamda*(-mu + z))/(2*lamda*sigma))/2 + 1/2)*exp(lamda**2*sigma**2/2 - lamda*(-mu + z)) + erf(sqrt(2)*(-mu + z)/(2*sigma))/2 + 1/2 >>> E(X) (lamda*mu + 1)/lamda >>> simplify(variance(X)) sigma**2 + lamda**(-2) >>> simplify(skewness(X)) 2/(lamda**2*sigma**2 + 1)**(3/2) References ========== .. [1] https://en.wikipedia.org/wiki/Exponentially_modified_Gaussian_distribution """ return rv(name, ExGaussianDistribution, (mean, std, rate)) #------------------------------------------------------------------------------- # Exponential distribution ----------------------------------------------------- class ExponentialDistribution(SingleContinuousDistribution): _argnames = ('rate',) set = Interval(0, oo) @staticmethod def check(rate): _value_check(rate > 0, "Rate must be positive.") def pdf(self, x): return self.rate * exp(-self.rate*x) def _cdf(self, x): return Piecewise( (S.One - exp(-self.rate*x), x >= 0), (0, True), ) def _characteristic_function(self, t): rate = self.rate return rate / (rate - I*t) def _moment_generating_function(self, t): rate = self.rate return rate / (rate - t) def _quantile(self, p): return -log(1-p)/self.rate def Exponential(name, rate): r""" Create a continuous random variable with an Exponential distribution. Explanation =========== The density of the exponential distribution is given by .. math:: f(x) := \lambda \exp(-\lambda x) with $x > 0$. Note that the expected value is `1/\lambda`. Parameters ========== rate : A positive Real number, `\lambda > 0`, the rate (or inverse scale/inverse mean) Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Exponential, density, cdf, E >>> from sympy.stats import variance, std, skewness, quantile >>> from sympy import Symbol >>> l = Symbol("lambda", positive=True) >>> z = Symbol("z") >>> p = Symbol("p") >>> X = Exponential("x", l) >>> density(X)(z) lambda*exp(-lambda*z) >>> cdf(X)(z) Piecewise((1 - exp(-lambda*z), z >= 0), (0, True)) >>> quantile(X)(p) -log(1 - p)/lambda >>> E(X) 1/lambda >>> variance(X) lambda**(-2) >>> skewness(X) 2 >>> X = Exponential('x', 10) >>> density(X)(z) 10*exp(-10*z) >>> E(X) 1/10 >>> std(X) 1/10 References ========== .. [1] https://en.wikipedia.org/wiki/Exponential_distribution .. [2] http://mathworld.wolfram.com/ExponentialDistribution.html """ return rv(name, ExponentialDistribution, (rate, )) # ------------------------------------------------------------------------------- # Exponential Power distribution ----------------------------------------------------- class ExponentialPowerDistribution(SingleContinuousDistribution): _argnames = ('mu', 'alpha', 'beta') set = Interval(-oo, oo) @staticmethod def check(mu, alpha, beta): _value_check(alpha > 0, "Scale parameter alpha must be positive.") _value_check(beta > 0, "Shape parameter beta must be positive.") def pdf(self, x): mu, alpha, beta = self.mu, self.alpha, self.beta num = beta*exp(-(Abs(x - mu)/alpha)**beta) den = 2*alpha*gamma(1/beta) return num/den def _cdf(self, x): mu, alpha, beta = self.mu, self.alpha, self.beta num = lowergamma(1/beta, (Abs(x - mu) / alpha)**beta) den = 2*gamma(1/beta) return sign(x - mu)*num/den + S.Half def ExponentialPower(name, mu, alpha, beta): r""" Create a Continuous Random Variable with Exponential Power distribution. This distribution is known also as Generalized Normal distribution version 1. Explanation =========== The density of the Exponential Power distribution is given by .. math:: f(x) := \frac{\beta}{2\alpha\Gamma(\frac{1}{\beta})} e^{{-(\frac{|x - \mu|}{\alpha})^{\beta}}} with :math:`x \in [ - \infty, \infty ]`. Parameters ========== mu : Real number A location. alpha : Real number,``alpha > 0`` A scale. beta : Real number, ``beta > 0`` A shape. Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import ExponentialPower, density, cdf >>> from sympy import Symbol, pprint >>> z = Symbol("z") >>> mu = Symbol("mu") >>> alpha = Symbol("alpha", positive=True) >>> beta = Symbol("beta", positive=True) >>> X = ExponentialPower("x", mu, alpha, beta) >>> pprint(density(X)(z), use_unicode=False) beta /|mu - z|\ -|--------| \ alpha / beta*e --------------------- / 1 \ 2*alpha*Gamma|----| \beta/ >>> cdf(X)(z) 1/2 + lowergamma(1/beta, (Abs(mu - z)/alpha)**beta)*sign(-mu + z)/(2*gamma(1/beta)) References ========== .. [1] https://reference.wolfram.com/language/ref/ExponentialPowerDistribution.html .. [2] https://en.wikipedia.org/wiki/Generalized_normal_distribution#Version_1 """ return rv(name, ExponentialPowerDistribution, (mu, alpha, beta)) #------------------------------------------------------------------------------- # F distribution --------------------------------------------------------------- class FDistributionDistribution(SingleContinuousDistribution): _argnames = ('d1', 'd2') set = Interval(0, oo) @staticmethod def check(d1, d2): _value_check((d1 > 0, d1.is_integer), "Degrees of freedom d1 must be positive integer.") _value_check((d2 > 0, d2.is_integer), "Degrees of freedom d2 must be positive integer.") def pdf(self, x): d1, d2 = self.d1, self.d2 return (sqrt((d1*x)**d1*d2**d2 / (d1*x+d2)**(d1+d2)) / (x * beta_fn(d1/2, d2/2))) def _moment_generating_function(self, t): raise NotImplementedError('The moment generating function for the ' 'F-distribution does not exist.') def FDistribution(name, d1, d2): r""" Create a continuous random variable with a F distribution. Explanation =========== The density of the F distribution is given by .. math:: f(x) := \frac{\sqrt{\frac{(d_1 x)^{d_1} d_2^{d_2}} {(d_1 x + d_2)^{d_1 + d_2}}}} {x \mathrm{B} \left(\frac{d_1}{2}, \frac{d_2}{2}\right)} with :math:`x > 0`. Parameters ========== d1 : `d_1 > 0`, where d_1 is the degrees of freedom (n_1 - 1) d2 : `d_2 > 0`, where d_2 is the degrees of freedom (n_2 - 1) Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import FDistribution, density >>> from sympy import Symbol, pprint >>> d1 = Symbol("d1", positive=True) >>> d2 = Symbol("d2", positive=True) >>> z = Symbol("z") >>> X = FDistribution("x", d1, d2) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) d2 -- ______________________________ 2 / d1 -d1 - d2 d2 *\/ (d1*z) *(d1*z + d2) -------------------------------------- /d1 d2\ z*B|--, --| \2 2 / References ========== .. [1] https://en.wikipedia.org/wiki/F-distribution .. [2] http://mathworld.wolfram.com/F-Distribution.html """ return rv(name, FDistributionDistribution, (d1, d2)) #------------------------------------------------------------------------------- # Fisher Z distribution -------------------------------------------------------- class FisherZDistribution(SingleContinuousDistribution): _argnames = ('d1', 'd2') set = Interval(-oo, oo) @staticmethod def check(d1, d2): _value_check(d1 > 0, "Degree of freedom d1 must be positive.") _value_check(d2 > 0, "Degree of freedom d2 must be positive.") def pdf(self, x): d1, d2 = self.d1, self.d2 return (2*d1**(d1/2)*d2**(d2/2) / beta_fn(d1/2, d2/2) * exp(d1*x) / (d1*exp(2*x)+d2)**((d1+d2)/2)) def FisherZ(name, d1, d2): r""" Create a Continuous Random Variable with an Fisher's Z distribution. Explanation =========== The density of the Fisher's Z distribution is given by .. math:: f(x) := \frac{2d_1^{d_1/2} d_2^{d_2/2}} {\mathrm{B}(d_1/2, d_2/2)} \frac{e^{d_1z}}{\left(d_1e^{2z}+d_2\right)^{\left(d_1+d_2\right)/2}} .. TODO - What is the difference between these degrees of freedom? Parameters ========== d1 : ``d_1 > 0`` Degree of freedom. d2 : ``d_2 > 0`` Degree of freedom. Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import FisherZ, density >>> from sympy import Symbol, pprint >>> d1 = Symbol("d1", positive=True) >>> d2 = Symbol("d2", positive=True) >>> z = Symbol("z") >>> X = FisherZ("x", d1, d2) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) d1 d2 d1 d2 - -- - -- -- -- 2 2 2 2 / 2*z \ d1*z 2*d1 *d2 *\d1*e + d2/ *e ----------------------------------------- /d1 d2\ B|--, --| \2 2 / References ========== .. [1] https://en.wikipedia.org/wiki/Fisher%27s_z-distribution .. [2] http://mathworld.wolfram.com/Fishersz-Distribution.html """ return rv(name, FisherZDistribution, (d1, d2)) #------------------------------------------------------------------------------- # Frechet distribution --------------------------------------------------------- class FrechetDistribution(SingleContinuousDistribution): _argnames = ('a', 's', 'm') set = Interval(0, oo) @staticmethod def check(a, s, m): _value_check(a > 0, "Shape parameter alpha must be positive.") _value_check(s > 0, "Scale parameter s must be positive.") def __new__(cls, a, s=1, m=0): a, s, m = list(map(sympify, (a, s, m))) return Basic.__new__(cls, a, s, m) def pdf(self, x): a, s, m = self.a, self.s, self.m return a/s * ((x-m)/s)**(-1-a) * exp(-((x-m)/s)**(-a)) def _cdf(self, x): a, s, m = self.a, self.s, self.m return Piecewise((exp(-((x-m)/s)**(-a)), x >= m), (S.Zero, True)) def Frechet(name, a, s=1, m=0): r""" Create a continuous random variable with a Frechet distribution. Explanation =========== The density of the Frechet distribution is given by .. math:: f(x) := \frac{\alpha}{s} \left(\frac{x-m}{s}\right)^{-1-\alpha} e^{-(\frac{x-m}{s})^{-\alpha}} with :math:`x \geq m`. Parameters ========== a : Real number, :math:`a \in \left(0, \infty\right)` the shape s : Real number, :math:`s \in \left(0, \infty\right)` the scale m : Real number, :math:`m \in \left(-\infty, \infty\right)` the minimum Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Frechet, density, cdf >>> from sympy import Symbol >>> a = Symbol("a", positive=True) >>> s = Symbol("s", positive=True) >>> m = Symbol("m", real=True) >>> z = Symbol("z") >>> X = Frechet("x", a, s, m) >>> density(X)(z) a*((-m + z)/s)**(-a - 1)*exp(-1/((-m + z)/s)**a)/s >>> cdf(X)(z) Piecewise((exp(-1/((-m + z)/s)**a), m <= z), (0, True)) References ========== .. [1] https://en.wikipedia.org/wiki/Fr%C3%A9chet_distribution """ return rv(name, FrechetDistribution, (a, s, m)) #------------------------------------------------------------------------------- # Gamma distribution ----------------------------------------------------------- class GammaDistribution(SingleContinuousDistribution): _argnames = ('k', 'theta') set = Interval(0, oo) @staticmethod def check(k, theta): _value_check(k > 0, "k must be positive") _value_check(theta > 0, "Theta must be positive") def pdf(self, x): k, theta = self.k, self.theta return x**(k - 1) * exp(-x/theta) / (gamma(k)*theta**k) def _cdf(self, x): k, theta = self.k, self.theta return Piecewise( (lowergamma(k, S(x)/theta)/gamma(k), x > 0), (S.Zero, True)) def _characteristic_function(self, t): return (1 - self.theta*I*t)**(-self.k) def _moment_generating_function(self, t): return (1- self.theta*t)**(-self.k) def Gamma(name, k, theta): r""" Create a continuous random variable with a Gamma distribution. Explanation =========== The density of the Gamma distribution is given by .. math:: f(x) := \frac{1}{\Gamma(k) \theta^k} x^{k - 1} e^{-\frac{x}{\theta}} with :math:`x \in [0,1]`. Parameters ========== k : Real number, ``k > 0``, a shape theta : Real number, `\theta > 0`, a scale Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Gamma, density, cdf, E, variance >>> from sympy import Symbol, pprint, simplify >>> k = Symbol("k", positive=True) >>> theta = Symbol("theta", positive=True) >>> z = Symbol("z") >>> X = Gamma("x", k, theta) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) -z ----- -k k - 1 theta theta *z *e --------------------- Gamma(k) >>> C = cdf(X, meijerg=True)(z) >>> pprint(C, use_unicode=False) / / z \ |k*lowergamma|k, -----| | \ theta/ <---------------------- for z >= 0 | Gamma(k + 1) | \ 0 otherwise >>> E(X) k*theta >>> V = simplify(variance(X)) >>> pprint(V, use_unicode=False) 2 k*theta References ========== .. [1] https://en.wikipedia.org/wiki/Gamma_distribution .. [2] http://mathworld.wolfram.com/GammaDistribution.html """ return rv(name, GammaDistribution, (k, theta)) #------------------------------------------------------------------------------- # Inverse Gamma distribution --------------------------------------------------- class GammaInverseDistribution(SingleContinuousDistribution): _argnames = ('a', 'b') set = Interval(0, oo) @staticmethod def check(a, b): _value_check(a > 0, "alpha must be positive") _value_check(b > 0, "beta must be positive") def pdf(self, x): a, b = self.a, self.b return b**a/gamma(a) * x**(-a-1) * exp(-b/x) def _cdf(self, x): a, b = self.a, self.b return Piecewise((uppergamma(a,b/x)/gamma(a), x > 0), (S.Zero, True)) def _characteristic_function(self, t): a, b = self.a, self.b return 2 * (-I*b*t)**(a/2) * besselk(a, sqrt(-4*I*b*t)) / gamma(a) def _moment_generating_function(self, t): raise NotImplementedError('The moment generating function for the ' 'gamma inverse distribution does not exist.') def GammaInverse(name, a, b): r""" Create a continuous random variable with an inverse Gamma distribution. Explanation =========== The density of the inverse Gamma distribution is given by .. math:: f(x) := \frac{\beta^\alpha}{\Gamma(\alpha)} x^{-\alpha - 1} \exp\left(\frac{-\beta}{x}\right) with :math:`x > 0`. Parameters ========== a : Real number, `a > 0` a shape b : Real number, `b > 0` a scale Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import GammaInverse, density, cdf >>> from sympy import Symbol, pprint >>> a = Symbol("a", positive=True) >>> b = Symbol("b", positive=True) >>> z = Symbol("z") >>> X = GammaInverse("x", a, b) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) -b --- a -a - 1 z b *z *e --------------- Gamma(a) >>> cdf(X)(z) Piecewise((uppergamma(a, b/z)/gamma(a), z > 0), (0, True)) References ========== .. [1] https://en.wikipedia.org/wiki/Inverse-gamma_distribution """ return rv(name, GammaInverseDistribution, (a, b)) #------------------------------------------------------------------------------- # Gumbel distribution (Maximum and Minimum) -------------------------------------------------------- class GumbelDistribution(SingleContinuousDistribution): _argnames = ('beta', 'mu', 'minimum') set = Interval(-oo, oo) @staticmethod def check(beta, mu, minimum): _value_check(beta > 0, "Scale parameter beta must be positive.") def pdf(self, x): beta, mu = self.beta, self.mu z = (x - mu)/beta f_max = (1/beta)*exp(-z - exp(-z)) f_min = (1/beta)*exp(z - exp(z)) return Piecewise((f_min, self.minimum), (f_max, not self.minimum)) def _cdf(self, x): beta, mu = self.beta, self.mu z = (x - mu)/beta F_max = exp(-exp(-z)) F_min = 1 - exp(-exp(z)) return Piecewise((F_min, self.minimum), (F_max, not self.minimum)) def _characteristic_function(self, t): cf_max = gamma(1 - I*self.beta*t) * exp(I*self.mu*t) cf_min = gamma(1 + I*self.beta*t) * exp(I*self.mu*t) return Piecewise((cf_min, self.minimum), (cf_max, not self.minimum)) def _moment_generating_function(self, t): mgf_max = gamma(1 - self.beta*t) * exp(self.mu*t) mgf_min = gamma(1 + self.beta*t) * exp(self.mu*t) return Piecewise((mgf_min, self.minimum), (mgf_max, not self.minimum)) def Gumbel(name, beta, mu, minimum=False): r""" Create a Continuous Random Variable with Gumbel distribution. Explanation =========== The density of the Gumbel distribution is given by For Maximum .. math:: f(x) := \dfrac{1}{\beta} \exp \left( -\dfrac{x-\mu}{\beta} - \exp \left( -\dfrac{x - \mu}{\beta} \right) \right) with :math:`x \in [ - \infty, \infty ]`. For Minimum .. math:: f(x) := \frac{e^{- e^{\frac{- \mu + x}{\beta}} + \frac{- \mu + x}{\beta}}}{\beta} with :math:`x \in [ - \infty, \infty ]`. Parameters ========== mu : Real number, 'mu' is a location beta : Real number, 'beta > 0' is a scale minimum : Boolean, by default, False, set to True for enabling minimum distribution Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Gumbel, density, cdf >>> from sympy import Symbol >>> x = Symbol("x") >>> mu = Symbol("mu") >>> beta = Symbol("beta", positive=True) >>> X = Gumbel("x", beta, mu) >>> density(X)(x) exp(-exp(-(-mu + x)/beta) - (-mu + x)/beta)/beta >>> cdf(X)(x) exp(-exp(-(-mu + x)/beta)) References ========== .. [1] http://mathworld.wolfram.com/GumbelDistribution.html .. [2] https://en.wikipedia.org/wiki/Gumbel_distribution .. [3] http://www.mathwave.com/help/easyfit/html/analyses/distributions/gumbel_max.html .. [4] http://www.mathwave.com/help/easyfit/html/analyses/distributions/gumbel_min.html """ return rv(name, GumbelDistribution, (beta, mu, minimum)) #------------------------------------------------------------------------------- # Gompertz distribution -------------------------------------------------------- class GompertzDistribution(SingleContinuousDistribution): _argnames = ('b', 'eta') set = Interval(0, oo) @staticmethod def check(b, eta): _value_check(b > 0, "b must be positive") _value_check(eta > 0, "eta must be positive") def pdf(self, x): eta, b = self.eta, self.b return b*eta*exp(b*x)*exp(eta)*exp(-eta*exp(b*x)) def _cdf(self, x): eta, b = self.eta, self.b return 1 - exp(eta)*exp(-eta*exp(b*x)) def _moment_generating_function(self, t): eta, b = self.eta, self.b return eta * exp(eta) * expint(t/b, eta) def Gompertz(name, b, eta): r""" Create a Continuous Random Variable with Gompertz distribution. Explanation =========== The density of the Gompertz distribution is given by .. math:: f(x) := b \eta e^{b x} e^{\eta} \exp \left(-\eta e^{bx} \right) with :math: 'x \in [0, \inf)'. Parameters ========== b: Real number, 'b > 0' a scale eta: Real number, 'eta > 0' a shape Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Gompertz, density >>> from sympy import Symbol >>> b = Symbol("b", positive=True) >>> eta = Symbol("eta", positive=True) >>> z = Symbol("z") >>> X = Gompertz("x", b, eta) >>> density(X)(z) b*eta*exp(eta)*exp(b*z)*exp(-eta*exp(b*z)) References ========== .. [1] https://en.wikipedia.org/wiki/Gompertz_distribution """ return rv(name, GompertzDistribution, (b, eta)) #------------------------------------------------------------------------------- # Kumaraswamy distribution ----------------------------------------------------- class KumaraswamyDistribution(SingleContinuousDistribution): _argnames = ('a', 'b') set = Interval(0, oo) @staticmethod def check(a, b): _value_check(a > 0, "a must be positive") _value_check(b > 0, "b must be positive") def pdf(self, x): a, b = self.a, self.b return a * b * x**(a-1) * (1-x**a)**(b-1) def _cdf(self, x): a, b = self.a, self.b return Piecewise( (S.Zero, x < S.Zero), (1 - (1 - x**a)**b, x <= S.One), (S.One, True)) def Kumaraswamy(name, a, b): r""" Create a Continuous Random Variable with a Kumaraswamy distribution. Explanation =========== The density of the Kumaraswamy distribution is given by .. math:: f(x) := a b x^{a-1} (1-x^a)^{b-1} with :math:`x \in [0,1]`. Parameters ========== a : Real number, ``a > 0`` a shape b : Real number, ``b > 0`` a shape Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Kumaraswamy, density, cdf >>> from sympy import Symbol, pprint >>> a = Symbol("a", positive=True) >>> b = Symbol("b", positive=True) >>> z = Symbol("z") >>> X = Kumaraswamy("x", a, b) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) b - 1 a - 1 / a\ a*b*z *\1 - z / >>> cdf(X)(z) Piecewise((0, z < 0), (1 - (1 - z**a)**b, z <= 1), (1, True)) References ========== .. [1] https://en.wikipedia.org/wiki/Kumaraswamy_distribution """ return rv(name, KumaraswamyDistribution, (a, b)) #------------------------------------------------------------------------------- # Laplace distribution --------------------------------------------------------- class LaplaceDistribution(SingleContinuousDistribution): _argnames = ('mu', 'b') set = Interval(-oo, oo) @staticmethod def check(mu, b): _value_check(b > 0, "Scale parameter b must be positive.") _value_check(mu.is_real, "Location parameter mu should be real") def pdf(self, x): mu, b = self.mu, self.b return 1/(2*b)*exp(-Abs(x - mu)/b) def _cdf(self, x): mu, b = self.mu, self.b return Piecewise( (S.Half*exp((x - mu)/b), x < mu), (S.One - S.Half*exp(-(x - mu)/b), x >= mu) ) def _characteristic_function(self, t): return exp(self.mu*I*t) / (1 + self.b**2*t**2) def _moment_generating_function(self, t): return exp(self.mu*t) / (1 - self.b**2*t**2) def Laplace(name, mu, b): r""" Create a continuous random variable with a Laplace distribution. Explanation =========== The density of the Laplace distribution is given by .. math:: f(x) := \frac{1}{2 b} \exp \left(-\frac{|x-\mu|}b \right) Parameters ========== mu : Real number or a list/matrix, the location (mean) or the location vector b : Real number or a positive definite matrix, representing a scale or the covariance matrix. Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Laplace, density, cdf >>> from sympy import Symbol, pprint >>> mu = Symbol("mu") >>> b = Symbol("b", positive=True) >>> z = Symbol("z") >>> X = Laplace("x", mu, b) >>> density(X)(z) exp(-Abs(mu - z)/b)/(2*b) >>> cdf(X)(z) Piecewise((exp((-mu + z)/b)/2, mu > z), (1 - exp((mu - z)/b)/2, True)) >>> L = Laplace('L', [1, 2], [[1, 0], [0, 1]]) >>> pprint(density(L)(1, 2), use_unicode=False) 5 / ____\ e *besselk\0, \/ 35 / --------------------- pi References ========== .. [1] https://en.wikipedia.org/wiki/Laplace_distribution .. [2] http://mathworld.wolfram.com/LaplaceDistribution.html """ if isinstance(mu, (list, MatrixBase)) and\ isinstance(b, (list, MatrixBase)): from sympy.stats.joint_rv_types import MultivariateLaplace return MultivariateLaplace(name, mu, b) return rv(name, LaplaceDistribution, (mu, b)) #------------------------------------------------------------------------------- # Levy distribution --------------------------------------------------------- class LevyDistribution(SingleContinuousDistribution): _argnames = ('mu', 'c') @property def set(self): return Interval(self.mu, oo) @staticmethod def check(mu, c): _value_check(c > 0, "c (scale parameter) must be positive") _value_check(mu.is_real, "mu (location paramater) must be real") def pdf(self, x): mu, c = self.mu, self.c return sqrt(c/(2*pi))*exp(-c/(2*(x - mu)))/((x - mu)**(S.One + S.Half)) def _cdf(self, x): mu, c = self.mu, self.c return erfc(sqrt(c/(2*(x - mu)))) def _characteristic_function(self, t): mu, c = self.mu, self.c return exp(I * mu * t - sqrt(-2 * I * c * t)) def _moment_generating_function(self, t): raise NotImplementedError('The moment generating function of Levy distribution does not exist.') def Levy(name, mu, c): r""" Create a continuous random variable with a Levy distribution. The density of the Levy distribution is given by .. math:: f(x) := \sqrt(\frac{c}{2 \pi}) \frac{\exp -\frac{c}{2 (x - \mu)}}{(x - \mu)^{3/2}} Parameters ========== mu : Real number The location parameter. c : Real number, ``c > 0`` A scale parameter. Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Levy, density, cdf >>> from sympy import Symbol >>> mu = Symbol("mu", real=True) >>> c = Symbol("c", positive=True) >>> z = Symbol("z") >>> X = Levy("x", mu, c) >>> density(X)(z) sqrt(2)*sqrt(c)*exp(-c/(-2*mu + 2*z))/(2*sqrt(pi)*(-mu + z)**(3/2)) >>> cdf(X)(z) erfc(sqrt(c)*sqrt(1/(-2*mu + 2*z))) References ========== .. [1] https://en.wikipedia.org/wiki/L%C3%A9vy_distribution .. [2] http://mathworld.wolfram.com/LevyDistribution.html """ return rv(name, LevyDistribution, (mu, c)) #------------------------------------------------------------------------------- # Log-Cauchy distribution -------------------------------------------------------- class LogCauchyDistribution(SingleContinuousDistribution): _argnames = ('mu', 'sigma') set = Interval.open(0, oo) @staticmethod def check(mu, sigma): _value_check((sigma > 0) != False, "Scale parameter Gamma must be positive.") _value_check(mu.is_real != False, "Location parameter must be real.") def pdf(self, x): mu, sigma = self.mu, self.sigma return 1/(x*pi)*(sigma/((log(x) - mu)**2 + sigma**2)) def _cdf(self, x): mu, sigma = self.mu, self.sigma return (1/pi)*atan((log(x) - mu)/sigma) + S.Half def _characteristic_function(self, t): raise NotImplementedError("The characteristic function for the " "Log-Cauchy distribution does not exist.") def _moment_generating_function(self, t): raise NotImplementedError("The moment generating function for the " "Log-Cauchy distribution does not exist.") def LogCauchy(name, mu, sigma): r""" Create a continuous random variable with a Log-Cauchy distribution. The density of the Log-Cauchy distribution is given by .. math:: f(x) := \frac{1}{\pi x} \frac{\sigma}{(log(x)-\mu^2) + \sigma^2} Parameters ========== mu : Real number, the location sigma : Real number, `\sigma > 0`, a scale Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import LogCauchy, density, cdf >>> from sympy import Symbol, S >>> mu = 2 >>> sigma = S.One / 5 >>> z = Symbol("z") >>> X = LogCauchy("x", mu, sigma) >>> density(X)(z) 1/(5*pi*z*((log(z) - 2)**2 + 1/25)) >>> cdf(X)(z) atan(5*log(z) - 10)/pi + 1/2 References ========== .. [1] https://en.wikipedia.org/wiki/Log-Cauchy_distribution """ return rv(name, LogCauchyDistribution, (mu, sigma)) #------------------------------------------------------------------------------- # Logistic distribution -------------------------------------------------------- class LogisticDistribution(SingleContinuousDistribution): _argnames = ('mu', 's') set = Interval(-oo, oo) @staticmethod def check(mu, s): _value_check(s > 0, "Scale parameter s must be positive.") def pdf(self, x): mu, s = self.mu, self.s return exp(-(x - mu)/s)/(s*(1 + exp(-(x - mu)/s))**2) def _cdf(self, x): mu, s = self.mu, self.s return S.One/(1 + exp(-(x - mu)/s)) def _characteristic_function(self, t): return Piecewise((exp(I*t*self.mu) * pi*self.s*t / sinh(pi*self.s*t), Ne(t, 0)), (S.One, True)) def _moment_generating_function(self, t): return exp(self.mu*t) * beta_fn(1 - self.s*t, 1 + self.s*t) def _quantile(self, p): return self.mu - self.s*log(-S.One + S.One/p) def Logistic(name, mu, s): r""" Create a continuous random variable with a logistic distribution. Explanation =========== The density of the logistic distribution is given by .. math:: f(x) := \frac{e^{-(x-\mu)/s}} {s\left(1+e^{-(x-\mu)/s}\right)^2} Parameters ========== mu : Real number, the location (mean) s : Real number, `s > 0` a scale Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Logistic, density, cdf >>> from sympy import Symbol >>> mu = Symbol("mu", real=True) >>> s = Symbol("s", positive=True) >>> z = Symbol("z") >>> X = Logistic("x", mu, s) >>> density(X)(z) exp((mu - z)/s)/(s*(exp((mu - z)/s) + 1)**2) >>> cdf(X)(z) 1/(exp((mu - z)/s) + 1) References ========== .. [1] https://en.wikipedia.org/wiki/Logistic_distribution .. [2] http://mathworld.wolfram.com/LogisticDistribution.html """ return rv(name, LogisticDistribution, (mu, s)) #------------------------------------------------------------------------------- # Log-logistic distribution -------------------------------------------------------- class LogLogisticDistribution(SingleContinuousDistribution): _argnames = ('alpha', 'beta') set = Interval(0, oo) @staticmethod def check(alpha, beta): _value_check(alpha > 0, "Scale parameter Alpha must be positive.") _value_check(beta > 0, "Shape parameter Beta must be positive.") def pdf(self, x): a, b = self.alpha, self.beta return ((b/a)*(x/a)**(b - 1))/(1 + (x/a)**b)**2 def _cdf(self, x): a, b = self.alpha, self.beta return 1/(1 + (x/a)**(-b)) def _quantile(self, p): a, b = self.alpha, self.beta return a*((p/(1 - p))**(1/b)) def expectation(self, expr, var, **kwargs): a, b = self.args return Piecewise((S.NaN, b <= 1), (pi*a/(b*sin(pi/b)), True)) def LogLogistic(name, alpha, beta): r""" Create a continuous random variable with a log-logistic distribution. The distribution is unimodal when ``beta > 1``. Explanation =========== The density of the log-logistic distribution is given by .. math:: f(x) := \frac{(\frac{\beta}{\alpha})(\frac{x}{\alpha})^{\beta - 1}} {(1 + (\frac{x}{\alpha})^{\beta})^2} Parameters ========== alpha : Real number, `\alpha > 0`, scale parameter and median of distribution beta : Real number, `\beta > 0` a shape parameter Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import LogLogistic, density, cdf, quantile >>> from sympy import Symbol, pprint >>> alpha = Symbol("alpha", real=True, positive=True) >>> beta = Symbol("beta", real=True, positive=True) >>> p = Symbol("p") >>> z = Symbol("z", positive=True) >>> X = LogLogistic("x", alpha, beta) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) beta - 1 / z \ beta*|-----| \alpha/ ------------------------ 2 / beta \ |/ z \ | alpha*||-----| + 1| \\alpha/ / >>> cdf(X)(z) 1/(1 + (z/alpha)**(-beta)) >>> quantile(X)(p) alpha*(p/(1 - p))**(1/beta) References ========== .. [1] https://en.wikipedia.org/wiki/Log-logistic_distribution """ return rv(name, LogLogisticDistribution, (alpha, beta)) #------------------------------------------------------------------------------- #Logit-Normal distribution------------------------------------------------------ class LogitNormalDistribution(SingleContinuousDistribution): _argnames = ('mu', 's') set = Interval.open(0, 1) @staticmethod def check(mu, s): _value_check((s ** 2).is_real is not False and s ** 2 > 0, "Squared scale parameter s must be positive.") _value_check(mu.is_real is not False, "Location parameter must be real") def _logit(self, x): return log(x / (1 - x)) def pdf(self, x): mu, s = self.mu, self.s return exp(-(self._logit(x) - mu)**2/(2*s**2))*(S.One/sqrt(2*pi*(s**2)))*(1/(x*(1 - x))) def _cdf(self, x): mu, s = self.mu, self.s return (S.One/2)*(1 + erf((self._logit(x) - mu)/(sqrt(2*s**2)))) def LogitNormal(name, mu, s): r""" Create a continuous random variable with a Logit-Normal distribution. The density of the logistic distribution is given by .. math:: f(x) := \frac{1}{s \sqrt{2 \pi}} \frac{1}{x(1 - x)} e^{- \frac{(logit(x) - \mu)^2}{s^2}} where logit(x) = \log(\frac{x}{1 - x}) Parameters ========== mu : Real number, the location (mean) s : Real number, `s > 0` a scale Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import LogitNormal, density, cdf >>> from sympy import Symbol,pprint >>> mu = Symbol("mu", real=True) >>> s = Symbol("s", positive=True) >>> z = Symbol("z") >>> X = LogitNormal("x",mu,s) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) 2 / / z \\ -|-mu + log|-----|| \ \1 - z// --------------------- 2 ___ 2*s \/ 2 *e ---------------------------- ____ 2*\/ pi *s*z*(1 - z) >>> density(X)(z) sqrt(2)*exp(-(-mu + log(z/(1 - z)))**2/(2*s**2))/(2*sqrt(pi)*s*z*(1 - z)) >>> cdf(X)(z) erf(sqrt(2)*(-mu + log(z/(1 - z)))/(2*s))/2 + 1/2 References ========== .. [1] https://en.wikipedia.org/wiki/Logit-normal_distribution """ return rv(name, LogitNormalDistribution, (mu, s)) #------------------------------------------------------------------------------- # Log Normal distribution ------------------------------------------------------ class LogNormalDistribution(SingleContinuousDistribution): _argnames = ('mean', 'std') set = Interval(0, oo) @staticmethod def check(mean, std): _value_check(std > 0, "Parameter std must be positive.") def pdf(self, x): mean, std = self.mean, self.std return exp(-(log(x) - mean)**2 / (2*std**2)) / (x*sqrt(2*pi)*std) def _cdf(self, x): mean, std = self.mean, self.std return Piecewise( (S.Half + S.Half*erf((log(x) - mean)/sqrt(2)/std), x > 0), (S.Zero, True) ) def _moment_generating_function(self, t): raise NotImplementedError('Moment generating function of the log-normal distribution is not defined.') def LogNormal(name, mean, std): r""" Create a continuous random variable with a log-normal distribution. Explanation =========== The density of the log-normal distribution is given by .. math:: f(x) := \frac{1}{x\sqrt{2\pi\sigma^2}} e^{-\frac{\left(\ln x-\mu\right)^2}{2\sigma^2}} with :math:`x \geq 0`. Parameters ========== mu : Real number The log-scale. sigma : Real number A shape. ($\sigma^2 > 0$) Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import LogNormal, density >>> from sympy import Symbol, pprint >>> mu = Symbol("mu", real=True) >>> sigma = Symbol("sigma", positive=True) >>> z = Symbol("z") >>> X = LogNormal("x", mu, sigma) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) 2 -(-mu + log(z)) ----------------- 2 ___ 2*sigma \/ 2 *e ------------------------ ____ 2*\/ pi *sigma*z >>> X = LogNormal('x', 0, 1) # Mean 0, standard deviation 1 >>> density(X)(z) sqrt(2)*exp(-log(z)**2/2)/(2*sqrt(pi)*z) References ========== .. [1] https://en.wikipedia.org/wiki/Lognormal .. [2] http://mathworld.wolfram.com/LogNormalDistribution.html """ return rv(name, LogNormalDistribution, (mean, std)) #------------------------------------------------------------------------------- # Lomax Distribution ----------------------------------------------------------- class LomaxDistribution(SingleContinuousDistribution): _argnames = ('alpha', 'lamda',) set = Interval(0, oo) @staticmethod def check(alpha, lamda): _value_check(alpha.is_real, "Shape parameter should be real.") _value_check(lamda.is_real, "Scale parameter should be real.") _value_check(alpha.is_positive, "Shape parameter should be positive.") _value_check(lamda.is_positive, "Scale parameter should be positive.") def pdf(self, x): lamba, alpha = self.lamda, self.alpha return (alpha/lamba) * (S.One + x/lamba)**(-alpha-1) def Lomax(name, alpha, lamda): r""" Create a continuous random variable with a Lomax distribution. Explanation =========== The density of the Lomax distribution is given by .. math:: f(x) := \frac{\alpha}{\lambda}\left[1+\frac{x}{\lambda}\right]^{-(\alpha+1)} Parameters ========== alpha : Real Number, `alpha > 0` Shape parameter lamda : Real Number, `lamda > 0` Scale parameter Examples ======== >>> from sympy.stats import Lomax, density, cdf, E >>> from sympy import symbols >>> a, l = symbols('a, l', positive=True) >>> X = Lomax('X', a, l) >>> x = symbols('x') >>> density(X)(x) a*(1 + x/l)**(-a - 1)/l >>> cdf(X)(x) Piecewise((1 - 1/(1 + x/l)**a, x >= 0), (0, True)) >>> a = 2 >>> X = Lomax('X', a, l) >>> E(X) l Returns ======= RandomSymbol References ========== .. [1] https://en.wikipedia.org/wiki/Lomax_distribution """ return rv(name, LomaxDistribution, (alpha, lamda)) #------------------------------------------------------------------------------- # Maxwell distribution --------------------------------------------------------- class MaxwellDistribution(SingleContinuousDistribution): _argnames = ('a',) set = Interval(0, oo) @staticmethod def check(a): _value_check(a > 0, "Parameter a must be positive.") def pdf(self, x): a = self.a return sqrt(2/pi)*x**2*exp(-x**2/(2*a**2))/a**3 def _cdf(self, x): a = self.a return erf(sqrt(2)*x/(2*a)) - sqrt(2)*x*exp(-x**2/(2*a**2))/(sqrt(pi)*a) def Maxwell(name, a): r""" Create a continuous random variable with a Maxwell distribution. Explanation =========== The density of the Maxwell distribution is given by .. math:: f(x) := \sqrt{\frac{2}{\pi}} \frac{x^2 e^{-x^2/(2a^2)}}{a^3} with :math:`x \geq 0`. .. TODO - what does the parameter mean? Parameters ========== a : Real number, `a > 0` Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Maxwell, density, E, variance >>> from sympy import Symbol, simplify >>> a = Symbol("a", positive=True) >>> z = Symbol("z") >>> X = Maxwell("x", a) >>> density(X)(z) sqrt(2)*z**2*exp(-z**2/(2*a**2))/(sqrt(pi)*a**3) >>> E(X) 2*sqrt(2)*a/sqrt(pi) >>> simplify(variance(X)) a**2*(-8 + 3*pi)/pi References ========== .. [1] https://en.wikipedia.org/wiki/Maxwell_distribution .. [2] http://mathworld.wolfram.com/MaxwellDistribution.html """ return rv(name, MaxwellDistribution, (a, )) #------------------------------------------------------------------------------- # Moyal Distribution ----------------------------------------------------------- class MoyalDistribution(SingleContinuousDistribution): _argnames = ('mu', 'sigma') @staticmethod def check(mu, sigma): _value_check(mu.is_real, "Location parameter must be real.") _value_check(sigma.is_real and sigma > 0, "Scale parameter must be real\ and positive.") def pdf(self, x): mu, sigma = self.mu, self.sigma num = exp(-(exp(-(x - mu)/sigma) + (x - mu)/(sigma))/2) den = (sqrt(2*pi) * sigma) return num/den def _characteristic_function(self, t): mu, sigma = self.mu, self.sigma term1 = exp(I*t*mu) term2 = (2**(-I*sigma*t) * gamma(Rational(1, 2) - I*t*sigma)) return (term1 * term2)/sqrt(pi) def _moment_generating_function(self, t): mu, sigma = self.mu, self.sigma term1 = exp(t*mu) term2 = (2**(-1*sigma*t) * gamma(Rational(1, 2) - t*sigma)) return (term1 * term2)/sqrt(pi) def Moyal(name, mu, sigma): r""" Create a continuous random variable with a Moyal distribution. Explanation =========== The density of the Moyal distribution is given by .. math:: f(x) := \frac{\exp-\frac{1}{2}\exp-\frac{x-\mu}{\sigma}-\frac{x-\mu}{2\sigma}}{\sqrt{2\pi}\sigma} with :math:`x \in \mathbb{R}`. Parameters ========== mu : Real number Location parameter sigma : Real positive number Scale parameter Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Moyal, density, cdf >>> from sympy import Symbol, simplify >>> mu = Symbol("mu", real=True) >>> sigma = Symbol("sigma", positive=True, real=True) >>> z = Symbol("z") >>> X = Moyal("x", mu, sigma) >>> density(X)(z) sqrt(2)*exp(-exp((mu - z)/sigma)/2 - (-mu + z)/(2*sigma))/(2*sqrt(pi)*sigma) >>> simplify(cdf(X)(z)) 1 - erf(sqrt(2)*exp((mu - z)/(2*sigma))/2) References ========== .. [1] https://reference.wolfram.com/language/ref/MoyalDistribution.html .. [2] http://www.stat.rice.edu/~dobelman/textfiles/DistributionsHandbook.pdf """ return rv(name, MoyalDistribution, (mu, sigma)) #------------------------------------------------------------------------------- # Nakagami distribution -------------------------------------------------------- class NakagamiDistribution(SingleContinuousDistribution): _argnames = ('mu', 'omega') set = Interval(0, oo) @staticmethod def check(mu, omega): _value_check(mu >= S.Half, "Shape parameter mu must be greater than equal to 1/2.") _value_check(omega > 0, "Spread parameter omega must be positive.") def pdf(self, x): mu, omega = self.mu, self.omega return 2*mu**mu/(gamma(mu)*omega**mu)*x**(2*mu - 1)*exp(-mu/omega*x**2) def _cdf(self, x): mu, omega = self.mu, self.omega return Piecewise( (lowergamma(mu, (mu/omega)*x**2)/gamma(mu), x > 0), (S.Zero, True)) def Nakagami(name, mu, omega): r""" Create a continuous random variable with a Nakagami distribution. Explanation =========== The density of the Nakagami distribution is given by .. math:: f(x) := \frac{2\mu^\mu}{\Gamma(\mu)\omega^\mu} x^{2\mu-1} \exp\left(-\frac{\mu}{\omega}x^2 \right) with :math:`x > 0`. Parameters ========== mu : Real number, `\mu \geq \frac{1}{2}` a shape omega : Real number, `\omega > 0`, the spread Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Nakagami, density, E, variance, cdf >>> from sympy import Symbol, simplify, pprint >>> mu = Symbol("mu", positive=True) >>> omega = Symbol("omega", positive=True) >>> z = Symbol("z") >>> X = Nakagami("x", mu, omega) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) 2 -mu*z ------- mu -mu 2*mu - 1 omega 2*mu *omega *z *e ---------------------------------- Gamma(mu) >>> simplify(E(X)) sqrt(mu)*sqrt(omega)*gamma(mu + 1/2)/gamma(mu + 1) >>> V = simplify(variance(X)) >>> pprint(V, use_unicode=False) 2 omega*Gamma (mu + 1/2) omega - ----------------------- Gamma(mu)*Gamma(mu + 1) >>> cdf(X)(z) Piecewise((lowergamma(mu, mu*z**2/omega)/gamma(mu), z > 0), (0, True)) References ========== .. [1] https://en.wikipedia.org/wiki/Nakagami_distribution """ return rv(name, NakagamiDistribution, (mu, omega)) #------------------------------------------------------------------------------- # Normal distribution ---------------------------------------------------------- class NormalDistribution(SingleContinuousDistribution): _argnames = ('mean', 'std') @staticmethod def check(mean, std): _value_check(std > 0, "Standard deviation must be positive") def pdf(self, x): return exp(-(x - self.mean)**2 / (2*self.std**2)) / (sqrt(2*pi)*self.std) def _cdf(self, x): mean, std = self.mean, self.std return erf(sqrt(2)*(-mean + x)/(2*std))/2 + S.Half def _characteristic_function(self, t): mean, std = self.mean, self.std return exp(I*mean*t - std**2*t**2/2) def _moment_generating_function(self, t): mean, std = self.mean, self.std return exp(mean*t + std**2*t**2/2) def _quantile(self, p): mean, std = self.mean, self.std return mean + std*sqrt(2)*erfinv(2*p - 1) def Normal(name, mean, std): r""" Create a continuous random variable with a Normal distribution. Explanation =========== The density of the Normal distribution is given by .. math:: f(x) := \frac{1}{\sigma\sqrt{2\pi}} e^{ -\frac{(x-\mu)^2}{2\sigma^2} } Parameters ========== mu : Real number or a list representing the mean or the mean vector sigma : Real number or a positive definite square matrix, :math:`\sigma^2 > 0` the variance Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Normal, density, E, std, cdf, skewness, quantile, marginal_distribution >>> from sympy import Symbol, simplify, pprint >>> mu = Symbol("mu") >>> sigma = Symbol("sigma", positive=True) >>> z = Symbol("z") >>> y = Symbol("y") >>> p = Symbol("p") >>> X = Normal("x", mu, sigma) >>> density(X)(z) sqrt(2)*exp(-(-mu + z)**2/(2*sigma**2))/(2*sqrt(pi)*sigma) >>> C = simplify(cdf(X))(z) # it needs a little more help... >>> pprint(C, use_unicode=False) / ___ \ |\/ 2 *(-mu + z)| erf|---------------| \ 2*sigma / 1 -------------------- + - 2 2 >>> quantile(X)(p) mu + sqrt(2)*sigma*erfinv(2*p - 1) >>> simplify(skewness(X)) 0 >>> X = Normal("x", 0, 1) # Mean 0, standard deviation 1 >>> density(X)(z) sqrt(2)*exp(-z**2/2)/(2*sqrt(pi)) >>> E(2*X + 1) 1 >>> simplify(std(2*X + 1)) 2 >>> m = Normal('X', [1, 2], [[2, 1], [1, 2]]) >>> pprint(density(m)(y, z), use_unicode=False) 2 2 y y*z z - -- + --- - -- + z - 1 ___ 3 3 3 \/ 3 *e ------------------------------ 6*pi >>> marginal_distribution(m, m[0])(1) 1/(2*sqrt(pi)) References ========== .. [1] https://en.wikipedia.org/wiki/Normal_distribution .. [2] http://mathworld.wolfram.com/NormalDistributionFunction.html """ if isinstance(mean, (list, MatrixBase, MatrixExpr)) and\ isinstance(std, (list, MatrixBase, MatrixExpr)): from sympy.stats.joint_rv_types import MultivariateNormal return MultivariateNormal(name, mean, std) return rv(name, NormalDistribution, (mean, std)) #------------------------------------------------------------------------------- # Inverse Gaussian distribution ---------------------------------------------------------- class GaussianInverseDistribution(SingleContinuousDistribution): _argnames = ('mean', 'shape') @property def set(self): return Interval(0, oo) @staticmethod def check(mean, shape): _value_check(shape > 0, "Shape parameter must be positive") _value_check(mean > 0, "Mean must be positive") def pdf(self, x): mu, s = self.mean, self.shape return exp(-s*(x - mu)**2 / (2*x*mu**2)) * sqrt(s/(2*pi*x**3)) def _cdf(self, x): from sympy.stats import cdf mu, s = self.mean, self.shape stdNormalcdf = cdf(Normal('x', 0, 1)) first_term = stdNormalcdf(sqrt(s/x) * ((x/mu) - S.One)) second_term = exp(2*s/mu) * stdNormalcdf(-sqrt(s/x)*(x/mu + S.One)) return first_term + second_term def _characteristic_function(self, t): mu, s = self.mean, self.shape return exp((s/mu)*(1 - sqrt(1 - (2*mu**2*I*t)/s))) def _moment_generating_function(self, t): mu, s = self.mean, self.shape return exp((s/mu)*(1 - sqrt(1 - (2*mu**2*t)/s))) def GaussianInverse(name, mean, shape): r""" Create a continuous random variable with an Inverse Gaussian distribution. Inverse Gaussian distribution is also known as Wald distribution. Explanation =========== The density of the Inverse Gaussian distribution is given by .. math:: f(x) := \sqrt{\frac{\lambda}{2\pi x^3}} e^{-\frac{\lambda(x-\mu)^2}{2x\mu^2}} Parameters ========== mu : Positive number representing the mean. lambda : Positive number representing the shape parameter. Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import GaussianInverse, density, E, std, skewness >>> from sympy import Symbol, pprint >>> mu = Symbol("mu", positive=True) >>> lamda = Symbol("lambda", positive=True) >>> z = Symbol("z", positive=True) >>> X = GaussianInverse("x", mu, lamda) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) 2 -lambda*(-mu + z) ------------------- 2 ___ ________ 2*mu *z \/ 2 *\/ lambda *e ------------------------------------- ____ 3/2 2*\/ pi *z >>> E(X) mu >>> std(X).expand() mu**(3/2)/sqrt(lambda) >>> skewness(X).expand() 3*sqrt(mu)/sqrt(lambda) References ========== .. [1] https://en.wikipedia.org/wiki/Inverse_Gaussian_distribution .. [2] http://mathworld.wolfram.com/InverseGaussianDistribution.html """ return rv(name, GaussianInverseDistribution, (mean, shape)) Wald = GaussianInverse #------------------------------------------------------------------------------- # Pareto distribution ---------------------------------------------------------- class ParetoDistribution(SingleContinuousDistribution): _argnames = ('xm', 'alpha') @property def set(self): return Interval(self.xm, oo) @staticmethod def check(xm, alpha): _value_check(xm > 0, "Xm must be positive") _value_check(alpha > 0, "Alpha must be positive") def pdf(self, x): xm, alpha = self.xm, self.alpha return alpha * xm**alpha / x**(alpha + 1) def _cdf(self, x): xm, alpha = self.xm, self.alpha return Piecewise( (S.One - xm**alpha/x**alpha, x>=xm), (0, True), ) def _moment_generating_function(self, t): xm, alpha = self.xm, self.alpha return alpha * (-xm*t)**alpha * uppergamma(-alpha, -xm*t) def _characteristic_function(self, t): xm, alpha = self.xm, self.alpha return alpha * (-I * xm * t) ** alpha * uppergamma(-alpha, -I * xm * t) def Pareto(name, xm, alpha): r""" Create a continuous random variable with the Pareto distribution. Explanation =========== The density of the Pareto distribution is given by .. math:: f(x) := \frac{\alpha\,x_m^\alpha}{x^{\alpha+1}} with :math:`x \in [x_m,\infty]`. Parameters ========== xm : Real number, `x_m > 0`, a scale alpha : Real number, `\alpha > 0`, a shape Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Pareto, density >>> from sympy import Symbol >>> xm = Symbol("xm", positive=True) >>> beta = Symbol("beta", positive=True) >>> z = Symbol("z") >>> X = Pareto("x", xm, beta) >>> density(X)(z) beta*xm**beta*z**(-beta - 1) References ========== .. [1] https://en.wikipedia.org/wiki/Pareto_distribution .. [2] http://mathworld.wolfram.com/ParetoDistribution.html """ return rv(name, ParetoDistribution, (xm, alpha)) #------------------------------------------------------------------------------- # PowerFunction distribution --------------------------------------------------- class PowerFunctionDistribution(SingleContinuousDistribution): _argnames=('alpha','a','b') @property def set(self): return Interval(self.a, self.b) @staticmethod def check(alpha, a, b): _value_check(a.is_real, "Continuous Boundary parameter should be real.") _value_check(b.is_real, "Continuous Boundary parameter should be real.") _value_check(a < b, " 'a' the left Boundary must be smaller than 'b' the right Boundary." ) _value_check(alpha.is_positive, "Continuous Shape parameter should be positive.") def pdf(self, x): alpha, a, b = self.alpha, self.a, self.b num = alpha*(x - a)**(alpha - 1) den = (b - a)**alpha return num/den def PowerFunction(name, alpha, a, b): r""" Creates a continuous random variable with a Power Function Distribution. Explanation =========== The density of PowerFunction distribution is given by .. math:: f(x) := \frac{{\alpha}(x - a)^{\alpha - 1}}{(b - a)^{\alpha}} with :math:`x \in [a,b]`. Parameters ========== alpha: Positive number, `0 < alpha` the shape paramater a : Real number, :math:`-\infty < a` the left boundary b : Real number, :math:`a < b < \infty` the right boundary Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import PowerFunction, density, cdf, E, variance >>> from sympy import Symbol >>> alpha = Symbol("alpha", positive=True) >>> a = Symbol("a", real=True) >>> b = Symbol("b", real=True) >>> z = Symbol("z") >>> X = PowerFunction("X", 2, a, b) >>> density(X)(z) (-2*a + 2*z)/(-a + b)**2 >>> cdf(X)(z) Piecewise((a**2/(a**2 - 2*a*b + b**2) - 2*a*z/(a**2 - 2*a*b + b**2) + z**2/(a**2 - 2*a*b + b**2), a <= z), (0, True)) >>> alpha = 2 >>> a = 0 >>> b = 1 >>> Y = PowerFunction("Y", alpha, a, b) >>> E(Y) 2/3 >>> variance(Y) 1/18 References ========== .. [1] http://www.mathwave.com/help/easyfit/html/analyses/distributions/power_func.html """ return rv(name, PowerFunctionDistribution, (alpha, a, b)) #------------------------------------------------------------------------------- # QuadraticU distribution ------------------------------------------------------ class QuadraticUDistribution(SingleContinuousDistribution): _argnames = ('a', 'b') @property def set(self): return Interval(self.a, self.b) @staticmethod def check(a, b): _value_check(b > a, "Parameter b must be in range (%s, oo)."%(a)) def pdf(self, x): a, b = self.a, self.b alpha = 12 / (b-a)**3 beta = (a+b) / 2 return Piecewise( (alpha * (x-beta)**2, And(a<=x, x<=b)), (S.Zero, True)) def _moment_generating_function(self, t): a, b = self.a, self.b return -3 * (exp(a*t) * (4 + (a**2 + 2*a*(-2 + b) + b**2) * t) \ - exp(b*t) * (4 + (-4*b + (a + b)**2) * t)) / ((a-b)**3 * t**2) def _characteristic_function(self, t): a, b = self.a, self.b return -3*I*(exp(I*a*t*exp(I*b*t)) * (4*I - (-4*b + (a+b)**2)*t)) \ / ((a-b)**3 * t**2) def QuadraticU(name, a, b): r""" Create a Continuous Random Variable with a U-quadratic distribution. Explanation =========== The density of the U-quadratic distribution is given by .. math:: f(x) := \alpha (x-\beta)^2 with :math:`x \in [a,b]`. Parameters ========== a : Real number b : Real number, :math:`a < b` Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import QuadraticU, density >>> from sympy import Symbol, pprint >>> a = Symbol("a", real=True) >>> b = Symbol("b", real=True) >>> z = Symbol("z") >>> X = QuadraticU("x", a, b) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) / 2 | / a b \ |12*|- - - - + z| | \ 2 2 / <----------------- for And(b >= z, a <= z) | 3 | (-a + b) | \ 0 otherwise References ========== .. [1] https://en.wikipedia.org/wiki/U-quadratic_distribution """ return rv(name, QuadraticUDistribution, (a, b)) #------------------------------------------------------------------------------- # RaisedCosine distribution ---------------------------------------------------- class RaisedCosineDistribution(SingleContinuousDistribution): _argnames = ('mu', 's') @property def set(self): return Interval(self.mu - self.s, self.mu + self.s) @staticmethod def check(mu, s): _value_check(s > 0, "s must be positive") def pdf(self, x): mu, s = self.mu, self.s return Piecewise( ((1+cos(pi*(x-mu)/s)) / (2*s), And(mu-s<=x, x<=mu+s)), (S.Zero, True)) def _characteristic_function(self, t): mu, s = self.mu, self.s return Piecewise((exp(-I*pi*mu/s)/2, Eq(t, -pi/s)), (exp(I*pi*mu/s)/2, Eq(t, pi/s)), (pi**2*sin(s*t)*exp(I*mu*t) / (s*t*(pi**2 - s**2*t**2)), True)) def _moment_generating_function(self, t): mu, s = self.mu, self.s return pi**2 * sinh(s*t) * exp(mu*t) / (s*t*(pi**2 + s**2*t**2)) def RaisedCosine(name, mu, s): r""" Create a Continuous Random Variable with a raised cosine distribution. Explanation =========== The density of the raised cosine distribution is given by .. math:: f(x) := \frac{1}{2s}\left(1+\cos\left(\frac{x-\mu}{s}\pi\right)\right) with :math:`x \in [\mu-s,\mu+s]`. Parameters ========== mu : Real number s : Real number, `s > 0` Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import RaisedCosine, density >>> from sympy import Symbol, pprint >>> mu = Symbol("mu", real=True) >>> s = Symbol("s", positive=True) >>> z = Symbol("z") >>> X = RaisedCosine("x", mu, s) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) / /pi*(-mu + z)\ |cos|------------| + 1 | \ s / <--------------------- for And(z >= mu - s, z <= mu + s) | 2*s | \ 0 otherwise References ========== .. [1] https://en.wikipedia.org/wiki/Raised_cosine_distribution """ return rv(name, RaisedCosineDistribution, (mu, s)) #------------------------------------------------------------------------------- # Rayleigh distribution -------------------------------------------------------- class RayleighDistribution(SingleContinuousDistribution): _argnames = ('sigma',) set = Interval(0, oo) @staticmethod def check(sigma): _value_check(sigma > 0, "Scale parameter sigma must be positive.") def pdf(self, x): sigma = self.sigma return x/sigma**2*exp(-x**2/(2*sigma**2)) def _cdf(self, x): sigma = self.sigma return 1 - exp(-(x**2/(2*sigma**2))) def _characteristic_function(self, t): sigma = self.sigma return 1 - sigma*t*exp(-sigma**2*t**2/2) * sqrt(pi/2) * (erfi(sigma*t/sqrt(2)) - I) def _moment_generating_function(self, t): sigma = self.sigma return 1 + sigma*t*exp(sigma**2*t**2/2) * sqrt(pi/2) * (erf(sigma*t/sqrt(2)) + 1) def Rayleigh(name, sigma): r""" Create a continuous random variable with a Rayleigh distribution. Explanation =========== The density of the Rayleigh distribution is given by .. math :: f(x) := \frac{x}{\sigma^2} e^{-x^2/2\sigma^2} with :math:`x > 0`. Parameters ========== sigma : Real number, `\sigma > 0` Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Rayleigh, density, E, variance >>> from sympy import Symbol >>> sigma = Symbol("sigma", positive=True) >>> z = Symbol("z") >>> X = Rayleigh("x", sigma) >>> density(X)(z) z*exp(-z**2/(2*sigma**2))/sigma**2 >>> E(X) sqrt(2)*sqrt(pi)*sigma/2 >>> variance(X) -pi*sigma**2/2 + 2*sigma**2 References ========== .. [1] https://en.wikipedia.org/wiki/Rayleigh_distribution .. [2] http://mathworld.wolfram.com/RayleighDistribution.html """ return rv(name, RayleighDistribution, (sigma, )) #------------------------------------------------------------------------------- # Reciprocal distribution -------------------------------------------------------- class ReciprocalDistribution(SingleContinuousDistribution): _argnames = ('a', 'b') @property def set(self): return Interval(self.a, self.b) @staticmethod def check(a, b): _value_check(a > 0, "Parameter > 0. a = %s"%a) _value_check((a < b), "Parameter b must be in range (%s, +oo]. b = %s"%(a, b)) def pdf(self, x): a, b = self.a, self.b return 1/(x*(log(b) - log(a))) def Reciprocal(name, a, b): r"""Creates a continuous random variable with a reciprocal distribution. Parameters ========== a : Real number, :math:`0 < a` b : Real number, :math:`a < b` Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Reciprocal, density, cdf >>> from sympy import symbols >>> a, b, x = symbols('a, b, x', positive=True) >>> R = Reciprocal('R', a, b) >>> density(R)(x) 1/(x*(-log(a) + log(b))) >>> cdf(R)(x) Piecewise((log(a)/(log(a) - log(b)) - log(x)/(log(a) - log(b)), a <= x), (0, True)) Reference ========= .. [1] https://en.wikipedia.org/wiki/Reciprocal_distribution """ return rv(name, ReciprocalDistribution, (a, b)) #------------------------------------------------------------------------------- # Shifted Gompertz distribution ------------------------------------------------ class ShiftedGompertzDistribution(SingleContinuousDistribution): _argnames = ('b', 'eta') set = Interval(0, oo) @staticmethod def check(b, eta): _value_check(b > 0, "b must be positive") _value_check(eta > 0, "eta must be positive") def pdf(self, x): b, eta = self.b, self.eta return b*exp(-b*x)*exp(-eta*exp(-b*x))*(1+eta*(1-exp(-b*x))) def ShiftedGompertz(name, b, eta): r""" Create a continuous random variable with a Shifted Gompertz distribution. Explanation =========== The density of the Shifted Gompertz distribution is given by .. math:: f(x) := b e^{-b x} e^{-\eta \exp(-b x)} \left[1 + \eta(1 - e^(-bx)) \right] with :math: 'x \in [0, \inf)'. Parameters ========== b: Real number, 'b > 0' a scale eta: Real number, 'eta > 0' a shape Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import ShiftedGompertz, density >>> from sympy import Symbol >>> b = Symbol("b", positive=True) >>> eta = Symbol("eta", positive=True) >>> x = Symbol("x") >>> X = ShiftedGompertz("x", b, eta) >>> density(X)(x) b*(eta*(1 - exp(-b*x)) + 1)*exp(-b*x)*exp(-eta*exp(-b*x)) References ========== .. [1] https://en.wikipedia.org/wiki/Shifted_Gompertz_distribution """ return rv(name, ShiftedGompertzDistribution, (b, eta)) #------------------------------------------------------------------------------- # StudentT distribution -------------------------------------------------------- class StudentTDistribution(SingleContinuousDistribution): _argnames = ('nu',) set = Interval(-oo, oo) @staticmethod def check(nu): _value_check(nu > 0, "Degrees of freedom nu must be positive.") def pdf(self, x): nu = self.nu return 1/(sqrt(nu)*beta_fn(S.Half, nu/2))*(1 + x**2/nu)**(-(nu + 1)/2) def _cdf(self, x): nu = self.nu return S.Half + x*gamma((nu+1)/2)*hyper((S.Half, (nu+1)/2), (Rational(3, 2),), -x**2/nu)/(sqrt(pi*nu)*gamma(nu/2)) def _moment_generating_function(self, t): raise NotImplementedError('The moment generating function for the Student-T distribution is undefined.') def StudentT(name, nu): r""" Create a continuous random variable with a student's t distribution. Explanation =========== The density of the student's t distribution is given by .. math:: f(x) := \frac{\Gamma \left(\frac{\nu+1}{2} \right)} {\sqrt{\nu\pi}\Gamma \left(\frac{\nu}{2} \right)} \left(1+\frac{x^2}{\nu} \right)^{-\frac{\nu+1}{2}} Parameters ========== nu : Real number, `\nu > 0`, the degrees of freedom Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import StudentT, density, cdf >>> from sympy import Symbol, pprint >>> nu = Symbol("nu", positive=True) >>> z = Symbol("z") >>> X = StudentT("x", nu) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) nu 1 - -- - - 2 2 / 2\ | z | |1 + --| \ nu/ ----------------- ____ / nu\ \/ nu *B|1/2, --| \ 2 / >>> cdf(X)(z) 1/2 + z*gamma(nu/2 + 1/2)*hyper((1/2, nu/2 + 1/2), (3/2,), -z**2/nu)/(sqrt(pi)*sqrt(nu)*gamma(nu/2)) References ========== .. [1] https://en.wikipedia.org/wiki/Student_t-distribution .. [2] http://mathworld.wolfram.com/Studentst-Distribution.html """ return rv(name, StudentTDistribution, (nu, )) #------------------------------------------------------------------------------- # Trapezoidal distribution ------------------------------------------------------ class TrapezoidalDistribution(SingleContinuousDistribution): _argnames = ('a', 'b', 'c', 'd') @property def set(self): return Interval(self.a, self.d) @staticmethod def check(a, b, c, d): _value_check(a < d, "Lower bound parameter a < %s. a = %s"%(d, a)) _value_check((a <= b, b < c), "Level start parameter b must be in range [%s, %s). b = %s"%(a, c, b)) _value_check((b < c, c <= d), "Level end parameter c must be in range (%s, %s]. c = %s"%(b, d, c)) _value_check(d >= c, "Upper bound parameter d > %s. d = %s"%(c, d)) def pdf(self, x): a, b, c, d = self.a, self.b, self.c, self.d return Piecewise( (2*(x-a) / ((b-a)*(d+c-a-b)), And(a <= x, x < b)), (2 / (d+c-a-b), And(b <= x, x < c)), (2*(d-x) / ((d-c)*(d+c-a-b)), And(c <= x, x <= d)), (S.Zero, True)) def Trapezoidal(name, a, b, c, d): r""" Create a continuous random variable with a trapezoidal distribution. Explanation =========== The density of the trapezoidal distribution is given by .. math:: f(x) := \begin{cases} 0 & \mathrm{for\ } x < a, \\ \frac{2(x-a)}{(b-a)(d+c-a-b)} & \mathrm{for\ } a \le x < b, \\ \frac{2}{d+c-a-b} & \mathrm{for\ } b \le x < c, \\ \frac{2(d-x)}{(d-c)(d+c-a-b)} & \mathrm{for\ } c \le x < d, \\ 0 & \mathrm{for\ } d < x. \end{cases} Parameters ========== a : Real number, :math:`a < d` b : Real number, :math:`a <= b < c` c : Real number, :math:`b < c <= d` d : Real number Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Trapezoidal, density >>> from sympy import Symbol, pprint >>> a = Symbol("a") >>> b = Symbol("b") >>> c = Symbol("c") >>> d = Symbol("d") >>> z = Symbol("z") >>> X = Trapezoidal("x", a,b,c,d) >>> pprint(density(X)(z), use_unicode=False) / -2*a + 2*z |------------------------- for And(a <= z, b > z) |(-a + b)*(-a - b + c + d) | | 2 | -------------- for And(b <= z, c > z) < -a - b + c + d | | 2*d - 2*z |------------------------- for And(d >= z, c <= z) |(-c + d)*(-a - b + c + d) | \ 0 otherwise References ========== .. [1] https://en.wikipedia.org/wiki/Trapezoidal_distribution """ return rv(name, TrapezoidalDistribution, (a, b, c, d)) #------------------------------------------------------------------------------- # Triangular distribution ------------------------------------------------------ class TriangularDistribution(SingleContinuousDistribution): _argnames = ('a', 'b', 'c') @property def set(self): return Interval(self.a, self.b) @staticmethod def check(a, b, c): _value_check(b > a, "Parameter b > %s. b = %s"%(a, b)) _value_check((a <= c, c <= b), "Parameter c must be in range [%s, %s]. c = %s"%(a, b, c)) def pdf(self, x): a, b, c = self.a, self.b, self.c return Piecewise( (2*(x - a)/((b - a)*(c - a)), And(a <= x, x < c)), (2/(b - a), Eq(x, c)), (2*(b - x)/((b - a)*(b - c)), And(c < x, x <= b)), (S.Zero, True)) def _characteristic_function(self, t): a, b, c = self.a, self.b, self.c return -2 *((b-c) * exp(I*a*t) - (b-a) * exp(I*c*t) + (c-a) * exp(I*b*t)) / ((b-a)*(c-a)*(b-c)*t**2) def _moment_generating_function(self, t): a, b, c = self.a, self.b, self.c return 2 * ((b - c) * exp(a * t) - (b - a) * exp(c * t) + (c - a) * exp(b * t)) / ( (b - a) * (c - a) * (b - c) * t ** 2) def Triangular(name, a, b, c): r""" Create a continuous random variable with a triangular distribution. Explanation =========== The density of the triangular distribution is given by .. math:: f(x) := \begin{cases} 0 & \mathrm{for\ } x < a, \\ \frac{2(x-a)}{(b-a)(c-a)} & \mathrm{for\ } a \le x < c, \\ \frac{2}{b-a} & \mathrm{for\ } x = c, \\ \frac{2(b-x)}{(b-a)(b-c)} & \mathrm{for\ } c < x \le b, \\ 0 & \mathrm{for\ } b < x. \end{cases} Parameters ========== a : Real number, :math:`a \in \left(-\infty, \infty\right)` b : Real number, :math:`a < b` c : Real number, :math:`a \leq c \leq b` Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Triangular, density >>> from sympy import Symbol, pprint >>> a = Symbol("a") >>> b = Symbol("b") >>> c = Symbol("c") >>> z = Symbol("z") >>> X = Triangular("x", a,b,c) >>> pprint(density(X)(z), use_unicode=False) / -2*a + 2*z |----------------- for And(a <= z, c > z) |(-a + b)*(-a + c) | | 2 | ------ for c = z < -a + b | | 2*b - 2*z |---------------- for And(b >= z, c < z) |(-a + b)*(b - c) | \ 0 otherwise References ========== .. [1] https://en.wikipedia.org/wiki/Triangular_distribution .. [2] http://mathworld.wolfram.com/TriangularDistribution.html """ return rv(name, TriangularDistribution, (a, b, c)) #------------------------------------------------------------------------------- # Uniform distribution --------------------------------------------------------- class UniformDistribution(SingleContinuousDistribution): _argnames = ('left', 'right') @property def set(self): return Interval(self.left, self.right) @staticmethod def check(left, right): _value_check(left < right, "Lower limit should be less than Upper limit.") def pdf(self, x): left, right = self.left, self.right return Piecewise( (S.One/(right - left), And(left <= x, x <= right)), (S.Zero, True) ) def _cdf(self, x): left, right = self.left, self.right return Piecewise( (S.Zero, x < left), ((x - left)/(right - left), x <= right), (S.One, True) ) def _characteristic_function(self, t): left, right = self.left, self.right return Piecewise(((exp(I*t*right) - exp(I*t*left)) / (I*t*(right - left)), Ne(t, 0)), (S.One, True)) def _moment_generating_function(self, t): left, right = self.left, self.right return Piecewise(((exp(t*right) - exp(t*left)) / (t * (right - left)), Ne(t, 0)), (S.One, True)) def expectation(self, expr, var, **kwargs): from sympy import Max, Min kwargs['evaluate'] = True result = SingleContinuousDistribution.expectation(self, expr, var, **kwargs) result = result.subs({Max(self.left, self.right): self.right, Min(self.left, self.right): self.left}) return result def Uniform(name, left, right): r""" Create a continuous random variable with a uniform distribution. Explanation =========== The density of the uniform distribution is given by .. math:: f(x) := \begin{cases} \frac{1}{b - a} & \text{for } x \in [a,b] \\ 0 & \text{otherwise} \end{cases} with :math:`x \in [a,b]`. Parameters ========== a : Real number, :math:`-\infty < a` the left boundary b : Real number, :math:`a < b < \infty` the right boundary Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Uniform, density, cdf, E, variance >>> from sympy import Symbol, simplify >>> a = Symbol("a", negative=True) >>> b = Symbol("b", positive=True) >>> z = Symbol("z") >>> X = Uniform("x", a, b) >>> density(X)(z) Piecewise((1/(-a + b), (b >= z) & (a <= z)), (0, True)) >>> cdf(X)(z) Piecewise((0, a > z), ((-a + z)/(-a + b), b >= z), (1, True)) >>> E(X) a/2 + b/2 >>> simplify(variance(X)) a**2/12 - a*b/6 + b**2/12 References ========== .. [1] https://en.wikipedia.org/wiki/Uniform_distribution_%28continuous%29 .. [2] http://mathworld.wolfram.com/UniformDistribution.html """ return rv(name, UniformDistribution, (left, right)) #------------------------------------------------------------------------------- # UniformSum distribution ------------------------------------------------------ class UniformSumDistribution(SingleContinuousDistribution): _argnames = ('n',) @property def set(self): return Interval(0, self.n) @staticmethod def check(n): _value_check((n > 0, n.is_integer), "Parameter n must be positive integer.") def pdf(self, x): n = self.n k = Dummy("k") return 1/factorial( n - 1)*Sum((-1)**k*binomial(n, k)*(x - k)**(n - 1), (k, 0, floor(x))) def _cdf(self, x): n = self.n k = Dummy("k") return Piecewise((S.Zero, x < 0), (1/factorial(n)*Sum((-1)**k*binomial(n, k)*(x - k)**(n), (k, 0, floor(x))), x <= n), (S.One, True)) def _characteristic_function(self, t): return ((exp(I*t) - 1) / (I*t))**self.n def _moment_generating_function(self, t): return ((exp(t) - 1) / t)**self.n def UniformSum(name, n): r""" Create a continuous random variable with an Irwin-Hall distribution. Explanation =========== The probability distribution function depends on a single parameter $n$ which is an integer. The density of the Irwin-Hall distribution is given by .. math :: f(x) := \frac{1}{(n-1)!}\sum_{k=0}^{\left\lfloor x\right\rfloor}(-1)^k \binom{n}{k}(x-k)^{n-1} Parameters ========== n : A positive Integer, `n > 0` Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import UniformSum, density, cdf >>> from sympy import Symbol, pprint >>> n = Symbol("n", integer=True) >>> z = Symbol("z") >>> X = UniformSum("x", n) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) floor(z) ___ \ ` \ k n - 1 /n\ ) (-1) *(-k + z) *| | / \k/ /__, k = 0 -------------------------------- (n - 1)! >>> cdf(X)(z) Piecewise((0, z < 0), (Sum((-1)**_k*(-_k + z)**n*binomial(n, _k), (_k, 0, floor(z)))/factorial(n), n >= z), (1, True)) Compute cdf with specific 'x' and 'n' values as follows : >>> cdf(UniformSum("x", 5), evaluate=False)(2).doit() 9/40 The argument evaluate=False prevents an attempt at evaluation of the sum for general n, before the argument 2 is passed. References ========== .. [1] https://en.wikipedia.org/wiki/Uniform_sum_distribution .. [2] http://mathworld.wolfram.com/UniformSumDistribution.html """ return rv(name, UniformSumDistribution, (n, )) #------------------------------------------------------------------------------- # VonMises distribution -------------------------------------------------------- class VonMisesDistribution(SingleContinuousDistribution): _argnames = ('mu', 'k') set = Interval(0, 2*pi) @staticmethod def check(mu, k): _value_check(k > 0, "k must be positive") def pdf(self, x): mu, k = self.mu, self.k return exp(k*cos(x-mu)) / (2*pi*besseli(0, k)) def VonMises(name, mu, k): r""" Create a Continuous Random Variable with a von Mises distribution. Explanation =========== The density of the von Mises distribution is given by .. math:: f(x) := \frac{e^{\kappa\cos(x-\mu)}}{2\pi I_0(\kappa)} with :math:`x \in [0,2\pi]`. Parameters ========== mu : Real number Measure of location. k : Real number Measure of concentration. Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import VonMises, density >>> from sympy import Symbol, pprint >>> mu = Symbol("mu") >>> k = Symbol("k", positive=True) >>> z = Symbol("z") >>> X = VonMises("x", mu, k) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) k*cos(mu - z) e ------------------ 2*pi*besseli(0, k) References ========== .. [1] https://en.wikipedia.org/wiki/Von_Mises_distribution .. [2] http://mathworld.wolfram.com/vonMisesDistribution.html """ return rv(name, VonMisesDistribution, (mu, k)) #------------------------------------------------------------------------------- # Weibull distribution --------------------------------------------------------- class WeibullDistribution(SingleContinuousDistribution): _argnames = ('alpha', 'beta') set = Interval(0, oo) @staticmethod def check(alpha, beta): _value_check(alpha > 0, "Alpha must be positive") _value_check(beta > 0, "Beta must be positive") def pdf(self, x): alpha, beta = self.alpha, self.beta return beta * (x/alpha)**(beta - 1) * exp(-(x/alpha)**beta) / alpha def Weibull(name, alpha, beta): r""" Create a continuous random variable with a Weibull distribution. Explanation =========== The density of the Weibull distribution is given by .. math:: f(x) := \begin{cases} \frac{k}{\lambda}\left(\frac{x}{\lambda}\right)^{k-1} e^{-(x/\lambda)^{k}} & x\geq0\\ 0 & x<0 \end{cases} Parameters ========== lambda : Real number, :math:`\lambda > 0` a scale k : Real number, ``k > 0`` a shape Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Weibull, density, E, variance >>> from sympy import Symbol, simplify >>> l = Symbol("lambda", positive=True) >>> k = Symbol("k", positive=True) >>> z = Symbol("z") >>> X = Weibull("x", l, k) >>> density(X)(z) k*(z/lambda)**(k - 1)*exp(-(z/lambda)**k)/lambda >>> simplify(E(X)) lambda*gamma(1 + 1/k) >>> simplify(variance(X)) lambda**2*(-gamma(1 + 1/k)**2 + gamma(1 + 2/k)) References ========== .. [1] https://en.wikipedia.org/wiki/Weibull_distribution .. [2] http://mathworld.wolfram.com/WeibullDistribution.html """ return rv(name, WeibullDistribution, (alpha, beta)) #------------------------------------------------------------------------------- # Wigner semicircle distribution ----------------------------------------------- class WignerSemicircleDistribution(SingleContinuousDistribution): _argnames = ('R',) @property def set(self): return Interval(-self.R, self.R) @staticmethod def check(R): _value_check(R > 0, "Radius R must be positive.") def pdf(self, x): R = self.R return 2/(pi*R**2)*sqrt(R**2 - x**2) def _characteristic_function(self, t): return Piecewise((2 * besselj(1, self.R*t) / (self.R*t), Ne(t, 0)), (S.One, True)) def _moment_generating_function(self, t): return Piecewise((2 * besseli(1, self.R*t) / (self.R*t), Ne(t, 0)), (S.One, True)) def WignerSemicircle(name, R): r""" Create a continuous random variable with a Wigner semicircle distribution. Explanation =========== The density of the Wigner semicircle distribution is given by .. math:: f(x) := \frac2{\pi R^2}\,\sqrt{R^2-x^2} with :math:`x \in [-R,R]`. Parameters ========== R : Real number, `R > 0`, the radius Returns ======= A `RandomSymbol`. Examples ======== >>> from sympy.stats import WignerSemicircle, density, E >>> from sympy import Symbol >>> R = Symbol("R", positive=True) >>> z = Symbol("z") >>> X = WignerSemicircle("x", R) >>> density(X)(z) 2*sqrt(R**2 - z**2)/(pi*R**2) >>> E(X) 0 References ========== .. [1] https://en.wikipedia.org/wiki/Wigner_semicircle_distribution .. [2] http://mathworld.wolfram.com/WignersSemicircleLaw.html """ return rv(name, WignerSemicircleDistribution, (R,))