hash
stringlengths
64
64
content
stringlengths
0
1.51M
68051618ff9212670df8223a333b8639bf41fd9ca331c486c86f4e78f5d6ea16
"""Implementation of :class:`AlgebraicField` class. """ from sympy.polys.domains.characteristiczero import CharacteristicZero from sympy.polys.domains.field import Field from sympy.polys.domains.simpledomain import SimpleDomain from sympy.polys.polyclasses import ANP from sympy.polys.polyerrors import CoercionFailed, DomainError, NotAlgebraic, IsomorphismFailed from sympy.utilities import public @public class AlgebraicField(Field, CharacteristicZero, SimpleDomain): """A class for representing algebraic number fields. """ dtype = ANP is_AlgebraicField = is_Algebraic = True is_Numerical = True has_assoc_Ring = False has_assoc_Field = True def __init__(self, dom, *ext): if not dom.is_QQ: raise DomainError("ground domain must be a rational field") from sympy.polys.numberfields import to_number_field if len(ext) == 1 and isinstance(ext[0], tuple): self.orig_ext = ext[0][1:] else: self.orig_ext = ext self.ext = to_number_field(ext) self.mod = self.ext.minpoly.rep self.domain = self.dom = dom self.ngens = 1 self.symbols = self.gens = (self.ext,) self.unit = self([dom(1), dom(0)]) self.zero = self.dtype.zero(self.mod.rep, dom) self.one = self.dtype.one(self.mod.rep, dom) def new(self, element): return self.dtype(element, self.mod.rep, self.dom) def __str__(self): return str(self.dom) + '<' + str(self.ext) + '>' def __hash__(self): return hash((self.__class__.__name__, self.dtype, self.dom, self.ext)) def __eq__(self, other): """Returns ``True`` if two domains are equivalent. """ return isinstance(other, AlgebraicField) and \ self.dtype == other.dtype and self.ext == other.ext def algebraic_field(self, *extension): r"""Returns an algebraic field, i.e. `\mathbb{Q}(\alpha, \ldots)`. """ return AlgebraicField(self.dom, *((self.ext,) + extension)) def to_sympy(self, a): """Convert ``a`` to a SymPy object. """ from sympy.polys.numberfields import AlgebraicNumber return AlgebraicNumber(self.ext, a).as_expr() def from_sympy(self, a): """Convert SymPy's expression to ``dtype``. """ try: return self([self.dom.from_sympy(a)]) except CoercionFailed: pass from sympy.polys.numberfields import to_number_field try: return self(to_number_field(a, self.ext).native_coeffs()) except (NotAlgebraic, IsomorphismFailed): raise CoercionFailed( "%s is not a valid algebraic number in %s" % (a, self)) def from_ZZ_python(K1, a, K0): """Convert a Python ``int`` 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 get_ring(self): """Returns a ring associated with ``self``. """ raise DomainError('there is no ring associated with %s' % self) def is_positive(self, a): """Returns True if ``a`` is positive. """ return self.dom.is_positive(a.LC()) def is_negative(self, a): """Returns True if ``a`` is negative. """ return self.dom.is_negative(a.LC()) def is_nonpositive(self, a): """Returns True if ``a`` is non-positive. """ return self.dom.is_nonpositive(a.LC()) def is_nonnegative(self, a): """Returns True if ``a`` is non-negative. """ return self.dom.is_nonnegative(a.LC()) def numer(self, a): """Returns numerator of ``a``. """ return a def denom(self, a): """Returns denominator of ``a``. """ return self.one def from_AlgebraicField(K1, a, K0): """Convert AlgebraicField element 'a' to another AlgebraicField """ return K1.from_sympy(K0.to_sympy(a)) def from_GaussianIntegerRing(K1, a, K0): """Convert a GaussianInteger element 'a' to ``dtype``. """ return K1.from_sympy(K0.to_sympy(a)) def from_GaussianRationalField(K1, a, K0): """Convert a GaussianRational element 'a' to ``dtype``. """ return K1.from_sympy(K0.to_sympy(a))
6e63152f72a3cf351ae0cdda4cebb494c228e541b649e800974d8957e26d27c8
"""Implementation of :class:`Ring` class. """ from sympy.polys.domains.domain import Domain from sympy.polys.polyerrors import ExactQuotientFailed, NotInvertible, NotReversible from sympy.utilities import public @public class Ring(Domain): """Represents a ring domain. """ is_Ring = True def get_ring(self): """Returns a ring associated with ``self``. """ return self def exquo(self, a, b): """Exact quotient of ``a`` and ``b``, implies ``__floordiv__``. """ if a % b: raise ExactQuotientFailed(a, b, self) else: return a // b def quo(self, a, b): """Quotient of ``a`` and ``b``, implies ``__floordiv__``. """ return a // b def rem(self, a, b): """Remainder of ``a`` and ``b``, implies ``__mod__``. """ return a % b def div(self, a, b): """Division of ``a`` and ``b``, implies ``__divmod__``. """ return divmod(a, b) def invert(self, a, b): """Returns inversion of ``a mod b``. """ s, t, h = self.gcdex(a, b) if self.is_one(h): return s % b else: raise NotInvertible("zero divisor") def revert(self, a): """Returns ``a**(-1)`` if possible. """ if self.is_one(a): return a else: raise NotReversible('only unity is reversible in a ring') def is_unit(self, a): try: self.revert(a) return True except NotReversible: return False def numer(self, a): """Returns numerator of ``a``. """ return a def denom(self, a): """Returns denominator of `a`. """ return self.one 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).free_module(2) QQ[x]**2 """ raise NotImplementedError def ideal(self, *gens): """ Generate an ideal of ``self``. >>> from sympy.abc import x >>> from sympy import QQ >>> QQ.old_poly_ring(x).ideal(x**2) <x**2> """ from sympy.polys.agca.ideals import ModuleImplementedIdeal return ModuleImplementedIdeal(self, self.free_module(1).submodule( *[[x] for x in gens])) def quotient_ring(self, e): """ Form a quotient ring of ``self``. Here ``e`` can be an ideal or an iterable. >>> from sympy.abc import x >>> from sympy import QQ >>> QQ.old_poly_ring(x).quotient_ring(QQ.old_poly_ring(x).ideal(x**2)) QQ[x]/<x**2> >>> QQ.old_poly_ring(x).quotient_ring([x**2]) QQ[x]/<x**2> The division operator has been overloaded for this: >>> QQ.old_poly_ring(x)/[x**2] QQ[x]/<x**2> """ from sympy.polys.agca.ideals import Ideal from sympy.polys.domains.quotientring import QuotientRing if not isinstance(e, Ideal): e = self.ideal(*e) return QuotientRing(self, e) def __truediv__(self, e): return self.quotient_ring(e)
09f8d8e165090577062e9246c2f6f8a989c5d0b1c3c37d43d9284773e27d0a50
"""Trait for implementing domain elements. """ from sympy.utilities import public @public class DomainElement: """ Represents an element of a domain. Mix in this trait into a class which instances should be recognized as elements of a domain. Method ``parent()`` gives that domain. """ def parent(self): raise NotImplementedError("abstract method")
984cf91e7317f80b62d09fc30d28ac5b462cb9a06ac97ba3e56f08924eae7bb4
"""Rational number type based on Python integers. """ import operator from sympy.core.numbers import Rational, Integer from sympy.core.sympify import converter from sympy.polys.polyutils import PicklableWithSlots from sympy.polys.domains.domainelement import DomainElement from sympy.printing.defaults import DefaultPrinting from sympy.utilities import public @public class PythonRational(DefaultPrinting, PicklableWithSlots, DomainElement): """ Rational number type based on Python integers. This was supposed to be needed for compatibility with older Python versions which don't support Fraction. However, Fraction is very slow so we don't use it anyway. Examples ======== >>> from sympy.polys.domains import PythonRational >>> PythonRational(1) 1 >>> PythonRational(2, 3) 2/3 >>> PythonRational(14, 10) 7/5 """ __slots__ = ('p', 'q') def parent(self): from sympy.polys.domains import PythonRationalField return PythonRationalField() def __init__(self, p, q=1, _gcd=True): from sympy.polys.domains.groundtypes import python_gcd as gcd if isinstance(p, Integer): p = p.p elif isinstance(p, Rational): p, q = p.p, p.q if not q: raise ZeroDivisionError('rational number') elif q < 0: p, q = -p, -q if not p: self.p = 0 self.q = 1 elif p == 1 or q == 1: self.p = p self.q = q else: if _gcd: x = gcd(p, q) if x != 1: p //= x q //= x self.p = p self.q = q @classmethod def new(cls, p, q): obj = object.__new__(cls) obj.p = p obj.q = q return obj def __hash__(self): if self.q == 1: return hash(self.p) else: return hash((self.p, self.q)) def __int__(self): p, q = self.p, self.q if p < 0: return -(-p//q) return p//q def __float__(self): return float(self.p)/self.q def __abs__(self): return self.new(abs(self.p), self.q) def __pos__(self): return self.new(+self.p, self.q) def __neg__(self): return self.new(-self.p, self.q) def __add__(self, other): from sympy.polys.domains.groundtypes import python_gcd as gcd if isinstance(other, PythonRational): ap, aq, bp, bq = self.p, self.q, other.p, other.q g = gcd(aq, bq) if g == 1: p = ap*bq + aq*bp q = bq*aq else: q1, q2 = aq//g, bq//g p, q = ap*q2 + bp*q1, q1*q2 g2 = gcd(p, g) p, q = (p // g2), q * (g // g2) elif isinstance(other, int): p = self.p + self.q*other q = self.q else: return NotImplemented return self.__class__(p, q, _gcd=False) def __radd__(self, other): if not isinstance(other, int): return NotImplemented p = self.p + self.q*other q = self.q return self.__class__(p, q, _gcd=False) def __sub__(self, other): from sympy.polys.domains.groundtypes import python_gcd as gcd if isinstance(other, PythonRational): ap, aq, bp, bq = self.p, self.q, other.p, other.q g = gcd(aq, bq) if g == 1: p = ap*bq - aq*bp q = bq*aq else: q1, q2 = aq//g, bq//g p, q = ap*q2 - bp*q1, q1*q2 g2 = gcd(p, g) p, q = (p // g2), q * (g // g2) elif isinstance(other, int): p = self.p - self.q*other q = self.q else: return NotImplemented return self.__class__(p, q, _gcd=False) def __rsub__(self, other): if not isinstance(other, int): return NotImplemented p = self.q*other - self.p q = self.q return self.__class__(p, q, _gcd=False) def __mul__(self, other): from sympy.polys.domains.groundtypes import python_gcd as gcd if isinstance(other, PythonRational): ap, aq, bp, bq = self.p, self.q, other.p, other.q x1 = gcd(ap, bq) x2 = gcd(bp, aq) p, q = ((ap//x1)*(bp//x2), (aq//x2)*(bq//x1)) elif isinstance(other, int): x = gcd(other, self.q) p = self.p*(other//x) q = self.q//x else: return NotImplemented return self.__class__(p, q, _gcd=False) def __rmul__(self, other): from sympy.polys.domains.groundtypes import python_gcd as gcd if not isinstance(other, int): return NotImplemented x = gcd(self.q, other) p = self.p*(other//x) q = self.q//x return self.__class__(p, q, _gcd=False) def __truediv__(self, other): from sympy.polys.domains.groundtypes import python_gcd as gcd if isinstance(other, PythonRational): ap, aq, bp, bq = self.p, self.q, other.p, other.q x1 = gcd(ap, bp) x2 = gcd(bq, aq) p, q = ((ap//x1)*(bq//x2), (aq//x2)*(bp//x1)) elif isinstance(other, int): x = gcd(other, self.p) p = self.p//x q = self.q*(other//x) else: return NotImplemented return self.__class__(p, q, _gcd=False) def __rtruediv__(self, other): from sympy.polys.domains.groundtypes import python_gcd as gcd if not isinstance(other, int): return NotImplemented x = gcd(self.p, other) p = self.q*(other//x) q = self.p//x return self.__class__(p, q) def __mod__(self, other): return self.__class__(0) def __divmod__(self, other): return (self//other, self % other) def __pow__(self, exp): p, q = self.p, self.q if exp < 0: p, q, exp = q, p, -exp return self.__class__(p**exp, q**exp, _gcd=False) def __bool__(self): return self.p != 0 def __eq__(self, other): if isinstance(other, PythonRational): return self.q == other.q and self.p == other.p elif isinstance(other, int): return self.q == 1 and self.p == other else: return NotImplemented def __ne__(self, other): return not self == other def _cmp(self, other, op): try: diff = self - other except TypeError: return NotImplemented else: return op(diff.p, 0) def __lt__(self, other): return self._cmp(other, operator.lt) def __le__(self, other): return self._cmp(other, operator.le) def __gt__(self, other): return self._cmp(other, operator.gt) def __ge__(self, other): return self._cmp(other, operator.ge) @property def numer(self): return self.p @property def denom(self): return self.q numerator = numer denominator = denom def sympify_pythonrational(arg): return Rational(arg.p, arg.q) converter[PythonRational] = sympify_pythonrational
fcaf99cfc3a97f9d39af77874ab6cf0259c68864a363f3b80b06b839378e4a86
"""Implementation of :class:`SimpleDomain` class. """ from sympy.polys.domains.domain import Domain from sympy.utilities import public @public class SimpleDomain(Domain): """Base class for simple domains, e.g. ZZ, QQ. """ is_Simple = True def inject(self, *gens): """Inject generators into this domain. """ return self.poly_ring(*gens)
fe36a7f5a2e95964ef411a44f2571c674234b7b88b2a1ade76a3c34fda44a7f1
"""Implementation of mathematical domains. """ __all__ = [ 'Domain', 'FiniteField', 'IntegerRing', 'RationalField', 'RealField', 'ComplexField', 'PythonFiniteField', 'GMPYFiniteField', 'PythonIntegerRing', 'GMPYIntegerRing', 'PythonRational', 'GMPYRationalField', 'AlgebraicField', 'PolynomialRing', 'FractionField', 'ExpressionDomain', 'PythonRational', 'FF_python', 'FF_gmpy', 'ZZ_python', 'ZZ_gmpy', 'QQ_python', 'QQ_gmpy', 'GF', 'FF', 'ZZ', 'QQ', 'ZZ_I', 'QQ_I', 'RR', 'CC', 'EX', ] from typing import Tuple, Type from .domain import Domain from .finitefield import FiniteField from .integerring import IntegerRing from .rationalfield import RationalField from .realfield import RealField from .complexfield import ComplexField from .pythonfinitefield import PythonFiniteField from .gmpyfinitefield import GMPYFiniteField from .pythonintegerring import PythonIntegerRing from .gmpyintegerring import GMPYIntegerRing from .pythonrationalfield import PythonRationalField from .gmpyrationalfield import GMPYRationalField from .algebraicfield import AlgebraicField from .polynomialring import PolynomialRing from .fractionfield import FractionField from .expressiondomain import ExpressionDomain from .pythonrational import PythonRational FF_python = PythonFiniteField FF_gmpy = GMPYFiniteField ZZ_python = PythonIntegerRing ZZ_gmpy = GMPYIntegerRing QQ_python = PythonRationalField QQ_gmpy = GMPYRationalField RR = RealField() CC = ComplexField() from sympy.core.compatibility import GROUND_TYPES _GROUND_TYPES_MAP = { 'gmpy': (FF_gmpy, ZZ_gmpy(), QQ_gmpy()), 'python': (FF_python, ZZ_python(), QQ_python()), } try: FF, ZZ, QQ = _GROUND_TYPES_MAP[GROUND_TYPES] # type: Tuple[Type[FiniteField], Domain, Domain] except KeyError: raise ValueError("invalid ground types: %s" % GROUND_TYPES) # Needs to be after ZZ and QQ are defined: from .gaussiandomains import ZZ_I, QQ_I GF = FF EX = ExpressionDomain()
70a801411df528c59ec9a78621dbc6e69b4cbecc71c97715519e7e08b7bdbdf4
"""Implementation of :class:`FiniteField` class. """ from sympy.polys.domains.field import Field from sympy.polys.domains.modularinteger import ModularIntegerFactory from sympy.polys.domains.simpledomain import SimpleDomain from sympy.polys.polyerrors import CoercionFailed from sympy.utilities import public from sympy.polys.domains.groundtypes import SymPyInteger @public class FiniteField(Field, SimpleDomain): """General class for finite fields. """ rep = 'FF' is_FiniteField = is_FF = True is_Numerical = True has_assoc_Ring = False has_assoc_Field = True dom = None mod = None def __init__(self, mod, dom=None, symmetric=True): if mod <= 0: raise ValueError('modulus must be a positive integer, got %s' % mod) if dom is None: from sympy.polys.domains import ZZ dom = ZZ self.dtype = ModularIntegerFactory(mod, dom, symmetric, self) self.zero = self.dtype(0) self.one = self.dtype(1) self.dom = dom self.mod = mod def __str__(self): return 'GF(%s)' % self.mod def __hash__(self): return hash((self.__class__.__name__, self.dtype, self.mod, self.dom)) def __eq__(self, other): """Returns ``True`` if two domains are equivalent. """ return isinstance(other, FiniteField) and \ self.mod == other.mod and self.dom == other.dom def characteristic(self): """Return the characteristic of this domain. """ return self.mod def get_field(self): """Returns a field associated with ``self``. """ return self 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 SymPy's ``Integer``. """ if a.is_Integer: return self.dtype(self.dom.dtype(int(a))) elif a.is_Float and int(a) == a: return self.dtype(self.dom.dtype(int(a))) else: raise CoercionFailed("expected an integer, got %s" % a) def from_FF_python(K1, a, K0=None): """Convert ``ModularInteger(int)`` to ``dtype``. """ return K1.dtype(K1.dom.from_ZZ_python(a.val, K0.dom)) def from_ZZ_python(K1, a, K0=None): """Convert Python's ``int`` to ``dtype``. """ return K1.dtype(K1.dom.from_ZZ_python(a, K0)) def from_QQ_python(K1, a, K0=None): """Convert Python's ``Fraction`` to ``dtype``. """ if a.denominator == 1: return K1.from_ZZ_python(a.numerator) def from_FF_gmpy(K1, a, K0=None): """Convert ``ModularInteger(mpz)`` to ``dtype``. """ return K1.dtype(K1.dom.from_ZZ_gmpy(a.val, K0.dom)) def from_ZZ_gmpy(K1, a, K0=None): """Convert GMPY's ``mpz`` to ``dtype``. """ return K1.dtype(K1.dom.from_ZZ_gmpy(a, K0)) def from_QQ_gmpy(K1, a, K0=None): """Convert GMPY's ``mpq`` to ``dtype``. """ if a.denominator == 1: return K1.from_ZZ_gmpy(a.numerator) def from_RealField(K1, a, K0): """Convert mpmath's ``mpf`` to ``dtype``. """ p, q = K0.to_rational(a) if q == 1: return K1.dtype(K1.dom.dtype(p))
f875179e1a507164ae6a663eb39335ec5fb9a16e89f9acc4b2671d10fffbea26
"""Implementation of :class:`PythonIntegerRing` class. """ from sympy.polys.domains.groundtypes import ( PythonInteger, SymPyInteger, python_sqrt, python_factorial, python_gcdex, python_gcd, python_lcm, ) from sympy.polys.domains.integerring import IntegerRing from sympy.polys.polyerrors import CoercionFailed from sympy.utilities import public @public class PythonIntegerRing(IntegerRing): """Integer ring based on Python's ``int`` type. """ dtype = PythonInteger zero = dtype(0) one = dtype(1) alias = 'ZZ_python' def __init__(self): """Allow instantiation of this domain. """ def to_sympy(self, a): """Convert ``a`` to a SymPy object. """ return SymPyInteger(a) def from_sympy(self, a): """Convert SymPy's Integer to ``dtype``. """ if a.is_Integer: return PythonInteger(a.p) elif a.is_Float and int(a) == a: return PythonInteger(int(a)) else: raise CoercionFailed("expected an integer, got %s" % a) def from_FF_python(K1, a, K0): """Convert ``ModularInteger(int)`` to Python's ``int``. """ return a.to_int() def from_ZZ_python(K1, a, K0): """Convert Python's ``int`` to Python's ``int``. """ return a def from_QQ_python(K1, a, K0): """Convert Python's ``Fraction`` to Python's ``int``. """ if a.denominator == 1: return a.numerator def from_FF_gmpy(K1, a, K0): """Convert ``ModularInteger(mpz)`` to Python's ``int``. """ return PythonInteger(a.to_int()) def from_ZZ_gmpy(K1, a, K0): """Convert GMPY's ``mpz`` to Python's ``int``. """ return PythonInteger(a) def from_QQ_gmpy(K1, a, K0): """Convert GMPY's ``mpq`` to Python's ``int``. """ if a.denom() == 1: return PythonInteger(a.numer()) def from_RealField(K1, a, K0): """Convert mpmath's ``mpf`` to Python's ``int``. """ p, q = K0.to_rational(a) if q == 1: return PythonInteger(p) def gcdex(self, a, b): """Compute extended GCD of ``a`` and ``b``. """ return python_gcdex(a, b) def gcd(self, a, b): """Compute GCD of ``a`` and ``b``. """ return python_gcd(a, b) def lcm(self, a, b): """Compute LCM of ``a`` and ``b``. """ return python_lcm(a, b) def sqrt(self, a): """Compute square root of ``a``. """ return python_sqrt(a) def factorial(self, a): """Compute factorial of ``a``. """ return python_factorial(a)
3d5f604811f8c540cea2271409661fdb732c06bdc02b1e2fec7fdb2c4fdebbf9
"""Implementation of :class:`GMPYRationalField` class. """ from sympy.polys.domains.groundtypes import ( GMPYRational, SymPyRational, gmpy_numer, gmpy_denom, gmpy_factorial, ) from sympy.polys.domains.rationalfield import RationalField from sympy.polys.polyerrors import CoercionFailed from sympy.utilities import public @public class GMPYRationalField(RationalField): """Rational field based on GMPY mpq class. """ dtype = GMPYRational zero = dtype(0) one = dtype(1) tp = type(one) alias = 'QQ_gmpy' def __init__(self): pass def get_ring(self): """Returns ring associated with ``self``. """ from sympy.polys.domains import GMPYIntegerRing return GMPYIntegerRing() def to_sympy(self, a): """Convert `a` to a SymPy object. """ return SymPyRational(int(gmpy_numer(a)), int(gmpy_denom(a))) def from_sympy(self, a): """Convert SymPy's Integer to `dtype`. """ if a.is_Rational: return GMPYRational(a.p, a.q) elif a.is_Float: from sympy.polys.domains import RR return GMPYRational(*map(int, RR.to_rational(a))) else: raise CoercionFailed("expected `Rational` object, got %s" % a) def from_ZZ_python(K1, a, K0): """Convert a Python `int` object to `dtype`. """ return GMPYRational(a) def from_QQ_python(K1, a, K0): """Convert a Python `Fraction` object to `dtype`. """ return GMPYRational(a.numerator, a.denominator) def from_ZZ_gmpy(K1, a, K0): """Convert a GMPY `mpz` object to `dtype`. """ return GMPYRational(a) def from_QQ_gmpy(K1, a, K0): """Convert a GMPY `mpq` object to `dtype`. """ return a def from_GaussianRationalField(K1, a, K0): """Convert a `GaussianElement` object to `dtype`. """ if a.y == 0: return GMPYRational(a.x) def from_RealField(K1, a, K0): """Convert a mpmath `mpf` object to `dtype`. """ return GMPYRational(*map(int, K0.to_rational(a))) def exquo(self, a, b): """Exact quotient of `a` and `b`, implies `__truediv__`. """ return GMPYRational(a) / GMPYRational(b) def quo(self, a, b): """Quotient of `a` and `b`, implies `__truediv__`. """ return GMPYRational(a) / GMPYRational(b) def rem(self, a, b): """Remainder of `a` and `b`, implies nothing. """ return self.zero def div(self, a, b): """Division of `a` and `b`, implies `__truediv__`. """ return GMPYRational(a) / GMPYRational(b), self.zero def numer(self, a): """Returns numerator of `a`. """ return a.numerator def denom(self, a): """Returns denominator of `a`. """ return a.denominator def factorial(self, a): """Returns factorial of `a`. """ return GMPYRational(gmpy_factorial(int(a)))
5ba3a13c3ed7db4ede4c51d6462455b7bce07c327caf7a978246bcfce3c8938e
"""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) 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): 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_python(K1, a, K0): """Convert a Python `int` object to `dtype`. """ return K1(K1.ring.convert(a, K0)) 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)
fba72ce21b3df6ba525e485fa7bcc94362c06fc9c4c31b2a9feab03e12191c3e
"""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_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_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)
45c2060bdc0aa07e5289a3aca02d93e3d310280c1628273f6392a456753aee57
"""Implementation of :class:`Field` class. """ from sympy.polys.domains.ring import Ring from sympy.polys.polyerrors import NotReversible, DomainError from sympy.utilities import public @public class Field(Ring): """Represents a field domain. """ is_Field = True is_PID = True 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``. """ return self def exquo(self, a, b): """Exact quotient of ``a`` and ``b``, implies ``__truediv__``. """ return a / b def quo(self, a, b): """Quotient of ``a`` and ``b``, implies ``__truediv__``. """ return a / b def rem(self, a, b): """Remainder of ``a`` and ``b``, implies nothing. """ return self.zero def div(self, a, b): """Division of ``a`` and ``b``, implies ``__truediv__``. """ return a / b, self.zero def gcd(self, a, b): """ Returns GCD of ``a`` and ``b``. This definition of GCD over fields allows to clear denominators in `primitive()`. Examples ======== >>> from sympy.polys.domains import QQ >>> from sympy import S, gcd, primitive >>> from sympy.abc import x >>> QQ.gcd(QQ(2, 3), QQ(4, 9)) 2/9 >>> gcd(S(2)/3, S(4)/9) 2/9 >>> primitive(2*x/3 + S(4)/9) (2/9, 3*x + 2) """ try: ring = self.get_ring() except DomainError: return self.one p = ring.gcd(self.numer(a), self.numer(b)) q = ring.lcm(self.denom(a), self.denom(b)) return self.convert(p, ring)/q def lcm(self, a, b): """ Returns LCM of ``a`` and ``b``. >>> from sympy.polys.domains import QQ >>> from sympy import S, lcm >>> QQ.lcm(QQ(2, 3), QQ(4, 9)) 4/3 >>> lcm(S(2)/3, S(4)/9) 4/3 """ try: ring = self.get_ring() except DomainError: return a*b p = ring.lcm(self.numer(a), self.numer(b)) q = ring.gcd(self.denom(a), self.denom(b)) return self.convert(p, ring)/q def revert(self, a): """Returns ``a**(-1)`` if possible. """ if a: return 1/a else: raise NotReversible('zero is not reversible')
d33512b6b888be2ded904c8322db83fd31eedd40db58a3f47e2c536a3d86f2a8
"""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 Python rational number type. """ 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
0c094cd4d589262f014cf6f4cdaf230941bae5947e7cd6b867a85c2328d455cc
"""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_python(K1, a, K0): """Convert a Python `int` 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_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)
138feb76cb72f63d07254ae2cf532f42ae155ffe4da718f886a00934157aff58
"""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 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_python(K1, a, K0): """Convert a Python `int` 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_AlgebraicField(K1, a, K0): """Convert an algebraic number to ``dtype``. """ if K1.domain == K0: 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 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))
fa1064f2e81f0598478fcd39387b7ed7d93597e4e0cce4b5cb3c9eca3a54662b
"""Implementation of :class:`IntegerRing` class. """ from sympy.polys.domains.characteristiczero import CharacteristicZero from sympy.polys.domains.ring import Ring from sympy.polys.domains.simpledomain import SimpleDomain from sympy.utilities import public import math @public class IntegerRing(Ring, CharacteristicZero, SimpleDomain): """General class for integer rings. """ rep = 'ZZ' is_IntegerRing = is_ZZ = True is_Numerical = True is_PID = True has_assoc_Ring = True has_assoc_Field = True def get_field(self): """Returns a field associated with ``self``. """ from sympy.polys.domains import QQ return QQ def algebraic_field(self, *extension): r"""Returns an algebraic field, i.e. `\mathbb{Q}(\alpha, \ldots)`. """ return self.get_field().algebraic_field(*extension) def from_AlgebraicField(K1, a, K0): """Convert a ``ANP`` object to ``dtype``. """ if a.is_ground: return K1.convert(a.LC(), K0.dom) def log(self, a, b): """Returns b-base logarithm of ``a``. """ return self.dtype(math.log(int(a), b))
14b7e60a2f7380f66b197286e968ac28147f61f27ba12e8603b091ec2846a6d2
"""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_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_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 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)
824a104bcdba933e852161ea339eb83eadcac4f248713ed7f9c9816e4ee75ad6
"""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_python(K1, a, K0): """Convert a Python `int` 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_AlgebraicField(K1, a, K0): """Convert an algebraic number to ``dtype``. """ if K1.domain == K0: return K1.new(a) def from_PolynomialRing(K1, a, K0): """Convert a polynomial to ``dtype``. """ 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))
696a765fc274c2c00cc0f21176ddf5b47bbb22112144aab82ab926b250d3c052
"""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 f.ex != 0 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_python(K1, a, K0): """Convert a Python ``int`` 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)
f566fb1d7c7cc0f2491ba2cfbee04ce4711ca520c4dda4fe50b9b575fca22325
"""Implementation of :class:`ModularInteger` class. """ from typing import Any, Dict, Tuple, Type import operator from sympy.polys.polyutils import PicklableWithSlots from sympy.polys.polyerrors import CoercionFailed from sympy.polys.domains.domainelement import DomainElement from sympy.utilities import public @public class ModularInteger(PicklableWithSlots, DomainElement): """A class representing a modular integer. """ mod, dom, sym, _parent = None, None, None, None __slots__ = ('val',) def parent(self): return self._parent def __init__(self, val): if isinstance(val, self.__class__): self.val = val.val % self.mod else: self.val = self.dom.convert(val) % self.mod def __hash__(self): return hash((self.val, self.mod)) def __repr__(self): return "%s(%s)" % (self.__class__.__name__, self.val) def __str__(self): return "%s mod %s" % (self.val, self.mod) def __int__(self): return int(self.to_int()) def to_int(self): if self.sym: if self.val <= self.mod // 2: return self.val else: return self.val - self.mod else: return self.val def __pos__(self): return self def __neg__(self): return self.__class__(-self.val) @classmethod def _get_val(cls, other): if isinstance(other, cls): return other.val else: try: return cls.dom.convert(other) except CoercionFailed: return None def __add__(self, other): val = self._get_val(other) if val is not None: return self.__class__(self.val + val) else: return NotImplemented def __radd__(self, other): return self.__add__(other) def __sub__(self, other): val = self._get_val(other) if val is not None: return self.__class__(self.val - val) else: return NotImplemented def __rsub__(self, other): return (-self).__add__(other) def __mul__(self, other): val = self._get_val(other) if val is not None: return self.__class__(self.val * val) else: return NotImplemented def __rmul__(self, other): return self.__mul__(other) def __truediv__(self, other): val = self._get_val(other) if val is not None: return self.__class__(self.val * self._invert(val)) else: return NotImplemented def __rtruediv__(self, other): return self.invert().__mul__(other) def __mod__(self, other): val = self._get_val(other) if val is not None: return self.__class__(self.val % val) else: return NotImplemented def __rmod__(self, other): val = self._get_val(other) if val is not None: return self.__class__(val % self.val) else: return NotImplemented def __pow__(self, exp): if not exp: return self.__class__(self.dom.one) if exp < 0: val, exp = self.invert().val, -exp else: val = self.val return self.__class__(pow(val, int(exp), self.mod)) def _compare(self, other, op): val = self._get_val(other) if val is not None: return op(self.val, val % self.mod) else: return NotImplemented def __eq__(self, other): return self._compare(other, operator.eq) def __ne__(self, other): return self._compare(other, operator.ne) def __lt__(self, other): return self._compare(other, operator.lt) def __le__(self, other): return self._compare(other, operator.le) def __gt__(self, other): return self._compare(other, operator.gt) def __ge__(self, other): return self._compare(other, operator.ge) def __bool__(self): return bool(self.val) @classmethod def _invert(cls, value): return cls.dom.invert(value, cls.mod) def invert(self): return self.__class__(self._invert(self.val)) _modular_integer_cache = {} # type: Dict[Tuple[Any, Any, Any], Type[ModularInteger]] def ModularIntegerFactory(_mod, _dom, _sym, parent): """Create custom class for specific integer modulus.""" try: _mod = _dom.convert(_mod) except CoercionFailed: ok = False else: ok = True if not ok or _mod < 1: raise ValueError("modulus must be a positive integer, got %s" % _mod) key = _mod, _dom, _sym try: cls = _modular_integer_cache[key] except KeyError: class cls(ModularInteger): mod, dom, sym = _mod, _dom, _sym _parent = parent if _sym: cls.__name__ = "SymmetricModularIntegerMod%s" % _mod else: cls.__name__ = "ModularIntegerMod%s" % _mod _modular_integer_cache[key] = cls return cls
7a4e06288ebef0ca29df4d3a8c95068a1672226f940d6c2a2b22fd5790f34740
"""Implementation of :class:`FractionField` class. """ from sympy.polys.domains.field import Field from sympy.polys.domains.compositedomain import CompositeDomain from sympy.polys.domains.characteristiczero import CharacteristicZero from sympy.polys.polyclasses import DMF from sympy.polys.polyerrors import GeneratorsNeeded from sympy.polys.polyutils import dict_from_basic, basic_from_dict, _dict_reorder from sympy.utilities import public @public class FractionField(Field, CharacteristicZero, CompositeDomain): """A class for representing rational function fields. """ dtype = DMF is_FractionField = is_Frac = True has_assoc_Ring = True has_assoc_Field = True def __init__(self, dom, *gens): 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 def new(self, element): return self.dtype(element, self.dom, len(self.gens) - 1, ring=self) def __str__(self): return str(self.dom) + '(' + ','.join(map(str, self.gens)) + ')' def __hash__(self): return hash((self.__class__.__name__, self.dtype, self.dom, self.gens)) def __eq__(self, other): """Returns ``True`` if two domains are equivalent. """ return isinstance(other, FractionField) and \ self.dtype == other.dtype and self.dom == other.dom and self.gens == other.gens 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 from_ZZ_python(K1, a, K0): """Convert a Python ``int`` 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_GlobalPolynomialRing(K1, a, K0): """Convert a ``DMF`` object to ``dtype``. """ if K1.gens == K0.gens: if K1.dom == K0.dom: return K1(a.rep) 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 from_FractionField(K1, a, K0): """ Convert a fraction field element to another fraction field. Examples ======== >>> from sympy.polys.polyclasses import DMF >>> from sympy.polys.domains import ZZ, QQ >>> from sympy.abc import x >>> f = DMF(([ZZ(1), ZZ(2)], [ZZ(1), ZZ(1)]), ZZ) >>> QQx = QQ.old_frac_field(x) >>> ZZx = ZZ.old_frac_field(x) >>> QQx.from_FractionField(f, ZZx) (x + 2)/(x + 1) """ if K1.gens == K0.gens: if K1.dom == K0.dom: return a else: return K1((a.numer().convert(K1.dom).rep, a.denom().convert(K1.dom).rep)) elif set(K0.gens).issubset(K1.gens): nmonoms, ncoeffs = _dict_reorder( a.numer().to_dict(), K0.gens, K1.gens) dmonoms, dcoeffs = _dict_reorder( a.denom().to_dict(), K0.gens, K1.gens) if K1.dom != K0.dom: ncoeffs = [ K1.dom.convert(c, K0.dom) for c in ncoeffs ] dcoeffs = [ K1.dom.convert(c, K0.dom) for c in dcoeffs ] return K1((dict(zip(nmonoms, ncoeffs)), dict(zip(dmonoms, dcoeffs)))) def get_ring(self): """Returns a ring associated with ``self``. """ from sympy.polys.domains import PolynomialRing return PolynomialRing(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 is_positive(self, a): """Returns True if ``a`` is positive. """ return self.dom.is_positive(a.numer().LC()) def is_negative(self, a): """Returns True if ``a`` is negative. """ return self.dom.is_negative(a.numer().LC()) def is_nonpositive(self, a): """Returns True if ``a`` is non-positive. """ return self.dom.is_nonpositive(a.numer().LC()) def is_nonnegative(self, a): """Returns True if ``a`` is non-negative. """ return self.dom.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.dom.factorial(a))
f57773b86981db43543e9e7618ad45b03a6202607edc1f6db7b25d8ef420e1b7
"""Domains of Gaussian type.""" from sympy.core.numbers import I from sympy.polys.polyerrors import CoercionFailed from sympy.polys.domains import ZZ, 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 __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): 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): 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) # Override the negative etc handlers because this isn't an ordered domain. 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_python(K1, a, K0): """Convert a ZZ_python element 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): """Ring of Gaussian integers.""" dom = ZZ dtype = GaussianInteger zero = dtype(0, 0) one = dtype(1, 0) imag_unit = dtype(0, 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.units[-d.quadrant()] # - for inverse power 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): """Field of Gaussian rational numbers.""" dom = QQ dtype = GaussianRational zero = dtype(0, 0) one = dtype(1, 0) 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()
3fe4098fdf53c09d7d1ae530303325af4fe4c8f48bde91ee03cf6ae0a4fa16da
"""Ground types for various mathematical domains in SymPy. """ from sympy.core.compatibility import builtins, HAS_GMPY 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 == 1: from gmpy import ( mpz as GMPYInteger, mpq as GMPYRational, fac as gmpy_factorial, numer as gmpy_numer, denom as gmpy_denom, gcdext as gmpy_gcdex, gcd as gmpy_gcd, lcm as gmpy_lcm, sqrt as gmpy_sqrt, qdiv as gmpy_qdiv, ) elif HAS_GMPY == 2: from gmpy2 import ( mpz as GMPYInteger, mpq as GMPYRational, fac as gmpy_factorial, numer as gmpy_numer, denom as gmpy_denom, gcdext as gmpy_gcdex, gcd as gmpy_gcd, lcm as gmpy_lcm, isqrt as gmpy_sqrt, qdiv as gmpy_qdiv, ) else: class _GMPYInteger: def __init__(self, obj): pass class _GMPYRational: def __init__(self, obj): pass GMPYInteger = _GMPYInteger GMPYRational = _GMPYRational gmpy_factorial = None gmpy_numer = None gmpy_denom = None gmpy_gcdex = None gmpy_gcd = None gmpy_lcm = None gmpy_sqrt = None gmpy_qdiv = None import mpmath.libmp as mlib def python_sqrt(n): return int(mlib.isqrt(n)) def python_factorial(n): return int(mlib.ifac(n)) __all__ = [ 'PythonInteger', 'PythonReal', 'PythonComplex', 'PythonRational', 'python_gcdex', 'python_gcd', 'python_lcm', 'SymPyReal', 'SymPyInteger', 'SymPyRational', 'GMPYInteger', 'GMPYRational', 'gmpy_factorial', 'gmpy_numer', 'gmpy_denom', 'gmpy_gcdex', 'gmpy_gcd', 'gmpy_lcm', 'gmpy_sqrt', 'gmpy_qdiv', 'GMPYInteger', 'GMPYRational', 'mlib', 'python_sqrt', 'python_factorial' ]
458c03460d7354b2c6b49bd55ef5a1c146630bdd60f295d3c008ee42859ece4b
"""Implementation of :class:`PythonFiniteField` class. """ from sympy.polys.domains.finitefield import FiniteField from sympy.polys.domains.pythonintegerring import PythonIntegerRing from sympy.utilities import public @public class PythonFiniteField(FiniteField): """Finite field based on Python's integers. """ alias = 'FF_python' def __init__(self, mod, symmetric=True): return super().__init__(mod, PythonIntegerRing(), symmetric)
40567e396fdcc316d07e4ee666bcb697157e02b385c72a8de7c756471be241b0
"""Implementation of :class:`GMPYIntegerRing` class. """ from sympy.polys.domains.groundtypes import ( GMPYInteger, SymPyInteger, gmpy_factorial, gmpy_gcdex, gmpy_gcd, gmpy_lcm, 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. """ 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_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)
2d225e1c6557307c591960a6b5cc0131d5ed6d2d797e24e29af9db4d33fc7988
"""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 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: """Represents an abstract domain. """ dtype = None # type: Optional[Type] zero = None # type: Optional[Any] one = None # type: Optional[Any] is_Ring = False is_Field = False has_assoc_Ring = False has_assoc_Field = False 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_Exact = True is_Numerical = False is_Simple = False is_Composite = False is_PID = False 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): 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 PythonIntegerRing, GMPYIntegerRing, GMPYRationalField, RealField, ComplexField if isinstance(element, int): return self.convert_from(element, PythonIntegerRing()) if HAS_GMPY: integers = GMPYIntegerRing() if isinstance(element, integers.tp): return self.convert_from(element, integers) rationals = GMPYRationalField() 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 ``a`` to a SymPy object. """ raise NotImplementedError def from_sympy(self, a): """Convert a SymPy object to ``dtype``. """ raise NotImplementedError 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_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_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): 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 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 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``, implies something. """ raise NotImplementedError def quo(self, a, b): """Quotient of ``a`` and ``b``, implies something. """ raise NotImplementedError def rem(self, a, b): """Remainder of ``a`` and ``b``, implies ``__mod__``. """ raise NotImplementedError def div(self, a, b): """Division of ``a`` and ``b``, implies something. """ 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']
0bf35df46b9b48c0499887b9becfc2d88b814fc60614be3180ae288b13423ab9
"""Implementation of :class:`GMPYFiniteField` class. """ from sympy.polys.domains.finitefield import FiniteField from sympy.polys.domains.gmpyintegerring import GMPYIntegerRing from sympy.utilities import public @public class GMPYFiniteField(FiniteField): """Finite field based on GMPY integers. """ alias = 'FF_gmpy' def __init__(self, mod, symmetric=True): return super().__init__(mod, GMPYIntegerRing(), symmetric)
331ca6c70946040dcfc76145cb321212d027915a317aaf9b24cd5f9368e412db
"""Real and complex elements. """ from sympy.polys.domains.domainelement import DomainElement from sympy.utilities import public from mpmath.ctx_mp_python import PythonMPContext, _mpf, _mpc, _constant from mpmath.libmp import (MPZ_ONE, fzero, fone, finf, fninf, fnan, round_nearest, mpf_mul, repr_dps, int_types, from_int, from_float, from_str, to_rational) from mpmath.rational import mpq @public class RealElement(_mpf, DomainElement): """An element of a real domain. """ __slots__ = ('__mpf__',) def _set_mpf(self, val): self.__mpf__ = val _mpf_ = property(lambda self: self.__mpf__, _set_mpf) def parent(self): return self.context._parent @public class ComplexElement(_mpc, DomainElement): """An element of a complex domain. """ __slots__ = ('__mpc__',) def _set_mpc(self, val): self.__mpc__ = val _mpc_ = property(lambda self: self.__mpc__, _set_mpc) def parent(self): return self.context._parent new = object.__new__ @public class MPContext(PythonMPContext): def __init__(ctx, prec=53, dps=None, tol=None, real=False): ctx._prec_rounding = [prec, round_nearest] if dps is None: ctx._set_prec(prec) else: ctx._set_dps(dps) ctx.mpf = RealElement ctx.mpc = ComplexElement ctx.mpf._ctxdata = [ctx.mpf, new, ctx._prec_rounding] ctx.mpc._ctxdata = [ctx.mpc, new, ctx._prec_rounding] if real: ctx.mpf.context = ctx else: ctx.mpc.context = ctx ctx.constant = _constant ctx.constant._ctxdata = [ctx.mpf, new, ctx._prec_rounding] ctx.constant.context = ctx ctx.types = [ctx.mpf, ctx.mpc, ctx.constant] ctx.trap_complex = True ctx.pretty = True if tol is None: ctx.tol = ctx._make_tol() elif tol is False: ctx.tol = fzero else: ctx.tol = ctx._convert_tol(tol) ctx.tolerance = ctx.make_mpf(ctx.tol) if not ctx.tolerance: ctx.max_denom = 1000000 else: ctx.max_denom = int(1/ctx.tolerance) ctx.zero = ctx.make_mpf(fzero) ctx.one = ctx.make_mpf(fone) ctx.j = ctx.make_mpc((fzero, fone)) ctx.inf = ctx.make_mpf(finf) ctx.ninf = ctx.make_mpf(fninf) ctx.nan = ctx.make_mpf(fnan) def _make_tol(ctx): hundred = (0, 25, 2, 5) eps = (0, MPZ_ONE, 1-ctx.prec, 1) return mpf_mul(hundred, eps) def make_tol(ctx): return ctx.make_mpf(ctx._make_tol()) def _convert_tol(ctx, tol): if isinstance(tol, int_types): return from_int(tol) if isinstance(tol, float): return from_float(tol) if hasattr(tol, "_mpf_"): return tol._mpf_ prec, rounding = ctx._prec_rounding if isinstance(tol, str): return from_str(tol, prec, rounding) raise ValueError("expected a real number, got %s" % tol) def _convert_fallback(ctx, x, strings): raise TypeError("cannot create mpf from " + repr(x)) @property def _repr_digits(ctx): return repr_dps(ctx._prec) @property def _str_digits(ctx): return ctx._dps def to_rational(ctx, s, limit=True): p, q = to_rational(s._mpf_) if not limit or q <= ctx.max_denom: return p, q p0, q0, p1, q1 = 0, 1, 1, 0 n, d = p, q while True: a = n//d q2 = q0 + a*q1 if q2 > ctx.max_denom: break p0, q0, p1, q1 = p1, q1, p0 + a*p1, q2 n, d = d, n - a*d k = (ctx.max_denom - q0)//q1 number = mpq(p, q) bound1 = mpq(p0 + k*p1, q0 + k*q1) bound2 = mpq(p1, q1) if not bound2 or not bound1: return p, q elif abs(bound2 - number) <= abs(bound1 - number): return bound2._mpq_ else: return bound1._mpq_ def almosteq(ctx, s, t, rel_eps=None, abs_eps=None): t = ctx.convert(t) if abs_eps is None and rel_eps is None: rel_eps = abs_eps = ctx.tolerance or ctx.make_tol() if abs_eps is None: abs_eps = ctx.convert(rel_eps) elif rel_eps is None: rel_eps = ctx.convert(abs_eps) diff = abs(s-t) if diff <= abs_eps: return True abss = abs(s) abst = abs(t) if abss < abst: err = diff/abst else: err = diff/abss return err <= rel_eps
b3952a01dddc7a1573c23db4273bef1b99c9be3777fa69f57690f35d3d5039ca
"""Tests for tools for constructing domains for expressions. """ from sympy.polys.constructor import construct_domain from sympy.polys.domains import ZZ, QQ, ZZ_I, QQ_I, RR, CC, EX from sympy.polys.domains.realfield import RealField from sympy.polys.domains.complexfield import ComplexField from sympy import S, sqrt, sin, Float, E, I, GoldenRatio, pi, Catalan, Rational from sympy.abc import x, y def test_construct_domain(): assert construct_domain([1, 2, 3]) == (ZZ, [ZZ(1), ZZ(2), ZZ(3)]) assert construct_domain([1, 2, 3], field=True) == (QQ, [QQ(1), QQ(2), QQ(3)]) assert construct_domain([S.One, S(2), S(3)]) == (ZZ, [ZZ(1), ZZ(2), ZZ(3)]) assert construct_domain([S.One, S(2), S(3)], field=True) == (QQ, [QQ(1), QQ(2), QQ(3)]) assert construct_domain([S.Half, S(2)]) == (QQ, [QQ(1, 2), QQ(2)]) result = construct_domain([3.14, 1, S.Half]) assert isinstance(result[0], RealField) assert result[1] == [RR(3.14), RR(1.0), RR(0.5)] result = construct_domain([3.14, I, S.Half]) assert isinstance(result[0], ComplexField) assert result[1] == [CC(3.14), CC(1.0j), CC(0.5)] assert construct_domain([1, I]) == (ZZ_I, [ZZ_I(1, 0), ZZ_I(0, 1)]) assert construct_domain([1, I/2]) == (QQ_I, [QQ_I(1, 0), QQ_I(0, S.Half)]) assert construct_domain([3.14, sqrt(2)], extension=None) == (EX, [EX(3.14), EX(sqrt(2))]) assert construct_domain([3.14, sqrt(2)], extension=True) == (EX, [EX(3.14), EX(sqrt(2))]) assert construct_domain([1, sqrt(2)], extension=None) == (EX, [EX(1), EX(sqrt(2))]) assert construct_domain([x, sqrt(x)]) == (EX, [EX(x), EX(sqrt(x))]) assert construct_domain([x, sqrt(x), sqrt(y)]) == (EX, [EX(x), EX(sqrt(x)), EX(sqrt(y))]) alg = QQ.algebraic_field(sqrt(2)) assert construct_domain([7, S.Half, sqrt(2)], extension=True) == \ (alg, [alg.convert(7), alg.convert(S.Half), alg.convert(sqrt(2))]) alg = QQ.algebraic_field(sqrt(2) + sqrt(3)) assert construct_domain([7, sqrt(2), sqrt(3)], extension=True) == \ (alg, [alg.convert(7), alg.convert(sqrt(2)), alg.convert(sqrt(3))]) dom = ZZ[x] assert construct_domain([2*x, 3]) == \ (dom, [dom.convert(2*x), dom.convert(3)]) dom = ZZ[x, y] assert construct_domain([2*x, 3*y]) == \ (dom, [dom.convert(2*x), dom.convert(3*y)]) dom = QQ[x] assert construct_domain([x/2, 3]) == \ (dom, [dom.convert(x/2), dom.convert(3)]) dom = QQ[x, y] assert construct_domain([x/2, 3*y]) == \ (dom, [dom.convert(x/2), dom.convert(3*y)]) dom = ZZ_I[x] assert construct_domain([2*x, I]) == \ (dom, [dom.convert(2*x), dom.convert(I)]) dom = ZZ_I[x, y] assert construct_domain([2*x, I*y]) == \ (dom, [dom.convert(2*x), dom.convert(I*y)]) dom = QQ_I[x] assert construct_domain([x/2, I]) == \ (dom, [dom.convert(x/2), dom.convert(I)]) dom = QQ_I[x, y] assert construct_domain([x/2, I*y]) == \ (dom, [dom.convert(x/2), dom.convert(I*y)]) dom = RR[x] assert construct_domain([x/2, 3.5]) == \ (dom, [dom.convert(x/2), dom.convert(3.5)]) dom = RR[x, y] assert construct_domain([x/2, 3.5*y]) == \ (dom, [dom.convert(x/2), dom.convert(3.5*y)]) dom = CC[x] assert construct_domain([I*x/2, 3.5]) == \ (dom, [dom.convert(I*x/2), dom.convert(3.5)]) dom = CC[x, y] assert construct_domain([I*x/2, 3.5*y]) == \ (dom, [dom.convert(I*x/2), dom.convert(3.5*y)]) dom = CC[x] assert construct_domain([x/2, I*3.5]) == \ (dom, [dom.convert(x/2), dom.convert(I*3.5)]) dom = CC[x, y] assert construct_domain([x/2, I*3.5*y]) == \ (dom, [dom.convert(x/2), dom.convert(I*3.5*y)]) dom = ZZ.frac_field(x) assert construct_domain([2/x, 3]) == \ (dom, [dom.convert(2/x), dom.convert(3)]) dom = ZZ.frac_field(x, y) assert construct_domain([2/x, 3*y]) == \ (dom, [dom.convert(2/x), dom.convert(3*y)]) dom = RR.frac_field(x) assert construct_domain([2/x, 3.5]) == \ (dom, [dom.convert(2/x), dom.convert(3.5)]) dom = RR.frac_field(x, y) assert construct_domain([2/x, 3.5*y]) == \ (dom, [dom.convert(2/x), dom.convert(3.5*y)]) dom = RealField(prec=336)[x] assert construct_domain([pi.evalf(100)*x]) == \ (dom, [dom.convert(pi.evalf(100)*x)]) assert construct_domain(2) == (ZZ, ZZ(2)) assert construct_domain(S(2)/3) == (QQ, QQ(2, 3)) assert construct_domain(Rational(2, 3)) == (QQ, QQ(2, 3)) assert construct_domain({}) == (ZZ, {}) def test_composite_option(): assert construct_domain({(1,): sin(y)}, composite=False) == \ (EX, {(1,): EX(sin(y))}) assert construct_domain({(1,): y}, composite=False) == \ (EX, {(1,): EX(y)}) assert construct_domain({(1, 1): 1}, composite=False) == \ (ZZ, {(1, 1): 1}) assert construct_domain({(1, 0): y}, composite=False) == \ (EX, {(1, 0): EX(y)}) def test_precision(): f1 = Float("1.01") f2 = Float("1.0000000000000000000001") for u in [1, 1e-2, 1e-6, 1e-13, 1e-14, 1e-16, 1e-20, 1e-100, 1e-300, f1, f2]: result = construct_domain([u]) v = float(result[1][0]) assert abs(u - v) / u < 1e-14 # Test relative accuracy result = construct_domain([f1]) y = result[1][0] assert y-1 > 1e-50 result = construct_domain([f2]) y = result[1][0] assert y-1 > 1e-50 def test_issue_11538(): for n in [E, pi, Catalan]: assert construct_domain(n)[0] == ZZ[n] assert construct_domain(x + n)[0] == ZZ[x, n] assert construct_domain(GoldenRatio)[0] == EX assert construct_domain(x + GoldenRatio)[0] == EX
dd8905ad606e0673d10238b737710a7496563499e1ff600b8b8fc0b529587291
"""Tests for algorithms for partial fraction decomposition of rational functions. """ from sympy.polys.partfrac import ( apart_undetermined_coeffs, apart, apart_list, assemble_partfrac_list ) from sympy import (S, Poly, E, pi, I, Matrix, Eq, RootSum, Lambda, Symbol, Dummy, factor, together, sqrt, Expr, Rational) from sympy.testing.pytest import raises, ON_TRAVIS, skip, XFAIL from sympy.abc import x, y, a, b, c def test_apart(): assert apart(1) == 1 assert apart(1, x) == 1 f, g = (x**2 + 1)/(x + 1), 2/(x + 1) + x - 1 assert apart(f, full=False) == g assert apart(f, full=True) == g f, g = 1/(x + 2)/(x + 1), 1/(1 + x) - 1/(2 + x) assert apart(f, full=False) == g assert apart(f, full=True) == g f, g = 1/(x + 1)/(x + 5), -1/(5 + x)/4 + 1/(1 + x)/4 assert apart(f, full=False) == g assert apart(f, full=True) == g assert apart((E*x + 2)/(x - pi)*(x - 1), x) == \ 2 - E + E*pi + E*x + (E*pi + 2)*(pi - 1)/(x - pi) assert apart(Eq((x**2 + 1)/(x + 1), x), x) == Eq(x - 1 + 2/(x + 1), x) assert apart(x/2, y) == x/2 f, g = (x+y)/(2*x - y), Rational(3, 2)*y/(2*x - y) + S.Half assert apart(f, x, full=False) == g assert apart(f, x, full=True) == g f, g = (x+y)/(2*x - y), 3*x/(2*x - y) - 1 assert apart(f, y, full=False) == g assert apart(f, y, full=True) == g raises(NotImplementedError, lambda: apart(1/(x + 1)/(y + 2))) def test_apart_matrix(): M = Matrix(2, 2, lambda i, j: 1/(x + i + 1)/(x + j)) assert apart(M) == Matrix([ [1/x - 1/(x + 1), (x + 1)**(-2)], [1/(2*x) - (S.Half)/(x + 2), 1/(x + 1) - 1/(x + 2)], ]) def test_apart_symbolic(): f = a*x**4 + (2*b + 2*a*c)*x**3 + (4*b*c - a**2 + a*c**2)*x**2 + \ (-2*a*b + 2*b*c**2)*x - b**2 g = a**2*x**4 + (2*a*b + 2*c*a**2)*x**3 + (4*a*b*c + b**2 + a**2*c**2)*x**2 + (2*c*b**2 + 2*a*b*c**2)*x + b**2*c**2 assert apart(f/g, x) == 1/a - 1/(x + c)**2 - b**2/(a*(a*x + b)**2) assert apart(1/((x + a)*(x + b)*(x + c)), x) == \ 1/((a - c)*(b - c)*(c + x)) - 1/((a - b)*(b - c)*(b + x)) + \ 1/((a - b)*(a - c)*(a + x)) def _make_extension_example(): # https://github.com/sympy/sympy/issues/18531 from sympy.core import Mul def mul2(expr): # 2-arg mul hack... return Mul(2, expr, evaluate=False) f = ((x**2 + 1)**3/((x - 1)**2*(x + 1)**2*(-x**2 + 2*x + 1)*(x**2 + 2*x - 1))) g = (1/mul2(x - sqrt(2) + 1) - 1/mul2(x - sqrt(2) - 1) + 1/mul2(x + 1 + sqrt(2)) - 1/mul2(x - 1 + sqrt(2)) + 1/mul2((x + 1)**2) + 1/mul2((x - 1)**2)) return f, g def test_apart_extension(): f = 2/(x**2 + 1) g = I/(x + I) - I/(x - I) assert apart(f, extension=I) == g assert apart(f, gaussian=True) == g f = x/((x - 2)*(x + I)) assert factor(together(apart(f)).expand()) == f f, g = _make_extension_example() # XXX: Only works with dotprodsimp. See test_apart_extension_xfail below from sympy.matrices import dotprodsimp with dotprodsimp(True): assert apart(f, x, extension={sqrt(2)}) == g # XXX: This is XFAIL just because it is slow @XFAIL def test_apart_extension_xfail(): if ON_TRAVIS: skip('Too slow for Travis') f, g = _make_extension_example() assert apart(f, x, extension={sqrt(2)}) == g def test_apart_full(): f = 1/(x**2 + 1) assert apart(f, full=False) == f assert apart(f, full=True).dummy_eq( -RootSum(x**2 + 1, Lambda(a, a/(x - a)), auto=False)/2) f = 1/(x**3 + x + 1) assert apart(f, full=False) == f assert apart(f, full=True).dummy_eq( RootSum(x**3 + x + 1, Lambda(a, (a**2*Rational(6, 31) - a*Rational(9, 31) + Rational(4, 31))/(x - a)), auto=False)) f = 1/(x**5 + 1) assert apart(f, full=False) == \ (Rational(-1, 5))*((x**3 - 2*x**2 + 3*x - 4)/(x**4 - x**3 + x**2 - x + 1)) + (Rational(1, 5))/(x + 1) assert apart(f, full=True).dummy_eq( -RootSum(x**4 - x**3 + x**2 - x + 1, Lambda(a, a/(x - a)), auto=False)/5 + (Rational(1, 5))/(x + 1)) def test_apart_undetermined_coeffs(): p = Poly(2*x - 3) q = Poly(x**9 - x**8 - x**6 + x**5 - 2*x**2 + 3*x - 1) r = (-x**7 - x**6 - x**5 + 4)/(x**8 - x**5 - 2*x + 1) + 1/(x - 1) assert apart_undetermined_coeffs(p, q) == r p = Poly(1, x, domain='ZZ[a,b]') q = Poly((x + a)*(x + b), x, domain='ZZ[a,b]') r = 1/((a - b)*(b + x)) - 1/((a - b)*(a + x)) assert apart_undetermined_coeffs(p, q) == r def test_apart_list(): from sympy.utilities.iterables import numbered_symbols def dummy_eq(i, j): if type(i) in (list, tuple): return all(dummy_eq(i, j) for i, j in zip(i, j)) return i == j or i.dummy_eq(j) w0, w1, w2 = Symbol("w0"), Symbol("w1"), Symbol("w2") _a = Dummy("a") f = (-2*x - 2*x**2) / (3*x**2 - 6*x) got = apart_list(f, x, dummies=numbered_symbols("w")) ans = (-1, Poly(Rational(2, 3), x, domain='QQ'), [(Poly(w0 - 2, w0, domain='ZZ'), Lambda(_a, 2), Lambda(_a, -_a + x), 1)]) assert dummy_eq(got, ans) got = apart_list(2/(x**2-2), x, dummies=numbered_symbols("w")) ans = (1, Poly(0, x, domain='ZZ'), [(Poly(w0**2 - 2, w0, domain='ZZ'), Lambda(_a, _a/2), Lambda(_a, -_a + x), 1)]) assert dummy_eq(got, ans) f = 36 / (x**5 - 2*x**4 - 2*x**3 + 4*x**2 + x - 2) got = apart_list(f, x, dummies=numbered_symbols("w")) ans = (1, Poly(0, x, domain='ZZ'), [(Poly(w0 - 2, w0, domain='ZZ'), Lambda(_a, 4), Lambda(_a, -_a + x), 1), (Poly(w1**2 - 1, w1, domain='ZZ'), Lambda(_a, -3*_a - 6), Lambda(_a, -_a + x), 2), (Poly(w2 + 1, w2, domain='ZZ'), Lambda(_a, -4), Lambda(_a, -_a + x), 1)]) assert dummy_eq(got, ans) def test_assemble_partfrac_list(): f = 36 / (x**5 - 2*x**4 - 2*x**3 + 4*x**2 + x - 2) pfd = apart_list(f) assert assemble_partfrac_list(pfd) == -4/(x + 1) - 3/(x + 1)**2 - 9/(x - 1)**2 + 4/(x - 2) a = Dummy("a") pfd = (1, Poly(0, x, domain='ZZ'), [([sqrt(2),-sqrt(2)], Lambda(a, a/2), Lambda(a, -a + x), 1)]) assert assemble_partfrac_list(pfd) == -1/(sqrt(2)*(x + sqrt(2))) + 1/(sqrt(2)*(x - sqrt(2))) @XFAIL def test_noncommutative_pseudomultivariate(): # apart doesn't go inside noncommutative expressions class foo(Expr): is_commutative=False e = x/(x + x*y) c = 1/(1 + y) assert apart(e + foo(e)) == c + foo(c) assert apart(e*foo(e)) == c*foo(c) def test_noncommutative(): class foo(Expr): is_commutative=False e = x/(x + x*y) c = 1/(1 + y) assert apart(e + foo()) == c + foo() def test_issue_5798(): assert apart( 2*x/(x**2 + 1) - (x - 1)/(2*(x**2 + 1)) + 1/(2*(x + 1)) - 2/x) == \ (3*x + 1)/(x**2 + 1)/2 + 1/(x + 1)/2 - 2/x
63aa8f155e884ff6e805e989a43bb40018ecbfb85fed5418f173577d9d4028f3
"""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_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) == a a, b = sqrt(-2), -sqrt(-2) assert gcd(a, b) in (a, b) 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 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 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.")
2e85622ad2bc20d3c9e04b8089a8945273e55038c382c768402b3015f1952ae8
from sympy.polys.galoistools import ( gf_crt, gf_crt1, gf_crt2, gf_int, gf_degree, gf_strip, gf_trunc, gf_normal, gf_from_dict, gf_to_dict, gf_from_int_poly, gf_to_int_poly, gf_neg, gf_add_ground, gf_sub_ground, gf_mul_ground, gf_add, gf_sub, gf_add_mul, gf_sub_mul, gf_mul, gf_sqr, gf_div, gf_rem, gf_quo, gf_exquo, gf_lshift, gf_rshift, gf_expand, gf_pow, gf_pow_mod, gf_gcdex, gf_gcd, gf_lcm, gf_cofactors, gf_LC, gf_TC, gf_monic, gf_eval, gf_multi_eval, gf_compose, gf_compose_mod, gf_trace_map, gf_diff, gf_irreducible, gf_irreducible_p, gf_irred_p_ben_or, gf_irred_p_rabin, gf_sqf_list, gf_sqf_part, gf_sqf_p, gf_Qmatrix, gf_Qbasis, gf_ddf_zassenhaus, gf_ddf_shoup, gf_edf_zassenhaus, gf_edf_shoup, gf_berlekamp, gf_factor_sqf, gf_factor, gf_value, linear_congruence, csolve_prime, gf_csolve, gf_frobenius_map, gf_frobenius_monomial_base ) from sympy.polys.polyerrors import ( ExactQuotientFailed, ) from sympy.polys import polyconfig as config from sympy.polys.domains import ZZ from sympy import pi, nextprime from sympy.testing.pytest import raises def test_gf_crt(): U = [49, 76, 65] M = [99, 97, 95] p = 912285 u = 639985 assert gf_crt(U, M, ZZ) == u E = [9215, 9405, 9603] S = [62, 24, 12] assert gf_crt1(M, ZZ) == (p, E, S) assert gf_crt2(U, M, p, E, S, ZZ) == u def test_gf_int(): assert gf_int(0, 5) == 0 assert gf_int(1, 5) == 1 assert gf_int(2, 5) == 2 assert gf_int(3, 5) == -2 assert gf_int(4, 5) == -1 assert gf_int(5, 5) == 0 def test_gf_degree(): assert gf_degree([]) == -1 assert gf_degree([1]) == 0 assert gf_degree([1, 0]) == 1 assert gf_degree([1, 0, 0, 0, 1]) == 4 def test_gf_strip(): assert gf_strip([]) == [] assert gf_strip([0]) == [] assert gf_strip([0, 0, 0]) == [] assert gf_strip([1]) == [1] assert gf_strip([0, 1]) == [1] assert gf_strip([0, 0, 0, 1]) == [1] assert gf_strip([1, 2, 0]) == [1, 2, 0] assert gf_strip([0, 1, 2, 0]) == [1, 2, 0] assert gf_strip([0, 0, 0, 1, 2, 0]) == [1, 2, 0] def test_gf_trunc(): assert gf_trunc([], 11) == [] assert gf_trunc([1], 11) == [1] assert gf_trunc([22], 11) == [] assert gf_trunc([12], 11) == [1] assert gf_trunc([11, 22, 17, 1, 0], 11) == [6, 1, 0] assert gf_trunc([12, 23, 17, 1, 0], 11) == [1, 1, 6, 1, 0] def test_gf_normal(): assert gf_normal([11, 22, 17, 1, 0], 11, ZZ) == [6, 1, 0] def test_gf_from_to_dict(): f = {11: 12, 6: 2, 0: 25} F = {11: 1, 6: 2, 0: 3} g = [1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 3] assert gf_from_dict(f, 11, ZZ) == g assert gf_to_dict(g, 11) == F f = {11: -5, 4: 0, 3: 1, 0: 12} F = {11: -5, 3: 1, 0: 1} g = [6, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1] assert gf_from_dict(f, 11, ZZ) == g assert gf_to_dict(g, 11) == F assert gf_to_dict([10], 11, symmetric=True) == {0: -1} assert gf_to_dict([10], 11, symmetric=False) == {0: 10} def test_gf_from_to_int_poly(): assert gf_from_int_poly([1, 0, 7, 2, 20], 5) == [1, 0, 2, 2, 0] assert gf_to_int_poly([1, 0, 4, 2, 3], 5) == [1, 0, -1, 2, -2] assert gf_to_int_poly([10], 11, symmetric=True) == [-1] assert gf_to_int_poly([10], 11, symmetric=False) == [10] def test_gf_LC(): assert gf_LC([], ZZ) == 0 assert gf_LC([1], ZZ) == 1 assert gf_LC([1, 2], ZZ) == 1 def test_gf_TC(): assert gf_TC([], ZZ) == 0 assert gf_TC([1], ZZ) == 1 assert gf_TC([1, 2], ZZ) == 2 def test_gf_monic(): assert gf_monic(ZZ.map([]), 11, ZZ) == (0, []) assert gf_monic(ZZ.map([1]), 11, ZZ) == (1, [1]) assert gf_monic(ZZ.map([2]), 11, ZZ) == (2, [1]) assert gf_monic(ZZ.map([1, 2, 3, 4]), 11, ZZ) == (1, [1, 2, 3, 4]) assert gf_monic(ZZ.map([2, 3, 4, 5]), 11, ZZ) == (2, [1, 7, 2, 8]) def test_gf_arith(): assert gf_neg([], 11, ZZ) == [] assert gf_neg([1], 11, ZZ) == [10] assert gf_neg([1, 2, 3], 11, ZZ) == [10, 9, 8] assert gf_add_ground([], 0, 11, ZZ) == [] assert gf_sub_ground([], 0, 11, ZZ) == [] assert gf_add_ground([], 3, 11, ZZ) == [3] assert gf_sub_ground([], 3, 11, ZZ) == [8] assert gf_add_ground([1], 3, 11, ZZ) == [4] assert gf_sub_ground([1], 3, 11, ZZ) == [9] assert gf_add_ground([8], 3, 11, ZZ) == [] assert gf_sub_ground([3], 3, 11, ZZ) == [] assert gf_add_ground([1, 2, 3], 3, 11, ZZ) == [1, 2, 6] assert gf_sub_ground([1, 2, 3], 3, 11, ZZ) == [1, 2, 0] assert gf_mul_ground([], 0, 11, ZZ) == [] assert gf_mul_ground([], 1, 11, ZZ) == [] assert gf_mul_ground([1], 0, 11, ZZ) == [] assert gf_mul_ground([1], 1, 11, ZZ) == [1] assert gf_mul_ground([1, 2, 3], 0, 11, ZZ) == [] assert gf_mul_ground([1, 2, 3], 1, 11, ZZ) == [1, 2, 3] assert gf_mul_ground([1, 2, 3], 7, 11, ZZ) == [7, 3, 10] assert gf_add([], [], 11, ZZ) == [] assert gf_add([1], [], 11, ZZ) == [1] assert gf_add([], [1], 11, ZZ) == [1] assert gf_add([1], [1], 11, ZZ) == [2] assert gf_add([1], [2], 11, ZZ) == [3] assert gf_add([1, 2], [1], 11, ZZ) == [1, 3] assert gf_add([1], [1, 2], 11, ZZ) == [1, 3] assert gf_add([1, 2, 3], [8, 9, 10], 11, ZZ) == [9, 0, 2] assert gf_sub([], [], 11, ZZ) == [] assert gf_sub([1], [], 11, ZZ) == [1] assert gf_sub([], [1], 11, ZZ) == [10] assert gf_sub([1], [1], 11, ZZ) == [] assert gf_sub([1], [2], 11, ZZ) == [10] assert gf_sub([1, 2], [1], 11, ZZ) == [1, 1] assert gf_sub([1], [1, 2], 11, ZZ) == [10, 10] assert gf_sub([3, 2, 1], [8, 9, 10], 11, ZZ) == [6, 4, 2] assert gf_add_mul( [1, 5, 6], [7, 3], [8, 0, 6, 1], 11, ZZ) == [1, 2, 10, 8, 9] assert gf_sub_mul( [1, 5, 6], [7, 3], [8, 0, 6, 1], 11, ZZ) == [10, 9, 3, 2, 3] assert gf_mul([], [], 11, ZZ) == [] assert gf_mul([], [1], 11, ZZ) == [] assert gf_mul([1], [], 11, ZZ) == [] assert gf_mul([1], [1], 11, ZZ) == [1] assert gf_mul([5], [7], 11, ZZ) == [2] assert gf_mul([3, 0, 0, 6, 1, 2], [4, 0, 1, 0], 11, ZZ) == [1, 0, 3, 2, 4, 3, 1, 2, 0] assert gf_mul([4, 0, 1, 0], [3, 0, 0, 6, 1, 2], 11, ZZ) == [1, 0, 3, 2, 4, 3, 1, 2, 0] assert gf_mul([2, 0, 0, 1, 7], [2, 0, 0, 1, 7], 11, ZZ) == [4, 0, 0, 4, 6, 0, 1, 3, 5] assert gf_sqr([], 11, ZZ) == [] assert gf_sqr([2], 11, ZZ) == [4] assert gf_sqr([1, 2], 11, ZZ) == [1, 4, 4] assert gf_sqr([2, 0, 0, 1, 7], 11, ZZ) == [4, 0, 0, 4, 6, 0, 1, 3, 5] def test_gf_division(): raises(ZeroDivisionError, lambda: gf_div([1, 2, 3], [], 11, ZZ)) raises(ZeroDivisionError, lambda: gf_rem([1, 2, 3], [], 11, ZZ)) raises(ZeroDivisionError, lambda: gf_quo([1, 2, 3], [], 11, ZZ)) raises(ZeroDivisionError, lambda: gf_quo([1, 2, 3], [], 11, ZZ)) assert gf_div([1], [1, 2, 3], 7, ZZ) == ([], [1]) assert gf_rem([1], [1, 2, 3], 7, ZZ) == [1] assert gf_quo([1], [1, 2, 3], 7, ZZ) == [] f = ZZ.map([5, 4, 3, 2, 1, 0]) g = ZZ.map([1, 2, 3]) q = [5, 1, 0, 6] r = [3, 3] assert gf_div(f, g, 7, ZZ) == (q, r) assert gf_rem(f, g, 7, ZZ) == r assert gf_quo(f, g, 7, ZZ) == q raises(ExactQuotientFailed, lambda: gf_exquo(f, g, 7, ZZ)) f = ZZ.map([5, 4, 3, 2, 1, 0]) g = ZZ.map([1, 2, 3, 0]) q = [5, 1, 0] r = [6, 1, 0] assert gf_div(f, g, 7, ZZ) == (q, r) assert gf_rem(f, g, 7, ZZ) == r assert gf_quo(f, g, 7, ZZ) == q raises(ExactQuotientFailed, lambda: gf_exquo(f, g, 7, ZZ)) assert gf_quo(ZZ.map([1, 2, 1]), ZZ.map([1, 1]), 11, ZZ) == [1, 1] def test_gf_shift(): f = [1, 2, 3, 4, 5] assert gf_lshift([], 5, ZZ) == [] assert gf_rshift([], 5, ZZ) == ([], []) assert gf_lshift(f, 1, ZZ) == [1, 2, 3, 4, 5, 0] assert gf_lshift(f, 2, ZZ) == [1, 2, 3, 4, 5, 0, 0] assert gf_rshift(f, 0, ZZ) == (f, []) assert gf_rshift(f, 1, ZZ) == ([1, 2, 3, 4], [5]) assert gf_rshift(f, 3, ZZ) == ([1, 2], [3, 4, 5]) assert gf_rshift(f, 5, ZZ) == ([], f) def test_gf_expand(): F = [([1, 1], 2), ([1, 2], 3)] assert gf_expand(F, 11, ZZ) == [1, 8, 3, 5, 6, 8] assert gf_expand((4, F), 11, ZZ) == [4, 10, 1, 9, 2, 10] def test_gf_powering(): assert gf_pow([1, 0, 0, 1, 8], 0, 11, ZZ) == [1] assert gf_pow([1, 0, 0, 1, 8], 1, 11, ZZ) == [1, 0, 0, 1, 8] assert gf_pow([1, 0, 0, 1, 8], 2, 11, ZZ) == [1, 0, 0, 2, 5, 0, 1, 5, 9] assert gf_pow([1, 0, 0, 1, 8], 5, 11, ZZ) == \ [1, 0, 0, 5, 7, 0, 10, 6, 2, 10, 9, 6, 10, 6, 6, 0, 5, 2, 5, 9, 10] assert gf_pow([1, 0, 0, 1, 8], 8, 11, ZZ) == \ [1, 0, 0, 8, 9, 0, 6, 8, 10, 1, 2, 5, 10, 7, 7, 9, 1, 2, 0, 0, 6, 2, 5, 2, 5, 7, 7, 9, 10, 10, 7, 5, 5] assert gf_pow([1, 0, 0, 1, 8], 45, 11, ZZ) == \ [ 1, 0, 0, 1, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 4, 10, 0, 0, 0, 0, 0, 0, 10, 0, 0, 10, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 6, 4, 0, 0, 0, 0, 0, 0, 8, 0, 0, 8, 9, 0, 0, 0, 0, 0, 0, 10, 0, 0, 10, 3, 0, 0, 0, 0, 0, 0, 4, 0, 0, 4, 10, 0, 0, 0, 0, 0, 0, 8, 0, 0, 8, 9, 0, 0, 0, 0, 0, 0, 9, 0, 0, 9, 6, 0, 0, 0, 0, 0, 0, 3, 0, 0, 3, 2, 0, 0, 0, 0, 0, 0, 10, 0, 0, 10, 3, 0, 0, 0, 0, 0, 0, 10, 0, 0, 10, 3, 0, 0, 0, 0, 0, 0, 2, 0, 0, 2, 5, 0, 0, 0, 0, 0, 0, 4, 0, 0, 4, 10] assert gf_pow_mod(ZZ.map([1, 0, 0, 1, 8]), 0, ZZ.map([2, 0, 7]), 11, ZZ) == [1] assert gf_pow_mod(ZZ.map([1, 0, 0, 1, 8]), 1, ZZ.map([2, 0, 7]), 11, ZZ) == [1, 1] assert gf_pow_mod(ZZ.map([1, 0, 0, 1, 8]), 2, ZZ.map([2, 0, 7]), 11, ZZ) == [2, 3] assert gf_pow_mod(ZZ.map([1, 0, 0, 1, 8]), 5, ZZ.map([2, 0, 7]), 11, ZZ) == [7, 8] assert gf_pow_mod(ZZ.map([1, 0, 0, 1, 8]), 8, ZZ.map([2, 0, 7]), 11, ZZ) == [1, 5] assert gf_pow_mod(ZZ.map([1, 0, 0, 1, 8]), 45, ZZ.map([2, 0, 7]), 11, ZZ) == [5, 4] def test_gf_gcdex(): assert gf_gcdex(ZZ.map([]), ZZ.map([]), 11, ZZ) == ([1], [], []) assert gf_gcdex(ZZ.map([2]), ZZ.map([]), 11, ZZ) == ([6], [], [1]) assert gf_gcdex(ZZ.map([]), ZZ.map([2]), 11, ZZ) == ([], [6], [1]) assert gf_gcdex(ZZ.map([2]), ZZ.map([2]), 11, ZZ) == ([], [6], [1]) assert gf_gcdex(ZZ.map([]), ZZ.map([3, 0]), 11, ZZ) == ([], [4], [1, 0]) assert gf_gcdex(ZZ.map([3, 0]), ZZ.map([]), 11, ZZ) == ([4], [], [1, 0]) assert gf_gcdex(ZZ.map([3, 0]), ZZ.map([3, 0]), 11, ZZ) == ([], [4], [1, 0]) assert gf_gcdex(ZZ.map([1, 8, 7]), ZZ.map([1, 7, 1, 7]), 11, ZZ) == ([5, 6], [6], [1, 7]) def test_gf_gcd(): assert gf_gcd(ZZ.map([]), ZZ.map([]), 11, ZZ) == [] assert gf_gcd(ZZ.map([2]), ZZ.map([]), 11, ZZ) == [1] assert gf_gcd(ZZ.map([]), ZZ.map([2]), 11, ZZ) == [1] assert gf_gcd(ZZ.map([2]), ZZ.map([2]), 11, ZZ) == [1] assert gf_gcd(ZZ.map([]), ZZ.map([1, 0]), 11, ZZ) == [1, 0] assert gf_gcd(ZZ.map([1, 0]), ZZ.map([]), 11, ZZ) == [1, 0] assert gf_gcd(ZZ.map([3, 0]), ZZ.map([3, 0]), 11, ZZ) == [1, 0] assert gf_gcd(ZZ.map([1, 8, 7]), ZZ.map([1, 7, 1, 7]), 11, ZZ) == [1, 7] def test_gf_lcm(): assert gf_lcm(ZZ.map([]), ZZ.map([]), 11, ZZ) == [] assert gf_lcm(ZZ.map([2]), ZZ.map([]), 11, ZZ) == [] assert gf_lcm(ZZ.map([]), ZZ.map([2]), 11, ZZ) == [] assert gf_lcm(ZZ.map([2]), ZZ.map([2]), 11, ZZ) == [1] assert gf_lcm(ZZ.map([]), ZZ.map([1, 0]), 11, ZZ) == [] assert gf_lcm(ZZ.map([1, 0]), ZZ.map([]), 11, ZZ) == [] assert gf_lcm(ZZ.map([3, 0]), ZZ.map([3, 0]), 11, ZZ) == [1, 0] assert gf_lcm(ZZ.map([1, 8, 7]), ZZ.map([1, 7, 1, 7]), 11, ZZ) == [1, 8, 8, 8, 7] def test_gf_cofactors(): assert gf_cofactors(ZZ.map([]), ZZ.map([]), 11, ZZ) == ([], [], []) assert gf_cofactors(ZZ.map([2]), ZZ.map([]), 11, ZZ) == ([1], [2], []) assert gf_cofactors(ZZ.map([]), ZZ.map([2]), 11, ZZ) == ([1], [], [2]) assert gf_cofactors(ZZ.map([2]), ZZ.map([2]), 11, ZZ) == ([1], [2], [2]) assert gf_cofactors(ZZ.map([]), ZZ.map([1, 0]), 11, ZZ) == ([1, 0], [], [1]) assert gf_cofactors(ZZ.map([1, 0]), ZZ.map([]), 11, ZZ) == ([1, 0], [1], []) assert gf_cofactors(ZZ.map([3, 0]), ZZ.map([3, 0]), 11, ZZ) == ( [1, 0], [3], [3]) assert gf_cofactors(ZZ.map([1, 8, 7]), ZZ.map([1, 7, 1, 7]), 11, ZZ) == ( ([1, 7], [1, 1], [1, 0, 1])) def test_gf_diff(): assert gf_diff([], 11, ZZ) == [] assert gf_diff([7], 11, ZZ) == [] assert gf_diff([7, 3], 11, ZZ) == [7] assert gf_diff([7, 3, 1], 11, ZZ) == [3, 3] assert gf_diff([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], 11, ZZ) == [] def test_gf_eval(): assert gf_eval([], 4, 11, ZZ) == 0 assert gf_eval([], 27, 11, ZZ) == 0 assert gf_eval([7], 4, 11, ZZ) == 7 assert gf_eval([7], 27, 11, ZZ) == 7 assert gf_eval([1, 0, 3, 2, 4, 3, 1, 2, 0], 0, 11, ZZ) == 0 assert gf_eval([1, 0, 3, 2, 4, 3, 1, 2, 0], 4, 11, ZZ) == 9 assert gf_eval([1, 0, 3, 2, 4, 3, 1, 2, 0], 27, 11, ZZ) == 5 assert gf_eval([4, 0, 0, 4, 6, 0, 1, 3, 5], 0, 11, ZZ) == 5 assert gf_eval([4, 0, 0, 4, 6, 0, 1, 3, 5], 4, 11, ZZ) == 3 assert gf_eval([4, 0, 0, 4, 6, 0, 1, 3, 5], 27, 11, ZZ) == 9 assert gf_multi_eval([3, 2, 1], [0, 1, 2, 3], 11, ZZ) == [1, 6, 6, 1] def test_gf_compose(): assert gf_compose([], [1, 0], 11, ZZ) == [] assert gf_compose_mod([], [1, 0], [1, 0], 11, ZZ) == [] assert gf_compose([1], [], 11, ZZ) == [1] assert gf_compose([1, 0], [], 11, ZZ) == [] assert gf_compose([1, 0], [1, 0], 11, ZZ) == [1, 0] f = ZZ.map([1, 1, 4, 9, 1]) g = ZZ.map([1, 1, 1]) h = ZZ.map([1, 0, 0, 2]) assert gf_compose(g, h, 11, ZZ) == [1, 0, 0, 5, 0, 0, 7] assert gf_compose_mod(g, h, f, 11, ZZ) == [3, 9, 6, 10] def test_gf_trace_map(): f = ZZ.map([1, 1, 4, 9, 1]) a = [1, 1, 1] c = ZZ.map([1, 0]) b = gf_pow_mod(c, 11, f, 11, ZZ) assert gf_trace_map(a, b, c, 0, f, 11, ZZ) == \ ([1, 1, 1], [1, 1, 1]) assert gf_trace_map(a, b, c, 1, f, 11, ZZ) == \ ([5, 2, 10, 3], [5, 3, 0, 4]) assert gf_trace_map(a, b, c, 2, f, 11, ZZ) == \ ([5, 9, 5, 3], [10, 1, 5, 7]) assert gf_trace_map(a, b, c, 3, f, 11, ZZ) == \ ([1, 10, 6, 0], [7]) assert gf_trace_map(a, b, c, 4, f, 11, ZZ) == \ ([1, 1, 1], [1, 1, 8]) assert gf_trace_map(a, b, c, 5, f, 11, ZZ) == \ ([5, 2, 10, 3], [5, 3, 0, 0]) assert gf_trace_map(a, b, c, 11, f, 11, ZZ) == \ ([1, 10, 6, 0], [10]) def test_gf_irreducible(): assert gf_irreducible_p(gf_irreducible(1, 11, ZZ), 11, ZZ) is True assert gf_irreducible_p(gf_irreducible(2, 11, ZZ), 11, ZZ) is True assert gf_irreducible_p(gf_irreducible(3, 11, ZZ), 11, ZZ) is True assert gf_irreducible_p(gf_irreducible(4, 11, ZZ), 11, ZZ) is True assert gf_irreducible_p(gf_irreducible(5, 11, ZZ), 11, ZZ) is True assert gf_irreducible_p(gf_irreducible(6, 11, ZZ), 11, ZZ) is True assert gf_irreducible_p(gf_irreducible(7, 11, ZZ), 11, ZZ) is True def test_gf_irreducible_p(): assert gf_irred_p_ben_or(ZZ.map([7]), 11, ZZ) is True assert gf_irred_p_ben_or(ZZ.map([7, 3]), 11, ZZ) is True assert gf_irred_p_ben_or(ZZ.map([7, 3, 1]), 11, ZZ) is False assert gf_irred_p_rabin(ZZ.map([7]), 11, ZZ) is True assert gf_irred_p_rabin(ZZ.map([7, 3]), 11, ZZ) is True assert gf_irred_p_rabin(ZZ.map([7, 3, 1]), 11, ZZ) is False config.setup('GF_IRRED_METHOD', 'ben-or') assert gf_irreducible_p(ZZ.map([7]), 11, ZZ) is True assert gf_irreducible_p(ZZ.map([7, 3]), 11, ZZ) is True assert gf_irreducible_p(ZZ.map([7, 3, 1]), 11, ZZ) is False config.setup('GF_IRRED_METHOD', 'rabin') assert gf_irreducible_p(ZZ.map([7]), 11, ZZ) is True assert gf_irreducible_p(ZZ.map([7, 3]), 11, ZZ) is True assert gf_irreducible_p(ZZ.map([7, 3, 1]), 11, ZZ) is False config.setup('GF_IRRED_METHOD', 'other') raises(KeyError, lambda: gf_irreducible_p([7], 11, ZZ)) config.setup('GF_IRRED_METHOD') f = ZZ.map([1, 9, 9, 13, 16, 15, 6, 7, 7, 7, 10]) g = ZZ.map([1, 7, 16, 7, 15, 13, 13, 11, 16, 10, 9]) h = gf_mul(f, g, 17, ZZ) assert gf_irred_p_ben_or(f, 17, ZZ) is True assert gf_irred_p_ben_or(g, 17, ZZ) is True assert gf_irred_p_ben_or(h, 17, ZZ) is False assert gf_irred_p_rabin(f, 17, ZZ) is True assert gf_irred_p_rabin(g, 17, ZZ) is True assert gf_irred_p_rabin(h, 17, ZZ) is False def test_gf_squarefree(): assert gf_sqf_list([], 11, ZZ) == (0, []) assert gf_sqf_list([1], 11, ZZ) == (1, []) assert gf_sqf_list([1, 1], 11, ZZ) == (1, [([1, 1], 1)]) assert gf_sqf_p([], 11, ZZ) is True assert gf_sqf_p([1], 11, ZZ) is True assert gf_sqf_p([1, 1], 11, ZZ) is True f = gf_from_dict({11: 1, 0: 1}, 11, ZZ) assert gf_sqf_p(f, 11, ZZ) is False assert gf_sqf_list(f, 11, ZZ) == \ (1, [([1, 1], 11)]) f = [1, 5, 8, 4] assert gf_sqf_p(f, 11, ZZ) is False assert gf_sqf_list(f, 11, ZZ) == \ (1, [([1, 1], 1), ([1, 2], 2)]) assert gf_sqf_part(f, 11, ZZ) == [1, 3, 2] f = [1, 0, 0, 2, 0, 0, 2, 0, 0, 1, 0] assert gf_sqf_list(f, 3, ZZ) == \ (1, [([1, 0], 1), ([1, 1], 3), ([1, 2], 6)]) def test_gf_frobenius_map(): f = ZZ.map([2, 0, 1, 0, 2, 2, 0, 2, 2, 2]) g = ZZ.map([1,1,0,2,0,1,0,2,0,1]) p = 3 b = gf_frobenius_monomial_base(g, p, ZZ) h = gf_frobenius_map(f, g, b, p, ZZ) h1 = gf_pow_mod(f, p, g, p, ZZ) assert h == h1 def test_gf_berlekamp(): f = gf_from_int_poly([1, -3, 1, -3, -1, -3, 1], 11) Q = [[1, 0, 0, 0, 0, 0], [3, 5, 8, 8, 6, 5], [3, 6, 6, 1, 10, 0], [9, 4, 10, 3, 7, 9], [7, 8, 10, 0, 0, 8], [8, 10, 7, 8, 10, 8]] V = [[1, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 0], [0, 0, 7, 9, 0, 1]] assert gf_Qmatrix(f, 11, ZZ) == Q assert gf_Qbasis(Q, 11, ZZ) == V assert gf_berlekamp(f, 11, ZZ) == \ [[1, 1], [1, 5, 3], [1, 2, 3, 4]] f = ZZ.map([1, 0, 1, 0, 10, 10, 8, 2, 8]) Q = ZZ.map([[1, 0, 0, 0, 0, 0, 0, 0], [2, 1, 7, 11, 10, 12, 5, 11], [3, 6, 4, 3, 0, 4, 7, 2], [4, 3, 6, 5, 1, 6, 2, 3], [2, 11, 8, 8, 3, 1, 3, 11], [6, 11, 8, 6, 2, 7, 10, 9], [5, 11, 7, 10, 0, 11, 7, 12], [3, 3, 12, 5, 0, 11, 9, 12]]) V = [[1, 0, 0, 0, 0, 0, 0, 0], [0, 5, 5, 0, 9, 5, 1, 0], [0, 9, 11, 9, 10, 12, 0, 1]] assert gf_Qmatrix(f, 13, ZZ) == Q assert gf_Qbasis(Q, 13, ZZ) == V assert gf_berlekamp(f, 13, ZZ) == \ [[1, 3], [1, 8, 4, 12], [1, 2, 3, 4, 6]] def test_gf_ddf(): f = gf_from_dict({15: ZZ(1), 0: ZZ(-1)}, 11, ZZ) g = [([1, 0, 0, 0, 0, 10], 1), ([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], 2)] assert gf_ddf_zassenhaus(f, 11, ZZ) == g assert gf_ddf_shoup(f, 11, ZZ) == g f = gf_from_dict({63: ZZ(1), 0: ZZ(1)}, 2, ZZ) g = [([1, 1], 1), ([1, 1, 1], 2), ([1, 1, 1, 1, 1, 1, 1], 3), ([1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1], 6)] assert gf_ddf_zassenhaus(f, 2, ZZ) == g assert gf_ddf_shoup(f, 2, ZZ) == g f = gf_from_dict({6: ZZ(1), 5: ZZ(-1), 4: ZZ(1), 3: ZZ(1), 1: ZZ(-1)}, 3, ZZ) g = [([1, 1, 0], 1), ([1, 1, 0, 1, 2], 2)] assert gf_ddf_zassenhaus(f, 3, ZZ) == g assert gf_ddf_shoup(f, 3, ZZ) == g f = ZZ.map([1, 2, 5, 26, 677, 436, 791, 325, 456, 24, 577]) g = [([1, 701], 1), ([1, 110, 559, 532, 694, 151, 110, 70, 735, 122], 9)] assert gf_ddf_zassenhaus(f, 809, ZZ) == g assert gf_ddf_shoup(f, 809, ZZ) == g p = ZZ(nextprime(int((2**15 * pi).evalf()))) f = gf_from_dict({15: 1, 1: 1, 0: 1}, p, ZZ) g = [([1, 22730, 68144], 2), ([1, 64876, 83977, 10787, 12561, 68608, 52650, 88001, 84356], 4), ([1, 15347, 95022, 84569, 94508, 92335], 5)] assert gf_ddf_zassenhaus(f, p, ZZ) == g assert gf_ddf_shoup(f, p, ZZ) == g def test_gf_edf(): f = ZZ.map([1, 1, 0, 1, 2]) g = ZZ.map([[1, 0, 1], [1, 1, 2]]) assert gf_edf_zassenhaus(f, 2, 3, ZZ) == g assert gf_edf_shoup(f, 2, 3, ZZ) == g def test_gf_factor(): assert gf_factor([], 11, ZZ) == (0, []) assert gf_factor([1], 11, ZZ) == (1, []) assert gf_factor([1, 1], 11, ZZ) == (1, [([1, 1], 1)]) assert gf_factor_sqf([], 11, ZZ) == (0, []) assert gf_factor_sqf([1], 11, ZZ) == (1, []) assert gf_factor_sqf([1, 1], 11, ZZ) == (1, [[1, 1]]) config.setup('GF_FACTOR_METHOD', 'berlekamp') assert gf_factor_sqf([], 11, ZZ) == (0, []) assert gf_factor_sqf([1], 11, ZZ) == (1, []) assert gf_factor_sqf([1, 1], 11, ZZ) == (1, [[1, 1]]) config.setup('GF_FACTOR_METHOD', 'zassenhaus') assert gf_factor_sqf([], 11, ZZ) == (0, []) assert gf_factor_sqf([1], 11, ZZ) == (1, []) assert gf_factor_sqf([1, 1], 11, ZZ) == (1, [[1, 1]]) config.setup('GF_FACTOR_METHOD', 'shoup') assert gf_factor_sqf(ZZ.map([]), 11, ZZ) == (0, []) assert gf_factor_sqf(ZZ.map([1]), 11, ZZ) == (1, []) assert gf_factor_sqf(ZZ.map([1, 1]), 11, ZZ) == (1, [[1, 1]]) f, p = ZZ.map([1, 0, 0, 1, 0]), 2 g = (1, [([1, 0], 1), ([1, 1], 1), ([1, 1, 1], 1)]) config.setup('GF_FACTOR_METHOD', 'berlekamp') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'zassenhaus') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'shoup') assert gf_factor(f, p, ZZ) == g g = (1, [[1, 0], [1, 1], [1, 1, 1]]) config.setup('GF_FACTOR_METHOD', 'berlekamp') assert gf_factor_sqf(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'zassenhaus') assert gf_factor_sqf(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'shoup') assert gf_factor_sqf(f, p, ZZ) == g f, p = gf_from_int_poly([1, -3, 1, -3, -1, -3, 1], 11), 11 g = (1, [([1, 1], 1), ([1, 5, 3], 1), ([1, 2, 3, 4], 1)]) config.setup('GF_FACTOR_METHOD', 'berlekamp') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'zassenhaus') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'shoup') assert gf_factor(f, p, ZZ) == g f, p = [1, 5, 8, 4], 11 g = (1, [([1, 1], 1), ([1, 2], 2)]) config.setup('GF_FACTOR_METHOD', 'berlekamp') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'zassenhaus') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'shoup') assert gf_factor(f, p, ZZ) == g f, p = [1, 1, 10, 1, 0, 10, 10, 10, 0, 0], 11 g = (1, [([1, 0], 2), ([1, 9, 5], 1), ([1, 3, 0, 8, 5, 2], 1)]) config.setup('GF_FACTOR_METHOD', 'berlekamp') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'zassenhaus') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'shoup') assert gf_factor(f, p, ZZ) == g f, p = gf_from_dict({32: 1, 0: 1}, 11, ZZ), 11 g = (1, [([1, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 10], 1), ([1, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 10], 1)]) config.setup('GF_FACTOR_METHOD', 'berlekamp') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'zassenhaus') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'shoup') assert gf_factor(f, p, ZZ) == g f, p = gf_from_dict({32: ZZ(8), 0: ZZ(5)}, 11, ZZ), 11 g = (8, [([1, 3], 1), ([1, 8], 1), ([1, 0, 9], 1), ([1, 2, 2], 1), ([1, 9, 2], 1), ([1, 0, 5, 0, 7], 1), ([1, 0, 6, 0, 7], 1), ([1, 0, 0, 0, 1, 0, 0, 0, 6], 1), ([1, 0, 0, 0, 10, 0, 0, 0, 6], 1)]) config.setup('GF_FACTOR_METHOD', 'berlekamp') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'zassenhaus') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'shoup') assert gf_factor(f, p, ZZ) == g f, p = gf_from_dict({63: ZZ(8), 0: ZZ(5)}, 11, ZZ), 11 g = (8, [([1, 7], 1), ([1, 4, 5], 1), ([1, 6, 8, 2], 1), ([1, 9, 9, 2], 1), ([1, 0, 0, 9, 0, 0, 4], 1), ([1, 2, 0, 8, 4, 6, 4], 1), ([1, 2, 3, 8, 0, 6, 4], 1), ([1, 2, 6, 0, 8, 4, 4], 1), ([1, 3, 3, 1, 6, 8, 4], 1), ([1, 5, 6, 0, 8, 6, 4], 1), ([1, 6, 2, 7, 9, 8, 4], 1), ([1, 10, 4, 7, 10, 7, 4], 1), ([1, 10, 10, 1, 4, 9, 4], 1)]) config.setup('GF_FACTOR_METHOD', 'berlekamp') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'zassenhaus') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'shoup') assert gf_factor(f, p, ZZ) == g # Gathen polynomials: x**n + x + 1 (mod p > 2**n * pi) p = ZZ(nextprime(int((2**15 * pi).evalf()))) f = gf_from_dict({15: 1, 1: 1, 0: 1}, p, ZZ) assert gf_sqf_p(f, p, ZZ) is True g = (1, [([1, 22730, 68144], 1), ([1, 81553, 77449, 86810, 4724], 1), ([1, 86276, 56779, 14859, 31575], 1), ([1, 15347, 95022, 84569, 94508, 92335], 1)]) config.setup('GF_FACTOR_METHOD', 'zassenhaus') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'shoup') assert gf_factor(f, p, ZZ) == g g = (1, [[1, 22730, 68144], [1, 81553, 77449, 86810, 4724], [1, 86276, 56779, 14859, 31575], [1, 15347, 95022, 84569, 94508, 92335]]) config.setup('GF_FACTOR_METHOD', 'zassenhaus') assert gf_factor_sqf(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'shoup') assert gf_factor_sqf(f, p, ZZ) == g # Shoup polynomials: f = a_0 x**n + a_1 x**(n-1) + ... + a_n # (mod p > 2**(n-2) * pi), where a_n = a_{n-1}**2 + 1, a_0 = 1 p = ZZ(nextprime(int((2**4 * pi).evalf()))) f = ZZ.map([1, 2, 5, 26, 41, 39, 38]) assert gf_sqf_p(f, p, ZZ) is True g = (1, [([1, 44, 26], 1), ([1, 11, 25, 18, 30], 1)]) config.setup('GF_FACTOR_METHOD', 'zassenhaus') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'shoup') assert gf_factor(f, p, ZZ) == g g = (1, [[1, 44, 26], [1, 11, 25, 18, 30]]) config.setup('GF_FACTOR_METHOD', 'zassenhaus') assert gf_factor_sqf(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'shoup') assert gf_factor_sqf(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'other') raises(KeyError, lambda: gf_factor([1, 1], 11, ZZ)) config.setup('GF_FACTOR_METHOD') def test_gf_csolve(): assert gf_value([1, 7, 2, 4], 11) == 2204 assert linear_congruence(4, 3, 5) == [2] assert linear_congruence(0, 3, 5) == [] assert linear_congruence(6, 1, 4) == [] assert linear_congruence(0, 5, 5) == [0, 1, 2, 3, 4] assert linear_congruence(3, 12, 15) == [4, 9, 14] assert linear_congruence(6, 0, 18) == [0, 3, 6, 9, 12, 15] # with power = 1 assert csolve_prime([1, 3, 2, 17], 7) == [3] assert csolve_prime([1, 3, 1, 5], 5) == [0, 1] assert csolve_prime([3, 6, 9, 3], 3) == [0, 1, 2] # with power > 1 assert csolve_prime( [1, 1, 223], 3, 4) == [4, 13, 22, 31, 40, 49, 58, 67, 76] assert csolve_prime([3, 5, 2, 25], 5, 3) == [16, 50, 99] assert csolve_prime([3, 2, 2, 49], 7, 3) == [147, 190, 234] assert gf_csolve([1, 1, 7], 189) == [13, 49, 76, 112, 139, 175] assert gf_csolve([1, 3, 4, 1, 30], 60) == [10, 30] assert gf_csolve([1, 1, 7], 15) == []
eb2180490b2f923e4f33c52b6343adbe5efb009eea1f9909f0912af340706062
"""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] 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_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)/2 - sqrt(3)*root(7, 3)*I/2: 1, -sqrt(2) - root(7, 3)/2 + sqrt(3)*root(7, 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))
f877336bdb1c855a14d1e292a9766e63b51e7b564659d4012fffdcf38b26d282
"""Computations with ideals of polynomial rings.""" from sympy.core.compatibility import reduce from sympy.polys.polyerrors import CoercionFailed class Ideal: """ Abstract base class for ideals. Do not instantiate - use explicit constructors in the ring class instead: >>> from sympy import QQ >>> from sympy.abc import x >>> QQ.old_poly_ring(x).ideal(x+1) <x + 1> Attributes - ring - the ring this ideal belongs to Non-implemented methods: - _contains_elem - _contains_ideal - _quotient - _intersect - _union - _product - is_whole_ring - is_zero - is_prime, is_maximal, is_primary, is_radical - is_principal - height, depth - radical Methods that likely should be overridden in subclasses: - reduce_element """ def _contains_elem(self, x): """Implementation of element containment.""" raise NotImplementedError def _contains_ideal(self, I): """Implementation of ideal containment.""" raise NotImplementedError def _quotient(self, J): """Implementation of ideal quotient.""" raise NotImplementedError def _intersect(self, J): """Implementation of ideal intersection.""" raise NotImplementedError def is_whole_ring(self): """Return True if ``self`` is the whole ring.""" raise NotImplementedError def is_zero(self): """Return True if ``self`` is the zero ideal.""" raise NotImplementedError def _equals(self, J): """Implementation of ideal equality.""" return self._contains_ideal(J) and J._contains_ideal(self) def is_prime(self): """Return True if ``self`` is a prime ideal.""" raise NotImplementedError def is_maximal(self): """Return True if ``self`` is a maximal ideal.""" raise NotImplementedError def is_radical(self): """Return True if ``self`` is a radical ideal.""" raise NotImplementedError def is_primary(self): """Return True if ``self`` is a primary ideal.""" raise NotImplementedError def is_principal(self): """Return True if ``self`` is a principal ideal.""" raise NotImplementedError def radical(self): """Compute the radical of ``self``.""" raise NotImplementedError def depth(self): """Compute the depth of ``self``.""" raise NotImplementedError def height(self): """Compute the height of ``self``.""" raise NotImplementedError # TODO more # non-implemented methods end here def __init__(self, ring): self.ring = ring def _check_ideal(self, J): """Helper to check ``J`` is an ideal of our ring.""" if not isinstance(J, Ideal) or J.ring != self.ring: raise ValueError( 'J must be an ideal of %s, got %s' % (self.ring, J)) def contains(self, elem): """ Return True if ``elem`` is an element of this ideal. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> QQ.old_poly_ring(x).ideal(x+1, x-1).contains(3) True >>> QQ.old_poly_ring(x).ideal(x**2, x**3).contains(x) False """ return self._contains_elem(self.ring.convert(elem)) def subset(self, other): """ Returns True if ``other`` is is a subset of ``self``. Here ``other`` may be an ideal. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> I = QQ.old_poly_ring(x).ideal(x+1) >>> I.subset([x**2 - 1, x**2 + 2*x + 1]) True >>> I.subset([x**2 + 1, x + 1]) False >>> I.subset(QQ.old_poly_ring(x).ideal(x**2 - 1)) True """ if isinstance(other, Ideal): return self._contains_ideal(other) return all(self._contains_elem(x) for x in other) def quotient(self, J, **opts): r""" Compute the ideal quotient of ``self`` by ``J``. That is, if ``self`` is the ideal `I`, compute the set `I : J = \{x \in R | xJ \subset I \}`. Examples ======== >>> from sympy.abc import x, y >>> from sympy import QQ >>> R = QQ.old_poly_ring(x, y) >>> R.ideal(x*y).quotient(R.ideal(x)) <y> """ self._check_ideal(J) return self._quotient(J, **opts) def intersect(self, J): """ Compute the intersection of self with ideal J. Examples ======== >>> from sympy.abc import x, y >>> from sympy import QQ >>> R = QQ.old_poly_ring(x, y) >>> R.ideal(x).intersect(R.ideal(y)) <x*y> """ self._check_ideal(J) return self._intersect(J) def saturate(self, J): r""" Compute the ideal saturation of ``self`` by ``J``. That is, if ``self`` is the ideal `I`, compute the set `I : J^\infty = \{x \in R | xJ^n \subset I \text{ for some } n\}`. """ raise NotImplementedError # Note this can be implemented using repeated quotient def union(self, J): """ Compute the ideal generated by the union of ``self`` and ``J``. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> QQ.old_poly_ring(x).ideal(x**2 - 1).union(QQ.old_poly_ring(x).ideal((x+1)**2)) == QQ.old_poly_ring(x).ideal(x+1) True """ self._check_ideal(J) return self._union(J) def product(self, J): r""" Compute the ideal product of ``self`` and ``J``. That is, compute the ideal generated by products `xy`, for `x` an element of ``self`` and `y \in J`. Examples ======== >>> from sympy.abc import x, y >>> from sympy import QQ >>> QQ.old_poly_ring(x, y).ideal(x).product(QQ.old_poly_ring(x, y).ideal(y)) <x*y> """ self._check_ideal(J) return self._product(J) def reduce_element(self, x): """ Reduce the element ``x`` of our ring modulo the ideal ``self``. Here "reduce" has no specific meaning: it could return a unique normal form, simplify the expression a bit, or just do nothing. """ return x def __add__(self, e): if not isinstance(e, Ideal): R = self.ring.quotient_ring(self) if isinstance(e, R.dtype): return e if isinstance(e, R.ring.dtype): return R(e) return R.convert(e) self._check_ideal(e) return self.union(e) __radd__ = __add__ def __mul__(self, e): if not isinstance(e, Ideal): try: e = self.ring.ideal(e) except CoercionFailed: return NotImplemented self._check_ideal(e) return self.product(e) __rmul__ = __mul__ def __pow__(self, exp): if exp < 0: raise NotImplementedError # TODO exponentiate by squaring return reduce(lambda x, y: x*y, [self]*exp, self.ring.ideal(1)) def __eq__(self, e): if not isinstance(e, Ideal) or e.ring != self.ring: return False return self._equals(e) def __ne__(self, e): return not (self == e) class ModuleImplementedIdeal(Ideal): """ Ideal implementation relying on the modules code. Attributes: - _module - the underlying module """ def __init__(self, ring, module): Ideal.__init__(self, ring) self._module = module def _contains_elem(self, x): return self._module.contains([x]) def _contains_ideal(self, J): if not isinstance(J, ModuleImplementedIdeal): raise NotImplementedError return self._module.is_submodule(J._module) def _intersect(self, J): if not isinstance(J, ModuleImplementedIdeal): raise NotImplementedError return self.__class__(self.ring, self._module.intersect(J._module)) def _quotient(self, J, **opts): if not isinstance(J, ModuleImplementedIdeal): raise NotImplementedError return self._module.module_quotient(J._module, **opts) def _union(self, J): if not isinstance(J, ModuleImplementedIdeal): raise NotImplementedError return self.__class__(self.ring, self._module.union(J._module)) @property def gens(self): """ Return generators for ``self``. Examples ======== >>> from sympy import QQ >>> from sympy.abc import x, y >>> list(QQ.old_poly_ring(x, y).ideal(x, y, x**2 + y).gens) [x, y, x**2 + y] """ return (x[0] for x in self._module.gens) def is_zero(self): """ Return True if ``self`` is the zero ideal. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> QQ.old_poly_ring(x).ideal(x).is_zero() False >>> QQ.old_poly_ring(x).ideal().is_zero() True """ return self._module.is_zero() def is_whole_ring(self): """ Return True if ``self`` is the whole ring, i.e. one generator is a unit. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ, ilex >>> QQ.old_poly_ring(x).ideal(x).is_whole_ring() False >>> QQ.old_poly_ring(x).ideal(3).is_whole_ring() True >>> QQ.old_poly_ring(x, order=ilex).ideal(2 + x).is_whole_ring() True """ return self._module.is_full_module() def __repr__(self): from sympy import sstr return '<' + ','.join(sstr(x) for [x] in self._module.gens) + '>' # NOTE this is the only method using the fact that the module is a SubModule def _product(self, J): if not isinstance(J, ModuleImplementedIdeal): raise NotImplementedError return self.__class__(self.ring, self._module.submodule( *[[x*y] for [x] in self._module.gens for [y] in J._module.gens])) def in_terms_of_generators(self, e): """ Express ``e`` in terms of the generators of ``self``. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> I = QQ.old_poly_ring(x).ideal(x**2 + 1, x) >>> I.in_terms_of_generators(1) [1, -x] """ return self._module.in_terms_of_generators([e]) def reduce_element(self, x, **options): return self._module.reduce_element([x], **options)[0]
7496f883fb3a6bce17a868c073bce56392f0b6ea5436647bc9bbc9c949d779f6
""" Computations with modules over polynomial rings. This module implements various classes that encapsulate groebner basis computations for modules. Most of them should not be instantiated by hand. Instead, use the constructing routines on objects you already have. For example, to construct a free module over ``QQ[x, y]``, call ``QQ[x, y].free_module(rank)`` instead of the ``FreeModule`` constructor. In fact ``FreeModule`` is an abstract base class that should not be instantiated, the ``free_module`` method instead returns the implementing class ``FreeModulePolyRing``. In general, the abstract base classes implement most functionality in terms of a few non-implemented methods. The concrete base classes supply only these non-implemented methods. They may also supply new implementations of the convenience methods, for example if there are faster algorithms available. """ from copy import copy from sympy.core.compatibility import iterable, reduce from sympy.polys.agca.ideals import Ideal from sympy.polys.domains.field import Field from sympy.polys.orderings import ProductOrder, monomial_key from sympy.polys.polyerrors import CoercionFailed from sympy.core.basic import _aresame # TODO # - module saturation # - module quotient/intersection for quotient rings # - free resoltutions / syzygies # - finding small/minimal generating sets # - ... ########################################################################## ## Abstract base classes ################################################# ########################################################################## class Module: """ Abstract base class for modules. Do not instantiate - use ring explicit constructors instead: >>> from sympy import QQ >>> from sympy.abc import x >>> QQ.old_poly_ring(x).free_module(2) QQ[x]**2 Attributes: - dtype - type of elements - ring - containing ring Non-implemented methods: - submodule - quotient_module - is_zero - is_submodule - multiply_ideal The method convert likely needs to be changed in subclasses. """ def __init__(self, ring): self.ring = ring def convert(self, elem, M=None): """ Convert ``elem`` into internal representation of this module. If ``M`` is not None, it should be a module containing it. """ if not isinstance(elem, self.dtype): raise CoercionFailed return elem def submodule(self, *gens): """Generate a submodule.""" raise NotImplementedError def quotient_module(self, other): """Generate a quotient module.""" raise NotImplementedError def __truediv__(self, e): if not isinstance(e, Module): e = self.submodule(*e) return self.quotient_module(e) def contains(self, elem): """Return True if ``elem`` is an element of this module.""" try: self.convert(elem) return True except CoercionFailed: return False def __contains__(self, elem): return self.contains(elem) def subset(self, other): """ Returns True if ``other`` is is a subset of ``self``. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> F = QQ.old_poly_ring(x).free_module(2) >>> F.subset([(1, x), (x, 2)]) True >>> F.subset([(1/x, x), (x, 2)]) False """ return all(self.contains(x) for x in other) def __eq__(self, other): return self.is_submodule(other) and other.is_submodule(self) def __ne__(self, other): return not (self == other) def is_zero(self): """Returns True if ``self`` is a zero module.""" raise NotImplementedError def is_submodule(self, other): """Returns True if ``other`` is a submodule of ``self``.""" raise NotImplementedError def multiply_ideal(self, other): """ Multiply ``self`` by the ideal ``other``. """ raise NotImplementedError def __mul__(self, e): if not isinstance(e, Ideal): try: e = self.ring.ideal(e) except (CoercionFailed, NotImplementedError): return NotImplemented return self.multiply_ideal(e) __rmul__ = __mul__ def identity_hom(self): """Return the identity homomorphism on ``self``.""" raise NotImplementedError class ModuleElement: """ Base class for module element wrappers. Use this class to wrap primitive data types as module elements. It stores a reference to the containing module, and implements all the arithmetic operators. Attributes: - module - containing module - data - internal data Methods that likely need change in subclasses: - add - mul - div - eq """ def __init__(self, module, data): self.module = module self.data = data def add(self, d1, d2): """Add data ``d1`` and ``d2``.""" return d1 + d2 def mul(self, m, d): """Multiply module data ``m`` by coefficient d.""" return m * d def div(self, m, d): """Divide module data ``m`` by coefficient d.""" return m / d def eq(self, d1, d2): """Return true if d1 and d2 represent the same element.""" return d1 == d2 def __add__(self, om): if not isinstance(om, self.__class__) or om.module != self.module: try: om = self.module.convert(om) except CoercionFailed: return NotImplemented return self.__class__(self.module, self.add(self.data, om.data)) __radd__ = __add__ def __neg__(self): return self.__class__(self.module, self.mul(self.data, self.module.ring.convert(-1))) def __sub__(self, om): if not isinstance(om, self.__class__) or om.module != self.module: try: om = self.module.convert(om) except CoercionFailed: return NotImplemented return self.__add__(-om) def __rsub__(self, om): return (-self).__add__(om) def __mul__(self, o): if not isinstance(o, self.module.ring.dtype): try: o = self.module.ring.convert(o) except CoercionFailed: return NotImplemented return self.__class__(self.module, self.mul(self.data, o)) __rmul__ = __mul__ def __truediv__(self, o): if not isinstance(o, self.module.ring.dtype): try: o = self.module.ring.convert(o) except CoercionFailed: return NotImplemented return self.__class__(self.module, self.div(self.data, o)) def __eq__(self, om): if not isinstance(om, self.__class__) or om.module != self.module: try: om = self.module.convert(om) except CoercionFailed: return False return self.eq(self.data, om.data) def __ne__(self, om): return not self == om ########################################################################## ## Free Modules ########################################################## ########################################################################## class FreeModuleElement(ModuleElement): """Element of a free module. Data stored as a tuple.""" def add(self, d1, d2): return tuple(x + y for x, y in zip(d1, d2)) def mul(self, d, p): return tuple(x * p for x in d) def div(self, d, p): return tuple(x / p for x in d) def __repr__(self): from sympy import sstr return '[' + ', '.join(sstr(x) for x in self.data) + ']' def __iter__(self): return self.data.__iter__() def __getitem__(self, idx): return self.data[idx] class FreeModule(Module): """ Abstract base class for free modules. Additional attributes: - rank - rank of the free module Non-implemented methods: - submodule """ dtype = FreeModuleElement def __init__(self, ring, rank): Module.__init__(self, ring) self.rank = rank def __repr__(self): return repr(self.ring) + "**" + repr(self.rank) def is_submodule(self, other): """ Returns True if ``other`` is a submodule of ``self``. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> F = QQ.old_poly_ring(x).free_module(2) >>> M = F.submodule([2, x]) >>> F.is_submodule(F) True >>> F.is_submodule(M) True >>> M.is_submodule(F) False """ if isinstance(other, SubModule): return other.container == self if isinstance(other, FreeModule): return other.ring == self.ring and other.rank == self.rank return False def convert(self, elem, M=None): """ Convert ``elem`` into the internal representation. This method is called implicitly whenever computations involve elements not in the internal representation. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> F = QQ.old_poly_ring(x).free_module(2) >>> F.convert([1, 0]) [1, 0] """ if isinstance(elem, FreeModuleElement): if elem.module is self: return elem if elem.module.rank != self.rank: raise CoercionFailed return FreeModuleElement(self, tuple(self.ring.convert(x, elem.module.ring) for x in elem.data)) elif iterable(elem): tpl = tuple(self.ring.convert(x) for x in elem) if len(tpl) != self.rank: raise CoercionFailed return FreeModuleElement(self, tpl) elif _aresame(elem, 0): return FreeModuleElement(self, (self.ring.convert(0),)*self.rank) else: raise CoercionFailed def is_zero(self): """ Returns True if ``self`` is a zero module. (If, as this implementation assumes, the coefficient ring is not the zero ring, then this is equivalent to the rank being zero.) Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> QQ.old_poly_ring(x).free_module(0).is_zero() True >>> QQ.old_poly_ring(x).free_module(1).is_zero() False """ return self.rank == 0 def basis(self): """ Return a set of basis elements. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> QQ.old_poly_ring(x).free_module(3).basis() ([1, 0, 0], [0, 1, 0], [0, 0, 1]) """ from sympy.matrices import eye M = eye(self.rank) return tuple(self.convert(M.row(i)) for i in range(self.rank)) def quotient_module(self, submodule): """ Return a quotient module. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> M = QQ.old_poly_ring(x).free_module(2) >>> M.quotient_module(M.submodule([1, x], [x, 2])) QQ[x]**2/<[1, x], [x, 2]> Or more conicisely, using the overloaded division operator: >>> QQ.old_poly_ring(x).free_module(2) / [[1, x], [x, 2]] QQ[x]**2/<[1, x], [x, 2]> """ return QuotientModule(self.ring, self, submodule) def multiply_ideal(self, other): """ Multiply ``self`` by the ideal ``other``. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> I = QQ.old_poly_ring(x).ideal(x) >>> F = QQ.old_poly_ring(x).free_module(2) >>> F.multiply_ideal(I) <[x, 0], [0, x]> """ return self.submodule(*self.basis()).multiply_ideal(other) def identity_hom(self): """ Return the identity homomorphism on ``self``. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> QQ.old_poly_ring(x).free_module(2).identity_hom() Matrix([ [1, 0], : QQ[x]**2 -> QQ[x]**2 [0, 1]]) """ from sympy.polys.agca.homomorphisms import homomorphism return homomorphism(self, self, self.basis()) class FreeModulePolyRing(FreeModule): """ Free module over a generalized polynomial ring. Do not instantiate this, use the constructor method of the ring instead: Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> F = QQ.old_poly_ring(x).free_module(3) >>> F QQ[x]**3 >>> F.contains([x, 1, 0]) True >>> F.contains([1/x, 0, 1]) False """ def __init__(self, ring, rank): from sympy.polys.domains.old_polynomialring import PolynomialRingBase FreeModule.__init__(self, ring, rank) if not isinstance(ring, PolynomialRingBase): raise NotImplementedError('This implementation only works over ' + 'polynomial rings, got %s' % ring) if not isinstance(ring.dom, Field): raise NotImplementedError('Ground domain must be a field, ' + 'got %s' % ring.dom) def submodule(self, *gens, **opts): """ Generate a submodule. Examples ======== >>> from sympy.abc import x, y >>> from sympy import QQ >>> M = QQ.old_poly_ring(x, y).free_module(2).submodule([x, x + y]) >>> M <[x, x + y]> >>> M.contains([2*x, 2*x + 2*y]) True >>> M.contains([x, y]) False """ return SubModulePolyRing(gens, self, **opts) class FreeModuleQuotientRing(FreeModule): """ Free module over a quotient ring. Do not instantiate this, use the constructor method of the ring instead: Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> F = (QQ.old_poly_ring(x)/[x**2 + 1]).free_module(3) >>> F (QQ[x]/<x**2 + 1>)**3 Attributes - quot - the quotient module `R^n / IR^n`, where `R/I` is our ring """ def __init__(self, ring, rank): from sympy.polys.domains.quotientring import QuotientRing FreeModule.__init__(self, ring, rank) if not isinstance(ring, QuotientRing): raise NotImplementedError('This implementation only works over ' + 'quotient rings, got %s' % ring) F = self.ring.ring.free_module(self.rank) self.quot = F / (self.ring.base_ideal*F) def __repr__(self): return "(" + repr(self.ring) + ")" + "**" + repr(self.rank) def submodule(self, *gens, **opts): """ Generate a submodule. Examples ======== >>> from sympy.abc import x, y >>> from sympy import QQ >>> M = (QQ.old_poly_ring(x, y)/[x**2 - y**2]).free_module(2).submodule([x, x + y]) >>> M <[x + <x**2 - y**2>, x + y + <x**2 - y**2>]> >>> M.contains([y**2, x**2 + x*y]) True >>> M.contains([x, y]) False """ return SubModuleQuotientRing(gens, self, **opts) def lift(self, elem): """ Lift the element ``elem`` of self to the module self.quot. Note that self.quot is the same set as self, just as an R-module and not as an R/I-module, so this makes sense. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> F = (QQ.old_poly_ring(x)/[x**2 + 1]).free_module(2) >>> e = F.convert([1, 0]) >>> e [1 + <x**2 + 1>, 0 + <x**2 + 1>] >>> L = F.quot >>> l = F.lift(e) >>> l [1, 0] + <[x**2 + 1, 0], [0, x**2 + 1]> >>> L.contains(l) True """ return self.quot.convert([x.data for x in elem]) def unlift(self, elem): """ Push down an element of self.quot to self. This undoes ``lift``. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> F = (QQ.old_poly_ring(x)/[x**2 + 1]).free_module(2) >>> e = F.convert([1, 0]) >>> l = F.lift(e) >>> e == l False >>> e == F.unlift(l) True """ return self.convert(elem.data) ########################################################################## ## Submodules and subquotients ########################################### ########################################################################## class SubModule(Module): """ Base class for submodules. Attributes: - container - containing module - gens - generators (subset of containing module) - rank - rank of containing module Non-implemented methods: - _contains - _syzygies - _in_terms_of_generators - _intersect - _module_quotient Methods that likely need change in subclasses: - reduce_element """ def __init__(self, gens, container): Module.__init__(self, container.ring) self.gens = tuple(container.convert(x) for x in gens) self.container = container self.rank = container.rank self.ring = container.ring self.dtype = container.dtype def __repr__(self): return "<" + ", ".join(repr(x) for x in self.gens) + ">" def _contains(self, other): """Implementation of containment. Other is guaranteed to be FreeModuleElement.""" raise NotImplementedError def _syzygies(self): """Implementation of syzygy computation wrt self generators.""" raise NotImplementedError def _in_terms_of_generators(self, e): """Implementation of expression in terms of generators.""" raise NotImplementedError def convert(self, elem, M=None): """ Convert ``elem`` into the internal represantition. Mostly called implicitly. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> M = QQ.old_poly_ring(x).free_module(2).submodule([1, x]) >>> M.convert([2, 2*x]) [2, 2*x] """ if isinstance(elem, self.container.dtype) and elem.module is self: return elem r = copy(self.container.convert(elem, M)) r.module = self if not self._contains(r): raise CoercionFailed return r def _intersect(self, other): """Implementation of intersection. Other is guaranteed to be a submodule of same free module.""" raise NotImplementedError def _module_quotient(self, other): """Implementation of quotient. Other is guaranteed to be a submodule of same free module.""" raise NotImplementedError def intersect(self, other, **options): """ Returns the intersection of ``self`` with submodule ``other``. Examples ======== >>> from sympy.abc import x, y >>> from sympy import QQ >>> F = QQ.old_poly_ring(x, y).free_module(2) >>> F.submodule([x, x]).intersect(F.submodule([y, y])) <[x*y, x*y]> Some implementation allow further options to be passed. Currently, to only one implemented is ``relations=True``, in which case the function will return a triple ``(res, rela, relb)``, where ``res`` is the intersection module, and ``rela`` and ``relb`` are lists of coefficient vectors, expressing the generators of ``res`` in terms of the generators of ``self`` (``rela``) and ``other`` (``relb``). >>> F.submodule([x, x]).intersect(F.submodule([y, y]), relations=True) (<[x*y, x*y]>, [(y,)], [(x,)]) The above result says: the intersection module is generated by the single element `(-xy, -xy) = -y (x, x) = -x (y, y)`, where `(x, x)` and `(y, y)` respectively are the unique generators of the two modules being intersected. """ if not isinstance(other, SubModule): raise TypeError('%s is not a SubModule' % other) if other.container != self.container: raise ValueError( '%s is contained in a different free module' % other) return self._intersect(other, **options) def module_quotient(self, other, **options): r""" Returns the module quotient of ``self`` by submodule ``other``. That is, if ``self`` is the module `M` and ``other`` is `N`, then return the ideal `\{f \in R | fN \subset M\}`. Examples ======== >>> from sympy import QQ >>> from sympy.abc import x, y >>> F = QQ.old_poly_ring(x, y).free_module(2) >>> S = F.submodule([x*y, x*y]) >>> T = F.submodule([x, x]) >>> S.module_quotient(T) <y> Some implementations allow further options to be passed. Currently, the only one implemented is ``relations=True``, which may only be passed if ``other`` is principal. In this case the function will return a pair ``(res, rel)`` where ``res`` is the ideal, and ``rel`` is a list of coefficient vectors, expressing the generators of the ideal, multiplied by the generator of ``other`` in terms of generators of ``self``. >>> S.module_quotient(T, relations=True) (<y>, [[1]]) This means that the quotient ideal is generated by the single element `y`, and that `y (x, x) = 1 (xy, xy)`, `(x, x)` and `(xy, xy)` being the generators of `T` and `S`, respectively. """ if not isinstance(other, SubModule): raise TypeError('%s is not a SubModule' % other) if other.container != self.container: raise ValueError( '%s is contained in a different free module' % other) return self._module_quotient(other, **options) def union(self, other): """ Returns the module generated by the union of ``self`` and ``other``. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> F = QQ.old_poly_ring(x).free_module(1) >>> M = F.submodule([x**2 + x]) # <x(x+1)> >>> N = F.submodule([x**2 - 1]) # <(x-1)(x+1)> >>> M.union(N) == F.submodule([x+1]) True """ if not isinstance(other, SubModule): raise TypeError('%s is not a SubModule' % other) if other.container != self.container: raise ValueError( '%s is contained in a different free module' % other) return self.__class__(self.gens + other.gens, self.container) def is_zero(self): """ Return True if ``self`` is a zero module. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> F = QQ.old_poly_ring(x).free_module(2) >>> F.submodule([x, 1]).is_zero() False >>> F.submodule([0, 0]).is_zero() True """ return all(x == 0 for x in self.gens) def submodule(self, *gens): """ Generate a submodule. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> M = QQ.old_poly_ring(x).free_module(2).submodule([x, 1]) >>> M.submodule([x**2, x]) <[x**2, x]> """ if not self.subset(gens): raise ValueError('%s not a subset of %s' % (gens, self)) return self.__class__(gens, self.container) def is_full_module(self): """ Return True if ``self`` is the entire free module. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> F = QQ.old_poly_ring(x).free_module(2) >>> F.submodule([x, 1]).is_full_module() False >>> F.submodule([1, 1], [1, 2]).is_full_module() True """ return all(self.contains(x) for x in self.container.basis()) def is_submodule(self, other): """ Returns True if ``other`` is a submodule of ``self``. >>> from sympy.abc import x >>> from sympy import QQ >>> F = QQ.old_poly_ring(x).free_module(2) >>> M = F.submodule([2, x]) >>> N = M.submodule([2*x, x**2]) >>> M.is_submodule(M) True >>> M.is_submodule(N) True >>> N.is_submodule(M) False """ if isinstance(other, SubModule): return self.container == other.container and \ all(self.contains(x) for x in other.gens) if isinstance(other, (FreeModule, QuotientModule)): return self.container == other and self.is_full_module() return False def syzygy_module(self, **opts): r""" Compute the syzygy module of the generators of ``self``. Suppose `M` is generated by `f_1, \ldots, f_n` over the ring `R`. Consider the homomorphism `\phi: R^n \to M`, given by sending `(r_1, \ldots, r_n) \to r_1 f_1 + \cdots + r_n f_n`. The syzygy module is defined to be the kernel of `\phi`. Examples ======== The syzygy module is zero iff the generators generate freely a free submodule: >>> from sympy.abc import x, y >>> from sympy import QQ >>> QQ.old_poly_ring(x).free_module(2).submodule([1, 0], [1, 1]).syzygy_module().is_zero() True A slightly more interesting example: >>> M = QQ.old_poly_ring(x, y).free_module(2).submodule([x, 2*x], [y, 2*y]) >>> S = QQ.old_poly_ring(x, y).free_module(2).submodule([y, -x]) >>> M.syzygy_module() == S True """ F = self.ring.free_module(len(self.gens)) # NOTE we filter out zero syzygies. This is for convenience of the # _syzygies function and not meant to replace any real "generating set # reduction" algorithm return F.submodule(*[x for x in self._syzygies() if F.convert(x) != 0], **opts) def in_terms_of_generators(self, e): """ Express element ``e`` of ``self`` in terms of the generators. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> F = QQ.old_poly_ring(x).free_module(2) >>> M = F.submodule([1, 0], [1, 1]) >>> M.in_terms_of_generators([x, x**2]) [-x**2 + x, x**2] """ try: e = self.convert(e) except CoercionFailed: raise ValueError('%s is not an element of %s' % (e, self)) return self._in_terms_of_generators(e) def reduce_element(self, x): """ Reduce the element ``x`` of our ring modulo the ideal ``self``. Here "reduce" has no specific meaning, it could return a unique normal form, simplify the expression a bit, or just do nothing. """ return x def quotient_module(self, other, **opts): """ Return a quotient module. This is the same as taking a submodule of a quotient of the containing module. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> F = QQ.old_poly_ring(x).free_module(2) >>> S1 = F.submodule([x, 1]) >>> S2 = F.submodule([x**2, x]) >>> S1.quotient_module(S2) <[x, 1] + <[x**2, x]>> Or more coincisely, using the overloaded division operator: >>> F.submodule([x, 1]) / [(x**2, x)] <[x, 1] + <[x**2, x]>> """ if not self.is_submodule(other): raise ValueError('%s not a submodule of %s' % (other, self)) return SubQuotientModule(self.gens, self.container.quotient_module(other), **opts) def __add__(self, oth): return self.container.quotient_module(self).convert(oth) __radd__ = __add__ def multiply_ideal(self, I): """ Multiply ``self`` by the ideal ``I``. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> I = QQ.old_poly_ring(x).ideal(x**2) >>> M = QQ.old_poly_ring(x).free_module(2).submodule([1, 1]) >>> I*M <[x**2, x**2]> """ return self.submodule(*[x*g for [x] in I._module.gens for g in self.gens]) def inclusion_hom(self): """ Return a homomorphism representing the inclusion map of ``self``. That is, the natural map from ``self`` to ``self.container``. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> QQ.old_poly_ring(x).free_module(2).submodule([x, x]).inclusion_hom() Matrix([ [1, 0], : <[x, x]> -> QQ[x]**2 [0, 1]]) """ return self.container.identity_hom().restrict_domain(self) def identity_hom(self): """ Return the identity homomorphism on ``self``. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> QQ.old_poly_ring(x).free_module(2).submodule([x, x]).identity_hom() Matrix([ [1, 0], : <[x, x]> -> <[x, x]> [0, 1]]) """ return self.container.identity_hom().restrict_domain( self).restrict_codomain(self) class SubQuotientModule(SubModule): """ Submodule of a quotient module. Equivalently, quotient module of a submodule. Do not instantiate this, instead use the submodule or quotient_module constructing methods: >>> from sympy.abc import x >>> from sympy import QQ >>> F = QQ.old_poly_ring(x).free_module(2) >>> S = F.submodule([1, 0], [1, x]) >>> Q = F/[(1, 0)] >>> S/[(1, 0)] == Q.submodule([5, x]) True Attributes: - base - base module we are quotient of - killed_module - submodule used to form the quotient """ def __init__(self, gens, container, **opts): SubModule.__init__(self, gens, container) self.killed_module = self.container.killed_module # XXX it is important for some code below that the generators of base # are in this particular order! self.base = self.container.base.submodule( *[x.data for x in self.gens], **opts).union(self.killed_module) def _contains(self, elem): return self.base.contains(elem.data) def _syzygies(self): # let N = self.killed_module be generated by e_1, ..., e_r # let F = self.base be generated by f_1, ..., f_s and e_1, ..., e_r # Then self = F/N. # Let phi: R**s --> self be the evident surjection. # Similarly psi: R**(s + r) --> F. # We need to find generators for ker(phi). Let chi: R**s --> F be the # evident lift of phi. For X in R**s, phi(X) = 0 iff chi(X) is # contained in N, iff there exists Y in R**r such that # psi(X, Y) = 0. # Hence if alpha: R**(s + r) --> R**s is the projection map, then # ker(phi) = alpha ker(psi). return [X[:len(self.gens)] for X in self.base._syzygies()] def _in_terms_of_generators(self, e): return self.base._in_terms_of_generators(e.data)[:len(self.gens)] def is_full_module(self): """ Return True if ``self`` is the entire free module. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> F = QQ.old_poly_ring(x).free_module(2) >>> F.submodule([x, 1]).is_full_module() False >>> F.submodule([1, 1], [1, 2]).is_full_module() True """ return self.base.is_full_module() def quotient_hom(self): """ Return the quotient homomorphism to self. That is, return the natural map from ``self.base`` to ``self``. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> M = (QQ.old_poly_ring(x).free_module(2) / [(1, x)]).submodule([1, 0]) >>> M.quotient_hom() Matrix([ [1, 0], : <[1, 0], [1, x]> -> <[1, 0] + <[1, x]>, [1, x] + <[1, x]>> [0, 1]]) """ return self.base.identity_hom().quotient_codomain(self.killed_module) _subs0 = lambda x: x[0] _subs1 = lambda x: x[1:] class ModuleOrder(ProductOrder): """A product monomial order with a zeroth term as module index.""" def __init__(self, o1, o2, TOP): if TOP: ProductOrder.__init__(self, (o2, _subs1), (o1, _subs0)) else: ProductOrder.__init__(self, (o1, _subs0), (o2, _subs1)) class SubModulePolyRing(SubModule): """ Submodule of a free module over a generalized polynomial ring. Do not instantiate this, use the constructor method of FreeModule instead: >>> from sympy.abc import x, y >>> from sympy import QQ >>> F = QQ.old_poly_ring(x, y).free_module(2) >>> F.submodule([x, y], [1, 0]) <[x, y], [1, 0]> Attributes: - order - monomial order used """ #self._gb - cached groebner basis #self._gbe - cached groebner basis relations def __init__(self, gens, container, order="lex", TOP=True): SubModule.__init__(self, gens, container) if not isinstance(container, FreeModulePolyRing): raise NotImplementedError('This implementation is for submodules of ' + 'FreeModulePolyRing, got %s' % container) self.order = ModuleOrder(monomial_key(order), self.ring.order, TOP) self._gb = None self._gbe = None def __eq__(self, other): if isinstance(other, SubModulePolyRing) and self.order != other.order: return False return SubModule.__eq__(self, other) def _groebner(self, extended=False): """Returns a standard basis in sdm form.""" from sympy.polys.distributedmodules import sdm_groebner, sdm_nf_mora if self._gbe is None and extended: gb, gbe = sdm_groebner( [self.ring._vector_to_sdm(x, self.order) for x in self.gens], sdm_nf_mora, self.order, self.ring.dom, extended=True) self._gb, self._gbe = tuple(gb), tuple(gbe) if self._gb is None: self._gb = tuple(sdm_groebner( [self.ring._vector_to_sdm(x, self.order) for x in self.gens], sdm_nf_mora, self.order, self.ring.dom)) if extended: return self._gb, self._gbe else: return self._gb def _groebner_vec(self, extended=False): """Returns a standard basis in element form.""" if not extended: return [self.convert(self.ring._sdm_to_vector(x, self.rank)) for x in self._groebner()] gb, gbe = self._groebner(extended=True) return ([self.convert(self.ring._sdm_to_vector(x, self.rank)) for x in gb], [self.ring._sdm_to_vector(x, len(self.gens)) for x in gbe]) def _contains(self, x): from sympy.polys.distributedmodules import sdm_zero, sdm_nf_mora return sdm_nf_mora(self.ring._vector_to_sdm(x, self.order), self._groebner(), self.order, self.ring.dom) == \ sdm_zero() def _syzygies(self): """Compute syzygies. See [SCA, algorithm 2.5.4].""" # NOTE if self.gens is a standard basis, this can be done more # efficiently using Schreyer's theorem from sympy.matrices import eye # First bullet point k = len(self.gens) r = self.rank im = eye(k) Rkr = self.ring.free_module(r + k) newgens = [] for j, f in enumerate(self.gens): m = [0]*(r + k) for i, v in enumerate(f): m[i] = f[i] for i in range(k): m[r + i] = im[j, i] newgens.append(Rkr.convert(m)) # Note: we need *descending* order on module index, and TOP=False to # get an elimination order F = Rkr.submodule(*newgens, order='ilex', TOP=False) # Second bullet point: standard basis of F G = F._groebner_vec() # Third bullet point: G0 = G intersect the new k components G0 = [x[r:] for x in G if all(y == self.ring.convert(0) for y in x[:r])] # Fourth and fifth bullet points: we are done return G0 def _in_terms_of_generators(self, e): """Expression in terms of generators. See [SCA, 2.8.1].""" # NOTE: if gens is a standard basis, this can be done more efficiently M = self.ring.free_module(self.rank).submodule(*((e,) + self.gens)) S = M.syzygy_module( order="ilex", TOP=False) # We want decreasing order! G = S._groebner_vec() # This list cannot not be empty since e is an element e = [x for x in G if self.ring.is_unit(x[0])][0] return [-x/e[0] for x in e[1:]] def reduce_element(self, x, NF=None): """ Reduce the element ``x`` of our container modulo ``self``. This applies the normal form ``NF`` to ``x``. If ``NF`` is passed as none, the default Mora normal form is used (which is not unique!). """ from sympy.polys.distributedmodules import sdm_nf_mora if NF is None: NF = sdm_nf_mora return self.container.convert(self.ring._sdm_to_vector(NF( self.ring._vector_to_sdm(x, self.order), self._groebner(), self.order, self.ring.dom), self.rank)) def _intersect(self, other, relations=False): # See: [SCA, section 2.8.2] fi = self.gens hi = other.gens r = self.rank ci = [[0]*(2*r) for _ in range(r)] for k in range(r): ci[k][k] = 1 ci[k][r + k] = 1 di = [list(f) + [0]*r for f in fi] ei = [[0]*r + list(h) for h in hi] syz = self.ring.free_module(2*r).submodule(*(ci + di + ei))._syzygies() nonzero = [x for x in syz if any(y != self.ring.zero for y in x[:r])] res = self.container.submodule(*([-y for y in x[:r]] for x in nonzero)) reln1 = [x[r:r + len(fi)] for x in nonzero] reln2 = [x[r + len(fi):] for x in nonzero] if relations: return res, reln1, reln2 return res def _module_quotient(self, other, relations=False): # See: [SCA, section 2.8.4] if relations and len(other.gens) != 1: raise NotImplementedError if len(other.gens) == 0: return self.ring.ideal(1) elif len(other.gens) == 1: # We do some trickery. Let f be the (vector!) generating ``other`` # and f1, .., fn be the (vectors) generating self. # Consider the submodule of R^{r+1} generated by (f, 1) and # {(fi, 0) | i}. Then the intersection with the last module # component yields the quotient. g1 = list(other.gens[0]) + [1] gi = [list(x) + [0] for x in self.gens] # NOTE: We *need* to use an elimination order M = self.ring.free_module(self.rank + 1).submodule(*([g1] + gi), order='ilex', TOP=False) if not relations: return self.ring.ideal(*[x[-1] for x in M._groebner_vec() if all(y == self.ring.zero for y in x[:-1])]) else: G, R = M._groebner_vec(extended=True) indices = [i for i, x in enumerate(G) if all(y == self.ring.zero for y in x[:-1])] return (self.ring.ideal(*[G[i][-1] for i in indices]), [[-x for x in R[i][1:]] for i in indices]) # For more generators, we use I : <h1, .., hn> = intersection of # {I : <hi> | i} # TODO this can be done more efficiently return reduce(lambda x, y: x.intersect(y), (self._module_quotient(self.container.submodule(x)) for x in other.gens)) class SubModuleQuotientRing(SubModule): """ Class for submodules of free modules over quotient rings. Do not instantiate this. Instead use the submodule methods. >>> from sympy.abc import x, y >>> from sympy import QQ >>> M = (QQ.old_poly_ring(x, y)/[x**2 - y**2]).free_module(2).submodule([x, x + y]) >>> M <[x + <x**2 - y**2>, x + y + <x**2 - y**2>]> >>> M.contains([y**2, x**2 + x*y]) True >>> M.contains([x, y]) False Attributes: - quot - the subquotient of `R^n/IR^n` generated by lifts of our generators """ def __init__(self, gens, container): SubModule.__init__(self, gens, container) self.quot = self.container.quot.submodule( *[self.container.lift(x) for x in self.gens]) def _contains(self, elem): return self.quot._contains(self.container.lift(elem)) def _syzygies(self): return [tuple(self.ring.convert(y, self.quot.ring) for y in x) for x in self.quot._syzygies()] def _in_terms_of_generators(self, elem): return [self.ring.convert(x, self.quot.ring) for x in self.quot._in_terms_of_generators(self.container.lift(elem))] ########################################################################## ## Quotient Modules ###################################################### ########################################################################## class QuotientModuleElement(ModuleElement): """Element of a quotient module.""" def eq(self, d1, d2): """Equality comparison.""" return self.module.killed_module.contains(d1 - d2) def __repr__(self): return repr(self.data) + " + " + repr(self.module.killed_module) class QuotientModule(Module): """ Class for quotient modules. Do not instantiate this directly. For subquotients, see the SubQuotientModule class. Attributes: - base - the base module we are a quotient of - killed_module - the submodule used to form the quotient - rank of the base """ dtype = QuotientModuleElement def __init__(self, ring, base, submodule): Module.__init__(self, ring) if not base.is_submodule(submodule): raise ValueError('%s is not a submodule of %s' % (submodule, base)) self.base = base self.killed_module = submodule self.rank = base.rank def __repr__(self): return repr(self.base) + "/" + repr(self.killed_module) def is_zero(self): """ Return True if ``self`` is a zero module. This happens if and only if the base module is the same as the submodule being killed. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> F = QQ.old_poly_ring(x).free_module(2) >>> (F/[(1, 0)]).is_zero() False >>> (F/[(1, 0), (0, 1)]).is_zero() True """ return self.base == self.killed_module def is_submodule(self, other): """ Return True if ``other`` is a submodule of ``self``. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> Q = QQ.old_poly_ring(x).free_module(2) / [(x, x)] >>> S = Q.submodule([1, 0]) >>> Q.is_submodule(S) True >>> S.is_submodule(Q) False """ if isinstance(other, QuotientModule): return self.killed_module == other.killed_module and \ self.base.is_submodule(other.base) if isinstance(other, SubQuotientModule): return other.container == self return False def submodule(self, *gens, **opts): """ Generate a submodule. This is the same as taking a quotient of a submodule of the base module. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> Q = QQ.old_poly_ring(x).free_module(2) / [(x, x)] >>> Q.submodule([x, 0]) <[x, 0] + <[x, x]>> """ return SubQuotientModule(gens, self, **opts) def convert(self, elem, M=None): """ Convert ``elem`` into the internal representation. This method is called implicitly whenever computations involve elements not in the internal representation. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> F = QQ.old_poly_ring(x).free_module(2) / [(1, 2), (1, x)] >>> F.convert([1, 0]) [1, 0] + <[1, 2], [1, x]> """ if isinstance(elem, QuotientModuleElement): if elem.module is self: return elem if self.killed_module.is_submodule(elem.module.killed_module): return QuotientModuleElement(self, self.base.convert(elem.data)) raise CoercionFailed return QuotientModuleElement(self, self.base.convert(elem)) def identity_hom(self): """ Return the identity homomorphism on ``self``. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> M = QQ.old_poly_ring(x).free_module(2) / [(1, 2), (1, x)] >>> M.identity_hom() Matrix([ [1, 0], : QQ[x]**2/<[1, 2], [1, x]> -> QQ[x]**2/<[1, 2], [1, x]> [0, 1]]) """ return self.base.identity_hom().quotient_codomain( self.killed_module).quotient_domain(self.killed_module) def quotient_hom(self): """ Return the quotient homomorphism to ``self``. That is, return a homomorphism representing the natural map from ``self.base`` to ``self``. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> M = QQ.old_poly_ring(x).free_module(2) / [(1, 2), (1, x)] >>> M.quotient_hom() Matrix([ [1, 0], : QQ[x]**2 -> QQ[x]**2/<[1, 2], [1, x]> [0, 1]]) """ return self.base.identity_hom().quotient_codomain( self.killed_module)
ca21d2ad1069387db78c9f344249b743919f8b6b491d39e908b8d3760c999b3d
""" Computations with homomorphisms of modules and rings. This module implements classes for representing homomorphisms of rings and their modules. Instead of instantiating the classes directly, you should use the function ``homomorphism(from, to, matrix)`` to create homomorphism objects. """ from sympy.polys.agca.modules import (Module, FreeModule, QuotientModule, SubModule, SubQuotientModule) from sympy.polys.polyerrors import CoercionFailed # The main computational task for module homomorphisms is kernels. # For this reason, the concrete classes are organised by domain module type. class ModuleHomomorphism: """ Abstract base class for module homomoprhisms. Do not instantiate. Instead, use the ``homomorphism`` function: >>> from sympy import QQ >>> from sympy.abc import x >>> from sympy.polys.agca import homomorphism >>> F = QQ.old_poly_ring(x).free_module(2) >>> homomorphism(F, F, [[1, 0], [0, 1]]) Matrix([ [1, 0], : QQ[x]**2 -> QQ[x]**2 [0, 1]]) Attributes: - ring - the ring over which we are considering modules - domain - the domain module - codomain - the codomain module - _ker - cached kernel - _img - cached image Non-implemented methods: - _kernel - _image - _restrict_domain - _restrict_codomain - _quotient_domain - _quotient_codomain - _apply - _mul_scalar - _compose - _add """ def __init__(self, domain, codomain): if not isinstance(domain, Module): raise TypeError('Source must be a module, got %s' % domain) if not isinstance(codomain, Module): raise TypeError('Target must be a module, got %s' % codomain) if domain.ring != codomain.ring: raise ValueError('Source and codomain must be over same ring, ' 'got %s != %s' % (domain, codomain)) self.domain = domain self.codomain = codomain self.ring = domain.ring self._ker = None self._img = None def kernel(self): r""" Compute the kernel of ``self``. That is, if ``self`` is the homomorphism `\phi: M \to N`, then compute `ker(\phi) = \{x \in M | \phi(x) = 0\}`. This is a submodule of `M`. Examples ======== >>> from sympy import QQ >>> from sympy.abc import x >>> from sympy.polys.agca import homomorphism >>> F = QQ.old_poly_ring(x).free_module(2) >>> homomorphism(F, F, [[1, 0], [x, 0]]).kernel() <[x, -1]> """ if self._ker is None: self._ker = self._kernel() return self._ker def image(self): r""" Compute the image of ``self``. That is, if ``self`` is the homomorphism `\phi: M \to N`, then compute `im(\phi) = \{\phi(x) | x \in M \}`. This is a submodule of `N`. Examples ======== >>> from sympy import QQ >>> from sympy.abc import x >>> from sympy.polys.agca import homomorphism >>> F = QQ.old_poly_ring(x).free_module(2) >>> homomorphism(F, F, [[1, 0], [x, 0]]).image() == F.submodule([1, 0]) True """ if self._img is None: self._img = self._image() return self._img def _kernel(self): """Compute the kernel of ``self``.""" raise NotImplementedError def _image(self): """Compute the image of ``self``.""" raise NotImplementedError def _restrict_domain(self, sm): """Implementation of domain restriction.""" raise NotImplementedError def _restrict_codomain(self, sm): """Implementation of codomain restriction.""" raise NotImplementedError def _quotient_domain(self, sm): """Implementation of domain quotient.""" raise NotImplementedError def _quotient_codomain(self, sm): """Implementation of codomain quotient.""" raise NotImplementedError def restrict_domain(self, sm): """ Return ``self``, with the domain restricted to ``sm``. Here ``sm`` has to be a submodule of ``self.domain``. Examples ======== >>> from sympy import QQ >>> from sympy.abc import x >>> from sympy.polys.agca import homomorphism >>> F = QQ.old_poly_ring(x).free_module(2) >>> h = homomorphism(F, F, [[1, 0], [x, 0]]) >>> h Matrix([ [1, x], : QQ[x]**2 -> QQ[x]**2 [0, 0]]) >>> h.restrict_domain(F.submodule([1, 0])) Matrix([ [1, x], : <[1, 0]> -> QQ[x]**2 [0, 0]]) This is the same as just composing on the right with the submodule inclusion: >>> h * F.submodule([1, 0]).inclusion_hom() Matrix([ [1, x], : <[1, 0]> -> QQ[x]**2 [0, 0]]) """ if not self.domain.is_submodule(sm): raise ValueError('sm must be a submodule of %s, got %s' % (self.domain, sm)) if sm == self.domain: return self return self._restrict_domain(sm) def restrict_codomain(self, sm): """ Return ``self``, with codomain restricted to to ``sm``. Here ``sm`` has to be a submodule of ``self.codomain`` containing the image. Examples ======== >>> from sympy import QQ >>> from sympy.abc import x >>> from sympy.polys.agca import homomorphism >>> F = QQ.old_poly_ring(x).free_module(2) >>> h = homomorphism(F, F, [[1, 0], [x, 0]]) >>> h Matrix([ [1, x], : QQ[x]**2 -> QQ[x]**2 [0, 0]]) >>> h.restrict_codomain(F.submodule([1, 0])) Matrix([ [1, x], : QQ[x]**2 -> <[1, 0]> [0, 0]]) """ if not sm.is_submodule(self.image()): raise ValueError('the image %s must contain sm, got %s' % (self.image(), sm)) if sm == self.codomain: return self return self._restrict_codomain(sm) def quotient_domain(self, sm): """ Return ``self`` with domain replaced by ``domain/sm``. Here ``sm`` must be a submodule of ``self.kernel()``. Examples ======== >>> from sympy import QQ >>> from sympy.abc import x >>> from sympy.polys.agca import homomorphism >>> F = QQ.old_poly_ring(x).free_module(2) >>> h = homomorphism(F, F, [[1, 0], [x, 0]]) >>> h Matrix([ [1, x], : QQ[x]**2 -> QQ[x]**2 [0, 0]]) >>> h.quotient_domain(F.submodule([-x, 1])) Matrix([ [1, x], : QQ[x]**2/<[-x, 1]> -> QQ[x]**2 [0, 0]]) """ if not self.kernel().is_submodule(sm): raise ValueError('kernel %s must contain sm, got %s' % (self.kernel(), sm)) if sm.is_zero(): return self return self._quotient_domain(sm) def quotient_codomain(self, sm): """ Return ``self`` with codomain replaced by ``codomain/sm``. Here ``sm`` must be a submodule of ``self.codomain``. Examples ======== >>> from sympy import QQ >>> from sympy.abc import x >>> from sympy.polys.agca import homomorphism >>> F = QQ.old_poly_ring(x).free_module(2) >>> h = homomorphism(F, F, [[1, 0], [x, 0]]) >>> h Matrix([ [1, x], : QQ[x]**2 -> QQ[x]**2 [0, 0]]) >>> h.quotient_codomain(F.submodule([1, 1])) Matrix([ [1, x], : QQ[x]**2 -> QQ[x]**2/<[1, 1]> [0, 0]]) This is the same as composing with the quotient map on the left: >>> (F/[(1, 1)]).quotient_hom() * h Matrix([ [1, x], : QQ[x]**2 -> QQ[x]**2/<[1, 1]> [0, 0]]) """ if not self.codomain.is_submodule(sm): raise ValueError('sm must be a submodule of codomain %s, got %s' % (self.codomain, sm)) if sm.is_zero(): return self return self._quotient_codomain(sm) def _apply(self, elem): """Apply ``self`` to ``elem``.""" raise NotImplementedError def __call__(self, elem): return self.codomain.convert(self._apply(self.domain.convert(elem))) def _compose(self, oth): """ Compose ``self`` with ``oth``, that is, return the homomorphism obtained by first applying then ``self``, then ``oth``. (This method is private since in this syntax, it is non-obvious which homomorphism is executed first.) """ raise NotImplementedError def _mul_scalar(self, c): """Scalar multiplication. ``c`` is guaranteed in self.ring.""" raise NotImplementedError def _add(self, oth): """ Homomorphism addition. ``oth`` is guaranteed to be a homomorphism with same domain/codomain. """ raise NotImplementedError def _check_hom(self, oth): """Helper to check that oth is a homomorphism with same domain/codomain.""" if not isinstance(oth, ModuleHomomorphism): return False return oth.domain == self.domain and oth.codomain == self.codomain def __mul__(self, oth): if isinstance(oth, ModuleHomomorphism) and self.domain == oth.codomain: return oth._compose(self) try: return self._mul_scalar(self.ring.convert(oth)) except CoercionFailed: return NotImplemented # NOTE: _compose will never be called from rmul __rmul__ = __mul__ def __truediv__(self, oth): try: return self._mul_scalar(1/self.ring.convert(oth)) except CoercionFailed: return NotImplemented def __add__(self, oth): if self._check_hom(oth): return self._add(oth) return NotImplemented def __sub__(self, oth): if self._check_hom(oth): return self._add(oth._mul_scalar(self.ring.convert(-1))) return NotImplemented def is_injective(self): """ Return True if ``self`` is injective. That is, check if the elements of the domain are mapped to the same codomain element. Examples ======== >>> from sympy import QQ >>> from sympy.abc import x >>> from sympy.polys.agca import homomorphism >>> F = QQ.old_poly_ring(x).free_module(2) >>> h = homomorphism(F, F, [[1, 0], [x, 0]]) >>> h.is_injective() False >>> h.quotient_domain(h.kernel()).is_injective() True """ return self.kernel().is_zero() def is_surjective(self): """ Return True if ``self`` is surjective. That is, check if every element of the codomain has at least one preimage. Examples ======== >>> from sympy import QQ >>> from sympy.abc import x >>> from sympy.polys.agca import homomorphism >>> F = QQ.old_poly_ring(x).free_module(2) >>> h = homomorphism(F, F, [[1, 0], [x, 0]]) >>> h.is_surjective() False >>> h.restrict_codomain(h.image()).is_surjective() True """ return self.image() == self.codomain def is_isomorphism(self): """ Return True if ``self`` is an isomorphism. That is, check if every element of the codomain has precisely one preimage. Equivalently, ``self`` is both injective and surjective. Examples ======== >>> from sympy import QQ >>> from sympy.abc import x >>> from sympy.polys.agca import homomorphism >>> F = QQ.old_poly_ring(x).free_module(2) >>> h = homomorphism(F, F, [[1, 0], [x, 0]]) >>> h = h.restrict_codomain(h.image()) >>> h.is_isomorphism() False >>> h.quotient_domain(h.kernel()).is_isomorphism() True """ return self.is_injective() and self.is_surjective() def is_zero(self): """ Return True if ``self`` is a zero morphism. That is, check if every element of the domain is mapped to zero under self. Examples ======== >>> from sympy import QQ >>> from sympy.abc import x >>> from sympy.polys.agca import homomorphism >>> F = QQ.old_poly_ring(x).free_module(2) >>> h = homomorphism(F, F, [[1, 0], [x, 0]]) >>> h.is_zero() False >>> h.restrict_domain(F.submodule()).is_zero() True >>> h.quotient_codomain(h.image()).is_zero() True """ return self.image().is_zero() def __eq__(self, oth): try: return (self - oth).is_zero() except TypeError: return False def __ne__(self, oth): return not (self == oth) class MatrixHomomorphism(ModuleHomomorphism): r""" Helper class for all homomoprhisms which are expressed via a matrix. That is, for such homomorphisms ``domain`` is contained in a module generated by finitely many elements `e_1, \ldots, e_n`, so that the homomorphism is determined uniquely by its action on the `e_i`. It can thus be represented as a vector of elements of the codomain module, or potentially a supermodule of the codomain module (and hence conventionally as a matrix, if there is a similar interpretation for elements of the codomain module). Note that this class does *not* assume that the `e_i` freely generate a submodule, nor that ``domain`` is even all of this submodule. It exists only to unify the interface. Do not instantiate. Attributes: - matrix - the list of images determining the homomorphism. NOTE: the elements of matrix belong to either self.codomain or self.codomain.container Still non-implemented methods: - kernel - _apply """ def __init__(self, domain, codomain, matrix): ModuleHomomorphism.__init__(self, domain, codomain) if len(matrix) != domain.rank: raise ValueError('Need to provide %s elements, got %s' % (domain.rank, len(matrix))) converter = self.codomain.convert if isinstance(self.codomain, (SubModule, SubQuotientModule)): converter = self.codomain.container.convert self.matrix = tuple(converter(x) for x in matrix) def _sympy_matrix(self): """Helper function which returns a sympy matrix ``self.matrix``.""" from sympy.matrices import Matrix c = lambda x: x if isinstance(self.codomain, (QuotientModule, SubQuotientModule)): c = lambda x: x.data return Matrix([[self.ring.to_sympy(y) for y in c(x)] for x in self.matrix]).T def __repr__(self): lines = repr(self._sympy_matrix()).split('\n') t = " : %s -> %s" % (self.domain, self.codomain) s = ' '*len(t) n = len(lines) for i in range(n // 2): lines[i] += s lines[n // 2] += t for i in range(n//2 + 1, n): lines[i] += s return '\n'.join(lines) def _restrict_domain(self, sm): """Implementation of domain restriction.""" return SubModuleHomomorphism(sm, self.codomain, self.matrix) def _restrict_codomain(self, sm): """Implementation of codomain restriction.""" return self.__class__(self.domain, sm, self.matrix) def _quotient_domain(self, sm): """Implementation of domain quotient.""" return self.__class__(self.domain/sm, self.codomain, self.matrix) def _quotient_codomain(self, sm): """Implementation of codomain quotient.""" Q = self.codomain/sm converter = Q.convert if isinstance(self.codomain, SubModule): converter = Q.container.convert return self.__class__(self.domain, self.codomain/sm, [converter(x) for x in self.matrix]) def _add(self, oth): return self.__class__(self.domain, self.codomain, [x + y for x, y in zip(self.matrix, oth.matrix)]) def _mul_scalar(self, c): return self.__class__(self.domain, self.codomain, [c*x for x in self.matrix]) def _compose(self, oth): return self.__class__(self.domain, oth.codomain, [oth(x) for x in self.matrix]) class FreeModuleHomomorphism(MatrixHomomorphism): """ Concrete class for homomorphisms with domain a free module or a quotient thereof. Do not instantiate; the constructor does not check that your data is well defined. Use the ``homomorphism`` function instead: >>> from sympy import QQ >>> from sympy.abc import x >>> from sympy.polys.agca import homomorphism >>> F = QQ.old_poly_ring(x).free_module(2) >>> homomorphism(F, F, [[1, 0], [0, 1]]) Matrix([ [1, 0], : QQ[x]**2 -> QQ[x]**2 [0, 1]]) """ def _apply(self, elem): if isinstance(self.domain, QuotientModule): elem = elem.data return sum(x * e for x, e in zip(elem, self.matrix)) def _image(self): return self.codomain.submodule(*self.matrix) def _kernel(self): # The domain is either a free module or a quotient thereof. # It does not matter if it is a quotient, because that won't increase # the kernel. # Our generators {e_i} are sent to the matrix entries {b_i}. # The kernel is essentially the syzygy module of these {b_i}. syz = self.image().syzygy_module() return self.domain.submodule(*syz.gens) class SubModuleHomomorphism(MatrixHomomorphism): """ Concrete class for homomorphism with domain a submodule of a free module or a quotient thereof. Do not instantiate; the constructor does not check that your data is well defined. Use the ``homomorphism`` function instead: >>> from sympy import QQ >>> from sympy.abc import x >>> from sympy.polys.agca import homomorphism >>> M = QQ.old_poly_ring(x).free_module(2)*x >>> homomorphism(M, M, [[1, 0], [0, 1]]) Matrix([ [1, 0], : <[x, 0], [0, x]> -> <[x, 0], [0, x]> [0, 1]]) """ def _apply(self, elem): if isinstance(self.domain, SubQuotientModule): elem = elem.data return sum(x * e for x, e in zip(elem, self.matrix)) def _image(self): return self.codomain.submodule(*[self(x) for x in self.domain.gens]) def _kernel(self): syz = self.image().syzygy_module() return self.domain.submodule( *[sum(xi*gi for xi, gi in zip(s, self.domain.gens)) for s in syz.gens]) def homomorphism(domain, codomain, matrix): r""" Create a homomorphism object. This function tries to build a homomorphism from ``domain`` to ``codomain`` via the matrix ``matrix``. Examples ======== >>> from sympy import QQ >>> from sympy.abc import x >>> from sympy.polys.agca import homomorphism >>> R = QQ.old_poly_ring(x) >>> T = R.free_module(2) If ``domain`` is a free module generated by `e_1, \ldots, e_n`, then ``matrix`` should be an n-element iterable `(b_1, \ldots, b_n)` where the `b_i` are elements of ``codomain``. The constructed homomorphism is the unique homomorphism sending `e_i` to `b_i`. >>> F = R.free_module(2) >>> h = homomorphism(F, T, [[1, x], [x**2, 0]]) >>> h Matrix([ [1, x**2], : QQ[x]**2 -> QQ[x]**2 [x, 0]]) >>> h([1, 0]) [1, x] >>> h([0, 1]) [x**2, 0] >>> h([1, 1]) [x**2 + 1, x] If ``domain`` is a submodule of a free module, them ``matrix`` determines a homomoprhism from the containing free module to ``codomain``, and the homomorphism returned is obtained by restriction to ``domain``. >>> S = F.submodule([1, 0], [0, x]) >>> homomorphism(S, T, [[1, x], [x**2, 0]]) Matrix([ [1, x**2], : <[1, 0], [0, x]> -> QQ[x]**2 [x, 0]]) If ``domain`` is a (sub)quotient `N/K`, then ``matrix`` determines a homomorphism from `N` to ``codomain``. If the kernel contains `K`, this homomorphism descends to ``domain`` and is returned; otherwise an exception is raised. >>> homomorphism(S/[(1, 0)], T, [0, [x**2, 0]]) Matrix([ [0, x**2], : <[1, 0] + <[1, 0]>, [0, x] + <[1, 0]>, [1, 0] + <[1, 0]>> -> QQ[x]**2 [0, 0]]) >>> homomorphism(S/[(0, x)], T, [0, [x**2, 0]]) Traceback (most recent call last): ... ValueError: kernel <[1, 0], [0, 0]> must contain sm, got <[0,x]> """ def freepres(module): """ Return a tuple ``(F, S, Q, c)`` where ``F`` is a free module, ``S`` is a submodule of ``F``, and ``Q`` a submodule of ``S``, such that ``module = S/Q``, and ``c`` is a conversion function. """ if isinstance(module, FreeModule): return module, module, module.submodule(), lambda x: module.convert(x) if isinstance(module, QuotientModule): return (module.base, module.base, module.killed_module, lambda x: module.convert(x).data) if isinstance(module, SubQuotientModule): return (module.base.container, module.base, module.killed_module, lambda x: module.container.convert(x).data) # an ordinary submodule return (module.container, module, module.submodule(), lambda x: module.container.convert(x)) SF, SS, SQ, _ = freepres(domain) TF, TS, TQ, c = freepres(codomain) # NOTE this is probably a bit inefficient (redundant checks) return FreeModuleHomomorphism(SF, TF, [c(x) for x in matrix] ).restrict_domain(SS).restrict_codomain(TS ).quotient_codomain(TQ).quotient_domain(SQ)
b646a3ff6b6f4184ef14633d69864823604b4d5a198a79515cc0209da3b2b66d
"""Finite extensions of ring domains.""" from sympy.polys.polyerrors import CoercionFailed, NotInvertible from sympy.polys.polytools import Poly from sympy.printing.defaults import DefaultPrinting class ExtensionElement(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 __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 inverse(f): """Multiplicative inverse. Raises ====== NotInvertible If the element is a zero divisor. """ if not f.ext.domain.is_Field: raise NotImplementedError("base field expected") return ExtElem(f.rep.invert(f.ext.mod), f.ext) def _invrep(f, g): rep = f._get_rep(g) if rep is not None: return rep.invert(f.ext.mod) else: return None def __truediv__(f, g): if not f.ext.domain.is_Field: return NotImplemented try: rep = f._invrep(g) except NotInvertible: raise ZeroDivisionError if rep is not None: return f*ExtElem(rep, f.ext) else: return NotImplemented __floordiv__ = __truediv__ def __rtruediv__(f, g): try: return f.ext.convert(g)/f except CoercionFailed: return NotImplemented __rfloordiv__ = __rtruediv__ 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__ ExtElem = ExtensionElement class MonogenicFiniteExtension: 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) Notes ===== ``FiniteExtension`` is not a subclass of :class:`~.Domain`. Consequently, a ``FiniteExtension`` can't currently be used as ``domain`` for the :class:`~.Poly` class. """ def __init__(self, mod): if not (isinstance(mod, Poly) and mod.is_univariate): raise TypeError("modulus must be a univariate Poly") mod, rem = mod.div(mod.LC()) if not rem.is_zero: raise ValueError("modulus could not be made monic") 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.generator = self.convert(gen) self.basis = tuple(self.convert(gen**i) for i in range(self.rank)) def convert(self, f): rep = self.ring.convert(f) return ExtElem(rep % self.mod, self) __call__ = convert def __str__(self): return "%s/(%s)" % (self.ring, self.modulus.as_expr()) __repr__ = __str__ FiniteExtension = MonogenicFiniteExtension
eadd9d965f8ac935b91d38447ffee60001701bab3eb47dd6baf0ea4787be2b57
"""Tests for homomorphisms.""" from sympy import QQ, S from sympy.abc import x, y from sympy.polys.agca import homomorphism from sympy.testing.pytest import raises def test_printing(): R = QQ.old_poly_ring(x) assert str(homomorphism(R.free_module(1), R.free_module(1), [0])) == \ 'Matrix([[0]]) : QQ[x]**1 -> QQ[x]**1' assert str(homomorphism(R.free_module(2), R.free_module(2), [0, 0])) == \ 'Matrix([ \n[0, 0], : QQ[x]**2 -> QQ[x]**2\n[0, 0]]) ' assert str(homomorphism(R.free_module(1), R.free_module(1) / [[x]], [0])) == \ 'Matrix([[0]]) : QQ[x]**1 -> QQ[x]**1/<[x]>' assert str(R.free_module(0).identity_hom()) == 'Matrix(0, 0, []) : QQ[x]**0 -> QQ[x]**0' def test_operations(): F = QQ.old_poly_ring(x).free_module(2) G = QQ.old_poly_ring(x).free_module(3) f = F.identity_hom() g = homomorphism(F, F, [0, [1, x]]) h = homomorphism(F, F, [[1, 0], 0]) i = homomorphism(F, G, [[1, 0, 0], [0, 1, 0]]) assert f == f assert f != g assert f != i assert (f != F.identity_hom()) is False assert 2*f == f*2 == homomorphism(F, F, [[2, 0], [0, 2]]) assert f/2 == homomorphism(F, F, [[S.Half, 0], [0, S.Half]]) assert f + g == homomorphism(F, F, [[1, 0], [1, x + 1]]) assert f - g == homomorphism(F, F, [[1, 0], [-1, 1 - x]]) assert f*g == g == g*f assert h*g == homomorphism(F, F, [0, [1, 0]]) assert g*h == homomorphism(F, F, [0, 0]) assert i*f == i assert f([1, 2]) == [1, 2] assert g([1, 2]) == [2, 2*x] assert i.restrict_domain(F.submodule([x, x]))([x, x]) == i([x, x]) h1 = h.quotient_domain(F.submodule([0, 1])) assert h1([1, 0]) == h([1, 0]) assert h1.restrict_domain(h1.domain.submodule([x, 0]))([x, 0]) == h([x, 0]) raises(TypeError, lambda: f/g) raises(TypeError, lambda: f + 1) raises(TypeError, lambda: f + i) raises(TypeError, lambda: f - 1) raises(TypeError, lambda: f*i) def test_creation(): F = QQ.old_poly_ring(x).free_module(3) G = QQ.old_poly_ring(x).free_module(2) SM = F.submodule([1, 1, 1]) Q = F / SM SQ = Q.submodule([1, 0, 0]) matrix = [[1, 0], [0, 1], [-1, -1]] h = homomorphism(F, G, matrix) h2 = homomorphism(Q, G, matrix) assert h.quotient_domain(SM) == h2 raises(ValueError, lambda: h.quotient_domain(F.submodule([1, 0, 0]))) assert h2.restrict_domain(SQ) == homomorphism(SQ, G, matrix) raises(ValueError, lambda: h.restrict_domain(G)) raises(ValueError, lambda: h.restrict_codomain(G.submodule([1, 0]))) raises(ValueError, lambda: h.quotient_codomain(F)) im = [[1, 0, 0], [0, 1, 0], [0, 0, 1]] for M in [F, SM, Q, SQ]: assert M.identity_hom() == homomorphism(M, M, im) assert SM.inclusion_hom() == homomorphism(SM, F, im) assert SQ.inclusion_hom() == homomorphism(SQ, Q, im) assert Q.quotient_hom() == homomorphism(F, Q, im) assert SQ.quotient_hom() == homomorphism(SQ.base, SQ, im) class conv: def convert(x, y=None): return x class dummy: container = conv() def submodule(*args): return None raises(TypeError, lambda: homomorphism(dummy(), G, matrix)) raises(TypeError, lambda: homomorphism(F, dummy(), matrix)) raises( ValueError, lambda: homomorphism(QQ.old_poly_ring(x, y).free_module(3), G, matrix)) raises(ValueError, lambda: homomorphism(F, G, [0, 0])) def test_properties(): R = QQ.old_poly_ring(x, y) F = R.free_module(2) h = homomorphism(F, F, [[x, 0], [y, 0]]) assert h.kernel() == F.submodule([-y, x]) assert h.image() == F.submodule([x, 0], [y, 0]) assert not h.is_injective() assert not h.is_surjective() assert h.restrict_codomain(h.image()).is_surjective() assert h.restrict_domain(F.submodule([1, 0])).is_injective() assert h.quotient_domain( h.kernel()).restrict_codomain(h.image()).is_isomorphism() R2 = QQ.old_poly_ring(x, y, order=(("lex", x), ("ilex", y))) / [x**2 + 1] F = R2.free_module(2) h = homomorphism(F, F, [[x, 0], [y, y + 1]]) assert h.is_isomorphism()
8cc214f9b1d94766218ebcde416ca33bddb147f05fbce3043d8059de59a2e117
from sympy.unify.core import Compound, Variable, CondVariable, allcombinations from sympy.unify import core a,b,c = 'abc' w,x,y,z = map(Variable, 'wxyz') C = Compound def is_associative(x): return isinstance(x, Compound) and (x.op in ('Add', 'Mul', 'CAdd', 'CMul')) def is_commutative(x): return isinstance(x, Compound) and (x.op in ('CAdd', 'CMul')) def unify(a, b, s={}): return core.unify(a, b, s=s, is_associative=is_associative, is_commutative=is_commutative) def test_basic(): assert list(unify(a, x, {})) == [{x: a}] assert list(unify(a, x, {x: 10})) == [] assert list(unify(1, x, {})) == [{x: 1}] assert list(unify(a, a, {})) == [{}] assert list(unify((w, x), (y, z), {})) == [{w: y, x: z}] assert list(unify(x, (a, b), {})) == [{x: (a, b)}] assert list(unify((a, b), (x, x), {})) == [] assert list(unify((y, z), (x, x), {}))!= [] assert list(unify((a, (b, c)), (a, (x, y)), {})) == [{x: b, y: c}] def test_ops(): assert list(unify(C('Add', (a,b,c)), C('Add', (a,x,y)), {})) == \ [{x:b, y:c}] assert list(unify(C('Add', (C('Mul', (1,2)), b,c)), C('Add', (x,y,c)), {})) == \ [{x: C('Mul', (1,2)), y:b}] def test_associative(): c1 = C('Add', (1,2,3)) c2 = C('Add', (x,y)) assert tuple(unify(c1, c2, {})) == ({x: 1, y: C('Add', (2, 3))}, {x: C('Add', (1, 2)), y: 3}) def test_commutative(): c1 = C('CAdd', (1,2,3)) c2 = C('CAdd', (x,y)) result = list(unify(c1, c2, {})) assert {x: 1, y: C('CAdd', (2, 3))} in result assert ({x: 2, y: C('CAdd', (1, 3))} in result or {x: 2, y: C('CAdd', (3, 1))} in result) def _test_combinations_assoc(): assert set(allcombinations((1,2,3), (a,b), True)) == \ {(((1, 2), (3,)), (a, b)), (((1,), (2, 3)), (a, b))} def _test_combinations_comm(): assert set(allcombinations((1,2,3), (a,b), None)) == \ {(((1,), (2, 3)), ('a', 'b')), (((2,), (3, 1)), ('a', 'b')), (((3,), (1, 2)), ('a', 'b')), (((1, 2), (3,)), ('a', 'b')), (((2, 3), (1,)), ('a', 'b')), (((3, 1), (2,)), ('a', 'b'))} def test_allcombinations(): assert set(allcombinations((1,2), (1,2), 'commutative')) ==\ {(((1,),(2,)), ((1,),(2,))), (((1,),(2,)), ((2,),(1,)))} def test_commutativity(): c1 = Compound('CAdd', (a, b)) c2 = Compound('CAdd', (x, y)) assert is_commutative(c1) and is_commutative(c2) assert len(list(unify(c1, c2, {}))) == 2 def test_CondVariable(): expr = C('CAdd', (1, 2)) x = Variable('x') y = CondVariable('y', lambda a: a % 2 == 0) z = CondVariable('z', lambda a: a > 3) pattern = C('CAdd', (x, y)) assert list(unify(expr, pattern, {})) == \ [{x: 1, y: 2}] z = CondVariable('z', lambda a: a > 3) pattern = C('CAdd', (z, y)) assert list(unify(expr, pattern, {})) == [] def test_defaultdict(): assert next(unify(Variable('x'), 'foo')) == {Variable('x'): 'foo'}
e70e85e895ba2bb960a5b0785fd4e3d15c3c01c35595f692baf6f029724a0fa7
""" Checks that SymPy does not contain indirect imports. An indirect import is importing a symbol from a module that itself imported the symbol from elsewhere. Such a constellation makes it harder to diagnose inter-module dependencies and import order problems, and is therefore strongly discouraged. (Indirect imports from end-user code is fine and in fact a best practice.) Implementation note: Forcing Python into actually unloading already-imported submodules is a tricky and partly undocumented process. To avoid these issues, the actual diagnostic code is in bin/diagnose_imports, which is run as a separate, pristine Python process. """ import subprocess import sys from os.path import abspath, dirname, join, normpath import inspect from sympy.testing.pytest import XFAIL @XFAIL def test_module_imports_are_direct(): my_filename = abspath(inspect.getfile(inspect.currentframe())) my_dirname = dirname(my_filename) diagnose_imports_filename = join(my_dirname, 'diagnose_imports.py') diagnose_imports_filename = normpath(diagnose_imports_filename) process = subprocess.Popen( [ sys.executable, normpath(diagnose_imports_filename), '--problems', '--by-importer' ], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=-1) output, _ = process.communicate() assert output == '', "There are import problems:\n" + output.decode()
89f0fa0c948ef54f1839c4836c6f8ec6a5080ef0a1987d0db6748d5ae7dfeb5d
#!/usr/bin/env python """ Import diagnostics. Run bin/diagnose_imports.py --help for details. """ from typing import Dict if __name__ == "__main__": import sys import inspect from sympy.core.compatibility import builtins import optparse from os.path import abspath, dirname, join, normpath this_file = abspath(__file__) sympy_dir = join(dirname(this_file), '..', '..', '..') sympy_dir = normpath(sympy_dir) sys.path.insert(0, sympy_dir) option_parser = optparse.OptionParser( usage= "Usage: %prog option [options]\n" "\n" "Import analysis for imports between SymPy modules.") option_group = optparse.OptionGroup( option_parser, 'Analysis options', 'Options that define what to do. Exactly one of these must be given.') option_group.add_option( '--problems', help= 'Print all import problems, that is: ' 'If an import pulls in a package instead of a module ' '(e.g. sympy.core instead of sympy.core.add); ' # see ##PACKAGE## 'if it imports a symbol that is already present; ' # see ##DUPLICATE## 'if it imports a symbol ' 'from somewhere other than the defining module.', # see ##ORIGIN## action='count') option_group.add_option( '--origins', help= 'For each imported symbol in each module, ' 'print the module that defined it. ' '(This is useful for import refactoring.)', action='count') option_parser.add_option_group(option_group) option_group = optparse.OptionGroup( option_parser, 'Sort options', 'These options define the sort order for output lines. ' 'At most one of these options is allowed. ' 'Unsorted output will reflect the order in which imports happened.') option_group.add_option( '--by-importer', help='Sort output lines by name of importing module.', action='count') option_group.add_option( '--by-origin', help='Sort output lines by name of imported module.', action='count') option_parser.add_option_group(option_group) (options, args) = option_parser.parse_args() if args: option_parser.error( 'Unexpected arguments %s (try %s --help)' % (args, sys.argv[0])) if options.problems > 1: option_parser.error('--problems must not be given more than once.') if options.origins > 1: option_parser.error('--origins must not be given more than once.') if options.by_importer > 1: option_parser.error('--by-importer must not be given more than once.') if options.by_origin > 1: option_parser.error('--by-origin must not be given more than once.') options.problems = options.problems == 1 options.origins = options.origins == 1 options.by_importer = options.by_importer == 1 options.by_origin = options.by_origin == 1 if not options.problems and not options.origins: option_parser.error( 'At least one of --problems and --origins is required') if options.problems and options.origins: option_parser.error( 'At most one of --problems and --origins is allowed') if options.by_importer and options.by_origin: option_parser.error( 'At most one of --by-importer and --by-origin is allowed') options.by_process = not options.by_importer and not options.by_origin builtin_import = builtins.__import__ class Definition: """Information about a symbol's definition.""" def __init__(self, name, value, definer): self.name = name self.value = value self.definer = definer def __hash__(self): return hash(self.name) def __eq__(self, other): return self.name == other.name and self.value == other.value def __ne__(self, other): return not (self == other) def __repr__(self): return 'Definition(%s, ..., %s)' % ( repr(self.name), repr(self.definer)) # Maps each function/variable to name of module to define it symbol_definers = {} # type: Dict[Definition, str] def in_module(a, b): """Is a the same module as or a submodule of b?""" return a == b or a != None and b != None and a.startswith(b + '.') def relevant(module): """Is module relevant for import checking? Only imports between relevant modules will be checked.""" return in_module(module, 'sympy') sorted_messages = [] def msg(msg, *args): global options, sorted_messages if options.by_process: print(msg % args) else: sorted_messages.append(msg % args) def tracking_import(module, globals=globals(), locals=[], fromlist=None, level=-1): """__import__ wrapper - does not change imports at all, but tracks them. Default order is implemented by doing output directly. All other orders are implemented by collecting output information into a sorted list that will be emitted after all imports are processed. Indirect imports can only occur after the requested symbol has been imported directly (because the indirect import would not have a module to pick the symbol up from). So this code detects indirect imports by checking whether the symbol in question was already imported. Keeps the semantics of __import__ unchanged.""" global options, symbol_definers caller_frame = inspect.getframeinfo(sys._getframe(1)) importer_filename = caller_frame.filename importer_module = globals['__name__'] if importer_filename == caller_frame.filename: importer_reference = '%s line %s' % ( importer_filename, str(caller_frame.lineno)) else: importer_reference = importer_filename result = builtin_import(module, globals, locals, fromlist, level) importee_module = result.__name__ # We're only interested if importer and importee are in SymPy if relevant(importer_module) and relevant(importee_module): for symbol in result.__dict__.iterkeys(): definition = Definition( symbol, result.__dict__[symbol], importer_module) if not definition in symbol_definers: symbol_definers[definition] = importee_module if hasattr(result, '__path__'): ##PACKAGE## # The existence of __path__ is documented in the tutorial on modules. # Python 3.3 documents this in http://docs.python.org/3.3/reference/import.html if options.by_origin: msg('Error: %s (a package) is imported by %s', module, importer_reference) else: msg('Error: %s contains package import %s', importer_reference, module) if fromlist != None: symbol_list = fromlist if '*' in symbol_list: if (importer_filename.endswith('__init__.py') or importer_filename.endswith('__init__.pyc') or importer_filename.endswith('__init__.pyo')): # We do not check starred imports inside __init__ # That's the normal "please copy over its imports to my namespace" symbol_list = [] else: symbol_list = result.__dict__.iterkeys() for symbol in symbol_list: if not symbol in result.__dict__: if options.by_origin: msg('Error: %s.%s is not defined (yet), but %s tries to import it', importee_module, symbol, importer_reference) else: msg('Error: %s tries to import %s.%s, which did not define it (yet)', importer_reference, importee_module, symbol) else: definition = Definition( symbol, result.__dict__[symbol], importer_module) symbol_definer = symbol_definers[definition] if symbol_definer == importee_module: ##DUPLICATE## if options.by_origin: msg('Error: %s.%s is imported again into %s', importee_module, symbol, importer_reference) else: msg('Error: %s imports %s.%s again', importer_reference, importee_module, symbol) else: ##ORIGIN## if options.by_origin: msg('Error: %s.%s is imported by %s, which should import %s.%s instead', importee_module, symbol, importer_reference, symbol_definer, symbol) else: msg('Error: %s imports %s.%s but should import %s.%s instead', importer_reference, importee_module, symbol, symbol_definer, symbol) return result builtins.__import__ = tracking_import __import__('sympy') sorted_messages.sort() for message in sorted_messages: print(message)
1f47fa7a5b911d6da374756d248e90d30d42048cdce8e486db1e434cf9b56531
# coding=utf-8 from os import walk, sep, pardir from os.path import split, join, abspath, exists, isfile from glob import glob import re import random import ast from sympy.testing.pytest import raises from sympy.testing.quality_unicode import _test_this_file_encoding # System path separator (usually slash or backslash) to be # used with excluded files, e.g. # exclude = set([ # "%(sep)smpmath%(sep)s" % sepd, # ]) sepd = {"sep": sep} # path and sympy_path SYMPY_PATH = abspath(join(split(__file__)[0], pardir, pardir)) # go to sympy/ assert exists(SYMPY_PATH) TOP_PATH = abspath(join(SYMPY_PATH, pardir)) BIN_PATH = join(TOP_PATH, "bin") EXAMPLES_PATH = join(TOP_PATH, "examples") # Error messages message_space = "File contains trailing whitespace: %s, line %s." message_implicit = "File contains an implicit import: %s, line %s." message_tabs = "File contains tabs instead of spaces: %s, line %s." message_carriage = "File contains carriage returns at end of line: %s, line %s" message_str_raise = "File contains string exception: %s, line %s" message_gen_raise = "File contains generic exception: %s, line %s" message_old_raise = "File contains old-style raise statement: %s, line %s, \"%s\"" message_eof = "File does not end with a newline: %s, line %s" message_multi_eof = "File ends with more than 1 newline: %s, line %s" message_test_suite_def = "Function should start with 'test_' or '_': %s, line %s" message_duplicate_test = "This is a duplicate test function: %s, line %s" message_self_assignments = "File contains assignments to self/cls: %s, line %s." message_func_is = "File contains '.func is': %s, line %s." implicit_test_re = re.compile(r'^\s*(>>> )?(\.\.\. )?from .* import .*\*') str_raise_re = re.compile( r'^\s*(>>> )?(\.\.\. )?raise(\s+(\'|\")|\s*(\(\s*)+(\'|\"))') gen_raise_re = re.compile( r'^\s*(>>> )?(\.\.\. )?raise(\s+Exception|\s*(\(\s*)+Exception)') old_raise_re = re.compile(r'^\s*(>>> )?(\.\.\. )?raise((\s*\(\s*)|\s+)\w+\s*,') test_suite_def_re = re.compile(r'^def\s+(?!(_|test))[^(]*\(\s*\)\s*:$') test_ok_def_re = re.compile(r'^def\s+test_.*:$') test_file_re = re.compile(r'.*[/\\]test_.*\.py$') func_is_re = re.compile(r'\.\s*func\s+is') def tab_in_leading(s): """Returns True if there are tabs in the leading whitespace of a line, including the whitespace of docstring code samples.""" n = len(s) - len(s.lstrip()) if not s[n:n + 3] in ['...', '>>>']: check = s[:n] else: smore = s[n + 3:] check = s[:n] + smore[:len(smore) - len(smore.lstrip())] return not (check.expandtabs() == check) def find_self_assignments(s): """Returns a list of "bad" assignments: if there are instances of assigning to the first argument of the class method (except for staticmethod's). """ t = [n for n in ast.parse(s).body if isinstance(n, ast.ClassDef)] bad = [] for c in t: for n in c.body: if not isinstance(n, ast.FunctionDef): continue if any(d.id == 'staticmethod' for d in n.decorator_list if isinstance(d, ast.Name)): continue if n.name == '__new__': continue if not n.args.args: continue first_arg = n.args.args[0].arg for m in ast.walk(n): if isinstance(m, ast.Assign): for a in m.targets: if isinstance(a, ast.Name) and a.id == first_arg: bad.append(m) elif (isinstance(a, ast.Tuple) and any(q.id == first_arg for q in a.elts if isinstance(q, ast.Name))): bad.append(m) return bad def check_directory_tree(base_path, file_check, exclusions=set(), pattern="*.py"): """ Checks all files in the directory tree (with base_path as starting point) with the file_check function provided, skipping files that contain any of the strings in the set provided by exclusions. """ if not base_path: return for root, dirs, files in walk(base_path): check_files(glob(join(root, pattern)), file_check, exclusions) def check_files(files, file_check, exclusions=set(), pattern=None): """ Checks all files with the file_check function provided, skipping files that contain any of the strings in the set provided by exclusions. """ if not files: return for fname in files: if not exists(fname) or not isfile(fname): continue if any(ex in fname for ex in exclusions): continue if pattern is None or re.match(pattern, fname): file_check(fname) def test_files(): """ This test tests all files in sympy and checks that: o no lines contains a trailing whitespace o no lines end with \r\n o no line uses tabs instead of spaces o that the file ends with a single newline o there are no general or string exceptions o there are no old style raise statements o name of arg-less test suite functions start with _ or test_ o no duplicate function names that start with test_ o no assignments to self variable in class methods o no lines contain ".func is" except in the test suite """ def test(fname): with open(fname, encoding="utf8") as test_file: test_this_file(fname, test_file) with open(fname, encoding='utf8') as test_file: _test_this_file_encoding(fname, test_file) def test_this_file(fname, test_file): line = None # to flag the case where there were no lines in file tests = 0 test_set = set() for idx, line in enumerate(test_file): if test_file_re.match(fname): if test_suite_def_re.match(line): assert False, message_test_suite_def % (fname, idx + 1) if test_ok_def_re.match(line): tests += 1 test_set.add(line[3:].split('(')[0].strip()) if len(test_set) != tests: assert False, message_duplicate_test % (fname, idx + 1) if line.endswith(" \n") or line.endswith("\t\n"): assert False, message_space % (fname, idx + 1) if line.endswith("\r\n"): assert False, message_carriage % (fname, idx + 1) if tab_in_leading(line): assert False, message_tabs % (fname, idx + 1) if str_raise_re.search(line): assert False, message_str_raise % (fname, idx + 1) if gen_raise_re.search(line): assert False, message_gen_raise % (fname, idx + 1) if (implicit_test_re.search(line) and not list(filter(lambda ex: ex in fname, import_exclude))): assert False, message_implicit % (fname, idx + 1) if func_is_re.search(line) and not test_file_re.search(fname): assert False, message_func_is % (fname, idx + 1) result = old_raise_re.search(line) if result is not None: assert False, message_old_raise % ( fname, idx + 1, result.group(2)) if line is not None: if line == '\n' and idx > 0: assert False, message_multi_eof % (fname, idx + 1) elif not line.endswith('\n'): # eof newline check assert False, message_eof % (fname, idx + 1) # Files to test at top level top_level_files = [join(TOP_PATH, file) for file in [ "isympy.py", "build.py", "setup.py", "setupegg.py", ]] # Files to exclude from all tests exclude = { "%(sep)ssympy%(sep)sparsing%(sep)sautolev%(sep)s_antlr%(sep)sautolevparser.py" % sepd, "%(sep)ssympy%(sep)sparsing%(sep)sautolev%(sep)s_antlr%(sep)sautolevlexer.py" % sepd, "%(sep)ssympy%(sep)sparsing%(sep)sautolev%(sep)s_antlr%(sep)sautolevlistener.py" % sepd, "%(sep)ssympy%(sep)sparsing%(sep)slatex%(sep)s_antlr%(sep)slatexparser.py" % sepd, "%(sep)ssympy%(sep)sparsing%(sep)slatex%(sep)s_antlr%(sep)slatexlexer.py" % sepd, } # Files to exclude from the implicit import test import_exclude = { # glob imports are allowed in top-level __init__.py: "%(sep)ssympy%(sep)s__init__.py" % sepd, # these __init__.py should be fixed: # XXX: not really, they use useful import pattern (DRY) "%(sep)svector%(sep)s__init__.py" % sepd, "%(sep)smechanics%(sep)s__init__.py" % sepd, "%(sep)squantum%(sep)s__init__.py" % sepd, "%(sep)spolys%(sep)s__init__.py" % sepd, "%(sep)spolys%(sep)sdomains%(sep)s__init__.py" % sepd, # interactive sympy executes ``from sympy import *``: "%(sep)sinteractive%(sep)ssession.py" % sepd, # isympy.py executes ``from sympy import *``: "%(sep)sisympy.py" % sepd, # these two are import timing tests: "%(sep)sbin%(sep)ssympy_time.py" % sepd, "%(sep)sbin%(sep)ssympy_time_cache.py" % sepd, # Taken from Python stdlib: "%(sep)sparsing%(sep)ssympy_tokenize.py" % sepd, # this one should be fixed: "%(sep)splotting%(sep)spygletplot%(sep)s" % sepd, # False positive in the docstring "%(sep)sbin%(sep)stest_external_imports.py" % sepd, "%(sep)sbin%(sep)stest_submodule_imports.py" % sepd, # These are deprecated stubs that can be removed at some point: "%(sep)sutilities%(sep)sruntests.py" % sepd, "%(sep)sutilities%(sep)spytest.py" % sepd, "%(sep)sutilities%(sep)srandtest.py" % sepd, "%(sep)sutilities%(sep)stmpfiles.py" % sepd, "%(sep)sutilities%(sep)squality_unicode.py" % sepd, "%(sep)sutilities%(sep)sbenchmarking.py" % sepd, } check_files(top_level_files, test) check_directory_tree(BIN_PATH, test, {"~", ".pyc", ".sh"}, "*") check_directory_tree(SYMPY_PATH, test, exclude) check_directory_tree(EXAMPLES_PATH, test, exclude) def _with_space(c): # return c with a random amount of leading space return random.randint(0, 10)*' ' + c def test_raise_statement_regular_expression(): candidates_ok = [ "some text # raise Exception, 'text'", "raise ValueError('text') # raise Exception, 'text'", "raise ValueError('text')", "raise ValueError", "raise ValueError('text')", "raise ValueError('text') #,", # Talking about an exception in a docstring ''''"""This function will raise ValueError, except when it doesn't"""''', "raise (ValueError('text')", ] str_candidates_fail = [ "raise 'exception'", "raise 'Exception'", 'raise "exception"', 'raise "Exception"', "raise 'ValueError'", ] gen_candidates_fail = [ "raise Exception('text') # raise Exception, 'text'", "raise Exception('text')", "raise Exception", "raise Exception('text')", "raise Exception('text') #,", "raise Exception, 'text'", "raise Exception, 'text' # raise Exception('text')", "raise Exception, 'text' # raise Exception, 'text'", ">>> raise Exception, 'text'", ">>> raise Exception, 'text' # raise Exception('text')", ">>> raise Exception, 'text' # raise Exception, 'text'", ] old_candidates_fail = [ "raise Exception, 'text'", "raise Exception, 'text' # raise Exception('text')", "raise Exception, 'text' # raise Exception, 'text'", ">>> raise Exception, 'text'", ">>> raise Exception, 'text' # raise Exception('text')", ">>> raise Exception, 'text' # raise Exception, 'text'", "raise ValueError, 'text'", "raise ValueError, 'text' # raise Exception('text')", "raise ValueError, 'text' # raise Exception, 'text'", ">>> raise ValueError, 'text'", ">>> raise ValueError, 'text' # raise Exception('text')", ">>> raise ValueError, 'text' # raise Exception, 'text'", "raise(ValueError,", "raise (ValueError,", "raise( ValueError,", "raise ( ValueError,", "raise(ValueError ,", "raise (ValueError ,", "raise( ValueError ,", "raise ( ValueError ,", ] for c in candidates_ok: assert str_raise_re.search(_with_space(c)) is None, c assert gen_raise_re.search(_with_space(c)) is None, c assert old_raise_re.search(_with_space(c)) is None, c for c in str_candidates_fail: assert str_raise_re.search(_with_space(c)) is not None, c for c in gen_candidates_fail: assert gen_raise_re.search(_with_space(c)) is not None, c for c in old_candidates_fail: assert old_raise_re.search(_with_space(c)) is not None, c def test_implicit_imports_regular_expression(): candidates_ok = [ "from sympy import something", ">>> from sympy import something", "from sympy.somewhere import something", ">>> from sympy.somewhere import something", "import sympy", ">>> import sympy", "import sympy.something.something", "... import sympy", "... import sympy.something.something", "... from sympy import something", "... from sympy.somewhere import something", ">> from sympy import *", # To allow 'fake' docstrings "# from sympy import *", "some text # from sympy import *", ] candidates_fail = [ "from sympy import *", ">>> from sympy import *", "from sympy.somewhere import *", ">>> from sympy.somewhere import *", "... from sympy import *", "... from sympy.somewhere import *", ] for c in candidates_ok: assert implicit_test_re.search(_with_space(c)) is None, c for c in candidates_fail: assert implicit_test_re.search(_with_space(c)) is not None, c def test_test_suite_defs(): candidates_ok = [ " def foo():\n", "def foo(arg):\n", "def _foo():\n", "def test_foo():\n", ] candidates_fail = [ "def foo():\n", "def foo() :\n", "def foo( ):\n", "def foo():\n", ] for c in candidates_ok: assert test_suite_def_re.search(c) is None, c for c in candidates_fail: assert test_suite_def_re.search(c) is not None, c def test_test_duplicate_defs(): candidates_ok = [ "def foo():\ndef foo():\n", "def test():\ndef test_():\n", "def test_():\ndef test__():\n", ] candidates_fail = [ "def test_():\ndef test_ ():\n", "def test_1():\ndef test_1():\n", ] ok = (None, 'check') def check(file): tests = 0 test_set = set() for idx, line in enumerate(file.splitlines()): if test_ok_def_re.match(line): tests += 1 test_set.add(line[3:].split('(')[0].strip()) if len(test_set) != tests: return False, message_duplicate_test % ('check', idx + 1) return None, 'check' for c in candidates_ok: assert check(c) == ok for c in candidates_fail: assert check(c) != ok def test_find_self_assignments(): candidates_ok = [ "class A(object):\n def foo(self, arg): arg = self\n", "class A(object):\n def foo(self, arg): self.prop = arg\n", "class A(object):\n def foo(self, arg): obj, obj2 = arg, self\n", "class A(object):\n @classmethod\n def bar(cls, arg): arg = cls\n", "class A(object):\n def foo(var, arg): arg = var\n", ] candidates_fail = [ "class A(object):\n def foo(self, arg): self = arg\n", "class A(object):\n def foo(self, arg): obj, self = arg, arg\n", "class A(object):\n def foo(self, arg):\n if arg: self = arg", "class A(object):\n @classmethod\n def foo(cls, arg): cls = arg\n", "class A(object):\n def foo(var, arg): var = arg\n", ] for c in candidates_ok: assert find_self_assignments(c) == [] for c in candidates_fail: assert find_self_assignments(c) != [] def test_test_unicode_encoding(): unicode_whitelist = ['foo'] unicode_strict_whitelist = ['bar'] fname = 'abc' test_file = ['α'] raises(AssertionError, lambda: _test_this_file_encoding( fname, test_file, unicode_whitelist, unicode_strict_whitelist)) fname = 'abc' test_file = ['# coding=utf-8', 'α'] raises(AssertionError, lambda: _test_this_file_encoding( fname, test_file, unicode_whitelist, unicode_strict_whitelist)) fname = 'abc' test_file = ['# coding=utf-8', 'abc'] raises(AssertionError, lambda: _test_this_file_encoding( fname, test_file, unicode_whitelist, unicode_strict_whitelist)) fname = 'abc' test_file = ['abc'] _test_this_file_encoding( fname, test_file, unicode_whitelist, unicode_strict_whitelist) fname = 'foo' test_file = ['α'] raises(AssertionError, lambda: _test_this_file_encoding( fname, test_file, unicode_whitelist, unicode_strict_whitelist)) fname = 'foo' test_file = ['# coding=utf-8', 'α'] _test_this_file_encoding( fname, test_file, unicode_whitelist, unicode_strict_whitelist) fname = 'foo' test_file = ['# coding=utf-8', 'abc'] raises(AssertionError, lambda: _test_this_file_encoding( fname, test_file, unicode_whitelist, unicode_strict_whitelist)) fname = 'foo' test_file = ['abc'] raises(AssertionError, lambda: _test_this_file_encoding( fname, test_file, unicode_whitelist, unicode_strict_whitelist)) fname = 'bar' test_file = ['α'] raises(AssertionError, lambda: _test_this_file_encoding( fname, test_file, unicode_whitelist, unicode_strict_whitelist)) fname = 'bar' test_file = ['# coding=utf-8', 'α'] _test_this_file_encoding( fname, test_file, unicode_whitelist, unicode_strict_whitelist) fname = 'bar' test_file = ['# coding=utf-8', 'abc'] _test_this_file_encoding( fname, test_file, unicode_whitelist, unicode_strict_whitelist) fname = 'bar' test_file = ['abc'] _test_this_file_encoding( fname, test_file, unicode_whitelist, unicode_strict_whitelist)
d59ab33af4d70b2312dd870b6a7c4a31d784e434a89490c7d4f84206571ffc0f
from sympy.core.function import Derivative from sympy.vector.vector import Vector from sympy.vector.coordsysrect import CoordSys3D from sympy.simplify import simplify from sympy.core.symbol import symbols from sympy.core import S from sympy import sin, cos from sympy.vector.vector import Dot from sympy.vector.operators import curl, divergence, gradient, Gradient, Divergence, Cross from sympy.vector.deloperator import Del from sympy.vector.functions import (is_conservative, is_solenoidal, scalar_potential, directional_derivative, laplacian, scalar_potential_difference) from sympy.testing.pytest import raises C = CoordSys3D('C') i, j, k = C.base_vectors() x, y, z = C.base_scalars() delop = Del() a, b, c, q = symbols('a b c q') def test_del_operator(): # Tests for curl assert delop ^ Vector.zero == Vector.zero assert ((delop ^ Vector.zero).doit() == Vector.zero == curl(Vector.zero)) assert delop.cross(Vector.zero) == delop ^ Vector.zero assert (delop ^ i).doit() == Vector.zero assert delop.cross(2*y**2*j, doit=True) == Vector.zero assert delop.cross(2*y**2*j) == delop ^ 2*y**2*j v = x*y*z * (i + j + k) assert ((delop ^ v).doit() == (-x*y + x*z)*i + (x*y - y*z)*j + (-x*z + y*z)*k == curl(v)) assert delop ^ v == delop.cross(v) assert (delop.cross(2*x**2*j) == (Derivative(0, C.y) - Derivative(2*C.x**2, C.z))*C.i + (-Derivative(0, C.x) + Derivative(0, C.z))*C.j + (-Derivative(0, C.y) + Derivative(2*C.x**2, C.x))*C.k) assert (delop.cross(2*x**2*j, doit=True) == 4*x*k == curl(2*x**2*j)) #Tests for divergence assert delop & Vector.zero is S.Zero == divergence(Vector.zero) assert (delop & Vector.zero).doit() is S.Zero assert delop.dot(Vector.zero) == delop & Vector.zero assert (delop & i).doit() is S.Zero assert (delop & x**2*i).doit() == 2*x == divergence(x**2*i) assert (delop.dot(v, doit=True) == x*y + y*z + z*x == divergence(v)) assert delop & v == delop.dot(v) assert delop.dot(1/(x*y*z) * (i + j + k), doit=True) == \ - 1 / (x*y*z**2) - 1 / (x*y**2*z) - 1 / (x**2*y*z) v = x*i + y*j + z*k assert (delop & v == Derivative(C.x, C.x) + Derivative(C.y, C.y) + Derivative(C.z, C.z)) assert delop.dot(v, doit=True) == 3 == divergence(v) assert delop & v == delop.dot(v) assert simplify((delop & v).doit()) == 3 #Tests for gradient assert (delop.gradient(0, doit=True) == Vector.zero == gradient(0)) assert delop.gradient(0) == delop(0) assert (delop(S.Zero)).doit() == Vector.zero assert (delop(x) == (Derivative(C.x, C.x))*C.i + (Derivative(C.x, C.y))*C.j + (Derivative(C.x, C.z))*C.k) assert (delop(x)).doit() == i == gradient(x) assert (delop(x*y*z) == (Derivative(C.x*C.y*C.z, C.x))*C.i + (Derivative(C.x*C.y*C.z, C.y))*C.j + (Derivative(C.x*C.y*C.z, C.z))*C.k) assert (delop.gradient(x*y*z, doit=True) == y*z*i + z*x*j + x*y*k == gradient(x*y*z)) assert delop(x*y*z) == delop.gradient(x*y*z) assert (delop(2*x**2)).doit() == 4*x*i assert ((delop(a*sin(y) / x)).doit() == -a*sin(y)/x**2 * i + a*cos(y)/x * j) #Tests for directional derivative assert (Vector.zero & delop)(a) is S.Zero assert ((Vector.zero & delop)(a)).doit() is S.Zero assert ((v & delop)(Vector.zero)).doit() == Vector.zero assert ((v & delop)(S.Zero)).doit() is S.Zero assert ((i & delop)(x)).doit() == 1 assert ((j & delop)(y)).doit() == 1 assert ((k & delop)(z)).doit() == 1 assert ((i & delop)(x*y*z)).doit() == y*z assert ((v & delop)(x)).doit() == x assert ((v & delop)(x*y*z)).doit() == 3*x*y*z assert (v & delop)(x + y + z) == C.x + C.y + C.z assert ((v & delop)(x + y + z)).doit() == x + y + z assert ((v & delop)(v)).doit() == v assert ((i & delop)(v)).doit() == i assert ((j & delop)(v)).doit() == j assert ((k & delop)(v)).doit() == k assert ((v & delop)(Vector.zero)).doit() == Vector.zero # Tests for laplacian on scalar fields assert laplacian(x*y*z) is S.Zero assert laplacian(x**2) == S(2) assert laplacian(x**2*y**2*z**2) == \ 2*y**2*z**2 + 2*x**2*z**2 + 2*x**2*y**2 A = CoordSys3D('A', transformation="spherical", variable_names=["r", "theta", "phi"]) B = CoordSys3D('B', transformation='cylindrical', variable_names=["r", "theta", "z"]) assert laplacian(A.r + A.theta + A.phi) == 2/A.r + cos(A.theta)/(A.r**2*sin(A.theta)) assert laplacian(B.r + B.theta + B.z) == 1/B.r # Tests for laplacian on vector fields assert laplacian(x*y*z*(i + j + k)) == Vector.zero assert laplacian(x*y**2*z*(i + j + k)) == \ 2*x*z*i + 2*x*z*j + 2*x*z*k def test_product_rules(): """ Tests the six product rules defined with respect to the Del operator References ========== .. [1] https://en.wikipedia.org/wiki/Del """ #Define the scalar and vector functions f = 2*x*y*z g = x*y + y*z + z*x u = x**2*i + 4*j - y**2*z*k v = 4*i + x*y*z*k # First product rule lhs = delop(f * g, doit=True) rhs = (f * delop(g) + g * delop(f)).doit() assert simplify(lhs) == simplify(rhs) # Second product rule lhs = delop(u & v).doit() rhs = ((u ^ (delop ^ v)) + (v ^ (delop ^ u)) + \ ((u & delop)(v)) + ((v & delop)(u))).doit() assert simplify(lhs) == simplify(rhs) # Third product rule lhs = (delop & (f*v)).doit() rhs = ((f * (delop & v)) + (v & (delop(f)))).doit() assert simplify(lhs) == simplify(rhs) # Fourth product rule lhs = (delop & (u ^ v)).doit() rhs = ((v & (delop ^ u)) - (u & (delop ^ v))).doit() assert simplify(lhs) == simplify(rhs) # Fifth product rule lhs = (delop ^ (f * v)).doit() rhs = (((delop(f)) ^ v) + (f * (delop ^ v))).doit() assert simplify(lhs) == simplify(rhs) # Sixth product rule lhs = (delop ^ (u ^ v)).doit() rhs = (u * (delop & v) - v * (delop & u) + (v & delop)(u) - (u & delop)(v)).doit() assert simplify(lhs) == simplify(rhs) P = C.orient_new_axis('P', q, C.k) # type: ignore scalar_field = 2*x**2*y*z grad_field = gradient(scalar_field) vector_field = y**2*i + 3*x*j + 5*y*z*k curl_field = curl(vector_field) def test_conservative(): assert is_conservative(Vector.zero) is True assert is_conservative(i) is True assert is_conservative(2 * i + 3 * j + 4 * k) is True assert (is_conservative(y*z*i + x*z*j + x*y*k) is True) assert is_conservative(x * j) is False assert is_conservative(grad_field) is True assert is_conservative(curl_field) is False assert (is_conservative(4*x*y*z*i + 2*x**2*z*j) is False) assert is_conservative(z*P.i + P.x*k) is True def test_solenoidal(): assert is_solenoidal(Vector.zero) is True assert is_solenoidal(i) is True assert is_solenoidal(2 * i + 3 * j + 4 * k) is True assert (is_solenoidal(y*z*i + x*z*j + x*y*k) is True) assert is_solenoidal(y * j) is False assert is_solenoidal(grad_field) is False assert is_solenoidal(curl_field) is True assert is_solenoidal((-2*y + 3)*k) is True assert is_solenoidal(cos(q)*i + sin(q)*j + cos(q)*P.k) is True assert is_solenoidal(z*P.i + P.x*k) is True def test_directional_derivative(): assert directional_derivative(C.x*C.y*C.z, 3*C.i + 4*C.j + C.k) == C.x*C.y + 4*C.x*C.z + 3*C.y*C.z assert directional_derivative(5*C.x**2*C.z, 3*C.i + 4*C.j + C.k) == 5*C.x**2 + 30*C.x*C.z assert directional_derivative(5*C.x**2*C.z, 4*C.j) is S.Zero D = CoordSys3D("D", "spherical", variable_names=["r", "theta", "phi"], vector_names=["e_r", "e_theta", "e_phi"]) r, theta, phi = D.base_scalars() e_r, e_theta, e_phi = D.base_vectors() assert directional_derivative(r**2*e_r, e_r) == 2*r*e_r assert directional_derivative(5*r**2*phi, 3*e_r + 4*e_theta + e_phi) == 5*r**2 + 30*r*phi def test_scalar_potential(): assert scalar_potential(Vector.zero, C) == 0 assert scalar_potential(i, C) == x assert scalar_potential(j, C) == y assert scalar_potential(k, C) == z assert scalar_potential(y*z*i + x*z*j + x*y*k, C) == x*y*z assert scalar_potential(grad_field, C) == scalar_field assert scalar_potential(z*P.i + P.x*k, C) == x*z*cos(q) + y*z*sin(q) assert scalar_potential(z*P.i + P.x*k, P) == P.x*P.z raises(ValueError, lambda: scalar_potential(x*j, C)) def test_scalar_potential_difference(): point1 = C.origin.locate_new('P1', 1*i + 2*j + 3*k) point2 = C.origin.locate_new('P2', 4*i + 5*j + 6*k) genericpointC = C.origin.locate_new('RP', x*i + y*j + z*k) genericpointP = P.origin.locate_new('PP', P.x*P.i + P.y*P.j + P.z*P.k) assert scalar_potential_difference(S.Zero, C, point1, point2) == 0 assert (scalar_potential_difference(scalar_field, C, C.origin, genericpointC) == scalar_field) assert (scalar_potential_difference(grad_field, C, C.origin, genericpointC) == scalar_field) assert scalar_potential_difference(grad_field, C, point1, point2) == 948 assert (scalar_potential_difference(y*z*i + x*z*j + x*y*k, C, point1, genericpointC) == x*y*z - 6) potential_diff_P = (2*P.z*(P.x*sin(q) + P.y*cos(q))* (P.x*cos(q) - P.y*sin(q))**2) assert (scalar_potential_difference(grad_field, P, P.origin, genericpointP).simplify() == potential_diff_P.simplify()) def test_differential_operators_curvilinear_system(): A = CoordSys3D('A', transformation="spherical", variable_names=["r", "theta", "phi"]) B = CoordSys3D('B', transformation='cylindrical', variable_names=["r", "theta", "z"]) # Test for spherical coordinate system and gradient assert gradient(3*A.r + 4*A.theta) == 3*A.i + 4/A.r*A.j assert gradient(3*A.r*A.phi + 4*A.theta) == 3*A.phi*A.i + 4/A.r*A.j + (3/sin(A.theta))*A.k assert gradient(0*A.r + 0*A.theta+0*A.phi) == Vector.zero assert gradient(A.r*A.theta*A.phi) == A.theta*A.phi*A.i + A.phi*A.j + (A.theta/sin(A.theta))*A.k # Test for spherical coordinate system and divergence assert divergence(A.r * A.i + A.theta * A.j + A.phi * A.k) == \ (sin(A.theta)*A.r + cos(A.theta)*A.r*A.theta)/(sin(A.theta)*A.r**2) + 3 + 1/(sin(A.theta)*A.r) assert divergence(3*A.r*A.phi*A.i + A.theta*A.j + A.r*A.theta*A.phi*A.k) == \ (sin(A.theta)*A.r + cos(A.theta)*A.r*A.theta)/(sin(A.theta)*A.r**2) + 9*A.phi + A.theta/sin(A.theta) assert divergence(Vector.zero) == 0 assert divergence(0*A.i + 0*A.j + 0*A.k) == 0 # Test for spherical coordinate system and curl assert curl(A.r*A.i + A.theta*A.j + A.phi*A.k) == \ (cos(A.theta)*A.phi/(sin(A.theta)*A.r))*A.i + (-A.phi/A.r)*A.j + A.theta/A.r*A.k assert curl(A.r*A.j + A.phi*A.k) == (cos(A.theta)*A.phi/(sin(A.theta)*A.r))*A.i + (-A.phi/A.r)*A.j + 2*A.k # Test for cylindrical coordinate system and gradient assert gradient(0*B.r + 0*B.theta+0*B.z) == Vector.zero assert gradient(B.r*B.theta*B.z) == B.theta*B.z*B.i + B.z*B.j + B.r*B.theta*B.k assert gradient(3*B.r) == 3*B.i assert gradient(2*B.theta) == 2/B.r * B.j assert gradient(4*B.z) == 4*B.k # Test for cylindrical coordinate system and divergence assert divergence(B.r*B.i + B.theta*B.j + B.z*B.k) == 3 + 1/B.r assert divergence(B.r*B.j + B.z*B.k) == 1 # Test for cylindrical coordinate system and curl assert curl(B.r*B.j + B.z*B.k) == 2*B.k assert curl(3*B.i + 2/B.r*B.j + 4*B.k) == Vector.zero def test_mixed_coordinates(): # gradient a = CoordSys3D('a') b = CoordSys3D('b') c = CoordSys3D('c') assert gradient(a.x*b.y) == b.y*a.i + a.x*b.j assert gradient(3*cos(q)*a.x*b.x+a.y*(a.x+(cos(q)+b.x))) ==\ (a.y + 3*b.x*cos(q))*a.i + (a.x + b.x + cos(q))*a.j + (3*a.x*cos(q) + a.y)*b.i # Some tests need further work: # assert gradient(a.x*(cos(a.x+b.x))) == (cos(a.x + b.x))*a.i + a.x*Gradient(cos(a.x + b.x)) # assert gradient(cos(a.x + b.x)*cos(a.x + b.z)) == Gradient(cos(a.x + b.x)*cos(a.x + b.z)) assert gradient(a.x**b.y) == Gradient(a.x**b.y) # assert gradient(cos(a.x+b.y)*a.z) == None assert gradient(cos(a.x*b.y)) == Gradient(cos(a.x*b.y)) assert gradient(3*cos(q)*a.x*b.x*a.z*a.y+ b.y*b.z + cos(a.x+a.y)*b.z) == \ (3*a.y*a.z*b.x*cos(q) - b.z*sin(a.x + a.y))*a.i + \ (3*a.x*a.z*b.x*cos(q) - b.z*sin(a.x + a.y))*a.j + (3*a.x*a.y*b.x*cos(q))*a.k + \ (3*a.x*a.y*a.z*cos(q))*b.i + b.z*b.j + (b.y + cos(a.x + a.y))*b.k # divergence assert divergence(a.i*a.x+a.j*a.y+a.z*a.k + b.i*b.x+b.j*b.y+b.z*b.k + c.i*c.x+c.j*c.y+c.z*c.k) == S(9) # assert divergence(3*a.i*a.x*cos(a.x+b.z) + a.j*b.x*c.z) == None assert divergence(3*a.i*a.x*a.z + b.j*b.x*c.z + 3*a.j*a.z*a.y) == \ 6*a.z + b.x*Dot(b.j, c.k) assert divergence(3*cos(q)*a.x*b.x*b.i*c.x) == \ 3*a.x*b.x*cos(q)*Dot(b.i, c.i) + 3*a.x*c.x*cos(q) + 3*b.x*c.x*cos(q)*Dot(b.i, a.i) assert divergence(a.x*b.x*c.x*Cross(a.x*a.i, a.y*b.j)) ==\ a.x*b.x*c.x*Divergence(Cross(a.x*a.i, a.y*b.j)) + \ b.x*c.x*Dot(Cross(a.x*a.i, a.y*b.j), a.i) + \ a.x*c.x*Dot(Cross(a.x*a.i, a.y*b.j), b.i) + \ a.x*b.x*Dot(Cross(a.x*a.i, a.y*b.j), c.i) assert divergence(a.x*b.x*c.x*(a.x*a.i + b.x*b.i)) == \ 4*a.x*b.x*c.x +\ a.x**2*c.x*Dot(a.i, b.i) +\ a.x**2*b.x*Dot(a.i, c.i) +\ b.x**2*c.x*Dot(b.i, a.i) +\ a.x*b.x**2*Dot(b.i, c.i)
bdf6317484a2955aca35bc0b73d49b75e0c3392e0ec286539a07c4acf8bbf4cd
from sympy import Dummy, S, symbols, pi, sqrt, asin, sin, cos, Rational from sympy.geometry import Line, Point, Ray, Segment, Point3D, Line3D, Ray3D, Segment3D, Plane, Circle from sympy.geometry.util import are_coplanar from sympy.testing.pytest import raises def test_plane(): x, y, z, u, v = symbols('x y z u v', real=True) p1 = Point3D(0, 0, 0) p2 = Point3D(1, 1, 1) p3 = Point3D(1, 2, 3) pl3 = Plane(p1, p2, p3) pl4 = Plane(p1, normal_vector=(1, 1, 1)) pl4b = Plane(p1, p2) pl5 = Plane(p3, normal_vector=(1, 2, 3)) pl6 = Plane(Point3D(2, 3, 7), normal_vector=(2, 2, 2)) pl7 = Plane(Point3D(1, -5, -6), normal_vector=(1, -2, 1)) pl8 = Plane(p1, normal_vector=(0, 0, 1)) pl9 = Plane(p1, normal_vector=(0, 12, 0)) pl10 = Plane(p1, normal_vector=(-2, 0, 0)) pl11 = Plane(p2, normal_vector=(0, 0, 1)) l1 = Line3D(Point3D(5, 0, 0), Point3D(1, -1, 1)) l2 = Line3D(Point3D(0, -2, 0), Point3D(3, 1, 1)) l3 = Line3D(Point3D(0, -1, 0), Point3D(5, -1, 9)) raises(ValueError, lambda: Plane(p1, p1, p1)) assert Plane(p1, p2, p3) != Plane(p1, p3, p2) assert Plane(p1, p2, p3).is_coplanar(Plane(p1, p3, p2)) assert Plane(p1, p2, p3).is_coplanar(p1) assert Plane(p1, p2, p3).is_coplanar(Circle(p1, 1)) is False assert Plane(p1, normal_vector=(0, 0, 1)).is_coplanar(Circle(p1, 1)) assert pl3 == Plane(Point3D(0, 0, 0), normal_vector=(1, -2, 1)) assert pl3 != pl4 assert pl4 == pl4b assert pl5 == Plane(Point3D(1, 2, 3), normal_vector=(1, 2, 3)) assert pl5.equation(x, y, z) == x + 2*y + 3*z - 14 assert pl3.equation(x, y, z) == x - 2*y + z assert pl3.p1 == p1 assert pl4.p1 == p1 assert pl5.p1 == p3 assert pl4.normal_vector == (1, 1, 1) assert pl5.normal_vector == (1, 2, 3) assert p1 in pl3 assert p1 in pl4 assert p3 in pl5 assert pl3.projection(Point(0, 0)) == p1 p = pl3.projection(Point3D(1, 1, 0)) assert p == Point3D(Rational(7, 6), Rational(2, 3), Rational(1, 6)) assert p in pl3 l = pl3.projection_line(Line(Point(0, 0), Point(1, 1))) assert l == Line3D(Point3D(0, 0, 0), Point3D(Rational(7, 6), Rational(2, 3), Rational(1, 6))) assert l in pl3 # get a segment that does not intersect the plane which is also # parallel to pl3's normal veector t = Dummy() r = pl3.random_point() a = pl3.perpendicular_line(r).arbitrary_point(t) s = Segment3D(a.subs(t, 1), a.subs(t, 2)) assert s.p1 not in pl3 and s.p2 not in pl3 assert pl3.projection_line(s).equals(r) assert pl3.projection_line(Segment(Point(1, 0), Point(1, 1))) == \ Segment3D(Point3D(Rational(5, 6), Rational(1, 3), Rational(-1, 6)), Point3D(Rational(7, 6), Rational(2, 3), Rational(1, 6))) assert pl6.projection_line(Ray(Point(1, 0), Point(1, 1))) == \ Ray3D(Point3D(Rational(14, 3), Rational(11, 3), Rational(11, 3)), Point3D(Rational(13, 3), Rational(13, 3), Rational(10, 3))) assert pl3.perpendicular_line(r.args) == pl3.perpendicular_line(r) assert pl3.is_parallel(pl6) is False assert pl4.is_parallel(pl6) assert pl3.is_parallel(Line(p1, p2)) assert pl6.is_parallel(l1) is False assert pl3.is_perpendicular(pl6) assert pl4.is_perpendicular(pl7) assert pl6.is_perpendicular(pl7) assert pl6.is_perpendicular(pl4) is False assert pl6.is_perpendicular(l1) is False assert pl6.is_perpendicular(Line((0, 0, 0), (1, 1, 1))) assert pl6.is_perpendicular((1, 1)) is False assert pl6.distance(pl6.arbitrary_point(u, v)) == 0 assert pl7.distance(pl7.arbitrary_point(u, v)) == 0 assert pl6.distance(pl6.arbitrary_point(t)) == 0 assert pl7.distance(pl7.arbitrary_point(t)) == 0 assert pl6.p1.distance(pl6.arbitrary_point(t)).simplify() == 1 assert pl7.p1.distance(pl7.arbitrary_point(t)).simplify() == 1 assert pl3.arbitrary_point(t) == Point3D(-sqrt(30)*sin(t)/30 + \ 2*sqrt(5)*cos(t)/5, sqrt(30)*sin(t)/15 + sqrt(5)*cos(t)/5, sqrt(30)*sin(t)/6) assert pl3.arbitrary_point(u, v) == Point3D(2*u - v, u + 2*v, 5*v) assert pl7.distance(Point3D(1, 3, 5)) == 5*sqrt(6)/6 assert pl6.distance(Point3D(0, 0, 0)) == 4*sqrt(3) assert pl6.distance(pl6.p1) == 0 assert pl7.distance(pl6) == 0 assert pl7.distance(l1) == 0 assert pl6.distance(Segment3D(Point3D(2, 3, 1), Point3D(1, 3, 4))) == \ pl6.distance(Point3D(1, 3, 4)) == 4*sqrt(3)/3 assert pl6.distance(Segment3D(Point3D(1, 3, 4), Point3D(0, 3, 7))) == \ pl6.distance(Point3D(0, 3, 7)) == 2*sqrt(3)/3 assert pl6.distance(Segment3D(Point3D(0, 3, 7), Point3D(-1, 3, 10))) == 0 assert pl6.distance(Segment3D(Point3D(-1, 3, 10), Point3D(-2, 3, 13))) == 0 assert pl6.distance(Segment3D(Point3D(-2, 3, 13), Point3D(-3, 3, 16))) == \ pl6.distance(Point3D(-2, 3, 13)) == 2*sqrt(3)/3 assert pl6.distance(Plane(Point3D(5, 5, 5), normal_vector=(8, 8, 8))) == sqrt(3) assert pl6.distance(Ray3D(Point3D(1, 3, 4), direction_ratio=[1, 0, -3])) == 4*sqrt(3)/3 assert pl6.distance(Ray3D(Point3D(2, 3, 1), direction_ratio=[-1, 0, 3])) == 0 assert pl6.angle_between(pl3) == pi/2 assert pl6.angle_between(pl6) == 0 assert pl6.angle_between(pl4) == 0 assert pl7.angle_between(Line3D(Point3D(2, 3, 5), Point3D(2, 4, 6))) == \ -asin(sqrt(3)/6) assert pl6.angle_between(Ray3D(Point3D(2, 4, 1), Point3D(6, 5, 3))) == \ asin(sqrt(7)/3) assert pl7.angle_between(Segment3D(Point3D(5, 6, 1), Point3D(1, 2, 4))) == \ asin(7*sqrt(246)/246) assert are_coplanar(l1, l2, l3) is False assert are_coplanar(l1) is False assert are_coplanar(Point3D(2, 7, 2), Point3D(0, 0, 2), Point3D(1, 1, 2), Point3D(1, 2, 2)) assert are_coplanar(Plane(p1, p2, p3), Plane(p1, p3, p2)) assert Plane.are_concurrent(pl3, pl4, pl5) is False assert Plane.are_concurrent(pl6) is False raises(ValueError, lambda: Plane.are_concurrent(Point3D(0, 0, 0))) raises(ValueError, lambda: Plane((1, 2, 3), normal_vector=(0, 0, 0))) assert pl3.parallel_plane(Point3D(1, 2, 5)) == Plane(Point3D(1, 2, 5), \ normal_vector=(1, -2, 1)) # perpendicular_plane p = Plane((0, 0, 0), (1, 0, 0)) # default assert p.perpendicular_plane() == Plane(Point3D(0, 0, 0), (0, 1, 0)) # 1 pt assert p.perpendicular_plane(Point3D(1, 0, 1)) == \ Plane(Point3D(1, 0, 1), (0, 1, 0)) # pts as tuples assert p.perpendicular_plane((1, 0, 1), (1, 1, 1)) == \ Plane(Point3D(1, 0, 1), (0, 0, -1)) # more than two planes raises(ValueError, lambda: p.perpendicular_plane((1, 0, 1), (1, 1, 1), (1, 1, 0))) a, b = Point3D(0, 0, 0), Point3D(0, 1, 0) Z = (0, 0, 1) p = Plane(a, normal_vector=Z) # case 4 assert p.perpendicular_plane(a, b) == Plane(a, (1, 0, 0)) n = Point3D(*Z) # case 1 assert p.perpendicular_plane(a, n) == Plane(a, (-1, 0, 0)) # case 2 assert Plane(a, normal_vector=b.args).perpendicular_plane(a, a + b) == \ Plane(Point3D(0, 0, 0), (1, 0, 0)) # case 1&3 assert Plane(b, normal_vector=Z).perpendicular_plane(b, b + n) == \ Plane(Point3D(0, 1, 0), (-1, 0, 0)) # case 2&3 assert Plane(b, normal_vector=b.args).perpendicular_plane(n, n + b) == \ Plane(Point3D(0, 0, 1), (1, 0, 0)) p = Plane(a, normal_vector=(0, 0, 1)) assert p.perpendicular_plane() == Plane(a, normal_vector=(1, 0, 0)) assert pl6.intersection(pl6) == [pl6] assert pl4.intersection(pl4.p1) == [pl4.p1] assert pl3.intersection(pl6) == [ Line3D(Point3D(8, 4, 0), Point3D(2, 4, 6))] assert pl3.intersection(Line3D(Point3D(1,2,4), Point3D(4,4,2))) == [ Point3D(2, Rational(8, 3), Rational(10, 3))] assert pl3.intersection(Plane(Point3D(6, 0, 0), normal_vector=(2, -5, 3)) ) == [Line3D(Point3D(-24, -12, 0), Point3D(-25, -13, -1))] assert pl6.intersection(Ray3D(Point3D(2, 3, 1), Point3D(1, 3, 4))) == [ Point3D(-1, 3, 10)] assert pl6.intersection(Segment3D(Point3D(2, 3, 1), Point3D(1, 3, 4))) == [] assert pl7.intersection(Line(Point(2, 3), Point(4, 2))) == [ Point3D(Rational(13, 2), Rational(3, 4), 0)] r = Ray(Point(2, 3), Point(4, 2)) assert Plane((1,2,0), normal_vector=(0,0,1)).intersection(r) == [ Ray3D(Point(2, 3), Point(4, 2))] assert pl9.intersection(pl8) == [Line3D(Point3D(0, 0, 0), Point3D(12, 0, 0))] assert pl10.intersection(pl11) == [Line3D(Point3D(0, 0, 1), Point3D(0, 2, 1))] assert pl4.intersection(pl8) == [Line3D(Point3D(0, 0, 0), Point3D(1, -1, 0))] assert pl11.intersection(pl8) == [] assert pl9.intersection(pl11) == [Line3D(Point3D(0, 0, 1), Point3D(12, 0, 1))] assert pl9.intersection(pl4) == [Line3D(Point3D(0, 0, 0), Point3D(12, 0, -12))] assert pl3.random_point() in pl3 assert pl3.random_point(seed=1) in pl3 # test geometrical entity using equals assert pl4.intersection(pl4.p1)[0].equals(pl4.p1) assert pl3.intersection(pl6)[0].equals(Line3D(Point3D(8, 4, 0), Point3D(2, 4, 6))) pl8 = Plane((1, 2, 0), normal_vector=(0, 0, 1)) assert pl8.intersection(Line3D(p1, (1, 12, 0)))[0].equals(Line((0, 0, 0), (0.1, 1.2, 0))) assert pl8.intersection(Ray3D(p1, (1, 12, 0)))[0].equals(Ray((0, 0, 0), (1, 12, 0))) assert pl8.intersection(Segment3D(p1, (21, 1, 0)))[0].equals(Segment3D(p1, (21, 1, 0))) assert pl8.intersection(Plane(p1, normal_vector=(0, 0, 112)))[0].equals(pl8) assert pl8.intersection(Plane(p1, normal_vector=(0, 12, 0)))[0].equals( Line3D(p1, direction_ratio=(112 * pi, 0, 0))) assert pl8.intersection(Plane(p1, normal_vector=(11, 0, 1)))[0].equals( Line3D(p1, direction_ratio=(0, -11, 0))) assert pl8.intersection(Plane(p1, normal_vector=(1, 0, 11)))[0].equals( Line3D(p1, direction_ratio=(0, 11, 0))) assert pl8.intersection(Plane(p1, normal_vector=(-1, -1, -11)))[0].equals( Line3D(p1, direction_ratio=(1, -1, 0))) assert pl3.random_point() in pl3 assert len(pl8.intersection(Ray3D(Point3D(0, 2, 3), Point3D(1, 0, 3)))) == 0 # check if two plane are equals assert pl6.intersection(pl6)[0].equals(pl6) assert pl8.equals(Plane(p1, normal_vector=(0, 12, 0))) is False assert pl8.equals(pl8) assert pl8.equals(Plane(p1, normal_vector=(0, 0, -12))) assert pl8.equals(Plane(p1, normal_vector=(0, 0, -12*sqrt(3)))) assert pl8.equals(p1) is False # issue 8570 l2 = Line3D(Point3D(Rational(50000004459633, 5000000000000), Rational(-891926590718643, 1000000000000000), Rational(231800966893633, 100000000000000)), Point3D(Rational(50000004459633, 50000000000000), Rational(-222981647679771, 250000000000000), Rational(231800966893633, 100000000000000))) p2 = Plane(Point3D(Rational(402775636372767, 100000000000000), Rational(-97224357654973, 100000000000000), Rational(216793600814789, 100000000000000)), (-S('9.00000087501922'), -S('4.81170658872543e-13'), S('0.0'))) assert str([i.n(2) for i in p2.intersection(l2)]) == \ '[Point3D(4.0, -0.89, 2.3)]' def test_dimension_normalization(): A = Plane(Point3D(1, 1, 2), normal_vector=(1, 1, 1)) b = Point(1, 1) assert A.projection(b) == Point(Rational(5, 3), Rational(5, 3), Rational(2, 3)) a, b = Point(0, 0), Point3D(0, 1) Z = (0, 0, 1) p = Plane(a, normal_vector=Z) assert p.perpendicular_plane(a, b) == Plane(Point3D(0, 0, 0), (1, 0, 0)) assert Plane((1, 2, 1), (2, 1, 0), (3, 1, 2) ).intersection((2, 1)) == [Point(2, 1, 0)] def test_parameter_value(): t, u, v = symbols("t, u v") p1, p2, p3 = Point(0, 0, 0), Point(0, 0, 1), Point(0, 1, 0) p = Plane(p1, p2, p3) assert p.parameter_value((0, -3, 2), t) == {t: asin(2*sqrt(13)/13)} assert p.parameter_value((0, -3, 2), u, v) == {u: 3, v: 2} assert p.parameter_value(p1, t) == p1 raises(ValueError, lambda: p.parameter_value((1, 0, 0), t)) raises(ValueError, lambda: p.parameter_value(Line(Point(0, 0), Point(1, 1)), t)) raises(ValueError, lambda: p.parameter_value((0, -3, 2), t, 1))
e628323b80b5e42eaacf038a8eb21cc5b37dc64df798ec958b5a56a3b6597f74
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))), ] # 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"/>'
5a742d91c2bd85980fbf3b12d1bad1687cdf384b03fc534a66ea6081e5534b56
from sympy import I, Rational, Symbol, pi, sqrt, sympify, S, Basic from sympy.geometry import Line, Point, Point2D, Point3D, Line3D, Plane from sympy.geometry.entity import rotate, scale, translate, GeometryEntity from sympy.matrices import Matrix from sympy.utilities.iterables import subsets, permutations, cartes from sympy.utilities.misc import Undecidable from sympy.testing.pytest import raises, warns def test_point(): x = Symbol('x', real=True) y = Symbol('y', real=True) x1 = Symbol('x1', real=True) x2 = Symbol('x2', real=True) y1 = Symbol('y1', real=True) y2 = Symbol('y2', real=True) half = S.Half p1 = Point(x1, x2) p2 = Point(y1, y2) p3 = Point(0, 0) p4 = Point(1, 1) p5 = Point(0, 1) line = Line(Point(1, 0), slope=1) assert p1 in p1 assert p1 not in p2 assert p2.y == y2 assert (p3 + p4) == p4 assert (p2 - p1) == Point(y1 - x1, y2 - x2) assert -p2 == Point(-y1, -y2) raises(TypeError, lambda: Point(1)) raises(ValueError, lambda: Point([1])) raises(ValueError, lambda: Point(3, I)) raises(ValueError, lambda: Point(2*I, I)) raises(ValueError, lambda: Point(3 + I, I)) assert Point(34.05, sqrt(3)) == Point(Rational(681, 20), sqrt(3)) assert Point.midpoint(p3, p4) == Point(half, half) assert Point.midpoint(p1, p4) == Point(half + half*x1, half + half*x2) assert Point.midpoint(p2, p2) == p2 assert p2.midpoint(p2) == p2 assert p1.origin == Point(0, 0) assert Point.distance(p3, p4) == sqrt(2) assert Point.distance(p1, p1) == 0 assert Point.distance(p3, p2) == sqrt(p2.x**2 + p2.y**2) raises(TypeError, lambda: Point.distance(p1, 0)) raises(TypeError, lambda: Point.distance(p1, GeometryEntity())) # distance should be symmetric assert p1.distance(line) == line.distance(p1) assert p4.distance(line) == line.distance(p4) assert Point.taxicab_distance(p4, p3) == 2 assert Point.canberra_distance(p4, p5) == 1 raises(ValueError, lambda: Point.canberra_distance(p3, p3)) p1_1 = Point(x1, x1) p1_2 = Point(y2, y2) p1_3 = Point(x1 + 1, x1) assert Point.is_collinear(p3) with warns(UserWarning): assert Point.is_collinear(p3, Point(p3, dim=4)) assert p3.is_collinear() assert Point.is_collinear(p3, p4) assert Point.is_collinear(p3, p4, p1_1, p1_2) assert Point.is_collinear(p3, p4, p1_1, p1_3) is False assert Point.is_collinear(p3, p3, p4, p5) is False raises(TypeError, lambda: Point.is_collinear(line)) raises(TypeError, lambda: p1_1.is_collinear(line)) assert p3.intersection(Point(0, 0)) == [p3] assert p3.intersection(p4) == [] assert p3.intersection(line) == [] assert Point.intersection(Point(0, 0, 0), Point(0, 0)) == [Point(0, 0, 0)] x_pos = Symbol('x', real=True, positive=True) p2_1 = Point(x_pos, 0) p2_2 = Point(0, x_pos) p2_3 = Point(-x_pos, 0) p2_4 = Point(0, -x_pos) p2_5 = Point(x_pos, 5) assert Point.is_concyclic(p2_1) assert Point.is_concyclic(p2_1, p2_2) assert Point.is_concyclic(p2_1, p2_2, p2_3, p2_4) for pts in permutations((p2_1, p2_2, p2_3, p2_5)): assert Point.is_concyclic(*pts) is False assert Point.is_concyclic(p4, p4 * 2, p4 * 3) is False assert Point(0, 0).is_concyclic((1, 1), (2, 2), (2, 1)) is False assert Point.is_concyclic(Point(0, 0, 0, 0), Point(1, 0, 0, 0), Point(1, 1, 0, 0), Point(1, 1, 1, 0)) is False assert p1.is_scalar_multiple(p1) assert p1.is_scalar_multiple(2*p1) assert not p1.is_scalar_multiple(p2) assert Point.is_scalar_multiple(Point(1, 1), (-1, -1)) assert Point.is_scalar_multiple(Point(0, 0), (0, -1)) # test when is_scalar_multiple can't be determined raises(Undecidable, lambda: Point.is_scalar_multiple(Point(sympify("x1%y1"), sympify("x2%y2")), Point(0, 1))) assert Point(0, 1).orthogonal_direction == Point(1, 0) assert Point(1, 0).orthogonal_direction == Point(0, 1) assert p1.is_zero is None assert p3.is_zero assert p4.is_zero is False assert p1.is_nonzero is None assert p3.is_nonzero is False assert p4.is_nonzero assert p4.scale(2, 3) == Point(2, 3) assert p3.scale(2, 3) == p3 assert p4.rotate(pi, Point(0.5, 0.5)) == p3 assert p1.__radd__(p2) == p1.midpoint(p2).scale(2, 2) assert (-p3).__rsub__(p4) == p3.midpoint(p4).scale(2, 2) assert p4 * 5 == Point(5, 5) assert p4 / 5 == Point(0.2, 0.2) assert 5 * p4 == Point(5, 5) raises(ValueError, lambda: Point(0, 0) + 10) # Point differences should be simplified assert Point(x*(x - 1), y) - Point(x**2 - x, y + 1) == Point(0, -1) a, b = S.Half, Rational(1, 3) assert Point(a, b).evalf(2) == \ Point(a.n(2), b.n(2), evaluate=False) raises(ValueError, lambda: Point(1, 2) + 1) # test project assert Point.project((0, 1), (1, 0)) == Point(0, 0) assert Point.project((1, 1), (1, 0)) == Point(1, 0) raises(ValueError, lambda: Point.project(p1, Point(0, 0))) # test transformations p = Point(1, 0) assert p.rotate(pi/2) == Point(0, 1) assert p.rotate(pi/2, p) == p p = Point(1, 1) assert p.scale(2, 3) == Point(2, 3) assert p.translate(1, 2) == Point(2, 3) assert p.translate(1) == Point(2, 1) assert p.translate(y=1) == Point(1, 2) assert p.translate(*p.args) == Point(2, 2) # Check invalid input for transform raises(ValueError, lambda: p3.transform(p3)) raises(ValueError, lambda: p.transform(Matrix([[1, 0], [0, 1]]))) # test __contains__ assert 0 in Point(0, 0, 0, 0) assert 1 not in Point(0, 0, 0, 0) # test affine_rank assert Point.affine_rank() == -1 def test_point3D(): x = Symbol('x', real=True) y = Symbol('y', real=True) x1 = Symbol('x1', real=True) x2 = Symbol('x2', real=True) x3 = Symbol('x3', real=True) y1 = Symbol('y1', real=True) y2 = Symbol('y2', real=True) y3 = Symbol('y3', real=True) half = S.Half p1 = Point3D(x1, x2, x3) p2 = Point3D(y1, y2, y3) p3 = Point3D(0, 0, 0) p4 = Point3D(1, 1, 1) p5 = Point3D(0, 1, 2) assert p1 in p1 assert p1 not in p2 assert p2.y == y2 assert (p3 + p4) == p4 assert (p2 - p1) == Point3D(y1 - x1, y2 - x2, y3 - x3) assert -p2 == Point3D(-y1, -y2, -y3) assert Point(34.05, sqrt(3)) == Point(Rational(681, 20), sqrt(3)) assert Point3D.midpoint(p3, p4) == Point3D(half, half, half) assert Point3D.midpoint(p1, p4) == Point3D(half + half*x1, half + half*x2, half + half*x3) assert Point3D.midpoint(p2, p2) == p2 assert p2.midpoint(p2) == p2 assert Point3D.distance(p3, p4) == sqrt(3) assert Point3D.distance(p1, p1) == 0 assert Point3D.distance(p3, p2) == sqrt(p2.x**2 + p2.y**2 + p2.z**2) p1_1 = Point3D(x1, x1, x1) p1_2 = Point3D(y2, y2, y2) p1_3 = Point3D(x1 + 1, x1, x1) Point3D.are_collinear(p3) assert Point3D.are_collinear(p3, p4) assert Point3D.are_collinear(p3, p4, p1_1, p1_2) assert Point3D.are_collinear(p3, p4, p1_1, p1_3) is False assert Point3D.are_collinear(p3, p3, p4, p5) is False assert p3.intersection(Point3D(0, 0, 0)) == [p3] assert p3.intersection(p4) == [] assert p4 * 5 == Point3D(5, 5, 5) assert p4 / 5 == Point3D(0.2, 0.2, 0.2) assert 5 * p4 == Point3D(5, 5, 5) raises(ValueError, lambda: Point3D(0, 0, 0) + 10) # Test coordinate properties assert p1.coordinates == (x1, x2, x3) assert p2.coordinates == (y1, y2, y3) assert p3.coordinates == (0, 0, 0) assert p4.coordinates == (1, 1, 1) assert p5.coordinates == (0, 1, 2) assert p5.x == 0 assert p5.y == 1 assert p5.z == 2 # Point differences should be simplified assert Point3D(x*(x - 1), y, 2) - Point3D(x**2 - x, y + 1, 1) == \ Point3D(0, -1, 1) a, b, c = S.Half, Rational(1, 3), Rational(1, 4) assert Point3D(a, b, c).evalf(2) == \ Point(a.n(2), b.n(2), c.n(2), evaluate=False) raises(ValueError, lambda: Point3D(1, 2, 3) + 1) # test transformations p = Point3D(1, 1, 1) assert p.scale(2, 3) == Point3D(2, 3, 1) assert p.translate(1, 2) == Point3D(2, 3, 1) assert p.translate(1) == Point3D(2, 1, 1) assert p.translate(z=1) == Point3D(1, 1, 2) assert p.translate(*p.args) == Point3D(2, 2, 2) # Test __new__ assert Point3D(0.1, 0.2, evaluate=False, on_morph='ignore').args[0].is_Float # Test length property returns correctly assert p.length == 0 assert p1_1.length == 0 assert p1_2.length == 0 # Test are_colinear type error raises(TypeError, lambda: Point3D.are_collinear(p, x)) # Test are_coplanar assert Point.are_coplanar() assert Point.are_coplanar((1, 2, 0), (1, 2, 0), (1, 3, 0)) assert Point.are_coplanar((1, 2, 0), (1, 2, 3)) with warns(UserWarning): raises(ValueError, lambda: Point2D.are_coplanar((1, 2), (1, 2, 3))) assert Point3D.are_coplanar((1, 2, 0), (1, 2, 3)) assert Point.are_coplanar((0, 0, 0), (1, 1, 0), (1, 1, 1), (1, 2, 1)) is False planar2 = Point3D(1, -1, 1) planar3 = Point3D(-1, 1, 1) assert Point3D.are_coplanar(p, planar2, planar3) == True assert Point3D.are_coplanar(p, planar2, planar3, p3) == False assert Point.are_coplanar(p, planar2) planar2 = Point3D(1, 1, 2) planar3 = Point3D(1, 1, 3) assert Point3D.are_coplanar(p, planar2, planar3) # line, not plane plane = Plane((1, 2, 1), (2, 1, 0), (3, 1, 2)) assert Point.are_coplanar(*[plane.projection(((-1)**i, i)) for i in range(4)]) # all 2D points are coplanar assert Point.are_coplanar(Point(x, y), Point(x, x + y), Point(y, x + 2)) is True # Test Intersection assert planar2.intersection(Line3D(p, planar3)) == [Point3D(1, 1, 2)] # Test Scale assert planar2.scale(1, 1, 1) == planar2 assert planar2.scale(2, 2, 2, planar3) == Point3D(1, 1, 1) assert planar2.scale(1, 1, 1, p3) == planar2 # Test Transform identity = Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]) assert p.transform(identity) == p trans = Matrix([[1, 0, 0, 1], [0, 1, 0, 1], [0, 0, 1, 1], [0, 0, 0, 1]]) assert p.transform(trans) == Point3D(2, 2, 2) raises(ValueError, lambda: p.transform(p)) raises(ValueError, lambda: p.transform(Matrix([[1, 0], [0, 1]]))) # Test Equals assert p.equals(x1) == False # Test __sub__ p_4d = Point(0, 0, 0, 1) with warns(UserWarning): assert p - p_4d == Point(1, 1, 1, -1) p_4d3d = Point(0, 0, 1, 0) with warns(UserWarning): assert p - p_4d3d == Point(1, 1, 0, 0) def test_Point2D(): # Test Distance p1 = Point2D(1, 5) p2 = Point2D(4, 2.5) p3 = (6, 3) assert p1.distance(p2) == sqrt(61)/2 assert p2.distance(p3) == sqrt(17)/2 # Test coordinates assert p1.x == 1 assert p1.y == 5 assert p2.x == 4 assert p2.y == 2.5 assert p1.coordinates == (1, 5) assert p2.coordinates == (4, 2.5) # test bounds assert p1.bounds == (1, 5, 1, 5) def test_issue_9214(): p1 = Point3D(4, -2, 6) p2 = Point3D(1, 2, 3) p3 = Point3D(7, 2, 3) assert Point3D.are_collinear(p1, p2, p3) is False def test_issue_11617(): p1 = Point3D(1,0,2) p2 = Point2D(2,0) with warns(UserWarning): assert p1.distance(p2) == sqrt(5) def test_transform(): p = Point(1, 1) assert p.transform(rotate(pi/2)) == Point(-1, 1) assert p.transform(scale(3, 2)) == Point(3, 2) assert p.transform(translate(1, 2)) == Point(2, 3) assert Point(1, 1).scale(2, 3, (4, 5)) == \ Point(-2, -7) assert Point(1, 1).translate(4, 5) == \ Point(5, 6) def test_concyclic_doctest_bug(): p1, p2 = Point(-1, 0), Point(1, 0) p3, p4 = Point(0, 1), Point(-1, 2) assert Point.is_concyclic(p1, p2, p3) assert not Point.is_concyclic(p1, p2, p3, p4) def test_arguments(): """Functions accepting `Point` objects in `geometry` should also accept tuples and lists and automatically convert them to points.""" singles2d = ((1,2), [1,2], Point(1,2)) singles2d2 = ((1,3), [1,3], Point(1,3)) doubles2d = cartes(singles2d, singles2d2) p2d = Point2D(1,2) singles3d = ((1,2,3), [1,2,3], Point(1,2,3)) doubles3d = subsets(singles3d, 2) p3d = Point3D(1,2,3) singles4d = ((1,2,3,4), [1,2,3,4], Point(1,2,3,4)) doubles4d = subsets(singles4d, 2) p4d = Point(1,2,3,4) # test 2D test_single = ['distance', 'is_scalar_multiple', 'taxicab_distance', 'midpoint', 'intersection', 'dot', 'equals', '__add__', '__sub__'] test_double = ['is_concyclic', 'is_collinear'] for p in singles2d: Point2D(p) for func in test_single: for p in singles2d: getattr(p2d, func)(p) for func in test_double: for p in doubles2d: getattr(p2d, func)(*p) # test 3D test_double = ['is_collinear'] for p in singles3d: Point3D(p) for func in test_single: for p in singles3d: getattr(p3d, func)(p) for func in test_double: for p in doubles3d: getattr(p3d, func)(*p) # test 4D test_double = ['is_collinear'] for p in singles4d: Point(p) for func in test_single: for p in singles4d: getattr(p4d, func)(p) for func in test_double: for p in doubles4d: getattr(p4d, func)(*p) # test evaluate=False for ops x = Symbol('x') a = Point(0, 1) assert a + (0.1, x) == Point(0.1, 1 + x, evaluate=False) a = Point(0, 1) assert a/10.0 == Point(0, 0.1, evaluate=False) a = Point(0, 1) assert a*10.0 == Point(0.0, 10.0, evaluate=False) # test evaluate=False when changing dimensions u = Point(.1, .2, evaluate=False) u4 = Point(u, dim=4, on_morph='ignore') assert u4.args == (.1, .2, 0, 0) assert all(i.is_Float for i in u4.args[:2]) # and even when *not* changing dimensions assert all(i.is_Float for i in Point(u).args) # never raise error if creating an origin assert Point(dim=3, on_morph='error') # raise error with unmatched dimension raises(ValueError, lambda: Point(1, 1, dim=3, on_morph='error')) # test unknown on_morph raises(ValueError, lambda: Point(1, 1, dim=3, on_morph='unknown')) # test invalid expressions raises(TypeError, lambda: Point(Basic(), Basic())) def test_unit(): assert Point(1, 1).unit == Point(sqrt(2)/2, sqrt(2)/2) def test_dot(): raises(TypeError, lambda: Point(1, 2).dot(Line((0, 0), (1, 1)))) def test__normalize_dimension(): assert Point._normalize_dimension(Point(1, 2), Point(3, 4)) == [ Point(1, 2), Point(3, 4)] assert Point._normalize_dimension( Point(1, 2), Point(3, 4, 0), on_morph='ignore') == [ Point(1, 2, 0), Point(3, 4, 0)] def test_direction_cosine(): p1 = Point3D(0, 0, 0) p2 = Point3D(1, 1, 1) assert p1.direction_cosine(Point3D(1, 0, 0)) == [1, 0, 0] assert p1.direction_cosine(Point3D(0, 1, 0)) == [0, 1, 0] assert p1.direction_cosine(Point3D(0, 0, pi)) == [0, 0, 1] assert p1.direction_cosine(Point3D(5, 0, 0)) == [1, 0, 0] assert p1.direction_cosine(Point3D(0, sqrt(3), 0)) == [0, 1, 0] assert p1.direction_cosine(Point3D(0, 0, 5)) == [0, 0, 1] assert p1.direction_cosine(Point3D(2.4, 2.4, 0)) == [sqrt(2)/2, sqrt(2)/2, 0] assert p1.direction_cosine(Point3D(1, 1, 1)) == [sqrt(3) / 3, sqrt(3) / 3, sqrt(3) / 3] assert p1.direction_cosine(Point3D(-12, 0 -15)) == [-4*sqrt(41)/41, -5*sqrt(41)/41, 0] assert p2.direction_cosine(Point3D(0, 0, 0)) == [-sqrt(3) / 3, -sqrt(3) / 3, -sqrt(3) / 3] assert p2.direction_cosine(Point3D(1, 1, 12)) == [0, 0, 1] assert p2.direction_cosine(Point3D(12, 1, 12)) == [sqrt(2) / 2, 0, sqrt(2) / 2]
63e973d9d7f03f2269161da2904cb379654c41abab68ae8e755954dfa63e9fde
from sympy import Symbol, Rational from sympy.geometry import Circle, Ellipse, Line, Point, Polygon, Ray, RegularPolygon, Segment, Triangle from sympy.geometry.entity import scale, GeometryEntity from sympy.testing.pytest import raises from random import random def test_entity(): x = Symbol('x', real=True) y = Symbol('y', real=True) assert GeometryEntity(x, y) in GeometryEntity(x, y) raises(NotImplementedError, lambda: Point(0, 0) in GeometryEntity(x, y)) assert GeometryEntity(x, y) == GeometryEntity(x, y) assert GeometryEntity(x, y).equals(GeometryEntity(x, y)) c = Circle((0, 0), 5) assert GeometryEntity.encloses(c, Point(0, 0)) assert GeometryEntity.encloses(c, Segment((0, 0), (1, 1))) assert GeometryEntity.encloses(c, Line((0, 0), (1, 1))) is False assert GeometryEntity.encloses(c, Circle((0, 0), 4)) assert GeometryEntity.encloses(c, Polygon(Point(0, 0), Point(1, 0), Point(0, 1))) assert GeometryEntity.encloses(c, RegularPolygon(Point(8, 8), 1, 3)) is False def test_subs(): x = Symbol('x', real=True) y = Symbol('y', real=True) p = Point(x, 2) q = Point(1, 1) r = Point(3, 4) for o in [p, Segment(p, q), Ray(p, q), Line(p, q), Triangle(p, q, r), RegularPolygon(p, 3, 6), Polygon(p, q, r, Point(5, 4)), Circle(p, 3), Ellipse(p, 3, 4)]: assert 'y' in str(o.subs(x, y)) assert p.subs({x: 1}) == Point(1, 2) assert Point(1, 2).subs(Point(1, 2), Point(3, 4)) == Point(3, 4) assert Point(1, 2).subs((1, 2), Point(3, 4)) == Point(3, 4) assert Point(1, 2).subs(Point(1, 2), Point(3, 4)) == Point(3, 4) assert Point(1, 2).subs({(1, 2)}) == Point(2, 2) raises(ValueError, lambda: Point(1, 2).subs(1)) raises(ValueError, lambda: Point(1, 1).subs((Point(1, 1), Point(1, 2)), 1, 2)) def test_transform(): assert scale(1, 2, (3, 4)).tolist() == \ [[1, 0, 0], [0, 2, 0], [0, -4, 1]] def test_reflect_entity_overrides(): x = Symbol('x', real=True) y = Symbol('y', real=True) b = Symbol('b') m = Symbol('m') l = Line((0, b), slope=m) p = Point(x, y) r = p.reflect(l) c = Circle((x, y), 3) cr = c.reflect(l) assert cr == Circle(r, -3) assert c.area == -cr.area pent = RegularPolygon((1, 2), 1, 5) l = Line(pent.vertices[1], slope=Rational(random() - .5, random() - .5)) rpent = pent.reflect(l) assert rpent.center == pent.center.reflect(l) rvert = [i.reflect(l) for i in pent.vertices] for v in rpent.vertices: for i in range(len(rvert)): ri = rvert[i] if ri.equals(v): rvert.remove(ri) break assert not rvert assert pent.area.equals(-rpent.area)
bd6131abd35f7b430a624b50a31f8c511eaf148dc79887a58f684acaaf28a56a
from sympy import (Abs, Rational, Float, S, Symbol, symbols, cos, sin, pi, sqrt, \ oo, acos) from sympy.functions.elementary.trigonometric import tan from sympy.geometry import (Circle, Ellipse, GeometryError, Point, Point2D, \ Polygon, Ray, RegularPolygon, Segment, Triangle, \ are_similar, convex_hull, intersection, Line, Ray2D) from sympy.testing.pytest import raises, slow, warns from sympy.testing.randtest import verify_numerically from sympy.geometry.polygon import rad, deg from sympy import integrate def feq(a, b): """Test if two floating point values are 'equal'.""" t_float = Float("1.0E-10") return -t_float < a - b < t_float @slow def test_polygon(): x = Symbol('x', real=True) y = Symbol('y', real=True) q = Symbol('q', real=True) u = Symbol('u', real=True) v = Symbol('v', real=True) w = Symbol('w', real=True) x1 = Symbol('x1', real=True) half = S.Half a, b, c = Point(0, 0), Point(2, 0), Point(3, 3) t = Triangle(a, b, c) assert Polygon(Point(0, 0)) == Point(0, 0) assert Polygon(a, Point(1, 0), b, c) == t assert Polygon(Point(1, 0), b, c, a) == t assert Polygon(b, c, a, Point(1, 0)) == t # 2 "remove folded" tests assert Polygon(a, Point(3, 0), b, c) == t assert Polygon(a, b, Point(3, -1), b, c) == t # remove multiple collinear points assert Polygon(Point(-4, 15), Point(-11, 15), Point(-15, 15), Point(-15, 33/5), Point(-15, -87/10), Point(-15, -15), Point(-42/5, -15), Point(-2, -15), Point(7, -15), Point(15, -15), Point(15, -3), Point(15, 10), Point(15, 15)) == \ Polygon(Point(-15, -15), Point(15, -15), Point(15, 15), Point(-15, 15)) p1 = Polygon( Point(0, 0), Point(3, -1), Point(6, 0), Point(4, 5), Point(2, 3), Point(0, 3)) p2 = Polygon( Point(6, 0), Point(3, -1), Point(0, 0), Point(0, 3), Point(2, 3), Point(4, 5)) p3 = Polygon( Point(0, 0), Point(3, 0), Point(5, 2), Point(4, 4)) p4 = Polygon( Point(0, 0), Point(4, 4), Point(5, 2), Point(3, 0)) p5 = Polygon( Point(0, 0), Point(4, 4), Point(0, 4)) p6 = Polygon( Point(-11, 1), Point(-9, 6.6), Point(-4, -3), Point(-8.4, -8.7)) p7 = Polygon( Point(x, y), Point(q, u), Point(v, w)) p8 = Polygon( Point(x, y), Point(v, w), Point(q, u)) p9 = Polygon( Point(0, 0), Point(4, 4), Point(3, 0), Point(5, 2)) p10 = Polygon( Point(0, 2), Point(2, 2), Point(0, 0), Point(2, 0)) p11 = Polygon(Point(0, 0), 1, n=3) p12 = Polygon(Point(0, 0), 1, 0, n=3) r = Ray(Point(-9, 6.6), Point(-9, 5.5)) # # General polygon # assert p1 == p2 assert len(p1.args) == 6 assert len(p1.sides) == 6 assert p1.perimeter == 5 + 2*sqrt(10) + sqrt(29) + sqrt(8) assert p1.area == 22 assert not p1.is_convex() assert Polygon((-1, 1), (2, -1), (2, 1), (-1, -1), (3, 0) ).is_convex() is False # ensure convex for both CW and CCW point specification assert p3.is_convex() assert p4.is_convex() dict5 = p5.angles assert dict5[Point(0, 0)] == pi / 4 assert dict5[Point(0, 4)] == pi / 2 assert p5.encloses_point(Point(x, y)) is None assert p5.encloses_point(Point(1, 3)) assert p5.encloses_point(Point(0, 0)) is False assert p5.encloses_point(Point(4, 0)) is False assert p1.encloses(Circle(Point(2.5, 2.5), 5)) is False assert p1.encloses(Ellipse(Point(2.5, 2), 5, 6)) is False p5.plot_interval('x') == [x, 0, 1] assert p5.distance( Polygon(Point(10, 10), Point(14, 14), Point(10, 14))) == 6 * sqrt(2) assert p5.distance( Polygon(Point(1, 8), Point(5, 8), Point(8, 12), Point(1, 12))) == 4 with warns(UserWarning, \ match="Polygons may intersect producing erroneous output"): Polygon(Point(0, 0), Point(1, 0), Point(1, 1)).distance( Polygon(Point(0, 0), Point(0, 1), Point(1, 1))) assert hash(p5) == hash(Polygon(Point(0, 0), Point(4, 4), Point(0, 4))) assert hash(p1) == hash(p2) assert hash(p7) == hash(p8) assert hash(p3) != hash(p9) assert p5 == Polygon(Point(4, 4), Point(0, 4), Point(0, 0)) assert Polygon(Point(4, 4), Point(0, 4), Point(0, 0)) in p5 assert p5 != Point(0, 4) assert Point(0, 1) in p5 assert p5.arbitrary_point('t').subs(Symbol('t', real=True), 0) == \ Point(0, 0) raises(ValueError, lambda: Polygon( Point(x, 0), Point(0, y), Point(x, y)).arbitrary_point('x')) assert p6.intersection(r) == [Point(-9, Rational(-84, 13)), Point(-9, Rational(33, 5))] assert p10.area == 0 assert p11 == RegularPolygon(Point(0, 0), 1, 3, 0) assert p11 == p12 assert p11.vertices[0] == Point(1, 0) assert p11.args[0] == Point(0, 0) p11.spin(pi/2) assert p11.vertices[0] == Point(0, 1) # # Regular polygon # p1 = RegularPolygon(Point(0, 0), 10, 5) p2 = RegularPolygon(Point(0, 0), 5, 5) raises(GeometryError, lambda: RegularPolygon(Point(0, 0), Point(0, 1), Point(1, 1))) raises(GeometryError, lambda: RegularPolygon(Point(0, 0), 1, 2)) raises(ValueError, lambda: RegularPolygon(Point(0, 0), 1, 2.5)) assert p1 != p2 assert p1.interior_angle == pi*Rational(3, 5) assert p1.exterior_angle == pi*Rational(2, 5) assert p2.apothem == 5*cos(pi/5) assert p2.circumcenter == p1.circumcenter == Point(0, 0) assert p1.circumradius == p1.radius == 10 assert p2.circumcircle == Circle(Point(0, 0), 5) assert p2.incircle == Circle(Point(0, 0), p2.apothem) assert p2.inradius == p2.apothem == (5 * (1 + sqrt(5)) / 4) p2.spin(pi / 10) dict1 = p2.angles assert dict1[Point(0, 5)] == 3 * pi / 5 assert p1.is_convex() assert p1.rotation == 0 assert p1.encloses_point(Point(0, 0)) assert p1.encloses_point(Point(11, 0)) is False assert p2.encloses_point(Point(0, 4.9)) p1.spin(pi/3) assert p1.rotation == pi/3 assert p1.vertices[0] == Point(5, 5*sqrt(3)) for var in p1.args: if isinstance(var, Point): assert var == Point(0, 0) else: assert var == 5 or var == 10 or var == pi / 3 assert p1 != Point(0, 0) assert p1 != p5 # while spin works in place (notice that rotation is 2pi/3 below) # rotate returns a new object p1_old = p1 assert p1.rotate(pi/3) == RegularPolygon(Point(0, 0), 10, 5, pi*Rational(2, 3)) assert p1 == p1_old assert p1.area == (-250*sqrt(5) + 1250)/(4*tan(pi/5)) assert p1.length == 20*sqrt(-sqrt(5)/8 + Rational(5, 8)) assert p1.scale(2, 2) == \ RegularPolygon(p1.center, p1.radius*2, p1._n, p1.rotation) assert RegularPolygon((0, 0), 1, 4).scale(2, 3) == \ Polygon(Point(2, 0), Point(0, 3), Point(-2, 0), Point(0, -3)) assert repr(p1) == str(p1) # # Angles # angles = p4.angles assert feq(angles[Point(0, 0)].evalf(), Float("0.7853981633974483")) assert feq(angles[Point(4, 4)].evalf(), Float("1.2490457723982544")) assert feq(angles[Point(5, 2)].evalf(), Float("1.8925468811915388")) assert feq(angles[Point(3, 0)].evalf(), Float("2.3561944901923449")) angles = p3.angles assert feq(angles[Point(0, 0)].evalf(), Float("0.7853981633974483")) assert feq(angles[Point(4, 4)].evalf(), Float("1.2490457723982544")) assert feq(angles[Point(5, 2)].evalf(), Float("1.8925468811915388")) assert feq(angles[Point(3, 0)].evalf(), Float("2.3561944901923449")) # # Triangle # p1 = Point(0, 0) p2 = Point(5, 0) p3 = Point(0, 5) t1 = Triangle(p1, p2, p3) t2 = Triangle(p1, p2, Point(Rational(5, 2), sqrt(Rational(75, 4)))) t3 = Triangle(p1, Point(x1, 0), Point(0, x1)) s1 = t1.sides assert Triangle(p1, p2, p1) == Polygon(p1, p2, p1) == Segment(p1, p2) raises(GeometryError, lambda: Triangle(Point(0, 0))) # Basic stuff assert Triangle(p1, p1, p1) == p1 assert Triangle(p2, p2*2, p2*3) == Segment(p2, p2*3) assert t1.area == Rational(25, 2) assert t1.is_right() assert t2.is_right() is False assert t3.is_right() assert p1 in t1 assert t1.sides[0] in t1 assert Segment((0, 0), (1, 0)) in t1 assert Point(5, 5) not in t2 assert t1.is_convex() assert feq(t1.angles[p1].evalf(), pi.evalf()/2) assert t1.is_equilateral() is False assert t2.is_equilateral() assert t3.is_equilateral() is False assert are_similar(t1, t2) is False assert are_similar(t1, t3) assert are_similar(t2, t3) is False assert t1.is_similar(Point(0, 0)) is False assert t1.is_similar(t2) is False # Bisectors bisectors = t1.bisectors() assert bisectors[p1] == Segment( p1, Point(Rational(5, 2), Rational(5, 2))) assert t2.bisectors()[p2] == Segment( Point(5, 0), Point(Rational(5, 4), 5*sqrt(3)/4)) p4 = Point(0, x1) assert t3.bisectors()[p4] == Segment(p4, Point(x1*(sqrt(2) - 1), 0)) ic = (250 - 125*sqrt(2))/50 assert t1.incenter == Point(ic, ic) # Inradius assert t1.inradius == t1.incircle.radius == 5 - 5*sqrt(2)/2 assert t2.inradius == t2.incircle.radius == 5*sqrt(3)/6 assert t3.inradius == t3.incircle.radius == x1**2/((2 + sqrt(2))*Abs(x1)) # Exradius assert t1.exradii[t1.sides[2]] == 5*sqrt(2)/2 # Excenters assert t1.excenters[t1.sides[2]] == Point2D(25*sqrt(2), -5*sqrt(2)/2) # Circumcircle assert t1.circumcircle.center == Point(2.5, 2.5) # Medians + Centroid m = t1.medians assert t1.centroid == Point(Rational(5, 3), Rational(5, 3)) assert m[p1] == Segment(p1, Point(Rational(5, 2), Rational(5, 2))) assert t3.medians[p1] == Segment(p1, Point(x1/2, x1/2)) assert intersection(m[p1], m[p2], m[p3]) == [t1.centroid] assert t1.medial == Triangle(Point(2.5, 0), Point(0, 2.5), Point(2.5, 2.5)) # Nine-point circle assert t1.nine_point_circle == Circle(Point(2.5, 0), Point(0, 2.5), Point(2.5, 2.5)) assert t1.nine_point_circle == Circle(Point(0, 0), Point(0, 2.5), Point(2.5, 2.5)) # Perpendicular altitudes = t1.altitudes assert altitudes[p1] == Segment(p1, Point(Rational(5, 2), Rational(5, 2))) assert altitudes[p2].equals(s1[0]) assert altitudes[p3] == s1[2] assert t1.orthocenter == p1 t = S('''Triangle( Point(100080156402737/5000000000000, 79782624633431/500000000000), Point(39223884078253/2000000000000, 156345163124289/1000000000000), Point(31241359188437/1250000000000, 338338270939941/1000000000000000))''') assert t.orthocenter == S('''Point(-780660869050599840216997''' '''79471538701955848721853/80368430960602242240789074233100000000000000,''' '''20151573611150265741278060334545897615974257/16073686192120448448157''' '''8148466200000000000)''') # Ensure assert len(intersection(*bisectors.values())) == 1 assert len(intersection(*altitudes.values())) == 1 assert len(intersection(*m.values())) == 1 # Distance p1 = Polygon( Point(0, 0), Point(1, 0), Point(1, 1), Point(0, 1)) p2 = Polygon( Point(0, Rational(5)/4), Point(1, Rational(5)/4), Point(1, Rational(9)/4), Point(0, Rational(9)/4)) p3 = Polygon( Point(1, 2), Point(2, 2), Point(2, 1)) p4 = Polygon( Point(1, 1), Point(Rational(6)/5, 1), Point(1, Rational(6)/5)) pt1 = Point(half, half) pt2 = Point(1, 1) '''Polygon to Point''' assert p1.distance(pt1) == half assert p1.distance(pt2) == 0 assert p2.distance(pt1) == Rational(3)/4 assert p3.distance(pt2) == sqrt(2)/2 '''Polygon to Polygon''' # p1.distance(p2) emits a warning with warns(UserWarning, \ match="Polygons may intersect producing erroneous output"): assert p1.distance(p2) == half/2 assert p1.distance(p3) == sqrt(2)/2 # p3.distance(p4) emits a warning with warns(UserWarning, \ match="Polygons may intersect producing erroneous output"): assert p3.distance(p4) == (sqrt(2)/2 - sqrt(Rational(2)/25)/2) def test_convex_hull(): p = [Point(-5, -1), Point(-2, 1), Point(-2, -1), Point(-1, -3), \ Point(0, 0), Point(1, 1), Point(2, 2), Point(2, -1), Point(3, 1), \ Point(4, -1), Point(6, 2)] ch = Polygon(p[0], p[3], p[9], p[10], p[6], p[1]) #test handling of duplicate points p.append(p[3]) #more than 3 collinear points another_p = [Point(-45, -85), Point(-45, 85), Point(-45, 26), \ Point(-45, -24)] ch2 = Segment(another_p[0], another_p[1]) assert convex_hull(*another_p) == ch2 assert convex_hull(*p) == ch assert convex_hull(p[0]) == p[0] assert convex_hull(p[0], p[1]) == Segment(p[0], p[1]) # no unique points assert convex_hull(*[p[-1]]*3) == p[-1] # collection of items assert convex_hull(*[Point(0, 0), \ Segment(Point(1, 0), Point(1, 1)), \ RegularPolygon(Point(2, 0), 2, 4)]) == \ Polygon(Point(0, 0), Point(2, -2), Point(4, 0), Point(2, 2)) def test_encloses(): # square with a dimpled left side s = Polygon(Point(0, 0), Point(1, 0), Point(1, 1), Point(0, 1), \ Point(S.Half, S.Half)) # the following is True if the polygon isn't treated as closing on itself assert s.encloses(Point(0, S.Half)) is False assert s.encloses(Point(S.Half, S.Half)) is False # it's a vertex assert s.encloses(Point(Rational(3, 4), S.Half)) is True def test_triangle_kwargs(): assert Triangle(sss=(3, 4, 5)) == \ Triangle(Point(0, 0), Point(3, 0), Point(3, 4)) assert Triangle(asa=(30, 2, 30)) == \ Triangle(Point(0, 0), Point(2, 0), Point(1, sqrt(3)/3)) assert Triangle(sas=(1, 45, 2)) == \ Triangle(Point(0, 0), Point(2, 0), Point(sqrt(2)/2, sqrt(2)/2)) assert Triangle(sss=(1, 2, 5)) is None assert deg(rad(180)) == 180 def test_transform(): pts = [Point(0, 0), Point(S.Half, Rational(1, 4)), Point(1, 1)] pts_out = [Point(-4, -10), Point(-3, Rational(-37, 4)), Point(-2, -7)] assert Triangle(*pts).scale(2, 3, (4, 5)) == Triangle(*pts_out) assert RegularPolygon((0, 0), 1, 4).scale(2, 3, (4, 5)) == \ Polygon(Point(-2, -10), Point(-4, -7), Point(-6, -10), Point(-4, -13)) # Checks for symmetric scaling assert RegularPolygon((0, 0), 1, 4).scale(2, 2) == \ RegularPolygon(Point2D(0, 0), 2, 4, 0) def test_reflect(): x = Symbol('x', real=True) y = Symbol('y', real=True) b = Symbol('b') m = Symbol('m') l = Line((0, b), slope=m) p = Point(x, y) r = p.reflect(l) dp = l.perpendicular_segment(p).length dr = l.perpendicular_segment(r).length assert verify_numerically(dp, dr) assert Polygon((1, 0), (2, 0), (2, 2)).reflect(Line((3, 0), slope=oo)) \ == Triangle(Point(5, 0), Point(4, 0), Point(4, 2)) assert Polygon((1, 0), (2, 0), (2, 2)).reflect(Line((0, 3), slope=oo)) \ == Triangle(Point(-1, 0), Point(-2, 0), Point(-2, 2)) assert Polygon((1, 0), (2, 0), (2, 2)).reflect(Line((0, 3), slope=0)) \ == Triangle(Point(1, 6), Point(2, 6), Point(2, 4)) assert Polygon((1, 0), (2, 0), (2, 2)).reflect(Line((3, 0), slope=0)) \ == Triangle(Point(1, 0), Point(2, 0), Point(2, -2)) def test_bisectors(): p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1) p = Polygon(Point(0, 0), Point(2, 0), Point(1, 1), Point(0, 3)) q = Polygon(Point(1, 0), Point(2, 0), Point(3, 3), Point(-1, 5)) poly = Polygon(Point(3, 4), Point(0, 0), Point(8, 7), Point(-1, 1), Point(19, -19)) t = Triangle(p1, p2, p3) assert t.bisectors()[p2] == Segment(Point(1, 0), Point(0, sqrt(2) - 1)) assert p.bisectors()[Point2D(0, 3)] == Ray2D(Point2D(0, 3), \ Point2D(sin(acos(2*sqrt(5)/5)/2), 3 - cos(acos(2*sqrt(5)/5)/2))) assert q.bisectors()[Point2D(-1, 5)] == \ Ray2D(Point2D(-1, 5), Point2D(-1 + sqrt(29)*(5*sin(acos(9*sqrt(145)/145)/2) + \ 2*cos(acos(9*sqrt(145)/145)/2))/29, sqrt(29)*(-5*cos(acos(9*sqrt(145)/145)/2) + \ 2*sin(acos(9*sqrt(145)/145)/2))/29 + 5)) assert poly.bisectors()[Point2D(-1, 1)] == Ray2D(Point2D(-1, 1), \ Point2D(-1 + sin(acos(sqrt(26)/26)/2 + pi/4), 1 - sin(-acos(sqrt(26)/26)/2 + pi/4))) def test_incenter(): assert Triangle(Point(0, 0), Point(1, 0), Point(0, 1)).incenter \ == Point(1 - sqrt(2)/2, 1 - sqrt(2)/2) def test_inradius(): assert Triangle(Point(0, 0), Point(4, 0), Point(0, 3)).inradius == 1 def test_incircle(): assert Triangle(Point(0, 0), Point(2, 0), Point(0, 2)).incircle \ == Circle(Point(2 - sqrt(2), 2 - sqrt(2)), 2 - sqrt(2)) def test_exradii(): t = Triangle(Point(0, 0), Point(6, 0), Point(0, 2)) assert t.exradii[t.sides[2]] == (-2 + sqrt(10)) def test_medians(): t = Triangle(Point(0, 0), Point(1, 0), Point(0, 1)) assert t.medians[Point(0, 0)] == Segment(Point(0, 0), Point(S.Half, S.Half)) def test_medial(): assert Triangle(Point(0, 0), Point(1, 0), Point(0, 1)).medial \ == Triangle(Point(S.Half, 0), Point(S.Half, S.Half), Point(0, S.Half)) def test_nine_point_circle(): assert Triangle(Point(0, 0), Point(1, 0), Point(0, 1)).nine_point_circle \ == Circle(Point2D(Rational(1, 4), Rational(1, 4)), sqrt(2)/4) def test_eulerline(): assert Triangle(Point(0, 0), Point(1, 0), Point(0, 1)).eulerline \ == Line(Point2D(0, 0), Point2D(S.Half, S.Half)) assert Triangle(Point(0, 0), Point(10, 0), Point(5, 5*sqrt(3))).eulerline \ == Point2D(5, 5*sqrt(3)/3) assert Triangle(Point(4, -6), Point(4, -1), Point(-3, 3)).eulerline \ == Line(Point2D(Rational(64, 7), 3), Point2D(Rational(-29, 14), Rational(-7, 2))) def test_intersection(): poly1 = Triangle(Point(0, 0), Point(1, 0), Point(0, 1)) poly2 = Polygon(Point(0, 1), Point(-5, 0), Point(0, -4), Point(0, Rational(1, 5)), Point(S.Half, -0.1), Point(1, 0), Point(0, 1)) assert poly1.intersection(poly2) == [Point2D(Rational(1, 3), 0), Segment(Point(0, Rational(1, 5)), Point(0, 0)), Segment(Point(1, 0), Point(0, 1))] assert poly2.intersection(poly1) == [Point(Rational(1, 3), 0), Segment(Point(0, 0), Point(0, Rational(1, 5))), Segment(Point(1, 0), Point(0, 1))] assert poly1.intersection(Point(0, 0)) == [Point(0, 0)] assert poly1.intersection(Point(-12, -43)) == [] assert poly2.intersection(Line((-12, 0), (12, 0))) == [Point(-5, 0), Point(0, 0), Point(Rational(1, 3), 0), Point(1, 0)] assert poly2.intersection(Line((-12, 12), (12, 12))) == [] assert poly2.intersection(Ray((-3, 4), (1, 0))) == [Segment(Point(1, 0), Point(0, 1))] assert poly2.intersection(Circle((0, -1), 1)) == [Point(0, -2), Point(0, 0)] assert poly1.intersection(poly1) == [Segment(Point(0, 0), Point(1, 0)), Segment(Point(0, 1), Point(0, 0)), Segment(Point(1, 0), Point(0, 1))] assert poly2.intersection(poly2) == [Segment(Point(-5, 0), Point(0, -4)), Segment(Point(0, -4), Point(0, Rational(1, 5))), Segment(Point(0, Rational(1, 5)), Point(S.Half, Rational(-1, 10))), Segment(Point(0, 1), Point(-5, 0)), Segment(Point(S.Half, Rational(-1, 10)), Point(1, 0)), Segment(Point(1, 0), Point(0, 1))] assert poly2.intersection(Triangle(Point(0, 1), Point(1, 0), Point(-1, 1))) \ == [Point(Rational(-5, 7), Rational(6, 7)), Segment(Point2D(0, 1), Point(1, 0))] assert poly1.intersection(RegularPolygon((-12, -15), 3, 3)) == [] def test_parameter_value(): t = Symbol('t') sq = Polygon((0, 0), (0, 1), (1, 1), (1, 0)) assert sq.parameter_value((0.5, 1), t) == {t: Rational(3, 8)} q = Polygon((0, 0), (2, 1), (2, 4), (4, 0)) assert q.parameter_value((4, 0), t) == {t: -6 + 3*sqrt(5)} # ~= 0.708 raises(ValueError, lambda: sq.parameter_value((5, 6), t)) raises(ValueError, lambda: sq.parameter_value(Circle(Point(0, 0), 1), t)) def test_issue_12966(): poly = Polygon(Point(0, 0), Point(0, 10), Point(5, 10), Point(5, 5), Point(10, 5), Point(10, 0)) t = Symbol('t') pt = poly.arbitrary_point(t) DELTA = 5/poly.perimeter assert [pt.subs(t, DELTA*i) for i in range(int(1/DELTA))] == [ Point(0, 0), Point(0, 5), Point(0, 10), Point(5, 10), Point(5, 5), Point(10, 5), Point(10, 0), Point(5, 0)] def test_second_moment_of_area(): x, y = symbols('x, y') # triangle p1, p2, p3 = [(0, 0), (4, 0), (0, 2)] p = (0, 0) # equation of hypotenuse eq_y = (1-x/4)*2 I_yy = integrate((x**2) * (integrate(1, (y, 0, eq_y))), (x, 0, 4)) I_xx = integrate(1 * (integrate(y**2, (y, 0, eq_y))), (x, 0, 4)) I_xy = integrate(x * (integrate(y, (y, 0, eq_y))), (x, 0, 4)) triangle = Polygon(p1, p2, p3) assert (I_xx - triangle.second_moment_of_area(p)[0]) == 0 assert (I_yy - triangle.second_moment_of_area(p)[1]) == 0 assert (I_xy - triangle.second_moment_of_area(p)[2]) == 0 # rectangle p1, p2, p3, p4=[(0, 0), (4, 0), (4, 2), (0, 2)] I_yy = integrate((x**2) * integrate(1, (y, 0, 2)), (x, 0, 4)) I_xx = integrate(1 * integrate(y**2, (y, 0, 2)), (x, 0, 4)) I_xy = integrate(x * integrate(y, (y, 0, 2)), (x, 0, 4)) rectangle = Polygon(p1, p2, p3, p4) assert (I_xx - rectangle.second_moment_of_area(p)[0]) == 0 assert (I_yy - rectangle.second_moment_of_area(p)[1]) == 0 assert (I_xy - rectangle.second_moment_of_area(p)[2]) == 0 r = RegularPolygon(Point(0, 0), 5, 3) assert r.second_moment_of_area() == (1875*sqrt(3)/S(32), 1875*sqrt(3)/S(32), 0) def test_first_moment(): a, b = symbols('a, b', positive=True) # rectangle p1 = Polygon((0, 0), (a, 0), (a, b), (0, b)) assert p1.first_moment_of_area() == (a*b**2/8, a**2*b/8) assert p1.first_moment_of_area((a/3, b/4)) == (-3*a*b**2/32, -a**2*b/9) p1 = Polygon((0, 0), (40, 0), (40, 30), (0, 30)) assert p1.first_moment_of_area() == (4500, 6000) # triangle p2 = Polygon((0, 0), (a, 0), (a/2, b)) assert p2.first_moment_of_area() == (4*a*b**2/81, a**2*b/24) assert p2.first_moment_of_area((a/8, b/6)) == (-25*a*b**2/648, -5*a**2*b/768) p2 = Polygon((0, 0), (12, 0), (12, 30)) p2.first_moment_of_area() == (1600/3, -640/3) def test_section_modulus_and_polar_second_moment_of_area(): a, b = symbols('a, b', positive=True) x, y = symbols('x, y') rectangle = Polygon((0, b), (0, 0), (a, 0), (a, b)) assert rectangle.section_modulus(Point(x, y)) == (a*b**3/12/(-b/2 + y), a**3*b/12/(-a/2 + x)) assert rectangle.polar_second_moment_of_area() == a**3*b/12 + a*b**3/12 convex = RegularPolygon((0, 0), 1, 6) assert convex.section_modulus() == (Rational(5, 8), sqrt(3)*Rational(5, 16)) assert convex.polar_second_moment_of_area() == 5*sqrt(3)/S(8) concave = Polygon((0, 0), (1, 8), (3, 4), (4, 6), (7, 1)) assert concave.section_modulus() == (Rational(-6371, 429), Rational(-9778, 519)) assert concave.polar_second_moment_of_area() == Rational(-38669, 252) def test_cut_section(): # concave polygon p = Polygon((-1, -1), (1, Rational(5, 2)), (2, 1), (3, Rational(5, 2)), (4, 2), (5, 3), (-1, 3)) l = Line((0, 0), (Rational(9, 2), 3)) p1 = p.cut_section(l)[0] p2 = p.cut_section(l)[1] assert p1 == Polygon( Point2D(Rational(-9, 13), Rational(-6, 13)), Point2D(1, Rational(5, 2)), Point2D(Rational(24, 13), Rational(16, 13)), Point2D(Rational(12, 5), Rational(8, 5)), Point2D(3, Rational(5, 2)), Point2D(Rational(24, 7), Rational(16, 7)), Point2D(Rational(9, 2), 3), Point2D(-1, 3), Point2D(-1, Rational(-2, 3))) assert p2 == Polygon(Point2D(-1, -1), Point2D(Rational(-9, 13), Rational(-6, 13)), Point2D(Rational(24, 13), Rational(16, 13)), Point2D(2, 1), Point2D(Rational(12, 5), Rational(8, 5)), Point2D(Rational(24, 7), Rational(16, 7)), Point2D(4, 2), Point2D(5, 3), Point2D(Rational(9, 2), 3), Point2D(-1, Rational(-2, 3))) # convex polygon p = RegularPolygon(Point2D(0, 0), 6, 6) s = p.cut_section(Line((0, 0), slope=1)) assert s[0] == Polygon(Point2D(-3*sqrt(3) + 9, -3*sqrt(3) + 9), Point2D(3, 3*sqrt(3)), Point2D(-3, 3*sqrt(3)), Point2D(-6, 0), Point2D(-9 + 3*sqrt(3), -9 + 3*sqrt(3))) assert s[1] == Polygon(Point2D(6, 0), Point2D(-3*sqrt(3) + 9, -3*sqrt(3) + 9), Point2D(-9 + 3*sqrt(3), -9 + 3*sqrt(3)), Point2D(-3, -3*sqrt(3)), Point2D(3, -3*sqrt(3))) # case where line does not intersects but coincides with the edge of polygon a, b = 20, 10 t1, t2, t3, t4 = [(0, b), (0, 0), (a, 0), (a, b)] p = Polygon(t1, t2, t3, t4) p1, p2 = p.cut_section(Line((0, b), slope=0)) assert p1 == None assert p2 == Polygon(Point2D(0, 10), Point2D(0, 0), Point2D(20, 0), Point2D(20, 10)) p3, p4 = p.cut_section(Line((0, 0), slope=0)) assert p3 == Polygon(Point2D(0, 10), Point2D(0, 0), Point2D(20, 0), Point2D(20, 10)) assert p4 == None # case where the line does not intersect with a polygon at all raises(ValueError, lambda: p.cut_section(Line((0, a), slope=0))) def test_type_of_triangle(): # Isoceles triangle p1 = Polygon(Point(0, 0), Point(5, 0), Point(2, 4)) assert p1.is_isosceles() == True assert p1.is_scalene() == False assert p1.is_equilateral() == False # Scalene triangle p2 = Polygon (Point(0, 0), Point(0, 2), Point(4, 0)) assert p2.is_isosceles() == False assert p2.is_scalene() == True assert p2.is_equilateral() == False # Equilateral triagle p3 = Polygon(Point(0, 0), Point(6, 0), Point(3, sqrt(27))) assert p3.is_isosceles() == True assert p3.is_scalene() == False assert p3.is_equilateral() == True def test_do_poly_distance(): # Non-intersecting polygons square1 = Polygon (Point(0, 0), Point(0, 1), Point(1, 1), Point(1, 0)) triangle1 = Polygon(Point(1, 2), Point(2, 2), Point(2, 1)) assert square1._do_poly_distance(triangle1) == sqrt(2)/2 # Polygons which sides intersect square2 = Polygon(Point(1, 0), Point(2, 0), Point(2, 1), Point(1, 1)) with warns(UserWarning, \ match="Polygons may intersect producing erroneous output"): assert square1._do_poly_distance(square2) == 0 # Polygons which bodies intersect triangle2 = Polygon(Point(0, -1), Point(2, -1), Point(S.Half, S.Half)) with warns(UserWarning, \ match="Polygons may intersect producing erroneous output"): assert triangle2._do_poly_distance(square1) == 0
423980a9e7fb9c48212ae332f1722294ed04c5c4f1718cfc4ef18a23aa312373
from sympy import Rational, oo, sqrt, S from sympy import Line, Point, Point2D, Parabola, Segment2D, Ray2D from sympy import Circle, Ellipse, symbols, sign from sympy.testing.pytest import raises def test_parabola_geom(): a, b = symbols('a b') p1 = Point(0, 0) p2 = Point(3, 7) p3 = Point(0, 4) p4 = Point(6, 0) p5 = Point(a, a) d1 = Line(Point(4, 0), Point(4, 9)) d2 = Line(Point(7, 6), Point(3, 6)) d3 = Line(Point(4, 0), slope=oo) d4 = Line(Point(7, 6), slope=0) d5 = Line(Point(b, a), slope=oo) d6 = Line(Point(a, b), slope=0) half = S.Half pa1 = Parabola(None, d2) pa2 = Parabola(directrix=d1) pa3 = Parabola(p1, d1) pa4 = Parabola(p2, d2) pa5 = Parabola(p2, d4) pa6 = Parabola(p3, d2) pa7 = Parabola(p2, d1) pa8 = Parabola(p4, d1) pa9 = Parabola(p4, d3) pa10 = Parabola(p5, d5) pa11 = Parabola(p5, d6) raises(ValueError, lambda: Parabola(Point(7, 8, 9), Line(Point(6, 7), Point(7, 7)))) raises(NotImplementedError, lambda: Parabola(Point(7, 8), Line(Point(3, 7), Point(2, 9)))) raises(ValueError, lambda: Parabola(Point(0, 2), Line(Point(7, 2), Point(6, 2)))) raises(ValueError, lambda: Parabola(Point(7, 8), Point(3, 8))) # Basic Stuff assert pa1.focus == Point(0, 0) assert pa1.ambient_dimension == S(2) assert pa2 == pa3 assert pa4 != pa7 assert pa6 != pa7 assert pa6.focus == Point2D(0, 4) assert pa6.focal_length == 1 assert pa6.p_parameter == -1 assert pa6.vertex == Point2D(0, 5) assert pa6.eccentricity == 1 assert pa7.focus == Point2D(3, 7) assert pa7.focal_length == half assert pa7.p_parameter == -half assert pa7.vertex == Point2D(7*half, 7) assert pa4.focal_length == half assert pa4.p_parameter == half assert pa4.vertex == Point2D(3, 13*half) assert pa8.focal_length == 1 assert pa8.p_parameter == 1 assert pa8.vertex == Point2D(5, 0) assert pa4.focal_length == pa5.focal_length assert pa4.p_parameter == pa5.p_parameter assert pa4.vertex == pa5.vertex assert pa4.equation() == pa5.equation() assert pa8.focal_length == pa9.focal_length assert pa8.p_parameter == pa9.p_parameter assert pa8.vertex == pa9.vertex assert pa8.equation() == pa9.equation() assert pa10.focal_length == pa11.focal_length == sqrt((a - b) ** 2) / 2 # if a, b real == abs(a - b)/2 assert pa11.vertex == Point(*pa10.vertex[::-1]) == Point(a, a - sqrt((a - b)**2)*sign(a - b)/2) # change axis x->y, y->x on pa10 def test_parabola_intersection(): l1 = Line(Point(1, -2), Point(-1,-2)) l2 = Line(Point(1, 2), Point(-1,2)) l3 = Line(Point(1, 0), Point(-1,0)) p1 = Point(0,0) p2 = Point(0, -2) p3 = Point(120, -12) parabola1 = Parabola(p1, l1) # parabola with parabola assert parabola1.intersection(parabola1) == [parabola1] assert parabola1.intersection(Parabola(p1, l2)) == [Point2D(-2, 0), Point2D(2, 0)] assert parabola1.intersection(Parabola(p2, l3)) == [Point2D(0, -1)] assert parabola1.intersection(Parabola(Point(16, 0), l1)) == [Point2D(8, 15)] assert parabola1.intersection(Parabola(Point(0, 16), l1)) == [Point2D(-6, 8), Point2D(6, 8)] assert parabola1.intersection(Parabola(p3, l3)) == [] # parabola with point assert parabola1.intersection(p1) == [] assert parabola1.intersection(Point2D(0, -1)) == [Point2D(0, -1)] assert parabola1.intersection(Point2D(4, 3)) == [Point2D(4, 3)] # parabola with line assert parabola1.intersection(Line(Point2D(-7, 3), Point(12, 3))) == [Point2D(-4, 3), Point2D(4, 3)] assert parabola1.intersection(Line(Point(-4, -1), Point(4, -1))) == [Point(0, -1)] assert parabola1.intersection(Line(Point(2, 0), Point(0, -2))) == [Point2D(2, 0)] raises(TypeError, lambda: parabola1.intersection(Line(Point(0, 0, 0), Point(1, 1, 1)))) # parabola with segment assert parabola1.intersection(Segment2D((-4, -5), (4, 3))) == [Point2D(0, -1), Point2D(4, 3)] assert parabola1.intersection(Segment2D((0, -5), (0, 6))) == [Point2D(0, -1)] assert parabola1.intersection(Segment2D((-12, -65), (14, -68))) == [] # parabola with ray assert parabola1.intersection(Ray2D((-4, -5), (4, 3))) == [Point2D(0, -1), Point2D(4, 3)] assert parabola1.intersection(Ray2D((0, 7), (1, 14))) == [Point2D(14 + 2*sqrt(57), 105 + 14*sqrt(57))] assert parabola1.intersection(Ray2D((0, 7), (0, 14))) == [] # parabola with ellipse/circle assert parabola1.intersection(Circle(p1, 2)) == [Point2D(-2, 0), Point2D(2, 0)] assert parabola1.intersection(Circle(p2, 1)) == [Point2D(0, -1), Point2D(0, -1)] assert parabola1.intersection(Ellipse(p2, 2, 1)) == [Point2D(0, -1), Point2D(0, -1)] assert parabola1.intersection(Ellipse(Point(0, 19), 5, 7)) == [] assert parabola1.intersection(Ellipse((0, 3), 12, 4)) == \ [Point2D(0, -1), Point2D(0, -1), Point2D(-4*sqrt(17)/3, Rational(59, 9)), Point2D(4*sqrt(17)/3, Rational(59, 9))] # parabola with unsupported type raises(TypeError, lambda: parabola1.intersection(2))
b46bc18c522288a3724e028e369c852febde89cf71c3af1e50bb58a4d4f05b69
from sympy import Symbol, pi, symbols, Tuple, S, sqrt, asinh, Rational from sympy.geometry import Curve, Line, Point, Ellipse, Ray, Segment, Circle, Polygon, RegularPolygon from sympy.testing.pytest import raises, slow def test_curve(): x = Symbol('x', real=True) s = Symbol('s') z = Symbol('z') # this curve is independent of the indicated parameter c = Curve([2*s, s**2], (z, 0, 2)) assert c.parameter == z assert c.functions == (2*s, s**2) assert c.arbitrary_point() == Point(2*s, s**2) assert c.arbitrary_point(z) == Point(2*s, s**2) # this is how it is normally used c = Curve([2*s, s**2], (s, 0, 2)) assert c.parameter == s assert c.functions == (2*s, s**2) t = Symbol('t') # the t returned as assumptions assert c.arbitrary_point() != Point(2*t, t**2) t = Symbol('t', real=True) # now t has the same assumptions so the test passes assert c.arbitrary_point() == Point(2*t, t**2) assert c.arbitrary_point(z) == Point(2*z, z**2) assert c.arbitrary_point(c.parameter) == Point(2*s, s**2) assert c.arbitrary_point(None) == Point(2*s, s**2) assert c.plot_interval() == [t, 0, 2] assert c.plot_interval(z) == [z, 0, 2] assert Curve([x, x], (x, 0, 1)).rotate(pi/2) == Curve([-x, x], (x, 0, 1)) assert Curve([x, x], (x, 0, 1)).rotate(pi/2, (1, 2)).scale(2, 3).translate( 1, 3).arbitrary_point(s) == \ Line((0, 0), (1, 1)).rotate(pi/2, (1, 2)).scale(2, 3).translate( 1, 3).arbitrary_point(s) == \ Point(-2*s + 7, 3*s + 6) raises(ValueError, lambda: Curve((s), (s, 1, 2))) raises(ValueError, lambda: Curve((x, x * 2), (1, x))) raises(ValueError, lambda: Curve((s, s + t), (s, 1, 2)).arbitrary_point()) raises(ValueError, lambda: Curve((s, s + t), (t, 1, 2)).arbitrary_point(s)) @slow def test_free_symbols(): a, b, c, d, e, f, s = symbols('a:f,s') assert Point(a, b).free_symbols == {a, b} assert Line((a, b), (c, d)).free_symbols == {a, b, c, d} assert Ray((a, b), (c, d)).free_symbols == {a, b, c, d} assert Ray((a, b), angle=c).free_symbols == {a, b, c} assert Segment((a, b), (c, d)).free_symbols == {a, b, c, d} assert Line((a, b), slope=c).free_symbols == {a, b, c} assert Curve((a*s, b*s), (s, c, d)).free_symbols == {a, b, c, d} assert Ellipse((a, b), c, d).free_symbols == {a, b, c, d} assert Ellipse((a, b), c, eccentricity=d).free_symbols == \ {a, b, c, d} assert Ellipse((a, b), vradius=c, eccentricity=d).free_symbols == \ {a, b, c, d} assert Circle((a, b), c).free_symbols == {a, b, c} assert Circle((a, b), (c, d), (e, f)).free_symbols == \ {e, d, c, b, f, a} assert Polygon((a, b), (c, d), (e, f)).free_symbols == \ {e, b, d, f, a, c} assert RegularPolygon((a, b), c, d, e).free_symbols == {e, a, b, c, d} def test_transform(): x = Symbol('x', real=True) y = Symbol('y', real=True) c = Curve((x, x**2), (x, 0, 1)) cout = Curve((2*x - 4, 3*x**2 - 10), (x, 0, 1)) pts = [Point(0, 0), Point(S.Half, Rational(1, 4)), Point(1, 1)] pts_out = [Point(-4, -10), Point(-3, Rational(-37, 4)), Point(-2, -7)] assert c.scale(2, 3, (4, 5)) == cout assert [c.subs(x, xi/2) for xi in Tuple(0, 1, 2)] == pts assert [cout.subs(x, xi/2) for xi in Tuple(0, 1, 2)] == pts_out assert Curve((x + y, 3*x), (x, 0, 1)).subs(y, S.Half) == \ Curve((x + S.Half, 3*x), (x, 0, 1)) assert Curve((x, 3*x), (x, 0, 1)).translate(4, 5) == \ Curve((x + 4, 3*x + 5), (x, 0, 1)) def test_length(): t = Symbol('t', real=True) c1 = Curve((t, 0), (t, 0, 1)) assert c1.length == 1 c2 = Curve((t, t), (t, 0, 1)) assert c2.length == sqrt(2) c3 = Curve((t ** 2, t), (t, 2, 5)) assert c3.length == -sqrt(17) - asinh(4) / 4 + asinh(10) / 4 + 5 * sqrt(101) / 2 def test_parameter_value(): t = Symbol('t') C = Curve([2*t, t**2], (t, 0, 2)) assert C.parameter_value((2, 1), t) == {t: 1} raises(ValueError, lambda: C.parameter_value((2, 0), t)) def test_issue_17997(): t, s = symbols('t s') c = Curve((t, t**2), (t, 0, 10)) p = Curve([2*s, s**2], (s, 0, 2)) assert c(2) == Point(2, 4) assert p(1) == Point(2, 1)
2ab6a2570daac4881878c453163b35be4322fa1aaa0e4c5406ff117368309022
"""Used for translating Fortran source code into a SymPy expression. """
9738706fa85a0f369f9b76423098e6b955f8bbd9373512e83a088f6186b77851
from sympy.external import import_module import os cin = import_module('clang.cindex', import_kwargs = {'fromlist': ['cindex']}) """ This module contains all the necessary Classes and Function used to Parse C and C++ code into SymPy expression The module serves as a backend for SymPyExpression to parse C code It is also dependent on Clang's AST and Sympy's Codegen AST. The module only supports the features currently supported by the Clang and codegen AST which will be updated as the development of codegen AST and this module progresses. You might find unexpected bugs and exceptions while using the module, feel free to report them to the SymPy Issue Tracker Features Supported ================== - Variable Declarations (integers and reals) - Assignment (using integer & floating literal and function calls) - Function Definitions nad Declaration - Function Calls - Compound statements, Return statements Notes ===== The module is dependent on an external dependency which needs to be installed to use the features of this module. Clang: The C and C++ compiler which is used to extract an AST from the provided C source code. Refrences ========= .. [1] https://github.com/sympy/sympy/issues .. [2] https://clang.llvm.org/docs/ .. [3] https://clang.llvm.org/docs/IntroductionToTheClangAST.html """ if cin: from sympy.codegen.ast import (Variable, Integer, Float, FunctionPrototype, FunctionDefinition, FunctionCall, none, Return, Assignment, intc, int8, int16, int64, uint8, uint16, uint32, uint64, float32, float64, float80, aug_assign, bool_, While, CodeBlock) from sympy.codegen.cnodes import (PreDecrement, PostDecrement, PreIncrement, PostIncrement) from sympy.core import Add, Mod, Mul, Pow, Rel from sympy.logic.boolalg import And, as_Boolean, Not, Or from sympy import Symbol, sympify, true, false import sys import tempfile class BaseParser: """Base Class for the C parser""" def __init__(self): """Initializes the Base parser creating a Clang AST index""" self.index = cin.Index.create() def diagnostics(self, out): """Diagostics function for the Clang AST""" for diag in self.tu.diagnostics: print('%s %s (line %s, col %s) %s' % ( { 4: 'FATAL', 3: 'ERROR', 2: 'WARNING', 1: 'NOTE', 0: 'IGNORED', }[diag.severity], diag.location.file, diag.location.line, diag.location.column, diag.spelling ), file=out) class CCodeConverter(BaseParser): """The Code Convereter for Clang AST The converter object takes the C source code or file as input and converts them to SymPy Expressions. """ def __init__(self): """Initializes the code converter""" super().__init__() self._py_nodes = [] self._data_types = { "void": { cin.TypeKind.VOID: none }, "bool": { cin.TypeKind.BOOL: bool_ }, "int": { cin.TypeKind.SCHAR: int8, cin.TypeKind.SHORT: int16, cin.TypeKind.INT: intc, cin.TypeKind.LONG: int64, cin.TypeKind.UCHAR: uint8, cin.TypeKind.USHORT: uint16, cin.TypeKind.UINT: uint32, cin.TypeKind.ULONG: uint64 }, "float": { cin.TypeKind.FLOAT: float32, cin.TypeKind.DOUBLE: float64, cin.TypeKind.LONGDOUBLE: float80 } } def parse(self, filenames, flags): """Function to parse a file with C source code It takes the filename as an attribute and creates a Clang AST Translation Unit parsing the file. Then the transformation function is called on the transaltion unit, whose reults are collected into a list which is returned by the function. Parameters ========== filenames : string Path to the C file to be parsed flags: list Arguments to be passed to Clang while parsing the C code Returns ======= py_nodes: list A list of sympy AST nodes """ filename = os.path.abspath(filenames) self.tu = self.index.parse( filename, args=flags, options=cin.TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD ) for child in self.tu.cursor.get_children(): if child.kind == cin.CursorKind.VAR_DECL: self._py_nodes.append(self.transform(child)) elif (child.kind == cin.CursorKind.FUNCTION_DECL): self._py_nodes.append(self.transform(child)) else: pass return self._py_nodes def parse_str(self, source, flags): """Function to parse a string with C source code It takes the source code as an attribute, stores it in a temporary file and creates a Clang AST Translation Unit parsing the file. Then the transformation function is called on the transaltion unit, whose reults are collected into a list which is returned by the function. Parameters ========== source : string Path to the C file to be parsed flags: list Arguments to be passed to Clang while parsing the C code Returns ======= py_nodes: list A list of sympy AST nodes """ file = tempfile.NamedTemporaryFile(mode = 'w+', suffix = '.cpp') file.write(source) file.seek(0) self.tu = self.index.parse( file.name, args=flags, options=cin.TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD ) file.close() for child in self.tu.cursor.get_children(): if child.kind == cin.CursorKind.VAR_DECL: self._py_nodes.append(self.transform(child)) elif (child.kind == cin.CursorKind.FUNCTION_DECL): self._py_nodes.append(self.transform(child)) else: pass return self._py_nodes def transform(self, node): """Transformation Function for Clang AST nodes It determines the kind of node and calls the respective transformation function for that node. Raises ====== NotImplementedError : if the transformation for the provided node is not implemented """ try: handler = getattr(self, 'transform_%s' % node.kind.name.lower()) except AttributeError: print( "Ignoring node of type %s (%s)" % ( node.kind, ' '.join( t.spelling for t in node.get_tokens()) ), file=sys.stderr ) handler = None if handler: result = handler(node) return result def transform_var_decl(self, node): """Transformation Function for Variable Declaration Used to create nodes for variable declarations and assignments with values or function call for the respective nodes in the clang AST Returns ======= A variable node as Declaration, with the initial value if given Raises ====== NotImplementedError : if called for data types not currently implemented Notes ===== The function currently supports following data types: Boolean: bool, _Bool Integer: 8-bit: signed char and unsigned char 16-bit: short, short int, signed short, signed short int, unsigned short, unsigned short int 32-bit: int, signed int, unsigned int 64-bit: long, long int, signed long, signed long int, unsigned long, unsigned long int Floating point: Single Precision: float Double Precision: double Extended Precision: long double """ if node.type.kind in self._data_types["int"]: type = self._data_types["int"][node.type.kind] elif node.type.kind in self._data_types["float"]: type = self._data_types["float"][node.type.kind] elif node.type.kind in self._data_types["bool"]: type = self._data_types["bool"][node.type.kind] else: raise NotImplementedError("Only bool, int " "and float are supported") try: children = node.get_children() child = next(children) #ignoring namespace and type details for the variable while child.kind == cin.CursorKind.NAMESPACE_REF: child = next(children) while child.kind == cin.CursorKind.TYPE_REF: child = next(children) val = self.transform(child) supported_rhs = [ cin.CursorKind.INTEGER_LITERAL, cin.CursorKind.FLOATING_LITERAL, cin.CursorKind.UNEXPOSED_EXPR, cin.CursorKind.BINARY_OPERATOR, cin.CursorKind.PAREN_EXPR, cin.CursorKind.UNARY_OPERATOR, cin.CursorKind.CXX_BOOL_LITERAL_EXPR ] if child.kind in supported_rhs: if isinstance(val, str): value = Symbol(val) elif isinstance(val, bool): if node.type.kind in self._data_types["int"]: value = Integer(0) if val == False else Integer(1) elif node.type.kind in self._data_types["float"]: value = Float(0.0) if val == False else Float(1.0) elif node.type.kind in self._data_types["bool"]: value = sympify(val) elif isinstance(val, (Integer, int, Float, float)): if node.type.kind in self._data_types["int"]: value = Integer(val) elif node.type.kind in self._data_types["float"]: value = Float(val) elif node.type.kind in self._data_types["bool"]: value = sympify(bool(val)) else: value = val return Variable( node.spelling ).as_Declaration( type = type, value = value ) elif child.kind == cin.CursorKind.CALL_EXPR: return Variable( node.spelling ).as_Declaration( value = val ) else: raise NotImplementedError("Given " "variable declaration \"{}\" " "is not possible to parse yet!" .format(" ".join( t.spelling for t in node.get_tokens() ) )) except StopIteration: return Variable( node.spelling ).as_Declaration( type = type ) def transform_function_decl(self, node): """Transformation Function For Function Declaration Used to create nodes for function declarations and definitions for the respective nodes in the clang AST Returns ======= function : Codegen AST node - FunctionPrototype node if function body is not present - FunctionDefinition node if the function body is present """ if node.result_type.kind in self._data_types["int"]: ret_type = self._data_types["int"][node.result_type.kind] elif node.result_type.kind in self._data_types["float"]: ret_type = self._data_types["float"][node.result_type.kind] elif node.result_type.kind in self._data_types["bool"]: ret_type = self._data_types["bool"][node.result_type.kind] elif node.result_type.kind in self._data_types["void"]: ret_type = self._data_types["void"][node.result_type.kind] else: raise NotImplementedError("Only void, bool, int " "and float are supported") body = [] param = [] try: children = node.get_children() child = next(children) # If the node has any children, the first children will be the # return type and namespace for the function declaration. These # nodes can be ignored. while child.kind == cin.CursorKind.NAMESPACE_REF: child = next(children) while child.kind == cin.CursorKind.TYPE_REF: child = next(children) # Subsequent nodes will be the parameters for the function. try: while True: decl = self.transform(child) if (child.kind == cin.CursorKind.PARM_DECL): param.append(decl) elif (child.kind == cin.CursorKind.COMPOUND_STMT): for val in decl: body.append(val) else: body.append(decl) child = next(children) except StopIteration: pass except StopIteration: pass if body == []: function = FunctionPrototype( return_type = ret_type, name = node.spelling, parameters = param ) else: function = FunctionDefinition( return_type = ret_type, name = node.spelling, parameters = param, body = body ) return function def transform_parm_decl(self, node): """Transformation function for Parameter Declaration Used to create parameter nodes for the required functions for the respective nodes in the clang AST Returns ======= param : Codegen AST Node Variable node with the value nad type of the variable Raises ====== ValueError if multiple children encountered in the parameter node """ if node.type.kind in self._data_types["int"]: type = self._data_types["int"][node.type.kind] elif node.type.kind in self._data_types["float"]: type = self._data_types["float"][node.type.kind] elif node.type.kind in self._data_types["bool"]: type = self._data_types["bool"][node.type.kind] else: raise NotImplementedError("Only bool, int " "and float are supported") try: children = node.get_children() child = next(children) # Any namespace nodes can be ignored while child.kind in [cin.CursorKind.NAMESPACE_REF, cin.CursorKind.TYPE_REF, cin.CursorKind.TEMPLATE_REF]: child = next(children) # If there is a child, it is the default value of the parameter. lit = self.transform(child) if node.type.kind in self._data_types["int"]: val = Integer(lit) elif node.type.kind in self._data_types["float"]: val = Float(lit) elif node.type.kind in self._data_types["bool"]: val = sympify(bool(lit)) else: raise NotImplementedError("Only bool, int " "and float are supported") param = Variable( node.spelling ).as_Declaration( type = type, value = val ) except StopIteration: param = Variable( node.spelling ).as_Declaration( type = type ) try: self.transform(next(children)) raise ValueError("Can't handle multiple children on parameter") except StopIteration: pass return param def transform_integer_literal(self, node): """Transformation function for integer literal Used to get the value and type of the given integer literal. Returns ======= val : list List with two arguments type and Value type contains the type of the integer value contains the value stored in the variable Notes ===== Only Base Integer type supported for now """ try: value = next(node.get_tokens()).spelling except StopIteration: # No tokens value = node.literal return int(value) def transform_floating_literal(self, node): """Transformation function for floating literal Used to get the value and type of the given floating literal. Returns ======= val : list List with two arguments type and Value type contains the type of float value contains the value stored in the variable Notes ===== Only Base Float type supported for now """ try: value = next(node.get_tokens()).spelling except (StopIteration, ValueError): # No tokens value = node.literal return float(value) def transform_string_literal(self, node): #TODO: No string type in AST #type = #try: # value = next(node.get_tokens()).spelling #except (StopIteration, ValueError): # No tokens # value = node.literal #val = [type, value] #return val pass def transform_character_literal(self, node): """Transformation function for character literal Used to get the value of the given character literal. Returns ======= val : int val contains the ascii value of the character literal Notes ===== Only for cases where character is assigned to a integer value, since character literal is not in sympy AST """ try: value = next(node.get_tokens()).spelling except (StopIteration, ValueError): # No tokens value = node.literal return ord(str(value[1])) def transform_cxx_bool_literal_expr(self, node): """Transformation function for boolean literal Used to get the value of the given boolean literal. Returns ======= value : bool value contains the boolean value of the variable """ try: value = next(node.get_tokens()).spelling except (StopIteration, ValueError): value = node.literal return True if value == 'true' else False def transform_unexposed_decl(self,node): """Transformation function for unexposed declarations""" pass def transform_unexposed_expr(self, node): """Transformation function for unexposed expression Unexposed expressions are used to wrap float, double literals and expressions Returns ======= expr : Codegen AST Node the result from the wrapped expression None : NoneType No childs are found for the node Raises ====== ValueError if the expression contains multiple children """ # Ignore unexposed nodes; pass whatever is the first # (and should be only) child unaltered. try: children = node.get_children() expr = self.transform(next(children)) except StopIteration: return None try: next(children) raise ValueError("Unexposed expression has > 1 children.") except StopIteration: pass return expr def transform_decl_ref_expr(self, node): """Returns the name of the declaration reference""" return node.spelling def transform_call_expr(self, node): """Transformation function for a call expression Used to create function call nodes for the function calls present in the C code Returns ======= FunctionCall : Codegen AST Node FunctionCall node with parameters if any parameters are present """ param = [] children = node.get_children() child = next(children) while child.kind == cin.CursorKind.NAMESPACE_REF: child = next(children) while child.kind == cin.CursorKind.TYPE_REF: child = next(children) first_child = self.transform(child) try: for child in children: arg = self.transform(child) if (child.kind == cin.CursorKind.INTEGER_LITERAL): param.append(Integer(arg)) elif (child.kind == cin.CursorKind.FLOATING_LITERAL): param.append(Float(arg)) else: param.append(arg) return FunctionCall(first_child, param) except StopIteration: return FunctionCall(first_child) def transform_return_stmt(self, node): """Returns the Return Node for a return statement""" return Return(next(node.get_children()).spelling) def transform_compound_stmt(self, node): """Transformation function for compond statemets Returns ======= expr : list list of Nodes for the expressions present in the statement None : NoneType if the compound statement is empty """ try: expr = [] children = node.get_children() for child in children: expr.append(self.transform(child)) except StopIteration: return None return expr def transform_decl_stmt(self, node): """Transformation function for declaration statements These statements are used to wrap different kinds of declararions like variable or function declaration The function calls the transformer function for the child of the given node Returns ======= statement : Codegen AST Node contains the node returned by the children node for the type of declaration Raises ====== ValueError if multiple children present """ try: children = node.get_children() statement = self.transform(next(children)) except StopIteration: pass try: self.transform(next(children)) raise ValueError("Don't know how to handle multiple statements") except StopIteration: pass return statement def transform_paren_expr(self, node): """Transformation function for Parenthesized expressions Returns the result from its children nodes """ return self.transform(next(node.get_children())) def transform_compound_assignment_operator(self, node): """Transformation function for handling shorthand operators Returns ======= augmented_assignment_expression: Codegen AST node shorthand assignment expression represented as Codegen AST Raises ====== NotImplementedError If the shorthand operator for bitwise operators (~=, ^=, &=, |=, <<=, >>=) is encountered """ return self.transform_binary_operator(node) def transform_unary_operator(self, node): """Transformation function for handling unary operators Returns ======= unary_expression: Codegen AST node simplified unary expression represented as Codegen AST Raises ====== NotImplementedError If dereferencing operator(*), address operator(&) or bitwise NOT operator(~) is encountered """ # supported operators list operators_list = ['+', '-', '++', '--', '!'] tokens = [token for token in node.get_tokens()] # it can be either pre increment/decrement or any other operator from the list if tokens[0].spelling in operators_list: child = self.transform(next(node.get_children())) # (decl_ref) e.g.; int a = ++b; or simply ++b; if isinstance(child, str): if tokens[0].spelling == '+': return Symbol(child) if tokens[0].spelling == '-': return Mul(Symbol(child), -1) if tokens[0].spelling == '++': return PreIncrement(Symbol(child)) if tokens[0].spelling == '--': return PreDecrement(Symbol(child)) if tokens[0].spelling == '!': return Not(Symbol(child)) # e.g.; int a = -1; or int b = -(1 + 2); else: if tokens[0].spelling == '+': return child if tokens[0].spelling == '-': return Mul(child, -1) if tokens[0].spelling == '!': return Not(sympify(bool(child))) # it can be either post increment/decrement # since variable name is obtained in token[0].spelling elif tokens[1].spelling in ['++', '--']: child = self.transform(next(node.get_children())) if tokens[1].spelling == '++': return PostIncrement(Symbol(child)) if tokens[1].spelling == '--': return PostDecrement(Symbol(child)) else: raise NotImplementedError("Dereferencing operator, " "Address operator and bitwise NOT operator " "have not been implemented yet!") def transform_binary_operator(self, node): """Transformation function for handling binary operators Returns ======= binary_expression: Codegen AST node simplified binary expression represented as Codegen AST Raises ====== NotImplementedError If a bitwise operator or unary operator(which is a child of any binary operator in Clang AST) is encountered """ # get all the tokens of assignment # and store it in the tokens list tokens = [token for token in node.get_tokens()] # supported operators list operators_list = ['+', '-', '*', '/', '%','=', '>', '>=', '<', '<=', '==', '!=', '&&', '||', '+=', '-=', '*=', '/=', '%='] # this stack will contain variable content # and type of variable in the rhs combined_variables_stack = [] # this stack will contain operators # to be processed in the rhs operators_stack = [] # iterate through every token for token in tokens: # token is either '(', ')' or # any of the supported operators from the operator list if token.kind == cin.TokenKind.PUNCTUATION: # push '(' to the operators stack if token.spelling == '(': operators_stack.append('(') elif token.spelling == ')': # keep adding the expression to the # combined variables stack unless # '(' is found while (operators_stack and operators_stack[-1] != '('): if len(combined_variables_stack) < 2: raise NotImplementedError( "Unary operators as a part of " "binary operators is not " "supported yet!") rhs = combined_variables_stack.pop() lhs = combined_variables_stack.pop() operator = operators_stack.pop() combined_variables_stack.append( self.perform_operation( lhs, rhs, operator)) # pop '(' operators_stack.pop() # token is an operator (supported) elif token.spelling in operators_list: while (operators_stack and self.priority_of(token.spelling) <= self.priority_of( operators_stack[-1])): if len(combined_variables_stack) < 2: raise NotImplementedError( "Unary operators as a part of " "binary operators is not " "supported yet!") rhs = combined_variables_stack.pop() lhs = combined_variables_stack.pop() operator = operators_stack.pop() combined_variables_stack.append( self.perform_operation( lhs, rhs, operator)) # push current operator operators_stack.append(token.spelling) # token is a bitwise operator elif token.spelling in ['&', '|', '^', '<<', '>>']: raise NotImplementedError( "Bitwise operator has not been " "implemented yet!") # token is a shorthand bitwise operator elif token.spelling in ['&=', '|=', '^=', '<<=', '>>=']: raise NotImplementedError( "Shorthand bitwise operator has not been " "implemented yet!") else: raise NotImplementedError( "Given token {} is not implemented yet!" .format(token.spelling)) # token is an identifier(variable) elif token.kind == cin.TokenKind.IDENTIFIER: combined_variables_stack.append( [token.spelling, 'identifier']) # token is a literal elif token.kind == cin.TokenKind.LITERAL: combined_variables_stack.append( [token.spelling, 'literal']) # token is a keyword, either true or false elif (token.kind == cin.TokenKind.KEYWORD and token.spelling in ['true', 'false']): combined_variables_stack.append( [token.spelling, 'boolean']) else: raise NotImplementedError( "Given token {} is not implemented yet!" .format(token.spelling)) # process remaining operators while operators_stack: if len(combined_variables_stack) < 2: raise NotImplementedError( "Unary operators as a part of " "binary operators is not " "supported yet!") rhs = combined_variables_stack.pop() lhs = combined_variables_stack.pop() operator = operators_stack.pop() combined_variables_stack.append( self.perform_operation(lhs, rhs, operator)) return combined_variables_stack[-1][0] def priority_of(self, op): """To get the priority of given operator""" if op in ['=', '+=', '-=', '*=', '/=', '%=']: return 1 if op in ['&&', '||']: return 2 if op in ['<', '<=', '>', '>=', '==', '!=']: return 3 if op in ['+', '-']: return 4 if op in ['*', '/', '%']: return 5 return 0 def perform_operation(self, lhs, rhs, op): """Performs operation supported by the sympy core Returns ======= combined_variable: list contains variable content and type of variable """ lhs_value = self.get_expr_for_operand(lhs) rhs_value = self.get_expr_for_operand(rhs) if op == '+': return [Add(lhs_value, rhs_value), 'expr'] if op == '-': return [Add(lhs_value, -rhs_value), 'expr'] if op == '*': return [Mul(lhs_value, rhs_value), 'expr'] if op == '/': return [Mul(lhs_value, Pow(rhs_value, Integer(-1))), 'expr'] if op == '%': return [Mod(lhs_value, rhs_value), 'expr'] if op in ['<', '<=', '>', '>=', '==', '!=']: return [Rel(lhs_value, rhs_value, op), 'expr'] if op == '&&': return [And(as_Boolean(lhs_value), as_Boolean(rhs_value)), 'expr'] if op == '||': return [Or(as_Boolean(lhs_value), as_Boolean(rhs_value)), 'expr'] if op == '=': return [Assignment(Variable(lhs_value), rhs_value), 'expr'] if op in ['+=', '-=', '*=', '/=', '%=']: return [aug_assign(Variable(lhs_value), op[0], rhs_value), 'expr'] def get_expr_for_operand(self, combined_variable): """Gives out SymPy Codegen AST node AST node returned is corresponding to combined variable passed.Combined variable contains variable content and type of variable """ if combined_variable[1] == 'identifier': return Symbol(combined_variable[0]) if combined_variable[1] == 'literal': if '.' in combined_variable[0]: return Float(float(combined_variable[0])) else: return Integer(int(combined_variable[0])) if combined_variable[1] == 'expr': return combined_variable[0] if combined_variable[1] == 'boolean': return true if combined_variable[0] == 'true' else false def transform_null_stmt(self, node): """Handles Null Statement and returns None""" return none def transform_while_stmt(self, node): """Transformation function for handling while statement Returns ======= while statement : Codegen AST Node contains the while statement node having condition and statement block """ children = node.get_children() condition = self.transform(next(children)) statements = self.transform(next(children)) if isinstance(statements, list): statement_block = CodeBlock(*statements) else: statement_block = CodeBlock(statements) return While(condition, statement_block) else: class CCodeConverter(): # type: ignore def __init__(self, *args, **kwargs): raise ImportError("Module not Installed") def parse_c(source): """Function for converting a C source code The function reads the source code present in the given file and parses it to give out SymPy Expressions Returns ======= src : list List of Python expression strings """ converter = CCodeConverter() if os.path.exists(source): src = converter.parse(source, flags = []) else: src = converter.parse_str(source, flags = []) return src
50fb4843e29f73b2457f25651daeb330ff2c28e577245f94969a3bfda1cbdd51
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, 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 _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 = [ ("0", 0), ("1", 1), ("-3.14", _Mul(-1, 3.14)), ("(-7.13)(1.5)", _Mul(_Mul(-1, 7.13), 1.5)), ("x", x), ("2x", 2*x), ("x^2", x**2), ("x^{3 + 1}", x**_Add(3, 1)), ("-c", -c), ("a \\cdot b", a * b), ("a / b", a / b), ("a \\div b", a / b), ("a + b", a + b), ("a + b - a", _Add(a+b, -a)), ("a^2 + b^2 = c^2", Eq(a**2 + b**2, c**2)), ("(x + y) z", _Mul(_Add(x, y), z)), ("\\left(x + y\\right) z", _Mul(_Add(x, y), z)), ("\\left( x + y\\right ) z", _Mul(_Add(x, y), z)), ("\\left( x + y\\right ) z", _Mul(_Add(x, y), z)), ("\\left[x + y\\right] z", _Mul(_Add(x, y), z)), ("\\left\\{x + y\\right\\} z", _Mul(_Add(x, y), z)), ("1+1", Add(1, 1, evaluate=False)), ("0+1", Add(0, 1, evaluate=False)), ("1*2", Mul(1, 2, evaluate=False)), ("0*1", Mul(0, 1, evaluate=False)), ("x = y", Eq(x, y)), ("x \\neq y", Ne(x, y)), ("x < y", Lt(x, y)), ("x > y", Gt(x, y)), ("x \\leq y", Le(x, y)), ("x \\geq y", Ge(x, y)), ("x \\le y", Le(x, y)), ("x \\ge y", Ge(x, y)), ("\\lfloor x \\rfloor", floor(x)), ("\\lceil x \\rceil", ceiling(x)), ("\\langle x |", Bra('x')), ("| x \\rangle", Ket('x')), ("\\sin \\theta", sin(theta)), ("\\sin(\\theta)", sin(theta)), ("\\sin^{-1} a", asin(a)), ("\\sin a \\cos b", _Mul(sin(a), cos(b))), ("\\sin \\cos \\theta", sin(cos(theta))), ("\\sin(\\cos \\theta)", sin(cos(theta))), ("\\frac{a}{b}", a / b), ("\\frac{a + b}{c}", _Mul(a + b, _Pow(c, -1))), ("\\frac{7}{3}", _Mul(7, _Pow(3, -1))), ("(\\csc x)(\\sec y)", csc(x)*sec(y)), ("\\lim_{x \\to 3} a", Limit(a, x, 3)), ("\\lim_{x \\rightarrow 3} a", Limit(a, x, 3)), ("\\lim_{x \\Rightarrow 3} a", Limit(a, x, 3)), ("\\lim_{x \\longrightarrow 3} a", Limit(a, x, 3)), ("\\lim_{x \\Longrightarrow 3} a", Limit(a, x, 3)), ("\\lim_{x \\to 3^{+}} a", Limit(a, x, 3, dir='+')), ("\\lim_{x \\to 3^{-}} a", Limit(a, x, 3, dir='-')), ("\\infty", oo), ("\\lim_{x \\to \\infty} \\frac{1}{x}", Limit(_Pow(x, -1), x, oo)), ("\\frac{d}{dx} x", Derivative(x, x)), ("\\frac{d}{dt} x", Derivative(x, t)), ("f(x)", f(x)), ("f(x, y)", f(x, y)), ("f(x, y, z)", f(x, y, z)), ("\\frac{d f(x)}{dx}", Derivative(f(x), x)), ("\\frac{d\\theta(x)}{dx}", Derivative(Function('theta')(x), x)), ("x \\neq y", Unequality(x, y)), ("|x|", _Abs(x)), ("||x||", _Abs(Abs(x))), ("|x||y|", _Abs(x)*_Abs(y)), ("||x||y||", _Abs(_Abs(x)*_Abs(y))), ("\\pi^{|xy|}", Symbol('pi')**_Abs(x*y)), ("\\int x dx", Integral(x, x)), ("\\int x d\\theta", Integral(x, theta)), ("\\int (x^2 - y)dx", Integral(x**2 - y, x)), ("\\int x + a dx", Integral(_Add(x, a), x)), ("\\int da", Integral(1, a)), ("\\int_0^7 dx", Integral(1, (x, 0, 7))), ("\\int_a^b x dx", Integral(x, (x, a, b))), ("\\int^b_a x dx", Integral(x, (x, a, b))), ("\\int_{a}^b x dx", Integral(x, (x, a, b))), ("\\int^{b}_a x dx", Integral(x, (x, a, b))), ("\\int_{a}^{b} x dx", Integral(x, (x, a, b))), ("\\int^{b}_{a} x dx", Integral(x, (x, a, b))), ("\\int_{f(a)}^{f(b)} f(z) dz", Integral(f(z), (z, f(a), f(b)))), ("\\int (x+a)", Integral(_Add(x, a), x)), ("\\int a + b + c dx", Integral(_Add(_Add(a, b), c), x)), ("\\int \\frac{dz}{z}", Integral(Pow(z, -1), z)), ("\\int \\frac{3 dz}{z}", Integral(3*Pow(z, -1), z)), ("\\int \\frac{1}{x} dx", Integral(Pow(x, -1), x)), ("\\int \\frac{1}{a} + \\frac{1}{b} dx", Integral(_Add(_Pow(a, -1), Pow(b, -1)), x)), ("\\int \\frac{3 \\cdot d\\theta}{\\theta}", Integral(3*_Pow(theta, -1), theta)), ("\\int \\frac{1}{x} + 1 dx", Integral(_Add(_Pow(x, -1), 1), x)), ("x_0", Symbol('x_{0}')), ("x_{1}", Symbol('x_{1}')), ("x_a", Symbol('x_{a}')), ("x_{b}", Symbol('x_{b}')), ("h_\\theta", Symbol('h_{theta}')), ("h_{\\theta}", Symbol('h_{theta}')), ("h_{\\theta}(x_0, x_1)", Function('h_{theta}')(Symbol('x_{0}'), Symbol('x_{1}'))), ("x!", _factorial(x)), ("100!", _factorial(100)), ("\\theta!", _factorial(theta)), ("(x + 1)!", _factorial(_Add(x, 1))), ("(x!)!", _factorial(_factorial(x))), ("x!!!", _factorial(_factorial(_factorial(x)))), ("5!7!", _Mul(_factorial(5), _factorial(7))), ("\\sqrt{x}", sqrt(x)), ("\\sqrt{x + b}", sqrt(_Add(x, b))), ("\\sqrt[3]{\\sin x}", root(sin(x), 3)), ("\\sqrt[y]{\\sin x}", root(sin(x), y)), ("\\sqrt[\\theta]{\\sin x}", root(sin(x), theta)), ("x < y", StrictLessThan(x, y)), ("x \\leq y", LessThan(x, y)), ("x > y", StrictGreaterThan(x, y)), ("x \\geq y", GreaterThan(x, y)), ("\\mathit{x}", Symbol('x')), ("\\mathit{test}", Symbol('test')), ("\\mathit{TEST}", Symbol('TEST')), ("\\mathit{HELLO world}", Symbol('HELLO world')), ("\\sum_{k = 1}^{3} c", Sum(c, (k, 1, 3))), ("\\sum_{k = 1}^3 c", Sum(c, (k, 1, 3))), ("\\sum^{3}_{k = 1} c", Sum(c, (k, 1, 3))), ("\\sum^3_{k = 1} c", Sum(c, (k, 1, 3))), ("\\sum_{k = 1}^{10} k^2", Sum(k**2, (k, 1, 10))), ("\\sum_{n = 0}^{\\infty} \\frac{1}{n!}", Sum(_Pow(_factorial(n), -1), (n, 0, oo))), ("\\prod_{a = b}^{c} x", Product(x, (a, b, c))), ("\\prod_{a = b}^c x", Product(x, (a, b, c))), ("\\prod^{c}_{a = b} x", Product(x, (a, b, c))), ("\\prod^c_{a = b} x", Product(x, (a, b, c))), ("\\exp x", _exp(x)), ("\\exp(x)", _exp(x)), ("\\ln x", _log(x, E)), ("\\ln xy", _log(x*y, E)), ("\\log x", _log(x, 10)), ("\\log xy", _log(x*y, 10)), ("\\log_{2} x", _log(x, 2)), ("\\log_{a} x", _log(x, a)), ("\\log_{11} x", _log(x, 11)), ("\\log_{a^2} x", _log(x, _Pow(a, 2))), ("[x]", x), ("[a + b]", _Add(a, b)), ("\\frac{d}{dx} [ \\tan x ]", Derivative(tan(x), x)), ("\\binom{n}{k}", _binomial(n, k)), ("\\tbinom{n}{k}", _binomial(n, k)), ("\\dbinom{n}{k}", _binomial(n, k)), ("\\binom{n}{0}", _binomial(n, 0)), ("a \\, b", _Mul(a, b)), ("a \\thinspace b", _Mul(a, b)), ("a \\: b", _Mul(a, b)), ("a \\medspace b", _Mul(a, b)), ("a \\; b", _Mul(a, b)), ("a \\thickspace b", _Mul(a, b)), ("a \\quad b", _Mul(a, b)), ("a \\qquad b", _Mul(a, b)), ("a \\! b", _Mul(a, b)), ("a \\negthinspace b", _Mul(a, b)), ("a \\negmedspace b", _Mul(a, b)), ("a \\negthickspace b", _Mul(a, b)), ("\\int x \\, dx", Integral(x, x)), ] 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 # At time of migration from latex2sympy, should work but doesn't FAILING_PAIRS = [ ("\\log_2 x", _log(x, 2)), ("\\log_a x", _log(x, a)), ] def test_failing_parseable(): from sympy.parsing.latex import parse_latex for latex_str, sympy_expr in FAILING_PAIRS: with raises(Exception): assert parse_latex(latex_str) == sympy_expr # These bad LaTeX strings should raise a LaTeXParsingError when parsed BAD_STRINGS = [ "(", ")", "\\frac{d}{dx}", "(\\frac{d}{dx})" "\\sqrt{}", "\\sqrt", "{", "}", "\\mathit{x + y}", "\\mathit{21}", "\\frac{2}{}", "\\frac{}{2}", "\\int", "!", "!0", "_", "^", "|", "||x|", "()", "((((((((((((((((()))))))))))))))))", "-", "\\frac{d}{dx} + \\frac{d}{dt}", "f(x,,y)", "f(x,y,", "\\sin^x", "\\cos^2", "@", "#", "$", "%", "&", "*", "\\", "~", "\\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 = [ "\\cos 1 \\cos", "f(,", "f()", "a \\div \\div b", "a \\cdot \\cdot b", "a // b", "a +", "1.1.1", "1 +", "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)
4b0a0337d829f8984ffd4a8dd500cb9ba1302d9b5eb817342681a5dc506d162b
from sympy.parsing.sym_expr import SymPyExpression from sympy.testing.pytest import raises, XFAIL from sympy.external import import_module cin = import_module('clang.cindex', import_kwargs = {'fromlist': ['cindex']}) if cin: from sympy.codegen.ast import (Variable, String, Return, FunctionDefinition, Integer, Float, Declaration, CodeBlock, FunctionPrototype, FunctionCall, NoneToken, Assignment, Type, IntBaseType, SignedIntType, UnsignedIntType, FloatType, AddAugmentedAssignment, SubAugmentedAssignment, MulAugmentedAssignment, DivAugmentedAssignment, ModAugmentedAssignment, While) from sympy.codegen.cnodes import (PreDecrement, PostDecrement, PreIncrement, PostIncrement) from sympy.core import (Add, Mul, Mod, Pow, Rational, StrictLessThan, LessThan, StrictGreaterThan, GreaterThan, Equality, Unequality) from sympy.logic.boolalg import And, Not, Or from sympy import Symbol, true, false import os def test_variable(): c_src1 = ( 'int a;' + '\n' + 'int b;' + '\n' ) c_src2 = ( 'float a;' + '\n' + 'float b;' + '\n' ) c_src3 = ( 'int a;' + '\n' + 'float b;' + '\n' + 'int c;' ) c_src4 = ( 'int x = 1, y = 6.78;' + '\n' + 'float p = 2, q = 9.67;' ) res1 = SymPyExpression(c_src1, 'c').return_expr() res2 = SymPyExpression(c_src2, 'c').return_expr() res3 = SymPyExpression(c_src3, 'c').return_expr() res4 = SymPyExpression(c_src4, 'c').return_expr() assert res1[0] == Declaration( Variable( Symbol('a'), type=IntBaseType(String('intc')) ) ) assert res1[1] == Declaration( Variable( Symbol('b'), type=IntBaseType(String('intc')) ) ) assert res2[0] == Declaration( Variable( Symbol('a'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ) ) ) assert res2[1] == Declaration( Variable( Symbol('b'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ) ) ) assert res3[0] == Declaration( Variable( Symbol('a'), type=IntBaseType(String('intc')) ) ) assert res3[1] == Declaration( Variable( Symbol('b'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ) ) ) assert res3[2] == Declaration( Variable( Symbol('c'), type=IntBaseType(String('intc')) ) ) assert res4[0] == Declaration( Variable( Symbol('x'), type=IntBaseType(String('intc')), value=Integer(1) ) ) assert res4[1] == Declaration( Variable( Symbol('y'), type=IntBaseType(String('intc')), value=Integer(6) ) ) assert res4[2] == Declaration( Variable( Symbol('p'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ), value=Float('2.0', precision=53) ) ) assert res4[3] == Declaration( Variable( Symbol('q'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ), value=Float('9.67', precision=53) ) ) @XFAIL def test_int(): c_src1 = 'int a = 1;' c_src2 = ( 'int a = 1;' + '\n' + 'int b = 2;' + '\n' ) c_src3 = 'int a = 2.345, b = 5.67;' c_src4 = 'int p = 6, q = 23.45;' c_src5 = "int x = '0', y = 'a';" c_src6 = "int r = true, s = false;" # cin.TypeKind.UCHAR c_src_type1 = ( "signed char a = 1, b = 5.1;" ) # cin.TypeKind.SHORT c_src_type2 = ( "short a = 1, b = 5.1;" "signed short c = 1, d = 5.1;" "short int e = 1, f = 5.1;" "signed short int g = 1, h = 5.1;" ) # cin.TypeKind.INT c_src_type3 = ( "signed int a = 1, b = 5.1;" "int c = 1, d = 5.1;" ) # cin.TypeKind.LONG c_src_type4 = ( "long a = 1, b = 5.1;" "long int c = 1, d = 5.1;" ) # cin.TypeKind.UCHAR c_src_type5 = "unsigned char a = 1, b = 5.1;" # cin.TypeKind.USHORT c_src_type6 = ( "unsigned short a = 1, b = 5.1;" "unsigned short int c = 1, d = 5.1;" ) # cin.TypeKind.UINT c_src_type7 = "unsigned int a = 1, b = 5.1;" # cin.TypeKind.ULONG c_src_type8 = ( "unsigned long a = 1, b = 5.1;" "unsigned long int c = 1, d = 5.1;" ) res1 = SymPyExpression(c_src1, 'c').return_expr() res2 = SymPyExpression(c_src2, 'c').return_expr() res3 = SymPyExpression(c_src3, 'c').return_expr() res4 = SymPyExpression(c_src4, 'c').return_expr() res5 = SymPyExpression(c_src5, 'c').return_expr() res6 = SymPyExpression(c_src6, 'c').return_expr() res_type1 = SymPyExpression(c_src_type1, 'c').return_expr() res_type2 = SymPyExpression(c_src_type2, 'c').return_expr() res_type3 = SymPyExpression(c_src_type3, 'c').return_expr() res_type4 = SymPyExpression(c_src_type4, 'c').return_expr() res_type5 = SymPyExpression(c_src_type5, 'c').return_expr() res_type6 = SymPyExpression(c_src_type6, 'c').return_expr() res_type7 = SymPyExpression(c_src_type7, 'c').return_expr() res_type8 = SymPyExpression(c_src_type8, 'c').return_expr() assert res1[0] == Declaration( Variable( Symbol('a'), type=IntBaseType(String('intc')), value=Integer(1) ) ) assert res2[0] == Declaration( Variable( Symbol('a'), type=IntBaseType(String('intc')), value=Integer(1) ) ) assert res2[1] == Declaration( Variable( Symbol('b'), type=IntBaseType(String('intc')), value=Integer(2) ) ) assert res3[0] == Declaration( Variable( Symbol('a'), type=IntBaseType(String('intc')), value=Integer(2) ) ) assert res3[1] == Declaration( Variable( Symbol('b'), type=IntBaseType(String('intc')), value=Integer(5) ) ) assert res4[0] == Declaration( Variable( Symbol('p'), type=IntBaseType(String('intc')), value=Integer(6) ) ) assert res4[1] == Declaration( Variable( Symbol('q'), type=IntBaseType(String('intc')), value=Integer(23) ) ) assert res5[0] == Declaration( Variable( Symbol('x'), type=IntBaseType(String('intc')), value=Integer(48) ) ) assert res5[1] == Declaration( Variable( Symbol('y'), type=IntBaseType(String('intc')), value=Integer(97) ) ) assert res6[0] == Declaration( Variable( Symbol('r'), type=IntBaseType(String('intc')), value=Integer(1) ) ) assert res6[1] == Declaration( Variable( Symbol('s'), type=IntBaseType(String('intc')), value=Integer(0) ) ) assert res_type1[0] == Declaration( Variable( Symbol('a'), type=SignedIntType( String('int8'), nbits=Integer(8) ), value=Integer(1) ) ) assert res_type1[1] == Declaration( Variable( Symbol('b'), type=SignedIntType( String('int8'), nbits=Integer(8) ), value=Integer(5) ) ) assert res_type2[0] == Declaration( Variable( Symbol('a'), type=SignedIntType( String('int16'), nbits=Integer(16) ), value=Integer(1) ) ) assert res_type2[1] == Declaration( Variable( Symbol('b'), type=SignedIntType( String('int16'), nbits=Integer(16) ), value=Integer(5) ) ) assert res_type2[2] == Declaration( Variable(Symbol('c'), type=SignedIntType( String('int16'), nbits=Integer(16) ), value=Integer(1) ) ) assert res_type2[3] == Declaration( Variable( Symbol('d'), type=SignedIntType( String('int16'), nbits=Integer(16) ), value=Integer(5) ) ) assert res_type2[4] == Declaration( Variable( Symbol('e'), type=SignedIntType( String('int16'), nbits=Integer(16) ), value=Integer(1) ) ) assert res_type2[5] == Declaration( Variable( Symbol('f'), type=SignedIntType( String('int16'), nbits=Integer(16) ), value=Integer(5) ) ) assert res_type2[6] == Declaration( Variable( Symbol('g'), type=SignedIntType( String('int16'), nbits=Integer(16) ), value=Integer(1) ) ) assert res_type2[7] == Declaration( Variable( Symbol('h'), type=SignedIntType( String('int16'), nbits=Integer(16) ), value=Integer(5) ) ) assert res_type3[0] == Declaration( Variable( Symbol('a'), type=IntBaseType(String('intc')), value=Integer(1) ) ) assert res_type3[1] == Declaration( Variable( Symbol('b'), type=IntBaseType(String('intc')), value=Integer(5) ) ) assert res_type3[2] == Declaration( Variable( Symbol('c'), type=IntBaseType(String('intc')), value=Integer(1) ) ) assert res_type3[3] == Declaration( Variable( Symbol('d'), type=IntBaseType(String('intc')), value=Integer(5) ) ) assert res_type4[0] == Declaration( Variable( Symbol('a'), type=SignedIntType( String('int64'), nbits=Integer(64) ), value=Integer(1) ) ) assert res_type4[1] == Declaration( Variable( Symbol('b'), type=SignedIntType( String('int64'), nbits=Integer(64) ), value=Integer(5) ) ) assert res_type4[2] == Declaration( Variable( Symbol('c'), type=SignedIntType( String('int64'), nbits=Integer(64) ), value=Integer(1) ) ) assert res_type4[3] == Declaration( Variable( Symbol('d'), type=SignedIntType( String('int64'), nbits=Integer(64) ), value=Integer(5) ) ) assert res_type5[0] == Declaration( Variable( Symbol('a'), type=UnsignedIntType( String('uint8'), nbits=Integer(8) ), value=Integer(1) ) ) assert res_type5[1] == Declaration( Variable( Symbol('b'), type=UnsignedIntType( String('uint8'), nbits=Integer(8) ), value=Integer(5) ) ) assert res_type6[0] == Declaration( Variable( Symbol('a'), type=UnsignedIntType( String('uint16'), nbits=Integer(16) ), value=Integer(1) ) ) assert res_type6[1] == Declaration( Variable( Symbol('b'), type=UnsignedIntType( String('uint16'), nbits=Integer(16) ), value=Integer(5) ) ) assert res_type6[2] == Declaration( Variable( Symbol('c'), type=UnsignedIntType( String('uint16'), nbits=Integer(16) ), value=Integer(1) ) ) assert res_type6[3] == Declaration( Variable( Symbol('d'), type=UnsignedIntType( String('uint16'), nbits=Integer(16) ), value=Integer(5) ) ) assert res_type7[0] == Declaration( Variable( Symbol('a'), type=UnsignedIntType( String('uint32'), nbits=Integer(32) ), value=Integer(1) ) ) assert res_type7[1] == Declaration( Variable( Symbol('b'), type=UnsignedIntType( String('uint32'), nbits=Integer(32) ), value=Integer(5) ) ) assert res_type8[0] == Declaration( Variable( Symbol('a'), type=UnsignedIntType( String('uint64'), nbits=Integer(64) ), value=Integer(1) ) ) assert res_type8[1] == Declaration( Variable( Symbol('b'), type=UnsignedIntType( String('uint64'), nbits=Integer(64) ), value=Integer(5) ) ) assert res_type8[2] == Declaration( Variable( Symbol('c'), type=UnsignedIntType( String('uint64'), nbits=Integer(64) ), value=Integer(1) ) ) assert res_type8[3] == Declaration( Variable( Symbol('d'), type=UnsignedIntType( String('uint64'), nbits=Integer(64) ), value=Integer(5) ) ) @XFAIL def test_float(): c_src1 = 'float a = 1.0;' c_src2 = ( 'float a = 1.25;' + '\n' + 'float b = 2.39;' + '\n' ) c_src3 = 'float x = 1, y = 2;' c_src4 = 'float p = 5, e = 7.89;' c_src5 = 'float r = true, s = false;' # cin.TypeKind.FLOAT c_src_type1 = 'float x = 1, y = 2.5;' # cin.TypeKind.DOUBLE c_src_type2 = 'double x = 1, y = 2.5;' # cin.TypeKind.LONGDOUBLE c_src_type3 = 'long double x = 1, y = 2.5;' res1 = SymPyExpression(c_src1, 'c').return_expr() res2 = SymPyExpression(c_src2, 'c').return_expr() res3 = SymPyExpression(c_src3, 'c').return_expr() res4 = SymPyExpression(c_src4, 'c').return_expr() res5 = SymPyExpression(c_src5, 'c').return_expr() res_type1 = SymPyExpression(c_src_type1, 'c').return_expr() res_type2 = SymPyExpression(c_src_type2, 'c').return_expr() res_type3 = SymPyExpression(c_src_type3, 'c').return_expr() assert res1[0] == Declaration( Variable( Symbol('a'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ), value=Float('1.0', precision=53) ) ) assert res2[0] == Declaration( Variable( Symbol('a'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ), value=Float('1.25', precision=53) ) ) assert res2[1] == Declaration( Variable( Symbol('b'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ), value=Float('2.3900000000000001', precision=53) ) ) assert res3[0] == Declaration( Variable( Symbol('x'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ), value=Float('1.0', precision=53) ) ) assert res3[1] == Declaration( Variable( Symbol('y'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ), value=Float('2.0', precision=53) ) ) assert res4[0] == Declaration( Variable( Symbol('p'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ), value=Float('5.0', precision=53) ) ) assert res4[1] == Declaration( Variable( Symbol('e'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ), value=Float('7.89', precision=53) ) ) assert res5[0] == Declaration( Variable( Symbol('r'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ), value=Float('1.0', precision=53) ) ) assert res5[1] == Declaration( Variable( Symbol('s'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ), value=Float('0.0', precision=53) ) ) assert res_type1[0] == Declaration( Variable( Symbol('x'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ), value=Float('1.0', precision=53) ) ) assert res_type1[1] == Declaration( Variable( Symbol('y'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ), value=Float('2.5', precision=53) ) ) assert res_type2[0] == Declaration( Variable( Symbol('x'), type=FloatType( String('float64'), nbits=Integer(64), nmant=Integer(52), nexp=Integer(11) ), value=Float('1.0', precision=53) ) ) assert res_type2[1] == Declaration( Variable( Symbol('y'), type=FloatType( String('float64'), nbits=Integer(64), nmant=Integer(52), nexp=Integer(11) ), value=Float('2.5', precision=53) ) ) assert res_type3[0] == Declaration( Variable( Symbol('x'), type=FloatType( String('float80'), nbits=Integer(80), nmant=Integer(63), nexp=Integer(15) ), value=Float('1.0', precision=53) ) ) assert res_type3[1] == Declaration( Variable( Symbol('y'), type=FloatType( String('float80'), nbits=Integer(80), nmant=Integer(63), nexp=Integer(15) ), value=Float('2.5', precision=53) ) ) @XFAIL def test_bool(): c_src1 = ( 'bool a = true, b = false;' ) c_src2 = ( 'bool a = 1, b = 0;' ) c_src3 = ( 'bool a = 10, b = 20;' ) c_src4 = ( 'bool a = 19.1, b = 9.0, c = 0.0;' ) res1 = SymPyExpression(c_src1, 'c').return_expr() res2 = SymPyExpression(c_src2, 'c').return_expr() res3 = SymPyExpression(c_src3, 'c').return_expr() res4 = SymPyExpression(c_src4, 'c').return_expr() assert res1[0] == Declaration( Variable(Symbol('a'), type=Type(String('bool')), value=true ) ) assert res1[1] == Declaration( Variable(Symbol('b'), type=Type(String('bool')), value=false ) ) assert res2[0] == Declaration( Variable(Symbol('a'), type=Type(String('bool')), value=true) ) assert res2[1] == Declaration( Variable(Symbol('b'), type=Type(String('bool')), value=false ) ) assert res3[0] == Declaration( Variable(Symbol('a'), type=Type(String('bool')), value=true ) ) assert res3[1] == Declaration( Variable(Symbol('b'), type=Type(String('bool')), value=true ) ) assert res4[0] == Declaration( Variable(Symbol('a'), type=Type(String('bool')), value=true) ) assert res4[1] == Declaration( Variable(Symbol('b'), type=Type(String('bool')), value=true ) ) assert res4[2] == Declaration( Variable(Symbol('c'), type=Type(String('bool')), value=false ) ) def test_function(): c_src1 = ( 'void fun1()' + '\n' + '{' + '\n' + 'int a;' + '\n' + '}' ) c_src2 = ( 'int fun2()' + '\n' + '{'+ '\n' + 'int a;' + '\n' + 'return a;' + '\n' + '}' ) c_src3 = ( 'float fun3()' + '\n' + '{' + '\n' + 'float b;' + '\n' + 'return b;' + '\n' + '}' ) c_src4 = ( 'float fun4()' + '\n' + '{}' ) res1 = SymPyExpression(c_src1, 'c').return_expr() res2 = SymPyExpression(c_src2, 'c').return_expr() res3 = SymPyExpression(c_src3, 'c').return_expr() res4 = SymPyExpression(c_src4, 'c').return_expr() assert res1[0] == FunctionDefinition( NoneToken(), name=String('fun1'), parameters=(), body=CodeBlock( Declaration( Variable( Symbol('a'), type=IntBaseType(String('intc')) ) ) ) ) assert res2[0] == FunctionDefinition( IntBaseType(String('intc')), name=String('fun2'), parameters=(), body=CodeBlock( Declaration( Variable( Symbol('a'), type=IntBaseType(String('intc')) ) ), Return('a') ) ) assert res3[0] == FunctionDefinition( FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ), name=String('fun3'), parameters=(), body=CodeBlock( Declaration( Variable( Symbol('b'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ) ) ), Return('b') ) ) assert res4[0] == FunctionPrototype( FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ), name=String('fun4'), parameters=() ) def test_parameters(): c_src1 = ( 'void fun1( int a)' + '\n' + '{' + '\n' + 'int i;' + '\n' + '}' ) c_src2 = ( 'int fun2(float x, float y)' + '\n' + '{'+ '\n' + 'int a;' + '\n' + 'return a;' + '\n' + '}' ) c_src3 = ( 'float fun3(int p, float q, int r)' + '\n' + '{' + '\n' + 'float b;' + '\n' + 'return b;' + '\n' + '}' ) res1 = SymPyExpression(c_src1, 'c').return_expr() res2 = SymPyExpression(c_src2, 'c').return_expr() res3 = SymPyExpression(c_src3, 'c').return_expr() assert res1[0] == FunctionDefinition( NoneToken(), name=String('fun1'), parameters=( Variable( Symbol('a'), type=IntBaseType(String('intc')) ), ), body=CodeBlock( Declaration( Variable( Symbol('i'), type=IntBaseType(String('intc')) ) ) ) ) assert res2[0] == FunctionDefinition( IntBaseType(String('intc')), name=String('fun2'), parameters=( Variable( Symbol('x'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ) ), Variable( Symbol('y'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ) ) ), body=CodeBlock( Declaration( Variable( Symbol('a'), type=IntBaseType(String('intc')) ) ), Return('a') ) ) assert res3[0] == FunctionDefinition( FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ), name=String('fun3'), parameters=( Variable( Symbol('p'), type=IntBaseType(String('intc')) ), Variable( Symbol('q'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ) ), Variable( Symbol('r'), type=IntBaseType(String('intc')) ) ), body=CodeBlock( Declaration( Variable( Symbol('b'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ) ) ), Return('b') ) ) def test_function_call(): c_src1 = ( 'int fun1(int x)' + '\n' + '{' + '\n' + 'return x;' + '\n' + '}' + '\n' + 'void caller()' + '\n' + '{' + '\n' + 'int x = fun1(2);' + '\n' + '}' ) c_src2 = ( 'int fun2(int a, int b, int c)' + '\n' + '{' + '\n' + 'return a;' + '\n' + '}' + '\n' + 'void caller()' + '\n' + '{' + '\n' + 'int y = fun2(2, 3, 4);' + '\n' + '}' ) c_src3 = ( 'int fun3(int a, int b, int c)' + '\n' + '{' + '\n' + 'return b;' + '\n' + '}' + '\n' + 'void caller()' + '\n' + '{' + '\n' + 'int p;' + '\n' + 'int q;' + '\n' + 'int r;' + '\n' + 'int z = fun3(p, q, r);' + '\n' + '}' ) c_src4 = ( 'int fun4(float a, float b, int c)' + '\n' + '{' + '\n' + 'return c;' + '\n' + '}' + '\n' + 'void caller()' + '\n' + '{' + '\n' + 'float x;' + '\n' + 'float y;' + '\n' + 'int z;' + '\n' + 'int i = fun4(x, y, z)' + '\n' + '}' ) c_src5 = ( 'int fun()' + '\n' + '{' + '\n' + 'return 1;' + '\n' + '}' + '\n' + 'void caller()' + '\n' + '{' + '\n' + 'int a = fun()' + '\n' + '}' ) res1 = SymPyExpression(c_src1, 'c').return_expr() res2 = SymPyExpression(c_src2, 'c').return_expr() res3 = SymPyExpression(c_src3, 'c').return_expr() res4 = SymPyExpression(c_src4, 'c').return_expr() res5 = SymPyExpression(c_src5, 'c').return_expr() assert res1[0] == FunctionDefinition( IntBaseType(String('intc')), name=String('fun1'), parameters=(Variable(Symbol('x'), type=IntBaseType(String('intc')) ), ), body=CodeBlock( Return('x') ) ) assert res1[1] == FunctionDefinition( NoneToken(), name=String('caller'), parameters=(), body=CodeBlock( Declaration( Variable(Symbol('x'), value=FunctionCall(String('fun1'), function_args=( Integer(2), ) ) ) ) ) ) assert res2[0] == FunctionDefinition( IntBaseType(String('intc')), name=String('fun2'), parameters=(Variable(Symbol('a'), type=IntBaseType(String('intc')) ), Variable(Symbol('b'), type=IntBaseType(String('intc')) ), Variable(Symbol('c'), type=IntBaseType(String('intc')) ) ), body=CodeBlock( Return('a') ) ) assert res2[1] == FunctionDefinition( NoneToken(), name=String('caller'), parameters=(), body=CodeBlock( Declaration( Variable(Symbol('y'), value=FunctionCall( String('fun2'), function_args=( Integer(2), Integer(3), Integer(4) ) ) ) ) ) ) assert res3[0] == FunctionDefinition( IntBaseType(String('intc')), name=String('fun3'), parameters=( Variable(Symbol('a'), type=IntBaseType(String('intc')) ), Variable(Symbol('b'), type=IntBaseType(String('intc')) ), Variable(Symbol('c'), type=IntBaseType(String('intc')) ) ), body=CodeBlock( Return('b') ) ) assert res3[1] == FunctionDefinition( NoneToken(), name=String('caller'), parameters=(), body=CodeBlock( Declaration( Variable(Symbol('p'), type=IntBaseType(String('intc')) ) ), Declaration( Variable(Symbol('q'), type=IntBaseType(String('intc')) ) ), Declaration( Variable(Symbol('r'), type=IntBaseType(String('intc')) ) ), Declaration( Variable(Symbol('z'), value=FunctionCall( String('fun3'), function_args=( Symbol('p'), Symbol('q'), Symbol('r') ) ) ) ) ) ) assert res4[0] == FunctionDefinition( IntBaseType(String('intc')), name=String('fun4'), parameters=(Variable(Symbol('a'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ) ), Variable(Symbol('b'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ) ), Variable(Symbol('c'), type=IntBaseType(String('intc')) ) ), body=CodeBlock( Return('c') ) ) assert res4[1] == FunctionDefinition( NoneToken(), name=String('caller'), parameters=(), body=CodeBlock( Declaration( Variable(Symbol('x'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ) ) ), Declaration( Variable(Symbol('y'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ) ) ), Declaration( Variable(Symbol('z'), type=IntBaseType(String('intc')) ) ), Declaration( Variable(Symbol('i'), value=FunctionCall(String('fun4'), function_args=( Symbol('x'), Symbol('y'), Symbol('z') ) ) ) ) ) ) assert res5[0] == FunctionDefinition( IntBaseType(String('intc')), name=String('fun'), parameters=(), body=CodeBlock( Return('') ) ) assert res5[1] == FunctionDefinition( NoneToken(), name=String('caller'), parameters=(), body=CodeBlock( Declaration( Variable(Symbol('a'), value=FunctionCall(String('fun'), function_args=() ) ) ) ) ) def test_parse(): c_src1 = ( 'int a;' + '\n' + 'int b;' + '\n' ) c_src2 = ( 'void fun1()' + '\n' + '{' + '\n' + 'int a;' + '\n' + '}' ) f1 = open('..a.h', 'w') f2 = open('..b.h', 'w') f1.write(c_src1) f2. write(c_src2) f1.close() f2.close() res1 = SymPyExpression('..a.h', 'c').return_expr() res2 = SymPyExpression('..b.h', 'c').return_expr() os.remove('..a.h') os.remove('..b.h') assert res1[0] == Declaration( Variable( Symbol('a'), type=IntBaseType(String('intc')) ) ) assert res1[1] == Declaration( Variable( Symbol('b'), type=IntBaseType(String('intc')) ) ) assert res2[0] == FunctionDefinition( NoneToken(), name=String('fun1'), parameters=(), body=CodeBlock( Declaration( Variable( Symbol('a'), type=IntBaseType(String('intc')) ) ) ) ) def test_binary_operators(): c_src1 = ( 'void func()'+ '{' + '\n' + 'int a;' + '\n' + 'a = 1;' + '\n' + '}' ) c_src2 = ( 'void func()'+ '{' + '\n' + 'int a = 0;' + '\n' + 'a = a + 1;' + '\n' + 'a = 3*a - 10;' + '\n' + '}' ) c_src3 = ( 'void func()'+ '{' + '\n' + 'int a = 10;' + '\n' + 'a = 1 + a - 3 * 6;' + '\n' + '}' ) c_src4 = ( 'void func()'+ '{' + '\n' + 'int a;' + '\n' + 'int b;' + '\n' + 'a = 100;' + '\n' + 'b = a*a + a*a + a + 19*a + 1 + 24;' + '\n' + '}' ) c_src5 = ( 'void func()'+ '{' + '\n' + 'int a;' + '\n' + 'int b;' + '\n' + 'int c;' + '\n' + 'int d;' + '\n' + 'a = 1;' + '\n' + 'b = 2;' + '\n' + 'c = b;' + '\n' + 'd = ((a+b)*(a+c))*((c-d)*(a+c));' + '\n' + '}' ) c_src6 = ( 'void func()'+ '{' + '\n' + 'int a;' + '\n' + 'int b;' + '\n' + 'int c;' + '\n' + 'int d;' + '\n' + 'a = 1;' + '\n' + 'b = 2;' + '\n' + 'c = 3;' + '\n' + 'd = (a*a*a*a + 3*b*b + b + b + c*d);' + '\n' + '}' ) c_src7 = ( 'void func()'+ '{' + '\n' + 'float a;' + '\n' + 'a = 1.01;' + '\n' + '}' ) c_src8 = ( 'void func()'+ '{' + '\n' + 'float a;' + '\n' + 'a = 10.0 + 2.5;' + '\n' + '}' ) c_src9 = ( 'void func()'+ '{' + '\n' + 'float a;' + '\n' + 'a = 10.0 / 2.5;' + '\n' + '}' ) c_src10 = ( 'void func()'+ '{' + '\n' + 'int a;' + '\n' + 'a = 100 / 4;' + '\n' + '}' ) c_src11 = ( 'void func()'+ '{' + '\n' + 'int a;' + '\n' + 'a = 20 - 100 / 4 * 5 + 10;' + '\n' + '}' ) c_src12 = ( 'void func()'+ '{' + '\n' + 'int a;' + '\n' + 'a = (20 - 100) / 4 * (5 + 10);' + '\n' + '}' ) c_src13 = ( 'void func()'+ '{' + '\n' + 'int a;' + '\n' + 'int b;' + '\n' + 'float c;' + '\n' + 'c = b/a;' + '\n' + '}' ) c_src14 = ( 'void func()'+ '{' + '\n' + 'int a = 2;' + '\n' + 'int d = 5;' + '\n' + 'int n = 10;' + '\n' + 'int s;' + '\n' + 's = (a/2)*(2*a + (n-1)*d);' + '\n' + '}' ) c_src15 = ( 'void func()'+ '{' + '\n' + 'int a;' + '\n' + 'a = 1 % 2;' + '\n' + '}' ) c_src16 = ( 'void func()'+ '{' + '\n' + 'int a = 2;' + '\n' + 'int b;' + '\n' + 'b = a % 3;' + '\n' + '}' ) c_src17 = ( 'void func()'+ '{' + '\n' + 'int a = 100;' + '\n' + 'int b = 3;' + '\n' + 'int c;' + '\n' + 'c = a % b;' + '\n' + '}' ) c_src18 = ( 'void func()'+ '{' + '\n' + 'int a = 100;' + '\n' + 'int b = 3;' + '\n' + 'int mod = 1000000007;' + '\n' + 'int c;' + '\n' + 'c = (a + b * (100/a)) % mod;' + '\n' + '}' ) c_src19 = ( 'void func()'+ '{' + '\n' + 'int a = 100;' + '\n' + 'int b = 3;' + '\n' + 'int mod = 1000000007;' + '\n' + 'int c;' + '\n' + 'c = ((a % mod + b % mod) % mod *(' \ 'a % mod - b % mod) % mod) % mod;' + '\n' + '}' ) c_src20 = ( 'void func()'+ '{' + '\n' + 'bool a' + '\n' + 'bool b;' + '\n' + 'a = 1 == 2;' + '\n' + 'b = 1 != 2;' + '\n' + '}' ) c_src21 = ( 'void func()'+ '{' + '\n' + 'bool a;' + '\n' + 'bool b;' + '\n' + 'bool c;' + '\n' + 'bool d;' + '\n' + 'a = 1 == 2;' + '\n' + 'b = 1 <= 2;' + '\n' + 'c = 1 > 2;' + '\n' + 'd = 1 >= 2;' + '\n' + '}' ) c_src22 = ( 'void func()'+ '{' + '\n' + 'int a = 1;' + '\n' + 'int b = 2;' + '\n' + 'bool c1;' + '\n' + 'bool c2;' + '\n' + 'bool c3;' + '\n' + 'bool c4;' + '\n' + 'bool c5;' + '\n' + 'bool c6;' + '\n' + 'bool c7;' + '\n' + 'bool c8;' + '\n' + 'c1 = a == 1;' + '\n' + 'c2 = b == 2;' + '\n' + 'c3 = 1 != a;' + '\n' + 'c4 = 1 != b;' + '\n' + 'c5 = a < 0;' + '\n' + 'c6 = b <= 10;' + '\n' + 'c7 = a > 0;' + '\n' + 'c8 = b >= 11;' + '\n' + '}' ) c_src23 = ( 'void func()'+ '{' + '\n' + 'int a = 3;' + '\n' + 'int b = 4;' + '\n' + 'bool c1;' + '\n' + 'bool c2;' + '\n' + 'bool c3;' + '\n' + 'bool c4;' + '\n' + 'bool c5;' + '\n' + 'bool c6;' + '\n' + 'c1 = a == b;' + '\n' + 'c2 = a != b;' + '\n' + 'c3 = a < b;' + '\n' + 'c4 = a <= b;' + '\n' + 'c5 = a > b;' + '\n' + 'c6 = a >= b;' + '\n' + '}' ) c_src24 = ( 'void func()'+ '{' + '\n' + 'float a = 1.25' 'float b = 2.5;' + '\n' + 'bool c1;' + '\n' + 'bool c2;' + '\n' + 'bool c3;' + '\n' + 'bool c4;' + '\n' + 'c1 = a == 1.25;' + '\n' + 'c2 = b == 2.54;' + '\n' + 'c3 = 1.2 != a;' + '\n' + 'c4 = 1.5 != b;' + '\n' + '}' ) c_src25 = ( 'void func()'+ '{' + '\n' + 'float a = 1.25' + '\n' + 'float b = 2.5;' + '\n' + 'bool c1;' + '\n' + 'bool c2;' + '\n' + 'bool c3;' + '\n' + 'bool c4;' + '\n' + 'bool c5;' + '\n' + 'bool c6;' + '\n' + 'c1 = a == b;' + '\n' + 'c2 = a != b;' + '\n' + 'c3 = a < b;' + '\n' + 'c4 = a <= b;' + '\n' + 'c5 = a > b;' + '\n' + 'c6 = a >= b;' + '\n' + '}' ) c_src26 = ( 'void func()'+ '{' + '\n' + 'bool c1;' + '\n' + 'bool c2;' + '\n' + 'bool c3;' + '\n' + 'bool c4;' + '\n' + 'bool c5;' + '\n' + 'bool c6;' + '\n' + 'c1 = true == true;' + '\n' + 'c2 = true == false;' + '\n' + 'c3 = false == false;' + '\n' + 'c4 = true != true;' + '\n' + 'c5 = true != false;' + '\n' + 'c6 = false != false;' + '\n' + '}' ) c_src27 = ( 'void func()'+ '{' + '\n' + 'bool c1;' + '\n' + 'bool c2;' + '\n' + 'bool c3;' + '\n' + 'bool c4;' + '\n' + 'bool c5;' + '\n' + 'bool c6;' + '\n' + 'c1 = true && true;' + '\n' + 'c2 = true && false;' + '\n' + 'c3 = false && false;' + '\n' + 'c4 = true || true;' + '\n' + 'c5 = true || false;' + '\n' + 'c6 = false || false;' + '\n' + '}' ) c_src28 = ( 'void func()'+ '{' + '\n' + 'bool a;' + '\n' + 'bool c1;' + '\n' + 'bool c2;' + '\n' + 'bool c3;' + '\n' + 'bool c4;' + '\n' + 'c1 = a && true;' + '\n' + 'c2 = false && a;' + '\n' + 'c3 = true || a;' + '\n' + 'c4 = a || false;' + '\n' + '}' ) c_src29 = ( 'void func()'+ '{' + '\n' + 'int a;' + '\n' + 'bool c1;' + '\n' + 'bool c2;' + '\n' + 'bool c3;' + '\n' + 'bool c4;' + '\n' + 'c1 = a && 1;' + '\n' + 'c2 = a && 0;' + '\n' + 'c3 = a || 1;' + '\n' + 'c4 = 0 || a;' + '\n' + '}' ) c_src30 = ( 'void func()'+ '{' + '\n' + 'int a;' + '\n' + 'int b;' + '\n' + 'bool c;'+ '\n' + 'bool d;'+ '\n' + 'bool c1;' + '\n' + 'bool c2;' + '\n' + 'bool c3;' + '\n' + 'bool c4;' + '\n' + 'bool c5;' + '\n' + 'bool c6;' + '\n' + 'c1 = a && b;' + '\n' + 'c2 = a && c;' + '\n' + 'c3 = c && d;' + '\n' + 'c4 = a || b;' + '\n' + 'c5 = a || c;' + '\n' + 'c6 = c || d;' + '\n' + '}' ) c_src_raise1 = ( 'void func()'+ '{' + '\n' + 'int a;' + '\n' + 'a = -1;' + '\n' + '}' ) c_src_raise2 = ( 'void func()'+ '{' + '\n' + 'int a;' + '\n' + 'a = -+1;' + '\n' + '}' ) c_src_raise3 = ( 'void func()'+ '{' + '\n' + 'int a;' + '\n' + 'a = 2*-2;' + '\n' + '}' ) c_src_raise4 = ( 'void func()'+ '{' + '\n' + 'int a;' + '\n' + 'a = (int)2.0;' + '\n' + '}' ) c_src_raise5 = ( 'void func()'+ '{' + '\n' + 'int a=100;' + '\n' + 'a = (a==100)?(1):(0);' + '\n' + '}' ) res1 = SymPyExpression(c_src1, 'c').return_expr() res2 = SymPyExpression(c_src2, 'c').return_expr() res3 = SymPyExpression(c_src3, 'c').return_expr() res4 = SymPyExpression(c_src4, 'c').return_expr() res5 = SymPyExpression(c_src5, 'c').return_expr() res6 = SymPyExpression(c_src6, 'c').return_expr() res7 = SymPyExpression(c_src7, 'c').return_expr() res8 = SymPyExpression(c_src8, 'c').return_expr() res9 = SymPyExpression(c_src9, 'c').return_expr() res10 = SymPyExpression(c_src10, 'c').return_expr() res11 = SymPyExpression(c_src11, 'c').return_expr() res12 = SymPyExpression(c_src12, 'c').return_expr() res13 = SymPyExpression(c_src13, 'c').return_expr() res14 = SymPyExpression(c_src14, 'c').return_expr() res15 = SymPyExpression(c_src15, 'c').return_expr() res16 = SymPyExpression(c_src16, 'c').return_expr() res17 = SymPyExpression(c_src17, 'c').return_expr() res18 = SymPyExpression(c_src18, 'c').return_expr() res19 = SymPyExpression(c_src19, 'c').return_expr() res20 = SymPyExpression(c_src20, 'c').return_expr() res21 = SymPyExpression(c_src21, 'c').return_expr() res22 = SymPyExpression(c_src22, 'c').return_expr() res23 = SymPyExpression(c_src23, 'c').return_expr() res24 = SymPyExpression(c_src24, 'c').return_expr() res25 = SymPyExpression(c_src25, 'c').return_expr() res26 = SymPyExpression(c_src26, 'c').return_expr() res27 = SymPyExpression(c_src27, 'c').return_expr() res28 = SymPyExpression(c_src28, 'c').return_expr() res29 = SymPyExpression(c_src29, 'c').return_expr() res30 = SymPyExpression(c_src30, 'c').return_expr() assert res1[0] == FunctionDefinition( NoneToken(), name=String('func'), parameters=(), body=CodeBlock( Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')) ) ), Assignment(Variable(Symbol('a')), Integer(1)) ) ) assert res2[0] == FunctionDefinition( NoneToken(), name=String('func'), parameters=(), body=CodeBlock( Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')), value=Integer(0))), Assignment( Variable(Symbol('a')), Add(Symbol('a'), Integer(1)) ), Assignment(Variable(Symbol('a')), Add( Mul( Integer(3), Symbol('a')), Integer(-10) ) ) ) ) assert res3[0] == FunctionDefinition( NoneToken(), name=String('func'), parameters=(), body=CodeBlock( Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')), value=Integer(10) ) ), Assignment( Variable(Symbol('a')), Add( Symbol('a'), Integer(-17) ) ) ) ) assert res4[0] == FunctionDefinition( NoneToken(), name=String('func'), parameters=(), body=CodeBlock( Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')) ) ), Declaration( Variable(Symbol('b'), type=IntBaseType(String('intc')) ) ), Assignment( Variable(Symbol('a')), Integer(100)), Assignment( Variable(Symbol('b')), Add( Mul( Integer(2), Pow( Symbol('a'), Integer(2)) ), Mul( Integer(20), Symbol('a')), Integer(25) ) ) ) ) assert res5[0] == FunctionDefinition( NoneToken(), name=String('func'), parameters=(), body=CodeBlock( Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')) ) ), Declaration( Variable(Symbol('b'), type=IntBaseType(String('intc')) ) ), Declaration( Variable(Symbol('c'), type=IntBaseType(String('intc')) ) ), Declaration( Variable(Symbol('d'), type=IntBaseType(String('intc')) ) ), Assignment( Variable(Symbol('a')), Integer(1)), Assignment( Variable(Symbol('b')), Integer(2) ), Assignment( Variable(Symbol('c')), Symbol('b')), Assignment( Variable(Symbol('d')), Mul( Add( Symbol('a'), Symbol('b')), Pow( Add( Symbol('a'), Symbol('c') ), Integer(2) ), Add( Symbol('c'), Mul( Integer(-1), Symbol('d') ) ) ) ) ) ) assert res6[0] == FunctionDefinition( NoneToken(), name=String('func'), parameters=(), body=CodeBlock( Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')) ) ), Declaration( Variable(Symbol('b'), type=IntBaseType(String('intc')) ) ), Declaration( Variable(Symbol('c'), type=IntBaseType(String('intc')) ) ), Declaration( Variable(Symbol('d'), type=IntBaseType(String('intc')) ) ), Assignment( Variable(Symbol('a')), Integer(1) ), Assignment( Variable(Symbol('b')), Integer(2) ), Assignment( Variable(Symbol('c')), Integer(3) ), Assignment( Variable(Symbol('d')), Add( Pow( Symbol('a'), Integer(4) ), Mul( Integer(3), Pow( Symbol('b'), Integer(2) ) ), Mul( Integer(2), Symbol('b') ), Mul( Symbol('c'), Symbol('d') ) ) ) ) ) assert res7[0] == FunctionDefinition( NoneToken(), name=String('func'), parameters=(), body=CodeBlock( Declaration( Variable(Symbol('a'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ) ) ), Assignment( Variable(Symbol('a')), Float('1.01', precision=53) ) ) ) assert res8[0] == FunctionDefinition( NoneToken(), name=String('func'), parameters=(), body=CodeBlock( Declaration( Variable(Symbol('a'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ) ) ), Assignment( Variable(Symbol('a')), Float('12.5', precision=53) ) ) ) assert res9[0] == FunctionDefinition( NoneToken(), name=String('func'), parameters=(), body=CodeBlock( Declaration( Variable(Symbol('a'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ) ) ), Assignment( Variable(Symbol('a')), Float('4.0', precision=53) ) ) ) assert res10[0] == FunctionDefinition( NoneToken(), name=String('func'), parameters=(), body=CodeBlock( Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')) ) ), Assignment( Variable(Symbol('a')), Integer(25) ) ) ) assert res11[0] == FunctionDefinition( NoneToken(), name=String('func'), parameters=(), body=CodeBlock( Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')) ) ), Assignment( Variable(Symbol('a')), Integer(-95) ) ) ) assert res12[0] == FunctionDefinition( NoneToken(), name=String('func'), parameters=(), body=CodeBlock( Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')) ) ), Assignment( Variable(Symbol('a')), Integer(-300) ) ) ) assert res13[0] == FunctionDefinition( NoneToken(), name=String('func'), parameters=(), body=CodeBlock( Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')) ) ), Declaration( Variable(Symbol('b'), type=IntBaseType(String('intc')) ) ), Declaration( Variable(Symbol('c'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ) ) ), Assignment( Variable(Symbol('c')), Mul( Pow( Symbol('a'), Integer(-1) ), Symbol('b') ) ) ) ) assert res14[0] == FunctionDefinition( NoneToken(), name=String('func'), parameters=(), body=CodeBlock( Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')), value=Integer(2) ) ), Declaration( Variable(Symbol('d'), type=IntBaseType(String('intc')), value=Integer(5) ) ), Declaration( Variable(Symbol('n'), type=IntBaseType(String('intc')), value=Integer(10) ) ), Declaration( Variable(Symbol('s'), type=IntBaseType(String('intc')) ) ), Assignment( Variable(Symbol('s')), Mul( Rational(1, 2), Symbol('a'), Add( Mul( Integer(2), Symbol('a') ), Mul( Symbol('d'), Add( Symbol('n'), Integer(-1) ) ) ) ) ) ) ) assert res15[0] == FunctionDefinition( NoneToken(), name=String('func'), parameters=(), body=CodeBlock( Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')) ) ), Assignment( Variable(Symbol('a')), Integer(1) ) ) ) assert res16[0] == FunctionDefinition( NoneToken(), name=String('func'), parameters=(), body=CodeBlock( Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')), value=Integer(2) ) ), Declaration( Variable(Symbol('b'), type=IntBaseType(String('intc')) ) ), Assignment( Variable(Symbol('b')), Mod( Symbol('a'), Integer(3) ) ) ) ) assert res17[0] == FunctionDefinition( NoneToken(), name=String('func'), parameters=(), body=CodeBlock( Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')), value=Integer(100) ) ), Declaration( Variable(Symbol('b'), type=IntBaseType(String('intc')), value=Integer(3) ) ), Declaration( Variable(Symbol('c'), type=IntBaseType(String('intc')) ) ), Assignment( Variable(Symbol('c')), Mod( Symbol('a'), Symbol('b') ) ) ) ) assert res18[0] == FunctionDefinition( NoneToken(), name=String('func'), parameters=(), body=CodeBlock( Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')), value=Integer(100) ) ), Declaration( Variable(Symbol('b'), type=IntBaseType(String('intc')), value=Integer(3) ) ), Declaration( Variable(Symbol('mod'), type=IntBaseType(String('intc')), value=Integer(1000000007) ) ), Declaration( Variable(Symbol('c'), type=IntBaseType(String('intc')) ) ), Assignment( Variable(Symbol('c')), Mod( Add( Symbol('a'), Mul( Integer(100), Pow( Symbol('a'), Integer(-1) ), Symbol('b') ) ), Symbol('mod') ) ) ) ) assert res19[0] == FunctionDefinition( NoneToken(), name=String('func'), parameters=(), body=CodeBlock( Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')), value=Integer(100) ) ), Declaration( Variable(Symbol('b'), type=IntBaseType(String('intc')), value=Integer(3) ) ), Declaration( Variable(Symbol('mod'), type=IntBaseType(String('intc')), value=Integer(1000000007) ) ), Declaration( Variable(Symbol('c'), type=IntBaseType(String('intc')) ) ), Assignment( Variable(Symbol('c')), Mod( Mul( Add( Symbol('a'), Mul(Integer(-1), Symbol('b') ) ), Add( Symbol('a'), Symbol('b') ) ), Symbol('mod') ) ) ) ) assert res20[0] == FunctionDefinition( NoneToken(), name=String('func'), parameters=(), body=CodeBlock( Declaration( Variable(Symbol('a'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('b'), type=Type(String('bool')) ) ), Assignment( Variable(Symbol('a')), false ), Assignment( Variable(Symbol('b')), true ) ) ) assert res21[0] == FunctionDefinition( NoneToken(), name=String('func'), parameters=(), body=CodeBlock( Declaration( Variable(Symbol('a'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('b'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('d'), type=Type(String('bool')) ) ), Assignment( Variable(Symbol('a')), false ), Assignment( Variable(Symbol('b')), true ), Assignment( Variable(Symbol('c')), false ), Assignment( Variable(Symbol('d')), false ) ) ) assert res22[0] == FunctionDefinition( NoneToken(), name=String('func'), parameters=(), body=CodeBlock( Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')), value=Integer(1) ) ), Declaration( Variable(Symbol('b'), type=IntBaseType(String('intc')), value=Integer(2) ) ), Declaration( Variable(Symbol('c1'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c2'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c3'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c4'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c5'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c6'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c7'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c8'), type=Type(String('bool')) ) ), Assignment( Variable(Symbol('c1')), Equality( Symbol('a'), Integer(1) ) ), Assignment( Variable(Symbol('c2')), Equality( Symbol('b'), Integer(2) ) ), Assignment( Variable(Symbol('c3')), Unequality( Integer(1), Symbol('a') ) ), Assignment( Variable(Symbol('c4')), Unequality( Integer(1), Symbol('b') ) ), Assignment( Variable(Symbol('c5')), StrictLessThan( Symbol('a'), Integer(0) ) ), Assignment( Variable(Symbol('c6')), LessThan( Symbol('b'), Integer(10) ) ), Assignment( Variable(Symbol('c7')), StrictGreaterThan( Symbol('a'), Integer(0) ) ), Assignment( Variable(Symbol('c8')), GreaterThan( Symbol('b'), Integer(11) ) ) ) ) assert res23[0] == FunctionDefinition( NoneToken(), name=String('func'), parameters=(), body=CodeBlock( Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')), value=Integer(3) ) ), Declaration( Variable(Symbol('b'), type=IntBaseType(String('intc')), value=Integer(4) ) ), Declaration( Variable(Symbol('c1'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c2'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c3'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c4'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c5'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c6'), type=Type(String('bool')) ) ), Assignment( Variable(Symbol('c1')), Equality( Symbol('a'), Symbol('b') ) ), Assignment( Variable(Symbol('c2')), Unequality( Symbol('a'), Symbol('b') ) ), Assignment( Variable(Symbol('c3')), StrictLessThan( Symbol('a'), Symbol('b') ) ), Assignment( Variable(Symbol('c4')), LessThan( Symbol('a'), Symbol('b') ) ), Assignment( Variable(Symbol('c5')), StrictGreaterThan( Symbol('a'), Symbol('b') ) ), Assignment( Variable(Symbol('c6')), GreaterThan( Symbol('a'), Symbol('b') ) ) ) ) assert res24[0] == FunctionDefinition( NoneToken(), name=String('func'), parameters=(), body=CodeBlock( Declaration( Variable(Symbol('a'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ) ) ), Declaration( Variable(Symbol('c1'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c2'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c3'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c4'), type=Type(String('bool')) ) ), Assignment( Variable(Symbol('c1')), Equality( Symbol('a'), Float('1.25', precision=53) ) ), Assignment( Variable(Symbol('c3')), Unequality( Float('1.2', precision=53), Symbol('a') ) ) ) ) assert res25[0] == FunctionDefinition( NoneToken(), name=String('func'), parameters=(), body=CodeBlock( Declaration( Variable(Symbol('a'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ), value=Float('1.25', precision=53) ) ), Declaration( Variable(Symbol('b'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ), value=Float('2.5', precision=53) ) ), Declaration( Variable(Symbol('c1'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c2'), type=Type(String('bool') ) ) ), Declaration( Variable(Symbol('c3'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c4'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c5'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c6'), type=Type(String('bool')) ) ), Assignment( Variable(Symbol('c1')), Equality( Symbol('a'), Symbol('b') ) ), Assignment( Variable(Symbol('c2')), Unequality( Symbol('a'), Symbol('b') ) ), Assignment( Variable(Symbol('c3')), StrictLessThan( Symbol('a'), Symbol('b') ) ), Assignment( Variable(Symbol('c4')), LessThan( Symbol('a'), Symbol('b') ) ), Assignment( Variable(Symbol('c5')), StrictGreaterThan( Symbol('a'), Symbol('b') ) ), Assignment( Variable(Symbol('c6')), GreaterThan( Symbol('a'), Symbol('b') ) ) ) ) assert res26[0] == FunctionDefinition( NoneToken(), name=String('func'), parameters=(), body=CodeBlock( Declaration( Variable(Symbol('c1'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c2'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c3'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c4'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c5'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c6'), type=Type(String('bool')) ) ), Assignment( Variable(Symbol('c1')), true ), Assignment( Variable(Symbol('c2')), false ), Assignment( Variable(Symbol('c3')), true ), Assignment( Variable(Symbol('c4')), false ), Assignment( Variable(Symbol('c5')), true ), Assignment( Variable(Symbol('c6')), false ) ) ) assert res27[0] == FunctionDefinition( NoneToken(), name=String('func'), parameters=(), body=CodeBlock( Declaration( Variable(Symbol('c1'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c2'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c3'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c4'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c5'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c6'), type=Type(String('bool')) ) ), Assignment( Variable(Symbol('c1')), true ), Assignment( Variable(Symbol('c2')), false ), Assignment( Variable(Symbol('c3')), false ), Assignment( Variable(Symbol('c4')), true ), Assignment( Variable(Symbol('c5')), true ), Assignment( Variable(Symbol('c6')), false) ) ) assert res28[0] == FunctionDefinition( NoneToken(), name=String('func'), parameters=(), body=CodeBlock( Declaration( Variable(Symbol('a'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c1'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c2'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c3'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c4'), type=Type(String('bool')) ) ), Assignment( Variable(Symbol('c1')), Symbol('a') ), Assignment( Variable(Symbol('c2')), false ), Assignment( Variable(Symbol('c3')), true ), Assignment( Variable(Symbol('c4')), Symbol('a') ) ) ) assert res29[0] == FunctionDefinition( NoneToken(), name=String('func'), parameters=(), body=CodeBlock( Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')) ) ), Declaration( Variable(Symbol('c1'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c2'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c3'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c4'), type=Type(String('bool')) ) ), Assignment( Variable(Symbol('c1')), Symbol('a') ), Assignment( Variable(Symbol('c2')), false ), Assignment( Variable(Symbol('c3')), true ), Assignment( Variable(Symbol('c4')), Symbol('a') ) ) ) assert res30[0] == FunctionDefinition( NoneToken(), name=String('func'), parameters=(), body=CodeBlock( Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')) ) ), Declaration( Variable(Symbol('b'), type=IntBaseType(String('intc')) ) ), Declaration( Variable(Symbol('c'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('d'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c1'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c2'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c3'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c4'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c5'), type=Type(String('bool')) ) ), Declaration( Variable(Symbol('c6'), type=Type(String('bool')) ) ), Assignment( Variable(Symbol('c1')), And( Symbol('a'), Symbol('b') ) ), Assignment( Variable(Symbol('c2')), And( Symbol('a'), Symbol('c') ) ), Assignment( Variable(Symbol('c3')), And( Symbol('c'), Symbol('d') ) ), Assignment( Variable(Symbol('c4')), Or( Symbol('a'), Symbol('b') ) ), Assignment( Variable(Symbol('c5')), Or( Symbol('a'), Symbol('c') ) ), Assignment( Variable(Symbol('c6')), Or( Symbol('c'), Symbol('d') ) ) ) ) raises(NotImplementedError, lambda: SymPyExpression(c_src_raise1, 'c')) raises(NotImplementedError, lambda: SymPyExpression(c_src_raise2, 'c')) raises(NotImplementedError, lambda: SymPyExpression(c_src_raise3, 'c')) raises(NotImplementedError, lambda: SymPyExpression(c_src_raise4, 'c')) raises(NotImplementedError, lambda: SymPyExpression(c_src_raise5, 'c')) @XFAIL def test_var_decl(): c_src1 = ( 'int b = 100;' + '\n' + 'int a = b;' + '\n' ) c_src2 = ( 'int a = 1;' + '\n' + 'int b = a + 1;' + '\n' ) c_src3 = ( 'float a = 10.0 + 2.5;' + '\n' + 'float b = a * 20.0;' + '\n' ) c_src4 = ( 'int a = 1 + 100 - 3 * 6;' + '\n' ) c_src5 = ( 'int a = (((1 + 100) * 12) - 3) * (6 - 10);' + '\n' ) c_src6 = ( 'int b = 2;' + '\n' + 'int c = 3;' + '\n' + 'int a = b + c * 4;' + '\n' ) c_src7 = ( 'int b = 1;' + '\n' + 'int c = b + 2;' + '\n' + 'int a = 10 * b * b * c;' + '\n' ) c_src8 = ( 'void func()'+ '{' + '\n' + 'int a = 1;' + '\n' + 'int b = 2;' + '\n' + 'int temp = a;' + '\n' + 'a = b;' + '\n' + 'b = temp;' + '\n' + '}' ) c_src9 = ( 'int a = 1;' + '\n' + 'int b = 2;' + '\n' + 'int c = a;' + '\n' + 'int d = a + b + c;' + '\n' + 'int e = a*a*a + 3*a*a*b + 3*a*b*b + b*b*b;' + '\n' 'int f = (a + b + c) * (a + b - c);' + '\n' + 'int g = (a + b + c + d)*(a + b + c + d)*(a * (b - c));' + '\n' ) c_src10 = ( 'float a = 10.0;' + '\n' + 'float b = 2.5;' + '\n' + 'float c = a*a + 2*a*b + b*b;' + '\n' ) c_src11 = ( 'float a = 10.0 / 2.5;' + '\n' ) c_src12 = ( 'int a = 100 / 4;' + '\n' ) c_src13 = ( 'int a = 20 - 100 / 4 * 5 + 10;' + '\n' ) c_src14 = ( 'int a = (20 - 100) / 4 * (5 + 10);' + '\n' ) c_src15 = ( 'int a = 4;' + '\n' + 'int b = 2;' + '\n' + 'float c = b/a;' + '\n' ) c_src16 = ( 'int a = 2;' + '\n' + 'int d = 5;' + '\n' + 'int n = 10;' + '\n' + 'int s = (a/2)*(2*a + (n-1)*d);' + '\n' ) c_src17 = ( 'int a = 1 % 2;' + '\n' ) c_src18 = ( 'int a = 2;' + '\n' + 'int b = a % 3;' + '\n' ) c_src19 = ( 'int a = 100;' + '\n' + 'int b = 3;' + '\n' + 'int c = a % b;' + '\n' ) c_src20 = ( 'int a = 100;' + '\n' + 'int b = 3;' + '\n' + 'int mod = 1000000007;' + '\n' + 'int c = (a + b * (100/a)) % mod;' + '\n' ) c_src21 = ( 'int a = 100;' + '\n' + 'int b = 3;' + '\n' + 'int mod = 1000000007;' + '\n' + 'int c = ((a % mod + b % mod) % mod *(' \ 'a % mod - b % mod) % mod) % mod;' + '\n' ) c_src22 = ( 'bool a = 1 == 2, b = 1 != 2;' ) c_src23 = ( 'bool a = 1 < 2, b = 1 <= 2, c = 1 > 2, d = 1 >= 2;' ) c_src24 = ( 'int a = 1, b = 2;' + '\n' + 'bool c1 = a == 1;' + '\n' + 'bool c2 = b == 2;' + '\n' + 'bool c3 = 1 != a;' + '\n' + 'bool c4 = 1 != b;' + '\n' + 'bool c5 = a < 0;' + '\n' + 'bool c6 = b <= 10;' + '\n' + 'bool c7 = a > 0;' + '\n' + 'bool c8 = b >= 11;' ) c_src25 = ( 'int a = 3, b = 4;' + '\n' + 'bool c1 = a == b;' + '\n' + 'bool c2 = a != b;' + '\n' + 'bool c3 = a < b;' + '\n' + 'bool c4 = a <= b;' + '\n' + 'bool c5 = a > b;' + '\n' + 'bool c6 = a >= b;' ) c_src26 = ( 'float a = 1.25, b = 2.5;' + '\n' + 'bool c1 = a == 1.25;' + '\n' + 'bool c2 = b == 2.54;' + '\n' + 'bool c3 = 1.2 != a;' + '\n' + 'bool c4 = 1.5 != b;' ) c_src27 = ( 'float a = 1.25, b = 2.5;' + '\n' + 'bool c1 = a == b;' + '\n' + 'bool c2 = a != b;' + '\n' + 'bool c3 = a < b;' + '\n' + 'bool c4 = a <= b;' + '\n' + 'bool c5 = a > b;' + '\n' + 'bool c6 = a >= b;' ) c_src28 = ( 'bool c1 = true == true;' + '\n' + 'bool c2 = true == false;' + '\n' + 'bool c3 = false == false;' + '\n' + 'bool c4 = true != true;' + '\n' + 'bool c5 = true != false;' + '\n' + 'bool c6 = false != false;' ) c_src29 = ( 'bool c1 = true && true;' + '\n' + 'bool c2 = true && false;' + '\n' + 'bool c3 = false && false;' + '\n' + 'bool c4 = true || true;' + '\n' + 'bool c5 = true || false;' + '\n' + 'bool c6 = false || false;' ) c_src30 = ( 'bool a = false;' + '\n' + 'bool c1 = a && true;' + '\n' + 'bool c2 = false && a;' + '\n' + 'bool c3 = true || a;' + '\n' + 'bool c4 = a || false;' ) c_src31 = ( 'int a = 1;' + '\n' + 'bool c1 = a && 1;' + '\n' + 'bool c2 = a && 0;' + '\n' + 'bool c3 = a || 1;' + '\n' + 'bool c4 = 0 || a;' ) c_src32 = ( 'int a = 1, b = 0;' + '\n' + 'bool c = false, d = true;'+ '\n' + 'bool c1 = a && b;' + '\n' + 'bool c2 = a && c;' + '\n' + 'bool c3 = c && d;' + '\n' + 'bool c4 = a || b;' + '\n' + 'bool c5 = a || c;' + '\n' + 'bool c6 = c || d;' ) c_src_raise1 = ( "char a = 'b';" ) c_src_raise2 = ( 'int a[] = {10, 20};' ) res1 = SymPyExpression(c_src1, 'c').return_expr() res2 = SymPyExpression(c_src2, 'c').return_expr() res3 = SymPyExpression(c_src3, 'c').return_expr() res4 = SymPyExpression(c_src4, 'c').return_expr() res5 = SymPyExpression(c_src5, 'c').return_expr() res6 = SymPyExpression(c_src6, 'c').return_expr() res7 = SymPyExpression(c_src7, 'c').return_expr() res8 = SymPyExpression(c_src8, 'c').return_expr() res9 = SymPyExpression(c_src9, 'c').return_expr() res10 = SymPyExpression(c_src10, 'c').return_expr() res11 = SymPyExpression(c_src11, 'c').return_expr() res12 = SymPyExpression(c_src12, 'c').return_expr() res13 = SymPyExpression(c_src13, 'c').return_expr() res14 = SymPyExpression(c_src14, 'c').return_expr() res15 = SymPyExpression(c_src15, 'c').return_expr() res16 = SymPyExpression(c_src16, 'c').return_expr() res17 = SymPyExpression(c_src17, 'c').return_expr() res18 = SymPyExpression(c_src18, 'c').return_expr() res19 = SymPyExpression(c_src19, 'c').return_expr() res20 = SymPyExpression(c_src20, 'c').return_expr() res21 = SymPyExpression(c_src21, 'c').return_expr() res22 = SymPyExpression(c_src22, 'c').return_expr() res23 = SymPyExpression(c_src23, 'c').return_expr() res24 = SymPyExpression(c_src24, 'c').return_expr() res25 = SymPyExpression(c_src25, 'c').return_expr() res26 = SymPyExpression(c_src26, 'c').return_expr() res27 = SymPyExpression(c_src27, 'c').return_expr() res28 = SymPyExpression(c_src28, 'c').return_expr() res29 = SymPyExpression(c_src29, 'c').return_expr() res30 = SymPyExpression(c_src30, 'c').return_expr() res31 = SymPyExpression(c_src31, 'c').return_expr() res32 = SymPyExpression(c_src32, 'c').return_expr() assert res1[0] == Declaration( Variable(Symbol('b'), type=IntBaseType(String('intc')), value=Integer(100) ) ) assert res1[1] == Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')), value=Symbol('b') ) ) assert res2[0] == Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')), value=Integer(1) ) ) assert res2[1] == Declaration(Variable(Symbol('b'), type=IntBaseType(String('intc')), value=Add( Symbol('a'), Integer(1) ) ) ) assert res3[0] == Declaration( Variable(Symbol('a'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ), value=Float('12.5', precision=53) ) ) assert res3[1] == Declaration( Variable(Symbol('b'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ), value=Mul( Float('20.0', precision=53), Symbol('a') ) ) ) assert res4[0] == Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')), value=Integer(83) ) ) assert res5[0] == Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')), value=Integer(-4836) ) ) assert res6[0] == Declaration( Variable(Symbol('b'), type=IntBaseType(String('intc')), value=Integer(2) ) ) assert res6[1] == Declaration( Variable(Symbol('c'), type=IntBaseType(String('intc')), value=Integer(3) ) ) assert res6[2] == Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')), value=Add( Symbol('b'), Mul( Integer(4), Symbol('c') ) ) ) ) assert res7[0] == Declaration( Variable(Symbol('b'), type=IntBaseType(String('intc')), value=Integer(1) ) ) assert res7[1] == Declaration( Variable(Symbol('c'), type=IntBaseType(String('intc')), value=Add( Symbol('b'), Integer(2) ) ) ) assert res7[2] == Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')), value=Mul( Integer(10), Pow( Symbol('b'), Integer(2) ), Symbol('c') ) ) ) assert res8[0] == FunctionDefinition( NoneToken(), name=String('func'), parameters=(), body=CodeBlock( Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')), value=Integer(1) ) ), Declaration( Variable(Symbol('b'), type=IntBaseType(String('intc')), value=Integer(2) ) ), Declaration( Variable(Symbol('temp'), type=IntBaseType(String('intc')), value=Symbol('a') ) ), Assignment( Variable(Symbol('a')), Symbol('b') ), Assignment( Variable(Symbol('b')), Symbol('temp') ) ) ) assert res9[0] == Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')), value=Integer(1) ) ) assert res9[1] == Declaration( Variable(Symbol('b'), type=IntBaseType(String('intc')), value=Integer(2) ) ) assert res9[2] == Declaration( Variable(Symbol('c'), type=IntBaseType(String('intc')), value=Symbol('a') ) ) assert res9[3] == Declaration( Variable(Symbol('d'), type=IntBaseType(String('intc')), value=Add( Symbol('a'), Symbol('b'), Symbol('c') ) ) ) assert res9[4] == Declaration( Variable(Symbol('e'), type=IntBaseType(String('intc')), value=Add( Pow( Symbol('a'), Integer(3) ), Mul( Integer(3), Pow( Symbol('a'), Integer(2) ), Symbol('b') ), Mul( Integer(3), Symbol('a'), Pow( Symbol('b'), Integer(2) ) ), Pow( Symbol('b'), Integer(3) ) ) ) ) assert res9[5] == Declaration( Variable(Symbol('f'), type=IntBaseType(String('intc')), value=Mul( Add( Symbol('a'), Symbol('b'), Mul( Integer(-1), Symbol('c') ) ), Add( Symbol('a'), Symbol('b'), Symbol('c') ) ) ) ) assert res9[6] == Declaration( Variable(Symbol('g'), type=IntBaseType(String('intc')), value=Mul( Symbol('a'), Add( Symbol('b'), Mul( Integer(-1), Symbol('c') ) ), Pow( Add( Symbol('a'), Symbol('b'), Symbol('c'), Symbol('d') ), Integer(2) ) ) ) ) assert res10[0] == Declaration( Variable(Symbol('a'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ), value=Float('10.0', precision=53) ) ) assert res10[1] == Declaration( Variable(Symbol('b'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ), value=Float('2.5', precision=53) ) ) assert res10[2] == Declaration( Variable(Symbol('c'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ), value=Add( Pow( Symbol('a'), Integer(2) ), Mul( Integer(2), Symbol('a'), Symbol('b') ), Pow( Symbol('b'), Integer(2) ) ) ) ) assert res11[0] == Declaration( Variable(Symbol('a'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ), value=Float('4.0', precision=53) ) ) assert res12[0] == Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')), value=Integer(25) ) ) assert res13[0] == Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')), value=Integer(-95) ) ) assert res14[0] == Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')), value=Integer(-300) ) ) assert res15[0] == Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')), value=Integer(4) ) ) assert res15[1] == Declaration( Variable(Symbol('b'), type=IntBaseType(String('intc')), value=Integer(2) ) ) assert res15[2] == Declaration( Variable(Symbol('c'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ), value=Mul( Pow( Symbol('a'), Integer(-1) ), Symbol('b') ) ) ) assert res16[0] == Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')), value=Integer(2) ) ) assert res16[1] == Declaration( Variable(Symbol('d'), type=IntBaseType(String('intc')), value=Integer(5) ) ) assert res16[2] == Declaration( Variable(Symbol('n'), type=IntBaseType(String('intc')), value=Integer(10) ) ) assert res16[3] == Declaration( Variable(Symbol('s'), type=IntBaseType(String('intc')), value=Mul( Rational(1, 2), Symbol('a'), Add( Mul( Integer(2), Symbol('a') ), Mul( Symbol('d'), Add( Symbol('n'), Integer(-1) ) ) ) ) ) ) assert res17[0] == Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')), value=Integer(1) ) ) assert res18[0] == Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')), value=Integer(2) ) ) assert res18[1] == Declaration( Variable(Symbol('b'), type=IntBaseType(String('intc')), value=Mod( Symbol('a'), Integer(3) ) ) ) assert res19[0] == Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')), value=Integer(100) ) ) assert res19[1] == Declaration( Variable(Symbol('b'), type=IntBaseType(String('intc')), value=Integer(3) ) ) assert res19[2] == Declaration( Variable(Symbol('c'), type=IntBaseType(String('intc')), value=Mod( Symbol('a'), Symbol('b') ) ) ) assert res20[0] == Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')), value=Integer(100) ) ) assert res20[1] == Declaration( Variable(Symbol('b'), type=IntBaseType(String('intc')), value=Integer(3) ) ) assert res20[2] == Declaration( Variable(Symbol('mod'), type=IntBaseType(String('intc')), value=Integer(1000000007) ) ) assert res20[3] == Declaration( Variable(Symbol('c'), type=IntBaseType(String('intc')), value=Mod( Add( Symbol('a'), Mul( Integer(100), Pow( Symbol('a'), Integer(-1) ), Symbol('b') ) ), Symbol('mod') ) ) ) assert res21[0] == Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')), value=Integer(100) ) ) assert res21[1] == Declaration( Variable(Symbol('b'), type=IntBaseType(String('intc')), value=Integer(3) ) ) assert res21[2] == Declaration( Variable(Symbol('mod'), type=IntBaseType(String('intc')), value=Integer(1000000007) ) ) assert res21[3] == Declaration( Variable(Symbol('c'), type=IntBaseType(String('intc')), value=Mod( Mul( Add( Symbol('a'), Mul( Integer(-1), Symbol('b') ) ), Add( Symbol('a'), Symbol('b') ) ), Symbol('mod') ) ) ) assert res22[0] == Declaration( Variable(Symbol('a'), type=Type(String('bool')), value=false ) ) assert res22[1] == Declaration( Variable(Symbol('b'), type=Type(String('bool')), value=true ) ) assert res23[0] == Declaration( Variable(Symbol('a'), type=Type(String('bool')), value=true ) ) assert res23[1] == Declaration( Variable(Symbol('b'), type=Type(String('bool')), value=true ) ) assert res23[2] == Declaration( Variable(Symbol('c'), type=Type(String('bool')), value=false ) ) assert res23[3] == Declaration( Variable(Symbol('d'), type=Type(String('bool')), value=false ) ) assert res24[0] == Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')), value=Integer(1) ) ) assert res24[1] == Declaration( Variable(Symbol('b'), type=IntBaseType(String('intc')), value=Integer(2) ) ) assert res24[2] == Declaration( Variable(Symbol('c1'), type=Type(String('bool')), value=Equality( Symbol('a'), Integer(1) ) ) ) assert res24[3] == Declaration( Variable(Symbol('c2'), type=Type(String('bool')), value=Equality( Symbol('b'), Integer(2) ) ) ) assert res24[4] == Declaration( Variable(Symbol('c3'), type=Type(String('bool')), value=Unequality( Integer(1), Symbol('a') ) ) ) assert res24[5] == Declaration( Variable(Symbol('c4'), type=Type(String('bool')), value=Unequality( Integer(1), Symbol('b') ) ) ) assert res24[6] == Declaration( Variable(Symbol('c5'), type=Type(String('bool')), value=StrictLessThan(Symbol('a'), Integer(0) ) ) ) assert res24[7] == Declaration( Variable(Symbol('c6'), type=Type(String('bool')), value=LessThan( Symbol('b'), Integer(10) ) ) ) assert res24[8] == Declaration( Variable(Symbol('c7'), type=Type(String('bool')), value=StrictGreaterThan( Symbol('a'), Integer(0) ) ) ) assert res24[9] == Declaration( Variable(Symbol('c8'), type=Type(String('bool')), value=GreaterThan( Symbol('b'), Integer(11) ) ) ) assert res25[0] == Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')), value=Integer(3) ) ) assert res25[1] == Declaration( Variable(Symbol('b'), type=IntBaseType(String('intc')), value=Integer(4) ) ) assert res25[2] == Declaration(Variable(Symbol('c1'), type=Type(String('bool')), value=Equality( Symbol('a'), Symbol('b') ) ) ) assert res25[3] == Declaration( Variable(Symbol('c2'), type=Type(String('bool')), value=Unequality( Symbol('a'), Symbol('b') ) ) ) assert res25[4] == Declaration( Variable(Symbol('c3'), type=Type(String('bool')), value=StrictLessThan( Symbol('a'), Symbol('b') ) ) ) assert res25[5] == Declaration( Variable(Symbol('c4'), type=Type(String('bool')), value=LessThan( Symbol('a'), Symbol('b') ) ) ) assert res25[6] == Declaration( Variable(Symbol('c5'), type=Type(String('bool')), value=StrictGreaterThan( Symbol('a'), Symbol('b') ) ) ) assert res25[7] == Declaration( Variable(Symbol('c6'), type=Type(String('bool')), value=GreaterThan( Symbol('a'), Symbol('b') ) ) ) assert res26[0] == Declaration( Variable(Symbol('a'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ), value=Float('1.25', precision=53) ) ) assert res26[1] == Declaration( Variable(Symbol('b'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ), value=Float('2.5', precision=53) ) ) assert res26[2] == Declaration( Variable(Symbol('c1'), type=Type(String('bool')), value=Equality( Symbol('a'), Float('1.25', precision=53) ) ) ) assert res26[3] == Declaration( Variable(Symbol('c2'), type=Type(String('bool')), value=Equality( Symbol('b'), Float('2.54', precision=53) ) ) ) assert res26[4] == Declaration( Variable(Symbol('c3'), type=Type(String('bool')), value=Unequality( Float('1.2', precision=53), Symbol('a') ) ) ) assert res26[5] == Declaration( Variable(Symbol('c4'), type=Type(String('bool')), value=Unequality( Float('1.5', precision=53), Symbol('b') ) ) ) assert res27[0] == Declaration( Variable(Symbol('a'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ), value=Float('1.25', precision=53) ) ) assert res27[1] == Declaration( Variable(Symbol('b'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ), value=Float('2.5', precision=53) ) ) assert res27[2] == Declaration( Variable(Symbol('c1'), type=Type(String('bool')), value=Equality( Symbol('a'), Symbol('b') ) ) ) assert res27[3] == Declaration( Variable(Symbol('c2'), type=Type(String('bool')), value=Unequality( Symbol('a'), Symbol('b') ) ) ) assert res27[4] == Declaration( Variable(Symbol('c3'), type=Type(String('bool')), value=StrictLessThan( Symbol('a'), Symbol('b') ) ) ) assert res27[5] == Declaration( Variable(Symbol('c4'), type=Type(String('bool')), value=LessThan( Symbol('a'), Symbol('b') ) ) ) assert res27[6] == Declaration( Variable(Symbol('c5'), type=Type(String('bool')), value=StrictGreaterThan( Symbol('a'), Symbol('b') ) ) ) assert res27[7] == Declaration( Variable(Symbol('c6'), type=Type(String('bool')), value=GreaterThan( Symbol('a'), Symbol('b') ) ) ) assert res28[0] == Declaration( Variable(Symbol('c1'), type=Type(String('bool')), value=true ) ) assert res28[1] == Declaration( Variable(Symbol('c2'), type=Type(String('bool')), value=false ) ) assert res28[2] == Declaration( Variable(Symbol('c3'), type=Type(String('bool')), value=true ) ) assert res28[3] == Declaration( Variable(Symbol('c4'), type=Type(String('bool')), value=false ) ) assert res28[4] == Declaration( Variable(Symbol('c5'), type=Type(String('bool')), value=true ) ) assert res28[5] == Declaration( Variable(Symbol('c6'), type=Type(String('bool')), value=false ) ) assert res29[0] == Declaration( Variable(Symbol('c1'), type=Type(String('bool')), value=true ) ) assert res29[1] == Declaration( Variable(Symbol('c2'), type=Type(String('bool')), value=false ) ) assert res29[2] == Declaration( Variable(Symbol('c3'), type=Type(String('bool')), value=false ) ) assert res29[3] == Declaration( Variable(Symbol('c4'), type=Type(String('bool')), value=true ) ) assert res29[4] == Declaration( Variable(Symbol('c5'), type=Type(String('bool')), value=true ) ) assert res29[5] == Declaration( Variable(Symbol('c6'), type=Type(String('bool')), value=false ) ) assert res30[0] == Declaration( Variable(Symbol('a'), type=Type(String('bool')), value=false ) ) assert res30[1] == Declaration( Variable(Symbol('c1'), type=Type(String('bool')), value=Symbol('a') ) ) assert res30[2] == Declaration( Variable(Symbol('c2'), type=Type(String('bool')), value=false ) ) assert res30[3] == Declaration( Variable(Symbol('c3'), type=Type(String('bool')), value=true ) ) assert res30[4] == Declaration( Variable(Symbol('c4'), type=Type(String('bool')), value=Symbol('a') ) ) assert res31[0] == Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')), value=Integer(1) ) ) assert res31[1] == Declaration( Variable(Symbol('c1'), type=Type(String('bool')), value=Symbol('a') ) ) assert res31[2] == Declaration( Variable(Symbol('c2'), type=Type(String('bool')), value=false ) ) assert res31[3] == Declaration( Variable(Symbol('c3'), type=Type(String('bool')), value=true ) ) assert res31[4] == Declaration( Variable(Symbol('c4'), type=Type(String('bool')), value=Symbol('a') ) ) assert res32[0] == Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')), value=Integer(1) ) ) assert res32[1] == Declaration( Variable(Symbol('b'), type=IntBaseType(String('intc')), value=Integer(0) ) ) assert res32[2] == Declaration( Variable(Symbol('c'), type=Type(String('bool')), value=false ) ) assert res32[3] == Declaration( Variable(Symbol('d'), type=Type(String('bool')), value=true ) ) assert res32[4] == Declaration( Variable(Symbol('c1'), type=Type(String('bool')), value=And( Symbol('a'), Symbol('b') ) ) ) assert res32[5] == Declaration( Variable(Symbol('c2'), type=Type(String('bool')), value=And( Symbol('a'), Symbol('c') ) ) ) assert res32[6] == Declaration( Variable(Symbol('c3'), type=Type(String('bool')), value=And( Symbol('c'), Symbol('d') ) ) ) assert res32[7] == Declaration( Variable(Symbol('c4'), type=Type(String('bool')), value=Or( Symbol('a'), Symbol('b') ) ) ) assert res32[8] == Declaration( Variable(Symbol('c5'), type=Type(String('bool')), value=Or( Symbol('a'), Symbol('c') ) ) ) assert res32[9] == Declaration( Variable(Symbol('c6'), type=Type(String('bool')), value=Or( Symbol('c'), Symbol('d') ) ) ) raises(NotImplementedError, lambda: SymPyExpression(c_src_raise1, 'c')) raises(NotImplementedError, lambda: SymPyExpression(c_src_raise2, 'c')) def test_paren_expr(): c_src1 = ( 'int a = (1);' 'int b = (1 + 2 * 3);' ) c_src2 = ( 'int a = 1, b = 2, c = 3;' 'int d = (a);' 'int e = (a + 1);' 'int f = (a + b * c - d / e);' ) res1 = SymPyExpression(c_src1, 'c').return_expr() res2 = SymPyExpression(c_src2, 'c').return_expr() assert res1[0] == Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')), value=Integer(1) ) ) assert res1[1] == Declaration( Variable(Symbol('b'), type=IntBaseType(String('intc')), value=Integer(7) ) ) assert res2[0] == Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')), value=Integer(1) ) ) assert res2[1] == Declaration( Variable(Symbol('b'), type=IntBaseType(String('intc')), value=Integer(2) ) ) assert res2[2] == Declaration( Variable(Symbol('c'), type=IntBaseType(String('intc')), value=Integer(3) ) ) assert res2[3] == Declaration( Variable(Symbol('d'), type=IntBaseType(String('intc')), value=Symbol('a') ) ) assert res2[4] == Declaration( Variable(Symbol('e'), type=IntBaseType(String('intc')), value=Add( Symbol('a'), Integer(1) ) ) ) assert res2[5] == Declaration( Variable(Symbol('f'), type=IntBaseType(String('intc')), value=Add( Symbol('a'), Mul( Symbol('b'), Symbol('c') ), Mul( Integer(-1), Symbol('d'), Pow( Symbol('e'), Integer(-1) ) ) ) ) ) def test_unary_operators(): c_src1 = ( 'void func()'+ '{' + '\n' + 'int a = 10;' + '\n' + 'int b = 20;' + '\n' + '++a;' + '\n' + '--b;' + '\n' + 'a++;' + '\n' + 'b--;' + '\n' + '}' ) c_src2 = ( 'void func()'+ '{' + '\n' + 'int a = 10;' + '\n' + 'int b = -100;' + '\n' + 'int c = +19;' + '\n' + 'int d = ++a;' + '\n' + 'int e = --b;' + '\n' + 'int f = a++;' + '\n' + 'int g = b--;' + '\n' + 'bool h = !false;' + '\n' + 'bool i = !d;' + '\n' + 'bool j = !0;' + '\n' + 'bool k = !10.0;' + '\n' + '}' ) c_src_raise1 = ( 'void func()'+ '{' + '\n' + 'int a = 10;' + '\n' + 'int b = ~a;' + '\n' + '}' ) c_src_raise2 = ( 'void func()'+ '{' + '\n' + 'int a = 10;' + '\n' + 'int b = *&a;' + '\n' + '}' ) res1 = SymPyExpression(c_src1, 'c').return_expr() res2 = SymPyExpression(c_src2, 'c').return_expr() assert res1[0] == FunctionDefinition( NoneToken(), name=String('func'), parameters=(), body=CodeBlock( Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')), value=Integer(10) ) ), Declaration( Variable(Symbol('b'), type=IntBaseType(String('intc')), value=Integer(20) ) ), PreIncrement(Symbol('a')), PreDecrement(Symbol('b')), PostIncrement(Symbol('a')), PostDecrement(Symbol('b')) ) ) assert res2[0] == FunctionDefinition( NoneToken(), name=String('func'), parameters=(), body=CodeBlock( Declaration( Variable(Symbol('a'), type=IntBaseType(String('intc')), value=Integer(10) ) ), Declaration( Variable(Symbol('b'), type=IntBaseType(String('intc')), value=Integer(-100) ) ), Declaration( Variable(Symbol('c'), type=IntBaseType(String('intc')), value=Integer(19) ) ), Declaration( Variable(Symbol('d'), type=IntBaseType(String('intc')), value=PreIncrement(Symbol('a')) ) ), Declaration( Variable(Symbol('e'), type=IntBaseType(String('intc')), value=PreDecrement(Symbol('b')) ) ), Declaration( Variable(Symbol('f'), type=IntBaseType(String('intc')), value=PostIncrement(Symbol('a')) ) ), Declaration( Variable(Symbol('g'), type=IntBaseType(String('intc')), value=PostDecrement(Symbol('b')) ) ), Declaration( Variable(Symbol('h'), type=Type(String('bool')), value=true ) ), Declaration( Variable(Symbol('i'), type=Type(String('bool')), value=Not(Symbol('d')) ) ), Declaration( Variable(Symbol('j'), type=Type(String('bool')), value=true ) ), Declaration( Variable(Symbol('k'), type=Type(String('bool')), value=false ) ) ) ) raises(NotImplementedError, lambda: SymPyExpression(c_src_raise1, 'c')) raises(NotImplementedError, lambda: SymPyExpression(c_src_raise2, 'c')) def test_compound_assignment_operator(): c_src = ( 'void func()'+ '{' + '\n' + 'int a = 100;' + '\n' + 'a += 10;' + '\n' + 'a -= 10;' + '\n' + 'a *= 10;' + '\n' + 'a /= 10;' + '\n' + 'a %= 10;' + '\n' + '}' ) res = SymPyExpression(c_src, 'c').return_expr() assert res[0] == FunctionDefinition( NoneToken(), name=String('func'), parameters=(), body=CodeBlock( Declaration( Variable( Symbol('a'), type=IntBaseType(String('intc')), value=Integer(100) ) ), AddAugmentedAssignment( Variable(Symbol('a')), Integer(10) ), SubAugmentedAssignment( Variable(Symbol('a')), Integer(10) ), MulAugmentedAssignment( Variable(Symbol('a')), Integer(10) ), DivAugmentedAssignment( Variable(Symbol('a')), Integer(10) ), ModAugmentedAssignment( Variable(Symbol('a')), Integer(10) ) ) ) def test_while_stmt(): c_src1 = ( 'void func()'+ '{' + '\n' + 'int i = 0;' + '\n' + 'while(i < 10)' + '\n' + '{' + '\n' + 'i++;' + '\n' + '}' '}' ) c_src2 = ( 'void func()'+ '{' + '\n' + 'int i = 0;' + '\n' + 'while(i < 10)' + '\n' + 'i++;' + '\n' + '}' ) c_src3 = ( 'void func()'+ '{' + '\n' + 'int i = 10;' + '\n' + 'int cnt = 0;' + '\n' + 'while(i > 0)' + '\n' + '{' + '\n' + 'i--;' + '\n' + 'cnt++;' + '\n' + '}' + '\n' + '}' ) c_src4 = ( 'int digit_sum(int n)'+ '{' + '\n' + 'int sum = 0;' + '\n' + 'while(n > 0)' + '\n' + '{' + '\n' + 'sum += (n % 10);' + '\n' + 'n /= 10;' + '\n' + '}' + '\n' + 'return sum;' + '\n' + '}' ) c_src5 = ( 'void func()'+ '{' + '\n' + 'while(1);' + '\n' + '}' ) res1 = SymPyExpression(c_src1, 'c').return_expr() res2 = SymPyExpression(c_src2, 'c').return_expr() res3 = SymPyExpression(c_src3, 'c').return_expr() res4 = SymPyExpression(c_src4, 'c').return_expr() res5 = SymPyExpression(c_src5, 'c').return_expr() assert res1[0] == FunctionDefinition( NoneToken(), name=String('func'), parameters=(), body=CodeBlock( Declaration( Variable(Symbol('i'), type=IntBaseType(String('intc')), value=Integer(0) ) ), While( StrictLessThan( Symbol('i'), Integer(10) ), body=CodeBlock( PostIncrement( Symbol('i') ) ) ) ) ) assert res2[0] == res1[0] assert res3[0] == FunctionDefinition( NoneToken(), name=String('func'), parameters=(), body=CodeBlock( Declaration( Variable( Symbol('i'), type=IntBaseType(String('intc')), value=Integer(10) ) ), Declaration( Variable( Symbol('cnt'), type=IntBaseType(String('intc')), value=Integer(0) ) ), While( StrictGreaterThan( Symbol('i'), Integer(0) ), body=CodeBlock( PostDecrement( Symbol('i') ), PostIncrement( Symbol('cnt') ) ) ) ) ) assert res4[0] == FunctionDefinition( IntBaseType(String('intc')), name=String('digit_sum'), parameters=( Variable( Symbol('n'), type=IntBaseType(String('intc')) ), ), body=CodeBlock( Declaration( Variable( Symbol('sum'), type=IntBaseType(String('intc')), value=Integer(0) ) ), While( StrictGreaterThan( Symbol('n'), Integer(0) ), body=CodeBlock( AddAugmentedAssignment( Variable( Symbol('sum') ), Mod( Symbol('n'), Integer(10) ) ), DivAugmentedAssignment( Variable( Symbol('n') ), Integer(10) ) ) ), Return('sum') ) ) assert res5[0] == FunctionDefinition( NoneToken(), name=String('func'), parameters=(), body=CodeBlock( While( Integer(1), body=CodeBlock( NoneToken() ) ) ) ) else: def test_raise(): from sympy.parsing.c.c_parser import CCodeConverter raises(ImportError, lambda: CCodeConverter()) raises(ImportError, lambda: SymPyExpression(' ', mode = 'c'))
5cce0cb536e936ac0517aa832f60966f0d442e70255dd793ee8c761c173cbfc7
# 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(): base = convert_expr(func.subexpr().expr()) 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) else: return sympy.sqrt(expr) 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
59fec92619b2211ef4bbd207378014627276603733ad318dd08cad7fb488a594
# encoding: utf-8 # *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND *** # # Generated from ../LaTeX.g4, derived from latex2sympy # latex2sympy is licensed under the MIT license # https://github.com/augustt198/latex2sympy/blob/master/LICENSE.txt # # Generated with antlr4 # antlr4 is licensed under the BSD-3-Clause License # https://github.com/antlr/antlr4/blob/master/LICENSE.txt from __future__ import print_function from antlr4 import * from io import StringIO import sys def serializedATN(): with StringIO() as buf: buf.write(u"\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2") buf.write(u"Y\u0384\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4") buf.write(u"\7\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\4\r") buf.write(u"\t\r\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22\t\22") buf.write(u"\4\23\t\23\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\4") buf.write(u"\30\t\30\4\31\t\31\4\32\t\32\4\33\t\33\4\34\t\34\4\35") buf.write(u"\t\35\4\36\t\36\4\37\t\37\4 \t \4!\t!\4\"\t\"\4#\t#\4") buf.write(u"$\t$\4%\t%\4&\t&\4\'\t\'\4(\t(\4)\t)\4*\t*\4+\t+\4,\t") buf.write(u",\4-\t-\4.\t.\4/\t/\4\60\t\60\4\61\t\61\4\62\t\62\4\63") buf.write(u"\t\63\4\64\t\64\4\65\t\65\4\66\t\66\4\67\t\67\48\t8\4") buf.write(u"9\t9\4:\t:\4;\t;\4<\t<\4=\t=\4>\t>\4?\t?\4@\t@\4A\tA") buf.write(u"\4B\tB\4C\tC\4D\tD\4E\tE\4F\tF\4G\tG\4H\tH\4I\tI\4J\t") buf.write(u"J\4K\tK\4L\tL\4M\tM\4N\tN\4O\tO\4P\tP\4Q\tQ\4R\tR\4S") buf.write(u"\tS\4T\tT\4U\tU\4V\tV\4W\tW\4X\tX\4Y\tY\4Z\tZ\3\2\3\2") buf.write(u"\3\3\6\3\u00b9\n\3\r\3\16\3\u00ba\3\3\3\3\3\4\3\4\3\4") buf.write(u"\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\5\4\u00cb\n\4\3") buf.write(u"\4\3\4\3\5\3\5\3\5\3\5\3\5\3\5\3\5\3\5\3\5\3\5\3\5\5") buf.write(u"\5\u00da\n\5\3\5\3\5\3\6\3\6\3\6\3\6\3\6\3\6\3\6\3\6") buf.write(u"\3\6\3\6\3\6\3\6\3\6\5\6\u00eb\n\6\3\6\3\6\3\7\3\7\3") buf.write(u"\7\3\7\3\7\3\7\3\7\3\7\3\b\3\b\3\b\3\b\3\b\3\b\3\b\3") buf.write(u"\b\3\b\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3\t\3") buf.write(u"\t\3\t\3\t\3\t\5\t\u010f\n\t\3\t\3\t\3\n\3\n\3\n\3\n") buf.write(u"\3\n\3\n\3\n\3\n\3\n\3\n\3\n\3\n\3\n\3\n\3\n\3\13\3\13") buf.write(u"\3\13\3\13\3\13\3\13\3\13\3\13\3\13\3\13\3\13\3\13\3") buf.write(u"\13\3\13\3\13\3\13\3\13\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3") buf.write(u"\f\3\r\3\r\3\r\3\r\3\r\3\r\3\r\3\r\3\r\3\16\3\16\3\16") buf.write(u"\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3") buf.write(u"\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16") buf.write(u"\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3") buf.write(u"\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16\3\16") buf.write(u"\3\16\3\16\3\16\3\16\3\16\3\16\5\16\u0177\n\16\3\16\3") buf.write(u"\16\3\17\3\17\3\20\3\20\3\21\3\21\3\22\3\22\3\23\3\23") buf.write(u"\3\24\3\24\3\25\3\25\3\26\3\26\3\27\3\27\3\27\3\30\3") buf.write(u"\30\3\30\3\31\3\31\3\32\3\32\3\33\3\33\3\34\3\34\3\34") buf.write(u"\3\34\3\34\3\34\3\34\3\34\3\35\3\35\3\35\3\35\3\35\3") buf.write(u"\35\3\35\3\36\3\36\3\36\3\36\3\36\3\36\3\36\3\36\3\37") buf.write(u"\3\37\3\37\3\37\3\37\3\37\3\37\3\37\3 \3 \3 \3 \3 \3") buf.write(u"!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!") buf.write(u"\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3") buf.write(u"!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!") buf.write(u"\3!\3!\5!\u01f2\n!\3\"\3\"\3\"\3\"\3\"\3#\3#\3#\3#\3") buf.write(u"#\3$\3$\3$\3$\3$\3$\3%\3%\3%\3%\3%\3&\3&\3&\3&\3&\3\'") buf.write(u"\3\'\3\'\3\'\3(\3(\3(\3(\3(\3)\3)\3)\3)\3)\3*\3*\3*\3") buf.write(u"*\3*\3+\3+\3+\3+\3+\3,\3,\3,\3,\3,\3-\3-\3-\3-\3-\3.") buf.write(u"\3.\3.\3.\3.\3.\3.\3.\3/\3/\3/\3/\3/\3/\3/\3/\3\60\3") buf.write(u"\60\3\60\3\60\3\60\3\60\3\60\3\60\3\61\3\61\3\61\3\61") buf.write(u"\3\61\3\61\3\61\3\61\3\62\3\62\3\62\3\62\3\62\3\62\3") buf.write(u"\62\3\62\3\63\3\63\3\63\3\63\3\63\3\63\3\63\3\63\3\64") buf.write(u"\3\64\3\64\3\64\3\64\3\64\3\65\3\65\3\65\3\65\3\65\3") buf.write(u"\65\3\66\3\66\3\66\3\66\3\66\3\66\3\67\3\67\3\67\3\67") buf.write(u"\3\67\3\67\3\67\3\67\38\38\38\38\38\38\38\38\39\39\3") buf.write(u"9\39\39\39\39\39\3:\3:\3:\3:\3:\3:\3:\3:\3;\3;\3;\3;") buf.write(u"\3;\3;\3;\3;\3<\3<\3<\3<\3<\3<\3<\3=\3=\3=\3=\3=\3=\3") buf.write(u"=\3>\3>\3>\3>\3>\3>\3?\3?\3?\3?\3?\3?\3?\3@\3@\3@\3@") buf.write(u"\3@\3@\3A\3A\3A\3A\3A\3B\3B\3B\3B\3B\3B\3C\3C\3C\3C\3") buf.write(u"C\3C\3C\3D\3D\3D\3D\3D\3D\3D\3D\3E\3E\3E\3E\3E\3E\3E") buf.write(u"\3E\3F\3F\3F\3F\3F\3F\3F\3F\3G\3G\3H\3H\3I\3I\3J\3J\3") buf.write(u"K\3K\7K\u02ef\nK\fK\16K\u02f2\13K\3K\3K\3K\6K\u02f7\n") buf.write(u"K\rK\16K\u02f8\5K\u02fb\nK\3L\3L\3M\3M\3N\6N\u0302\n") buf.write(u"N\rN\16N\u0303\3N\3N\3N\3N\3N\7N\u030b\nN\fN\16N\u030e") buf.write(u"\13N\3N\7N\u0311\nN\fN\16N\u0314\13N\3N\3N\3N\3N\3N\7") buf.write(u"N\u031b\nN\fN\16N\u031e\13N\3N\3N\6N\u0322\nN\rN\16N") buf.write(u"\u0323\5N\u0326\nN\3O\3O\7O\u032a\nO\fO\16O\u032d\13") buf.write(u"O\5O\u032f\nO\3O\3O\3O\7O\u0334\nO\fO\16O\u0337\13O\3") buf.write(u"O\5O\u033a\nO\5O\u033c\nO\3P\3P\3P\3P\3P\3Q\3Q\3R\3R") buf.write(u"\3R\3R\3R\3R\3R\3R\3R\5R\u034e\nR\3S\3S\3S\3S\3S\3S\3") buf.write(u"T\3T\3T\3T\3T\3T\3T\3T\3T\3T\3U\3U\3V\3V\3V\3V\3V\3V") buf.write(u"\3V\3V\3V\5V\u036b\nV\3W\3W\3W\3W\3W\3W\3X\3X\3X\3X\3") buf.write(u"X\3X\3X\3X\3X\3X\3Y\3Y\3Z\3Z\6Z\u0381\nZ\rZ\16Z\u0382") buf.write(u"\5\u02f0\u032b\u0335\2[\3\3\5\4\7\5\t\6\13\7\r\b\17\t") buf.write(u"\21\n\23\13\25\f\27\r\31\16\33\17\35\20\37\21!\22#\23") buf.write(u"%\24\'\25)\26+\27-\30/\31\61\32\63\33\65\34\67\359\36") buf.write(u";\37= ?!A\"C#E$G%I&K\'M(O)Q*S+U,W-Y.[/]\60_\61a\62c\63") buf.write(u"e\64g\65i\66k\67m8o9q:s;u<w=y>{?}@\177A\u0081B\u0083") buf.write(u"C\u0085D\u0087E\u0089F\u008bG\u008dH\u008fI\u0091J\u0093") buf.write(u"\2\u0095K\u0097L\u0099\2\u009bM\u009dN\u009fO\u00a1P") buf.write(u"\u00a3Q\u00a5R\u00a7S\u00a9T\u00abU\u00adV\u00afW\u00b1") buf.write(u"X\u00b3Y\3\2\5\5\2\13\f\17\17\"\"\4\2C\\c|\3\2\62;\2") buf.write(u"\u03ab\2\3\3\2\2\2\2\5\3\2\2\2\2\7\3\2\2\2\2\t\3\2\2") buf.write(u"\2\2\13\3\2\2\2\2\r\3\2\2\2\2\17\3\2\2\2\2\21\3\2\2\2") buf.write(u"\2\23\3\2\2\2\2\25\3\2\2\2\2\27\3\2\2\2\2\31\3\2\2\2") buf.write(u"\2\33\3\2\2\2\2\35\3\2\2\2\2\37\3\2\2\2\2!\3\2\2\2\2") buf.write(u"#\3\2\2\2\2%\3\2\2\2\2\'\3\2\2\2\2)\3\2\2\2\2+\3\2\2") buf.write(u"\2\2-\3\2\2\2\2/\3\2\2\2\2\61\3\2\2\2\2\63\3\2\2\2\2") buf.write(u"\65\3\2\2\2\2\67\3\2\2\2\29\3\2\2\2\2;\3\2\2\2\2=\3\2") buf.write(u"\2\2\2?\3\2\2\2\2A\3\2\2\2\2C\3\2\2\2\2E\3\2\2\2\2G\3") buf.write(u"\2\2\2\2I\3\2\2\2\2K\3\2\2\2\2M\3\2\2\2\2O\3\2\2\2\2") buf.write(u"Q\3\2\2\2\2S\3\2\2\2\2U\3\2\2\2\2W\3\2\2\2\2Y\3\2\2\2") buf.write(u"\2[\3\2\2\2\2]\3\2\2\2\2_\3\2\2\2\2a\3\2\2\2\2c\3\2\2") buf.write(u"\2\2e\3\2\2\2\2g\3\2\2\2\2i\3\2\2\2\2k\3\2\2\2\2m\3\2") buf.write(u"\2\2\2o\3\2\2\2\2q\3\2\2\2\2s\3\2\2\2\2u\3\2\2\2\2w\3") buf.write(u"\2\2\2\2y\3\2\2\2\2{\3\2\2\2\2}\3\2\2\2\2\177\3\2\2\2") buf.write(u"\2\u0081\3\2\2\2\2\u0083\3\2\2\2\2\u0085\3\2\2\2\2\u0087") buf.write(u"\3\2\2\2\2\u0089\3\2\2\2\2\u008b\3\2\2\2\2\u008d\3\2") buf.write(u"\2\2\2\u008f\3\2\2\2\2\u0091\3\2\2\2\2\u0095\3\2\2\2") buf.write(u"\2\u0097\3\2\2\2\2\u009b\3\2\2\2\2\u009d\3\2\2\2\2\u009f") buf.write(u"\3\2\2\2\2\u00a1\3\2\2\2\2\u00a3\3\2\2\2\2\u00a5\3\2") buf.write(u"\2\2\2\u00a7\3\2\2\2\2\u00a9\3\2\2\2\2\u00ab\3\2\2\2") buf.write(u"\2\u00ad\3\2\2\2\2\u00af\3\2\2\2\2\u00b1\3\2\2\2\2\u00b3") buf.write(u"\3\2\2\2\3\u00b5\3\2\2\2\5\u00b8\3\2\2\2\7\u00ca\3\2") buf.write(u"\2\2\t\u00d9\3\2\2\2\13\u00ea\3\2\2\2\r\u00ee\3\2\2\2") buf.write(u"\17\u00f6\3\2\2\2\21\u010e\3\2\2\2\23\u0112\3\2\2\2\25") buf.write(u"\u0121\3\2\2\2\27\u0132\3\2\2\2\31\u013a\3\2\2\2\33\u0176") buf.write(u"\3\2\2\2\35\u017a\3\2\2\2\37\u017c\3\2\2\2!\u017e\3\2") buf.write(u"\2\2#\u0180\3\2\2\2%\u0182\3\2\2\2\'\u0184\3\2\2\2)\u0186") buf.write(u"\3\2\2\2+\u0188\3\2\2\2-\u018a\3\2\2\2/\u018d\3\2\2\2") buf.write(u"\61\u0190\3\2\2\2\63\u0192\3\2\2\2\65\u0194\3\2\2\2\67") buf.write(u"\u0196\3\2\2\29\u019e\3\2\2\2;\u01a5\3\2\2\2=\u01ad\3") buf.write(u"\2\2\2?\u01b5\3\2\2\2A\u01f1\3\2\2\2C\u01f3\3\2\2\2E") buf.write(u"\u01f8\3\2\2\2G\u01fd\3\2\2\2I\u0203\3\2\2\2K\u0208\3") buf.write(u"\2\2\2M\u020d\3\2\2\2O\u0211\3\2\2\2Q\u0216\3\2\2\2S") buf.write(u"\u021b\3\2\2\2U\u0220\3\2\2\2W\u0225\3\2\2\2Y\u022a\3") buf.write(u"\2\2\2[\u022f\3\2\2\2]\u0237\3\2\2\2_\u023f\3\2\2\2a") buf.write(u"\u0247\3\2\2\2c\u024f\3\2\2\2e\u0257\3\2\2\2g\u025f\3") buf.write(u"\2\2\2i\u0265\3\2\2\2k\u026b\3\2\2\2m\u0271\3\2\2\2o") buf.write(u"\u0279\3\2\2\2q\u0281\3\2\2\2s\u0289\3\2\2\2u\u0291\3") buf.write(u"\2\2\2w\u0299\3\2\2\2y\u02a0\3\2\2\2{\u02a7\3\2\2\2}") buf.write(u"\u02ad\3\2\2\2\177\u02b4\3\2\2\2\u0081\u02ba\3\2\2\2") buf.write(u"\u0083\u02bf\3\2\2\2\u0085\u02c5\3\2\2\2\u0087\u02cc") buf.write(u"\3\2\2\2\u0089\u02d4\3\2\2\2\u008b\u02dc\3\2\2\2\u008d") buf.write(u"\u02e4\3\2\2\2\u008f\u02e6\3\2\2\2\u0091\u02e8\3\2\2") buf.write(u"\2\u0093\u02ea\3\2\2\2\u0095\u02ec\3\2\2\2\u0097\u02fc") buf.write(u"\3\2\2\2\u0099\u02fe\3\2\2\2\u009b\u0325\3\2\2\2\u009d") buf.write(u"\u033b\3\2\2\2\u009f\u033d\3\2\2\2\u00a1\u0342\3\2\2") buf.write(u"\2\u00a3\u034d\3\2\2\2\u00a5\u034f\3\2\2\2\u00a7\u0355") buf.write(u"\3\2\2\2\u00a9\u035f\3\2\2\2\u00ab\u036a\3\2\2\2\u00ad") buf.write(u"\u036c\3\2\2\2\u00af\u0372\3\2\2\2\u00b1\u037c\3\2\2") buf.write(u"\2\u00b3\u037e\3\2\2\2\u00b5\u00b6\7.\2\2\u00b6\4\3\2") buf.write(u"\2\2\u00b7\u00b9\t\2\2\2\u00b8\u00b7\3\2\2\2\u00b9\u00ba") buf.write(u"\3\2\2\2\u00ba\u00b8\3\2\2\2\u00ba\u00bb\3\2\2\2\u00bb") buf.write(u"\u00bc\3\2\2\2\u00bc\u00bd\b\3\2\2\u00bd\6\3\2\2\2\u00be") buf.write(u"\u00bf\7^\2\2\u00bf\u00cb\7.\2\2\u00c0\u00c1\7^\2\2\u00c1") buf.write(u"\u00c2\7v\2\2\u00c2\u00c3\7j\2\2\u00c3\u00c4\7k\2\2\u00c4") buf.write(u"\u00c5\7p\2\2\u00c5\u00c6\7u\2\2\u00c6\u00c7\7r\2\2\u00c7") buf.write(u"\u00c8\7c\2\2\u00c8\u00c9\7e\2\2\u00c9\u00cb\7g\2\2\u00ca") buf.write(u"\u00be\3\2\2\2\u00ca\u00c0\3\2\2\2\u00cb\u00cc\3\2\2") buf.write(u"\2\u00cc\u00cd\b\4\2\2\u00cd\b\3\2\2\2\u00ce\u00cf\7") buf.write(u"^\2\2\u00cf\u00da\7<\2\2\u00d0\u00d1\7^\2\2\u00d1\u00d2") buf.write(u"\7o\2\2\u00d2\u00d3\7g\2\2\u00d3\u00d4\7f\2\2\u00d4\u00d5") buf.write(u"\7u\2\2\u00d5\u00d6\7r\2\2\u00d6\u00d7\7c\2\2\u00d7\u00d8") buf.write(u"\7e\2\2\u00d8\u00da\7g\2\2\u00d9\u00ce\3\2\2\2\u00d9") buf.write(u"\u00d0\3\2\2\2\u00da\u00db\3\2\2\2\u00db\u00dc\b\5\2") buf.write(u"\2\u00dc\n\3\2\2\2\u00dd\u00de\7^\2\2\u00de\u00eb\7=") buf.write(u"\2\2\u00df\u00e0\7^\2\2\u00e0\u00e1\7v\2\2\u00e1\u00e2") buf.write(u"\7j\2\2\u00e2\u00e3\7k\2\2\u00e3\u00e4\7e\2\2\u00e4\u00e5") buf.write(u"\7m\2\2\u00e5\u00e6\7u\2\2\u00e6\u00e7\7r\2\2\u00e7\u00e8") buf.write(u"\7c\2\2\u00e8\u00e9\7e\2\2\u00e9\u00eb\7g\2\2\u00ea\u00dd") buf.write(u"\3\2\2\2\u00ea\u00df\3\2\2\2\u00eb\u00ec\3\2\2\2\u00ec") buf.write(u"\u00ed\b\6\2\2\u00ed\f\3\2\2\2\u00ee\u00ef\7^\2\2\u00ef") buf.write(u"\u00f0\7s\2\2\u00f0\u00f1\7w\2\2\u00f1\u00f2\7c\2\2\u00f2") buf.write(u"\u00f3\7f\2\2\u00f3\u00f4\3\2\2\2\u00f4\u00f5\b\7\2\2") buf.write(u"\u00f5\16\3\2\2\2\u00f6\u00f7\7^\2\2\u00f7\u00f8\7s\2") buf.write(u"\2\u00f8\u00f9\7s\2\2\u00f9\u00fa\7w\2\2\u00fa\u00fb") buf.write(u"\7c\2\2\u00fb\u00fc\7f\2\2\u00fc\u00fd\3\2\2\2\u00fd") buf.write(u"\u00fe\b\b\2\2\u00fe\20\3\2\2\2\u00ff\u0100\7^\2\2\u0100") buf.write(u"\u010f\7#\2\2\u0101\u0102\7^\2\2\u0102\u0103\7p\2\2\u0103") buf.write(u"\u0104\7g\2\2\u0104\u0105\7i\2\2\u0105\u0106\7v\2\2\u0106") buf.write(u"\u0107\7j\2\2\u0107\u0108\7k\2\2\u0108\u0109\7p\2\2\u0109") buf.write(u"\u010a\7u\2\2\u010a\u010b\7r\2\2\u010b\u010c\7c\2\2\u010c") buf.write(u"\u010d\7e\2\2\u010d\u010f\7g\2\2\u010e\u00ff\3\2\2\2") buf.write(u"\u010e\u0101\3\2\2\2\u010f\u0110\3\2\2\2\u0110\u0111") buf.write(u"\b\t\2\2\u0111\22\3\2\2\2\u0112\u0113\7^\2\2\u0113\u0114") buf.write(u"\7p\2\2\u0114\u0115\7g\2\2\u0115\u0116\7i\2\2\u0116\u0117") buf.write(u"\7o\2\2\u0117\u0118\7g\2\2\u0118\u0119\7f\2\2\u0119\u011a") buf.write(u"\7u\2\2\u011a\u011b\7r\2\2\u011b\u011c\7c\2\2\u011c\u011d") buf.write(u"\7e\2\2\u011d\u011e\7g\2\2\u011e\u011f\3\2\2\2\u011f") buf.write(u"\u0120\b\n\2\2\u0120\24\3\2\2\2\u0121\u0122\7^\2\2\u0122") buf.write(u"\u0123\7p\2\2\u0123\u0124\7g\2\2\u0124\u0125\7i\2\2\u0125") buf.write(u"\u0126\7v\2\2\u0126\u0127\7j\2\2\u0127\u0128\7k\2\2\u0128") buf.write(u"\u0129\7e\2\2\u0129\u012a\7m\2\2\u012a\u012b\7u\2\2\u012b") buf.write(u"\u012c\7r\2\2\u012c\u012d\7c\2\2\u012d\u012e\7e\2\2\u012e") buf.write(u"\u012f\7g\2\2\u012f\u0130\3\2\2\2\u0130\u0131\b\13\2") buf.write(u"\2\u0131\26\3\2\2\2\u0132\u0133\7^\2\2\u0133\u0134\7") buf.write(u"n\2\2\u0134\u0135\7g\2\2\u0135\u0136\7h\2\2\u0136\u0137") buf.write(u"\7v\2\2\u0137\u0138\3\2\2\2\u0138\u0139\b\f\2\2\u0139") buf.write(u"\30\3\2\2\2\u013a\u013b\7^\2\2\u013b\u013c\7t\2\2\u013c") buf.write(u"\u013d\7k\2\2\u013d\u013e\7i\2\2\u013e\u013f\7j\2\2\u013f") buf.write(u"\u0140\7v\2\2\u0140\u0141\3\2\2\2\u0141\u0142\b\r\2\2") buf.write(u"\u0142\32\3\2\2\2\u0143\u0144\7^\2\2\u0144\u0145\7x\2") buf.write(u"\2\u0145\u0146\7t\2\2\u0146\u0147\7w\2\2\u0147\u0148") buf.write(u"\7n\2\2\u0148\u0177\7g\2\2\u0149\u014a\7^\2\2\u014a\u014b") buf.write(u"\7x\2\2\u014b\u014c\7e\2\2\u014c\u014d\7g\2\2\u014d\u014e") buf.write(u"\7p\2\2\u014e\u014f\7v\2\2\u014f\u0150\7g\2\2\u0150\u0177") buf.write(u"\7t\2\2\u0151\u0152\7^\2\2\u0152\u0153\7x\2\2\u0153\u0154") buf.write(u"\7d\2\2\u0154\u0155\7q\2\2\u0155\u0177\7z\2\2\u0156\u0157") buf.write(u"\7^\2\2\u0157\u0158\7x\2\2\u0158\u0159\7u\2\2\u0159\u015a") buf.write(u"\7m\2\2\u015a\u015b\7k\2\2\u015b\u0177\7r\2\2\u015c\u015d") buf.write(u"\7^\2\2\u015d\u015e\7x\2\2\u015e\u015f\7u\2\2\u015f\u0160") buf.write(u"\7r\2\2\u0160\u0161\7c\2\2\u0161\u0162\7e\2\2\u0162\u0177") buf.write(u"\7g\2\2\u0163\u0164\7^\2\2\u0164\u0165\7j\2\2\u0165\u0166") buf.write(u"\7h\2\2\u0166\u0167\7k\2\2\u0167\u0177\7n\2\2\u0168\u0169") buf.write(u"\7^\2\2\u0169\u0177\7,\2\2\u016a\u016b\7^\2\2\u016b\u0177") buf.write(u"\7/\2\2\u016c\u016d\7^\2\2\u016d\u0177\7\60\2\2\u016e") buf.write(u"\u016f\7^\2\2\u016f\u0177\7\61\2\2\u0170\u0171\7^\2\2") buf.write(u"\u0171\u0177\7$\2\2\u0172\u0173\7^\2\2\u0173\u0177\7") buf.write(u"*\2\2\u0174\u0175\7^\2\2\u0175\u0177\7?\2\2\u0176\u0143") buf.write(u"\3\2\2\2\u0176\u0149\3\2\2\2\u0176\u0151\3\2\2\2\u0176") buf.write(u"\u0156\3\2\2\2\u0176\u015c\3\2\2\2\u0176\u0163\3\2\2") buf.write(u"\2\u0176\u0168\3\2\2\2\u0176\u016a\3\2\2\2\u0176\u016c") buf.write(u"\3\2\2\2\u0176\u016e\3\2\2\2\u0176\u0170\3\2\2\2\u0176") buf.write(u"\u0172\3\2\2\2\u0176\u0174\3\2\2\2\u0177\u0178\3\2\2") buf.write(u"\2\u0178\u0179\b\16\2\2\u0179\34\3\2\2\2\u017a\u017b") buf.write(u"\7-\2\2\u017b\36\3\2\2\2\u017c\u017d\7/\2\2\u017d \3") buf.write(u"\2\2\2\u017e\u017f\7,\2\2\u017f\"\3\2\2\2\u0180\u0181") buf.write(u"\7\61\2\2\u0181$\3\2\2\2\u0182\u0183\7*\2\2\u0183&\3") buf.write(u"\2\2\2\u0184\u0185\7+\2\2\u0185(\3\2\2\2\u0186\u0187") buf.write(u"\7}\2\2\u0187*\3\2\2\2\u0188\u0189\7\177\2\2\u0189,\3") buf.write(u"\2\2\2\u018a\u018b\7^\2\2\u018b\u018c\7}\2\2\u018c.\3") buf.write(u"\2\2\2\u018d\u018e\7^\2\2\u018e\u018f\7\177\2\2\u018f") buf.write(u"\60\3\2\2\2\u0190\u0191\7]\2\2\u0191\62\3\2\2\2\u0192") buf.write(u"\u0193\7_\2\2\u0193\64\3\2\2\2\u0194\u0195\7~\2\2\u0195") buf.write(u"\66\3\2\2\2\u0196\u0197\7^\2\2\u0197\u0198\7t\2\2\u0198") buf.write(u"\u0199\7k\2\2\u0199\u019a\7i\2\2\u019a\u019b\7j\2\2\u019b") buf.write(u"\u019c\7v\2\2\u019c\u019d\7~\2\2\u019d8\3\2\2\2\u019e") buf.write(u"\u019f\7^\2\2\u019f\u01a0\7n\2\2\u01a0\u01a1\7g\2\2\u01a1") buf.write(u"\u01a2\7h\2\2\u01a2\u01a3\7v\2\2\u01a3\u01a4\7~\2\2\u01a4") buf.write(u":\3\2\2\2\u01a5\u01a6\7^\2\2\u01a6\u01a7\7n\2\2\u01a7") buf.write(u"\u01a8\7c\2\2\u01a8\u01a9\7p\2\2\u01a9\u01aa\7i\2\2\u01aa") buf.write(u"\u01ab\7n\2\2\u01ab\u01ac\7g\2\2\u01ac<\3\2\2\2\u01ad") buf.write(u"\u01ae\7^\2\2\u01ae\u01af\7t\2\2\u01af\u01b0\7c\2\2\u01b0") buf.write(u"\u01b1\7p\2\2\u01b1\u01b2\7i\2\2\u01b2\u01b3\7n\2\2\u01b3") buf.write(u"\u01b4\7g\2\2\u01b4>\3\2\2\2\u01b5\u01b6\7^\2\2\u01b6") buf.write(u"\u01b7\7n\2\2\u01b7\u01b8\7k\2\2\u01b8\u01b9\7o\2\2\u01b9") buf.write(u"@\3\2\2\2\u01ba\u01bb\7^\2\2\u01bb\u01bc\7v\2\2\u01bc") buf.write(u"\u01f2\7q\2\2\u01bd\u01be\7^\2\2\u01be\u01bf\7t\2\2\u01bf") buf.write(u"\u01c0\7k\2\2\u01c0\u01c1\7i\2\2\u01c1\u01c2\7j\2\2\u01c2") buf.write(u"\u01c3\7v\2\2\u01c3\u01c4\7c\2\2\u01c4\u01c5\7t\2\2\u01c5") buf.write(u"\u01c6\7t\2\2\u01c6\u01c7\7q\2\2\u01c7\u01f2\7y\2\2\u01c8") buf.write(u"\u01c9\7^\2\2\u01c9\u01ca\7T\2\2\u01ca\u01cb\7k\2\2\u01cb") buf.write(u"\u01cc\7i\2\2\u01cc\u01cd\7j\2\2\u01cd\u01ce\7v\2\2\u01ce") buf.write(u"\u01cf\7c\2\2\u01cf\u01d0\7t\2\2\u01d0\u01d1\7t\2\2\u01d1") buf.write(u"\u01d2\7q\2\2\u01d2\u01f2\7y\2\2\u01d3\u01d4\7^\2\2\u01d4") buf.write(u"\u01d5\7n\2\2\u01d5\u01d6\7q\2\2\u01d6\u01d7\7p\2\2\u01d7") buf.write(u"\u01d8\7i\2\2\u01d8\u01d9\7t\2\2\u01d9\u01da\7k\2\2\u01da") buf.write(u"\u01db\7i\2\2\u01db\u01dc\7j\2\2\u01dc\u01dd\7v\2\2\u01dd") buf.write(u"\u01de\7c\2\2\u01de\u01df\7t\2\2\u01df\u01e0\7t\2\2\u01e0") buf.write(u"\u01e1\7q\2\2\u01e1\u01f2\7y\2\2\u01e2\u01e3\7^\2\2\u01e3") buf.write(u"\u01e4\7N\2\2\u01e4\u01e5\7q\2\2\u01e5\u01e6\7p\2\2\u01e6") buf.write(u"\u01e7\7i\2\2\u01e7\u01e8\7t\2\2\u01e8\u01e9\7k\2\2\u01e9") buf.write(u"\u01ea\7i\2\2\u01ea\u01eb\7j\2\2\u01eb\u01ec\7v\2\2\u01ec") buf.write(u"\u01ed\7c\2\2\u01ed\u01ee\7t\2\2\u01ee\u01ef\7t\2\2\u01ef") buf.write(u"\u01f0\7q\2\2\u01f0\u01f2\7y\2\2\u01f1\u01ba\3\2\2\2") buf.write(u"\u01f1\u01bd\3\2\2\2\u01f1\u01c8\3\2\2\2\u01f1\u01d3") buf.write(u"\3\2\2\2\u01f1\u01e2\3\2\2\2\u01f2B\3\2\2\2\u01f3\u01f4") buf.write(u"\7^\2\2\u01f4\u01f5\7k\2\2\u01f5\u01f6\7p\2\2\u01f6\u01f7") buf.write(u"\7v\2\2\u01f7D\3\2\2\2\u01f8\u01f9\7^\2\2\u01f9\u01fa") buf.write(u"\7u\2\2\u01fa\u01fb\7w\2\2\u01fb\u01fc\7o\2\2\u01fcF") buf.write(u"\3\2\2\2\u01fd\u01fe\7^\2\2\u01fe\u01ff\7r\2\2\u01ff") buf.write(u"\u0200\7t\2\2\u0200\u0201\7q\2\2\u0201\u0202\7f\2\2\u0202") buf.write(u"H\3\2\2\2\u0203\u0204\7^\2\2\u0204\u0205\7g\2\2\u0205") buf.write(u"\u0206\7z\2\2\u0206\u0207\7r\2\2\u0207J\3\2\2\2\u0208") buf.write(u"\u0209\7^\2\2\u0209\u020a\7n\2\2\u020a\u020b\7q\2\2\u020b") buf.write(u"\u020c\7i\2\2\u020cL\3\2\2\2\u020d\u020e\7^\2\2\u020e") buf.write(u"\u020f\7n\2\2\u020f\u0210\7p\2\2\u0210N\3\2\2\2\u0211") buf.write(u"\u0212\7^\2\2\u0212\u0213\7u\2\2\u0213\u0214\7k\2\2\u0214") buf.write(u"\u0215\7p\2\2\u0215P\3\2\2\2\u0216\u0217\7^\2\2\u0217") buf.write(u"\u0218\7e\2\2\u0218\u0219\7q\2\2\u0219\u021a\7u\2\2\u021a") buf.write(u"R\3\2\2\2\u021b\u021c\7^\2\2\u021c\u021d\7v\2\2\u021d") buf.write(u"\u021e\7c\2\2\u021e\u021f\7p\2\2\u021fT\3\2\2\2\u0220") buf.write(u"\u0221\7^\2\2\u0221\u0222\7e\2\2\u0222\u0223\7u\2\2\u0223") buf.write(u"\u0224\7e\2\2\u0224V\3\2\2\2\u0225\u0226\7^\2\2\u0226") buf.write(u"\u0227\7u\2\2\u0227\u0228\7g\2\2\u0228\u0229\7e\2\2\u0229") buf.write(u"X\3\2\2\2\u022a\u022b\7^\2\2\u022b\u022c\7e\2\2\u022c") buf.write(u"\u022d\7q\2\2\u022d\u022e\7v\2\2\u022eZ\3\2\2\2\u022f") buf.write(u"\u0230\7^\2\2\u0230\u0231\7c\2\2\u0231\u0232\7t\2\2\u0232") buf.write(u"\u0233\7e\2\2\u0233\u0234\7u\2\2\u0234\u0235\7k\2\2\u0235") buf.write(u"\u0236\7p\2\2\u0236\\\3\2\2\2\u0237\u0238\7^\2\2\u0238") buf.write(u"\u0239\7c\2\2\u0239\u023a\7t\2\2\u023a\u023b\7e\2\2\u023b") buf.write(u"\u023c\7e\2\2\u023c\u023d\7q\2\2\u023d\u023e\7u\2\2\u023e") buf.write(u"^\3\2\2\2\u023f\u0240\7^\2\2\u0240\u0241\7c\2\2\u0241") buf.write(u"\u0242\7t\2\2\u0242\u0243\7e\2\2\u0243\u0244\7v\2\2\u0244") buf.write(u"\u0245\7c\2\2\u0245\u0246\7p\2\2\u0246`\3\2\2\2\u0247") buf.write(u"\u0248\7^\2\2\u0248\u0249\7c\2\2\u0249\u024a\7t\2\2\u024a") buf.write(u"\u024b\7e\2\2\u024b\u024c\7e\2\2\u024c\u024d\7u\2\2\u024d") buf.write(u"\u024e\7e\2\2\u024eb\3\2\2\2\u024f\u0250\7^\2\2\u0250") buf.write(u"\u0251\7c\2\2\u0251\u0252\7t\2\2\u0252\u0253\7e\2\2\u0253") buf.write(u"\u0254\7u\2\2\u0254\u0255\7g\2\2\u0255\u0256\7e\2\2\u0256") buf.write(u"d\3\2\2\2\u0257\u0258\7^\2\2\u0258\u0259\7c\2\2\u0259") buf.write(u"\u025a\7t\2\2\u025a\u025b\7e\2\2\u025b\u025c\7e\2\2\u025c") buf.write(u"\u025d\7q\2\2\u025d\u025e\7v\2\2\u025ef\3\2\2\2\u025f") buf.write(u"\u0260\7^\2\2\u0260\u0261\7u\2\2\u0261\u0262\7k\2\2\u0262") buf.write(u"\u0263\7p\2\2\u0263\u0264\7j\2\2\u0264h\3\2\2\2\u0265") buf.write(u"\u0266\7^\2\2\u0266\u0267\7e\2\2\u0267\u0268\7q\2\2\u0268") buf.write(u"\u0269\7u\2\2\u0269\u026a\7j\2\2\u026aj\3\2\2\2\u026b") buf.write(u"\u026c\7^\2\2\u026c\u026d\7v\2\2\u026d\u026e\7c\2\2\u026e") buf.write(u"\u026f\7p\2\2\u026f\u0270\7j\2\2\u0270l\3\2\2\2\u0271") buf.write(u"\u0272\7^\2\2\u0272\u0273\7c\2\2\u0273\u0274\7t\2\2\u0274") buf.write(u"\u0275\7u\2\2\u0275\u0276\7k\2\2\u0276\u0277\7p\2\2\u0277") buf.write(u"\u0278\7j\2\2\u0278n\3\2\2\2\u0279\u027a\7^\2\2\u027a") buf.write(u"\u027b\7c\2\2\u027b\u027c\7t\2\2\u027c\u027d\7e\2\2\u027d") buf.write(u"\u027e\7q\2\2\u027e\u027f\7u\2\2\u027f\u0280\7j\2\2\u0280") buf.write(u"p\3\2\2\2\u0281\u0282\7^\2\2\u0282\u0283\7c\2\2\u0283") buf.write(u"\u0284\7t\2\2\u0284\u0285\7v\2\2\u0285\u0286\7c\2\2\u0286") buf.write(u"\u0287\7p\2\2\u0287\u0288\7j\2\2\u0288r\3\2\2\2\u0289") buf.write(u"\u028a\7^\2\2\u028a\u028b\7n\2\2\u028b\u028c\7h\2\2\u028c") buf.write(u"\u028d\7n\2\2\u028d\u028e\7q\2\2\u028e\u028f\7q\2\2\u028f") buf.write(u"\u0290\7t\2\2\u0290t\3\2\2\2\u0291\u0292\7^\2\2\u0292") buf.write(u"\u0293\7t\2\2\u0293\u0294\7h\2\2\u0294\u0295\7n\2\2\u0295") buf.write(u"\u0296\7q\2\2\u0296\u0297\7q\2\2\u0297\u0298\7t\2\2\u0298") buf.write(u"v\3\2\2\2\u0299\u029a\7^\2\2\u029a\u029b\7n\2\2\u029b") buf.write(u"\u029c\7e\2\2\u029c\u029d\7g\2\2\u029d\u029e\7k\2\2\u029e") buf.write(u"\u029f\7n\2\2\u029fx\3\2\2\2\u02a0\u02a1\7^\2\2\u02a1") buf.write(u"\u02a2\7t\2\2\u02a2\u02a3\7e\2\2\u02a3\u02a4\7g\2\2\u02a4") buf.write(u"\u02a5\7k\2\2\u02a5\u02a6\7n\2\2\u02a6z\3\2\2\2\u02a7") buf.write(u"\u02a8\7^\2\2\u02a8\u02a9\7u\2\2\u02a9\u02aa\7s\2\2\u02aa") buf.write(u"\u02ab\7t\2\2\u02ab\u02ac\7v\2\2\u02ac|\3\2\2\2\u02ad") buf.write(u"\u02ae\7^\2\2\u02ae\u02af\7v\2\2\u02af\u02b0\7k\2\2\u02b0") buf.write(u"\u02b1\7o\2\2\u02b1\u02b2\7g\2\2\u02b2\u02b3\7u\2\2\u02b3") buf.write(u"~\3\2\2\2\u02b4\u02b5\7^\2\2\u02b5\u02b6\7e\2\2\u02b6") buf.write(u"\u02b7\7f\2\2\u02b7\u02b8\7q\2\2\u02b8\u02b9\7v\2\2\u02b9") buf.write(u"\u0080\3\2\2\2\u02ba\u02bb\7^\2\2\u02bb\u02bc\7f\2\2") buf.write(u"\u02bc\u02bd\7k\2\2\u02bd\u02be\7x\2\2\u02be\u0082\3") buf.write(u"\2\2\2\u02bf\u02c0\7^\2\2\u02c0\u02c1\7h\2\2\u02c1\u02c2") buf.write(u"\7t\2\2\u02c2\u02c3\7c\2\2\u02c3\u02c4\7e\2\2\u02c4\u0084") buf.write(u"\3\2\2\2\u02c5\u02c6\7^\2\2\u02c6\u02c7\7d\2\2\u02c7") buf.write(u"\u02c8\7k\2\2\u02c8\u02c9\7p\2\2\u02c9\u02ca\7q\2\2\u02ca") buf.write(u"\u02cb\7o\2\2\u02cb\u0086\3\2\2\2\u02cc\u02cd\7^\2\2") buf.write(u"\u02cd\u02ce\7f\2\2\u02ce\u02cf\7d\2\2\u02cf\u02d0\7") buf.write(u"k\2\2\u02d0\u02d1\7p\2\2\u02d1\u02d2\7q\2\2\u02d2\u02d3") buf.write(u"\7o\2\2\u02d3\u0088\3\2\2\2\u02d4\u02d5\7^\2\2\u02d5") buf.write(u"\u02d6\7v\2\2\u02d6\u02d7\7d\2\2\u02d7\u02d8\7k\2\2\u02d8") buf.write(u"\u02d9\7p\2\2\u02d9\u02da\7q\2\2\u02da\u02db\7o\2\2\u02db") buf.write(u"\u008a\3\2\2\2\u02dc\u02dd\7^\2\2\u02dd\u02de\7o\2\2") buf.write(u"\u02de\u02df\7c\2\2\u02df\u02e0\7v\2\2\u02e0\u02e1\7") buf.write(u"j\2\2\u02e1\u02e2\7k\2\2\u02e2\u02e3\7v\2\2\u02e3\u008c") buf.write(u"\3\2\2\2\u02e4\u02e5\7a\2\2\u02e5\u008e\3\2\2\2\u02e6") buf.write(u"\u02e7\7`\2\2\u02e7\u0090\3\2\2\2\u02e8\u02e9\7<\2\2") buf.write(u"\u02e9\u0092\3\2\2\2\u02ea\u02eb\t\2\2\2\u02eb\u0094") buf.write(u"\3\2\2\2\u02ec\u02f0\7f\2\2\u02ed\u02ef\5\u0093J\2\u02ee") buf.write(u"\u02ed\3\2\2\2\u02ef\u02f2\3\2\2\2\u02f0\u02f1\3\2\2") buf.write(u"\2\u02f0\u02ee\3\2\2\2\u02f1\u02fa\3\2\2\2\u02f2\u02f0") buf.write(u"\3\2\2\2\u02f3\u02fb\t\3\2\2\u02f4\u02f6\7^\2\2\u02f5") buf.write(u"\u02f7\t\3\2\2\u02f6\u02f5\3\2\2\2\u02f7\u02f8\3\2\2") buf.write(u"\2\u02f8\u02f6\3\2\2\2\u02f8\u02f9\3\2\2\2\u02f9\u02fb") buf.write(u"\3\2\2\2\u02fa\u02f3\3\2\2\2\u02fa\u02f4\3\2\2\2\u02fb") buf.write(u"\u0096\3\2\2\2\u02fc\u02fd\t\3\2\2\u02fd\u0098\3\2\2") buf.write(u"\2\u02fe\u02ff\t\4\2\2\u02ff\u009a\3\2\2\2\u0300\u0302") buf.write(u"\5\u0099M\2\u0301\u0300\3\2\2\2\u0302\u0303\3\2\2\2\u0303") buf.write(u"\u0301\3\2\2\2\u0303\u0304\3\2\2\2\u0304\u030c\3\2\2") buf.write(u"\2\u0305\u0306\7.\2\2\u0306\u0307\5\u0099M\2\u0307\u0308") buf.write(u"\5\u0099M\2\u0308\u0309\5\u0099M\2\u0309\u030b\3\2\2") buf.write(u"\2\u030a\u0305\3\2\2\2\u030b\u030e\3\2\2\2\u030c\u030a") buf.write(u"\3\2\2\2\u030c\u030d\3\2\2\2\u030d\u0326\3\2\2\2\u030e") buf.write(u"\u030c\3\2\2\2\u030f\u0311\5\u0099M\2\u0310\u030f\3\2") buf.write(u"\2\2\u0311\u0314\3\2\2\2\u0312\u0310\3\2\2\2\u0312\u0313") buf.write(u"\3\2\2\2\u0313\u031c\3\2\2\2\u0314\u0312\3\2\2\2\u0315") buf.write(u"\u0316\7.\2\2\u0316\u0317\5\u0099M\2\u0317\u0318\5\u0099") buf.write(u"M\2\u0318\u0319\5\u0099M\2\u0319\u031b\3\2\2\2\u031a") buf.write(u"\u0315\3\2\2\2\u031b\u031e\3\2\2\2\u031c\u031a\3\2\2") buf.write(u"\2\u031c\u031d\3\2\2\2\u031d\u031f\3\2\2\2\u031e\u031c") buf.write(u"\3\2\2\2\u031f\u0321\7\60\2\2\u0320\u0322\5\u0099M\2") buf.write(u"\u0321\u0320\3\2\2\2\u0322\u0323\3\2\2\2\u0323\u0321") buf.write(u"\3\2\2\2\u0323\u0324\3\2\2\2\u0324\u0326\3\2\2\2\u0325") buf.write(u"\u0301\3\2\2\2\u0325\u0312\3\2\2\2\u0326\u009c\3\2\2") buf.write(u"\2\u0327\u032b\7(\2\2\u0328\u032a\5\u0093J\2\u0329\u0328") buf.write(u"\3\2\2\2\u032a\u032d\3\2\2\2\u032b\u032c\3\2\2\2\u032b") buf.write(u"\u0329\3\2\2\2\u032c\u032f\3\2\2\2\u032d\u032b\3\2\2") buf.write(u"\2\u032e\u0327\3\2\2\2\u032e\u032f\3\2\2\2\u032f\u0330") buf.write(u"\3\2\2\2\u0330\u033c\7?\2\2\u0331\u0339\7?\2\2\u0332") buf.write(u"\u0334\5\u0093J\2\u0333\u0332\3\2\2\2\u0334\u0337\3\2") buf.write(u"\2\2\u0335\u0336\3\2\2\2\u0335\u0333\3\2\2\2\u0336\u0338") buf.write(u"\3\2\2\2\u0337\u0335\3\2\2\2\u0338\u033a\7(\2\2\u0339") buf.write(u"\u0335\3\2\2\2\u0339\u033a\3\2\2\2\u033a\u033c\3\2\2") buf.write(u"\2\u033b\u032e\3\2\2\2\u033b\u0331\3\2\2\2\u033c\u009e") buf.write(u"\3\2\2\2\u033d\u033e\7^\2\2\u033e\u033f\7p\2\2\u033f") buf.write(u"\u0340\7g\2\2\u0340\u0341\7s\2\2\u0341\u00a0\3\2\2\2") buf.write(u"\u0342\u0343\7>\2\2\u0343\u00a2\3\2\2\2\u0344\u0345\7") buf.write(u"^\2\2\u0345\u0346\7n\2\2\u0346\u0347\7g\2\2\u0347\u034e") buf.write(u"\7s\2\2\u0348\u0349\7^\2\2\u0349\u034a\7n\2\2\u034a\u034e") buf.write(u"\7g\2\2\u034b\u034e\5\u00a5S\2\u034c\u034e\5\u00a7T\2") buf.write(u"\u034d\u0344\3\2\2\2\u034d\u0348\3\2\2\2\u034d\u034b") buf.write(u"\3\2\2\2\u034d\u034c\3\2\2\2\u034e\u00a4\3\2\2\2\u034f") buf.write(u"\u0350\7^\2\2\u0350\u0351\7n\2\2\u0351\u0352\7g\2\2\u0352") buf.write(u"\u0353\7s\2\2\u0353\u0354\7s\2\2\u0354\u00a6\3\2\2\2") buf.write(u"\u0355\u0356\7^\2\2\u0356\u0357\7n\2\2\u0357\u0358\7") buf.write(u"g\2\2\u0358\u0359\7s\2\2\u0359\u035a\7u\2\2\u035a\u035b") buf.write(u"\7n\2\2\u035b\u035c\7c\2\2\u035c\u035d\7p\2\2\u035d\u035e") buf.write(u"\7v\2\2\u035e\u00a8\3\2\2\2\u035f\u0360\7@\2\2\u0360") buf.write(u"\u00aa\3\2\2\2\u0361\u0362\7^\2\2\u0362\u0363\7i\2\2") buf.write(u"\u0363\u0364\7g\2\2\u0364\u036b\7s\2\2\u0365\u0366\7") buf.write(u"^\2\2\u0366\u0367\7i\2\2\u0367\u036b\7g\2\2\u0368\u036b") buf.write(u"\5\u00adW\2\u0369\u036b\5\u00afX\2\u036a\u0361\3\2\2") buf.write(u"\2\u036a\u0365\3\2\2\2\u036a\u0368\3\2\2\2\u036a\u0369") buf.write(u"\3\2\2\2\u036b\u00ac\3\2\2\2\u036c\u036d\7^\2\2\u036d") buf.write(u"\u036e\7i\2\2\u036e\u036f\7g\2\2\u036f\u0370\7s\2\2\u0370") buf.write(u"\u0371\7s\2\2\u0371\u00ae\3\2\2\2\u0372\u0373\7^\2\2") buf.write(u"\u0373\u0374\7i\2\2\u0374\u0375\7g\2\2\u0375\u0376\7") buf.write(u"s\2\2\u0376\u0377\7u\2\2\u0377\u0378\7n\2\2\u0378\u0379") buf.write(u"\7c\2\2\u0379\u037a\7p\2\2\u037a\u037b\7v\2\2\u037b\u00b0") buf.write(u"\3\2\2\2\u037c\u037d\7#\2\2\u037d\u00b2\3\2\2\2\u037e") buf.write(u"\u0380\7^\2\2\u037f\u0381\t\3\2\2\u0380\u037f\3\2\2\2") buf.write(u"\u0381\u0382\3\2\2\2\u0382\u0380\3\2\2\2\u0382\u0383") buf.write(u"\3\2\2\2\u0383\u00b4\3\2\2\2\33\2\u00ba\u00ca\u00d9\u00ea") buf.write(u"\u010e\u0176\u01f1\u02f0\u02f8\u02fa\u0303\u030c\u0312") buf.write(u"\u031c\u0323\u0325\u032b\u032e\u0335\u0339\u033b\u034d") buf.write(u"\u036a\u0382\3\b\2\2") return buf.getvalue() class LaTeXLexer(Lexer): atn = ATNDeserializer().deserialize(serializedATN()) decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ] T__0 = 1 WS = 2 THINSPACE = 3 MEDSPACE = 4 THICKSPACE = 5 QUAD = 6 QQUAD = 7 NEGTHINSPACE = 8 NEGMEDSPACE = 9 NEGTHICKSPACE = 10 CMD_LEFT = 11 CMD_RIGHT = 12 IGNORE = 13 ADD = 14 SUB = 15 MUL = 16 DIV = 17 L_PAREN = 18 R_PAREN = 19 L_BRACE = 20 R_BRACE = 21 L_BRACE_LITERAL = 22 R_BRACE_LITERAL = 23 L_BRACKET = 24 R_BRACKET = 25 BAR = 26 R_BAR = 27 L_BAR = 28 L_ANGLE = 29 R_ANGLE = 30 FUNC_LIM = 31 LIM_APPROACH_SYM = 32 FUNC_INT = 33 FUNC_SUM = 34 FUNC_PROD = 35 FUNC_EXP = 36 FUNC_LOG = 37 FUNC_LN = 38 FUNC_SIN = 39 FUNC_COS = 40 FUNC_TAN = 41 FUNC_CSC = 42 FUNC_SEC = 43 FUNC_COT = 44 FUNC_ARCSIN = 45 FUNC_ARCCOS = 46 FUNC_ARCTAN = 47 FUNC_ARCCSC = 48 FUNC_ARCSEC = 49 FUNC_ARCCOT = 50 FUNC_SINH = 51 FUNC_COSH = 52 FUNC_TANH = 53 FUNC_ARSINH = 54 FUNC_ARCOSH = 55 FUNC_ARTANH = 56 L_FLOOR = 57 R_FLOOR = 58 L_CEIL = 59 R_CEIL = 60 FUNC_SQRT = 61 CMD_TIMES = 62 CMD_CDOT = 63 CMD_DIV = 64 CMD_FRAC = 65 CMD_BINOM = 66 CMD_DBINOM = 67 CMD_TBINOM = 68 CMD_MATHIT = 69 UNDERSCORE = 70 CARET = 71 COLON = 72 DIFFERENTIAL = 73 LETTER = 74 NUMBER = 75 EQUAL = 76 NEQ = 77 LT = 78 LTE = 79 LTE_Q = 80 LTE_S = 81 GT = 82 GTE = 83 GTE_Q = 84 GTE_S = 85 BANG = 86 SYMBOL = 87 channelNames = [ u"DEFAULT_TOKEN_CHANNEL", u"HIDDEN" ] modeNames = [ u"DEFAULT_MODE" ] literalNames = [ u"<INVALID>", u"','", u"'\\quad'", u"'\\qquad'", u"'\\negmedspace'", u"'\\negthickspace'", u"'\\left'", u"'\\right'", u"'+'", u"'-'", u"'*'", u"'/'", u"'('", u"')'", u"'{'", u"'}'", u"'\\{'", u"'\\}'", u"'['", u"']'", u"'|'", u"'\\right|'", u"'\\left|'", u"'\\langle'", u"'\\rangle'", u"'\\lim'", u"'\\int'", u"'\\sum'", u"'\\prod'", u"'\\exp'", u"'\\log'", u"'\\ln'", u"'\\sin'", u"'\\cos'", u"'\\tan'", u"'\\csc'", u"'\\sec'", u"'\\cot'", u"'\\arcsin'", u"'\\arccos'", u"'\\arctan'", u"'\\arccsc'", u"'\\arcsec'", u"'\\arccot'", u"'\\sinh'", u"'\\cosh'", u"'\\tanh'", u"'\\arsinh'", u"'\\arcosh'", u"'\\artanh'", u"'\\lfloor'", u"'\\rfloor'", u"'\\lceil'", u"'\\rceil'", u"'\\sqrt'", u"'\\times'", u"'\\cdot'", u"'\\div'", u"'\\frac'", u"'\\binom'", u"'\\dbinom'", u"'\\tbinom'", u"'\\mathit'", u"'_'", u"'^'", u"':'", u"'\\neq'", u"'<'", u"'\\leqq'", u"'\\leqslant'", u"'>'", u"'\\geqq'", u"'\\geqslant'", u"'!'" ] symbolicNames = [ u"<INVALID>", u"WS", u"THINSPACE", u"MEDSPACE", u"THICKSPACE", u"QUAD", u"QQUAD", u"NEGTHINSPACE", u"NEGMEDSPACE", u"NEGTHICKSPACE", u"CMD_LEFT", u"CMD_RIGHT", u"IGNORE", u"ADD", u"SUB", u"MUL", u"DIV", u"L_PAREN", u"R_PAREN", u"L_BRACE", u"R_BRACE", u"L_BRACE_LITERAL", u"R_BRACE_LITERAL", u"L_BRACKET", u"R_BRACKET", u"BAR", u"R_BAR", u"L_BAR", u"L_ANGLE", u"R_ANGLE", u"FUNC_LIM", u"LIM_APPROACH_SYM", u"FUNC_INT", u"FUNC_SUM", u"FUNC_PROD", u"FUNC_EXP", u"FUNC_LOG", u"FUNC_LN", u"FUNC_SIN", u"FUNC_COS", u"FUNC_TAN", u"FUNC_CSC", u"FUNC_SEC", u"FUNC_COT", u"FUNC_ARCSIN", u"FUNC_ARCCOS", u"FUNC_ARCTAN", u"FUNC_ARCCSC", u"FUNC_ARCSEC", u"FUNC_ARCCOT", u"FUNC_SINH", u"FUNC_COSH", u"FUNC_TANH", u"FUNC_ARSINH", u"FUNC_ARCOSH", u"FUNC_ARTANH", u"L_FLOOR", u"R_FLOOR", u"L_CEIL", u"R_CEIL", u"FUNC_SQRT", u"CMD_TIMES", u"CMD_CDOT", u"CMD_DIV", u"CMD_FRAC", u"CMD_BINOM", u"CMD_DBINOM", u"CMD_TBINOM", u"CMD_MATHIT", u"UNDERSCORE", u"CARET", u"COLON", u"DIFFERENTIAL", u"LETTER", u"NUMBER", u"EQUAL", u"NEQ", u"LT", u"LTE", u"LTE_Q", u"LTE_S", u"GT", u"GTE", u"GTE_Q", u"GTE_S", u"BANG", u"SYMBOL" ] ruleNames = [ u"T__0", u"WS", u"THINSPACE", u"MEDSPACE", u"THICKSPACE", u"QUAD", u"QQUAD", u"NEGTHINSPACE", u"NEGMEDSPACE", u"NEGTHICKSPACE", u"CMD_LEFT", u"CMD_RIGHT", u"IGNORE", u"ADD", u"SUB", u"MUL", u"DIV", u"L_PAREN", u"R_PAREN", u"L_BRACE", u"R_BRACE", u"L_BRACE_LITERAL", u"R_BRACE_LITERAL", u"L_BRACKET", u"R_BRACKET", u"BAR", u"R_BAR", u"L_BAR", u"L_ANGLE", u"R_ANGLE", u"FUNC_LIM", u"LIM_APPROACH_SYM", u"FUNC_INT", u"FUNC_SUM", u"FUNC_PROD", u"FUNC_EXP", u"FUNC_LOG", u"FUNC_LN", u"FUNC_SIN", u"FUNC_COS", u"FUNC_TAN", u"FUNC_CSC", u"FUNC_SEC", u"FUNC_COT", u"FUNC_ARCSIN", u"FUNC_ARCCOS", u"FUNC_ARCTAN", u"FUNC_ARCCSC", u"FUNC_ARCSEC", u"FUNC_ARCCOT", u"FUNC_SINH", u"FUNC_COSH", u"FUNC_TANH", u"FUNC_ARSINH", u"FUNC_ARCOSH", u"FUNC_ARTANH", u"L_FLOOR", u"R_FLOOR", u"L_CEIL", u"R_CEIL", u"FUNC_SQRT", u"CMD_TIMES", u"CMD_CDOT", u"CMD_DIV", u"CMD_FRAC", u"CMD_BINOM", u"CMD_DBINOM", u"CMD_TBINOM", u"CMD_MATHIT", u"UNDERSCORE", u"CARET", u"COLON", u"WS_CHAR", u"DIFFERENTIAL", u"LETTER", u"DIGIT", u"NUMBER", u"EQUAL", u"NEQ", u"LT", u"LTE", u"LTE_Q", u"LTE_S", u"GT", u"GTE", u"GTE_Q", u"GTE_S", u"BANG", u"SYMBOL" ] grammarFileName = u"LaTeX.g4" def __init__(self, input=None, output=sys.stdout): super(LaTeXLexer, self).__init__(input, output=output) self.checkVersion("4.7.2") self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache()) self._actions = None self._predicates = None
4a6afde9d8f23e6415916a809d72b7ee4c2cd9bc5dad1b7bda84a0c1f41e9d17
# encoding: utf-8 # *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND *** # # Generated from ../LaTeX.g4, derived from latex2sympy # latex2sympy is licensed under the MIT license # https://github.com/augustt198/latex2sympy/blob/master/LICENSE.txt # # Generated with antlr4 # antlr4 is licensed under the BSD-3-Clause License # https://github.com/antlr/antlr4/blob/master/LICENSE.txt from __future__ import print_function from antlr4 import * from io import StringIO import sys def serializedATN(): with StringIO() as buf: buf.write(u"\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\3") buf.write(u"Y\u01d0\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t") buf.write(u"\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\4\r\t\r") buf.write(u"\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22\t\22\4") buf.write(u"\23\t\23\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\4\30") buf.write(u"\t\30\4\31\t\31\4\32\t\32\4\33\t\33\4\34\t\34\4\35\t") buf.write(u"\35\4\36\t\36\4\37\t\37\4 \t \4!\t!\4\"\t\"\4#\t#\4$") buf.write(u"\t$\4%\t%\4&\t&\4\'\t\'\4(\t(\4)\t)\3\2\3\2\3\3\3\3\3") buf.write(u"\3\3\3\3\3\3\3\7\3[\n\3\f\3\16\3^\13\3\3\4\3\4\3\4\3") buf.write(u"\4\3\5\3\5\3\6\3\6\3\6\3\6\3\6\3\6\7\6l\n\6\f\6\16\6") buf.write(u"o\13\6\3\7\3\7\3\7\3\7\3\7\3\7\7\7w\n\7\f\7\16\7z\13") buf.write(u"\7\3\b\3\b\3\b\3\b\3\b\3\b\7\b\u0082\n\b\f\b\16\b\u0085") buf.write(u"\13\b\3\t\3\t\3\t\6\t\u008a\n\t\r\t\16\t\u008b\5\t\u008e") buf.write(u"\n\t\3\n\3\n\3\n\3\n\7\n\u0094\n\n\f\n\16\n\u0097\13") buf.write(u"\n\5\n\u0099\n\n\3\13\3\13\7\13\u009d\n\13\f\13\16\13") buf.write(u"\u00a0\13\13\3\f\3\f\7\f\u00a4\n\f\f\f\16\f\u00a7\13") buf.write(u"\f\3\r\3\r\5\r\u00ab\n\r\3\16\3\16\3\16\3\16\3\16\3\16") buf.write(u"\5\16\u00b3\n\16\3\17\3\17\3\17\3\17\5\17\u00b9\n\17") buf.write(u"\3\17\3\17\3\20\3\20\3\20\3\20\5\20\u00c1\n\20\3\20\3") buf.write(u"\20\3\21\3\21\3\21\3\21\3\21\3\21\3\21\3\21\3\21\3\21") buf.write(u"\5\21\u00cf\n\21\3\21\5\21\u00d2\n\21\7\21\u00d4\n\21") buf.write(u"\f\21\16\21\u00d7\13\21\3\22\3\22\3\22\3\22\3\22\3\22") buf.write(u"\3\22\3\22\3\22\3\22\5\22\u00e3\n\22\3\22\5\22\u00e6") buf.write(u"\n\22\7\22\u00e8\n\22\f\22\16\22\u00eb\13\22\3\23\3\23") buf.write(u"\3\23\3\23\3\23\3\23\3\23\3\23\5\23\u00f5\n\23\3\24\3") buf.write(u"\24\3\24\3\24\3\24\3\24\3\24\5\24\u00fe\n\24\3\25\3\25") buf.write(u"\3\25\3\25\3\25\3\25\3\25\3\25\3\25\3\25\3\25\3\25\3") buf.write(u"\25\3\25\3\25\3\25\5\25\u0110\n\25\3\26\3\26\3\26\3\26") buf.write(u"\3\27\3\27\5\27\u0118\n\27\3\27\3\27\3\27\3\27\3\27\5") buf.write(u"\27\u011f\n\27\3\30\3\30\3\30\3\30\3\31\3\31\3\31\3\31") buf.write(u"\3\32\3\32\3\32\3\32\3\32\3\33\7\33\u012f\n\33\f\33\16") buf.write(u"\33\u0132\13\33\3\34\3\34\3\34\3\34\3\34\3\34\3\34\3") buf.write(u"\34\3\35\3\35\3\35\3\35\3\35\3\35\3\35\3\35\3\36\3\36") buf.write(u"\3\36\3\36\3\37\3\37\3\37\3\37\3 \3 \3!\3!\5!\u0150\n") buf.write(u"!\3!\5!\u0153\n!\3!\5!\u0156\n!\3!\5!\u0159\n!\5!\u015b") buf.write(u"\n!\3!\3!\3!\3!\3!\5!\u0162\n!\3!\3!\5!\u0166\n!\3!\3") buf.write(u"!\3!\3!\3!\3!\3!\3!\3!\3!\3!\5!\u0173\n!\3!\5!\u0176") buf.write(u"\n!\3!\3!\3!\5!\u017b\n!\3!\3!\3!\3!\3!\5!\u0182\n!\3") buf.write(u"!\3!\3!\3!\3!\3!\3!\3!\3!\3!\3!\5!\u018f\n!\3!\3!\3!") buf.write(u"\3!\3!\3!\5!\u0197\n!\3\"\3\"\3\"\3\"\3\"\5\"\u019e\n") buf.write(u"\"\3#\3#\3#\3#\3#\3#\3#\3#\3#\5#\u01a9\n#\3#\3#\3$\3") buf.write(u"$\3$\3$\3$\5$\u01b2\n$\3%\3%\3&\3&\3&\3&\3&\3&\5&\u01bc") buf.write(u"\n&\3\'\3\'\3\'\3\'\3\'\3\'\5\'\u01c4\n\'\3(\3(\3(\3") buf.write(u"(\3(\3)\3)\3)\3)\3)\3)\2\b\4\n\f\16 \"*\2\4\6\b\n\f\16") buf.write(u"\20\22\24\26\30\32\34\36 \"$&(*,.\60\62\64\668:<>@BD") buf.write(u"FHJLNP\2\13\4\2NQTU\3\2\20\21\5\2\22\23@BJJ\4\2LLYY\3") buf.write(u"\2\34\35\4\2\34\34\36\36\3\2DF\3\2&:\3\2$%\2\u01eb\2") buf.write(u"R\3\2\2\2\4T\3\2\2\2\6_\3\2\2\2\bc\3\2\2\2\ne\3\2\2\2") buf.write(u"\fp\3\2\2\2\16{\3\2\2\2\20\u008d\3\2\2\2\22\u0098\3\2") buf.write(u"\2\2\24\u009a\3\2\2\2\26\u00a1\3\2\2\2\30\u00aa\3\2\2") buf.write(u"\2\32\u00ac\3\2\2\2\34\u00b4\3\2\2\2\36\u00bc\3\2\2\2") buf.write(u" \u00c4\3\2\2\2\"\u00d8\3\2\2\2$\u00f4\3\2\2\2&\u00fd") buf.write(u"\3\2\2\2(\u010f\3\2\2\2*\u0111\3\2\2\2,\u011e\3\2\2\2") buf.write(u".\u0120\3\2\2\2\60\u0124\3\2\2\2\62\u0128\3\2\2\2\64") buf.write(u"\u0130\3\2\2\2\66\u0133\3\2\2\28\u013b\3\2\2\2:\u0143") buf.write(u"\3\2\2\2<\u0147\3\2\2\2>\u014b\3\2\2\2@\u0196\3\2\2\2") buf.write(u"B\u019d\3\2\2\2D\u019f\3\2\2\2F\u01b1\3\2\2\2H\u01b3") buf.write(u"\3\2\2\2J\u01b5\3\2\2\2L\u01bd\3\2\2\2N\u01c5\3\2\2\2") buf.write(u"P\u01ca\3\2\2\2RS\5\4\3\2S\3\3\2\2\2TU\b\3\1\2UV\5\b") buf.write(u"\5\2V\\\3\2\2\2WX\f\4\2\2XY\t\2\2\2Y[\5\4\3\5ZW\3\2\2") buf.write(u"\2[^\3\2\2\2\\Z\3\2\2\2\\]\3\2\2\2]\5\3\2\2\2^\\\3\2") buf.write(u"\2\2_`\5\b\5\2`a\7N\2\2ab\5\b\5\2b\7\3\2\2\2cd\5\n\6") buf.write(u"\2d\t\3\2\2\2ef\b\6\1\2fg\5\f\7\2gm\3\2\2\2hi\f\4\2\2") buf.write(u"ij\t\3\2\2jl\5\n\6\5kh\3\2\2\2lo\3\2\2\2mk\3\2\2\2mn") buf.write(u"\3\2\2\2n\13\3\2\2\2om\3\2\2\2pq\b\7\1\2qr\5\20\t\2r") buf.write(u"x\3\2\2\2st\f\4\2\2tu\t\4\2\2uw\5\f\7\5vs\3\2\2\2wz\3") buf.write(u"\2\2\2xv\3\2\2\2xy\3\2\2\2y\r\3\2\2\2zx\3\2\2\2{|\b\b") buf.write(u"\1\2|}\5\22\n\2}\u0083\3\2\2\2~\177\f\4\2\2\177\u0080") buf.write(u"\t\4\2\2\u0080\u0082\5\16\b\5\u0081~\3\2\2\2\u0082\u0085") buf.write(u"\3\2\2\2\u0083\u0081\3\2\2\2\u0083\u0084\3\2\2\2\u0084") buf.write(u"\17\3\2\2\2\u0085\u0083\3\2\2\2\u0086\u0087\t\3\2\2\u0087") buf.write(u"\u008e\5\20\t\2\u0088\u008a\5\24\13\2\u0089\u0088\3\2") buf.write(u"\2\2\u008a\u008b\3\2\2\2\u008b\u0089\3\2\2\2\u008b\u008c") buf.write(u"\3\2\2\2\u008c\u008e\3\2\2\2\u008d\u0086\3\2\2\2\u008d") buf.write(u"\u0089\3\2\2\2\u008e\21\3\2\2\2\u008f\u0090\t\3\2\2\u0090") buf.write(u"\u0099\5\22\n\2\u0091\u0095\5\24\13\2\u0092\u0094\5\26") buf.write(u"\f\2\u0093\u0092\3\2\2\2\u0094\u0097\3\2\2\2\u0095\u0093") buf.write(u"\3\2\2\2\u0095\u0096\3\2\2\2\u0096\u0099\3\2\2\2\u0097") buf.write(u"\u0095\3\2\2\2\u0098\u008f\3\2\2\2\u0098\u0091\3\2\2") buf.write(u"\2\u0099\23\3\2\2\2\u009a\u009e\5 \21\2\u009b\u009d\5") buf.write(u"\30\r\2\u009c\u009b\3\2\2\2\u009d\u00a0\3\2\2\2\u009e") buf.write(u"\u009c\3\2\2\2\u009e\u009f\3\2\2\2\u009f\25\3\2\2\2\u00a0") buf.write(u"\u009e\3\2\2\2\u00a1\u00a5\5\"\22\2\u00a2\u00a4\5\30") buf.write(u"\r\2\u00a3\u00a2\3\2\2\2\u00a4\u00a7\3\2\2\2\u00a5\u00a3") buf.write(u"\3\2\2\2\u00a5\u00a6\3\2\2\2\u00a6\27\3\2\2\2\u00a7\u00a5") buf.write(u"\3\2\2\2\u00a8\u00ab\7X\2\2\u00a9\u00ab\5\32\16\2\u00aa") buf.write(u"\u00a8\3\2\2\2\u00aa\u00a9\3\2\2\2\u00ab\31\3\2\2\2\u00ac") buf.write(u"\u00b2\7\34\2\2\u00ad\u00b3\5\36\20\2\u00ae\u00b3\5\34") buf.write(u"\17\2\u00af\u00b0\5\36\20\2\u00b0\u00b1\5\34\17\2\u00b1") buf.write(u"\u00b3\3\2\2\2\u00b2\u00ad\3\2\2\2\u00b2\u00ae\3\2\2") buf.write(u"\2\u00b2\u00af\3\2\2\2\u00b3\33\3\2\2\2\u00b4\u00b5\7") buf.write(u"H\2\2\u00b5\u00b8\7\26\2\2\u00b6\u00b9\5\b\5\2\u00b7") buf.write(u"\u00b9\5\6\4\2\u00b8\u00b6\3\2\2\2\u00b8\u00b7\3\2\2") buf.write(u"\2\u00b9\u00ba\3\2\2\2\u00ba\u00bb\7\27\2\2\u00bb\35") buf.write(u"\3\2\2\2\u00bc\u00bd\7I\2\2\u00bd\u00c0\7\26\2\2\u00be") buf.write(u"\u00c1\5\b\5\2\u00bf\u00c1\5\6\4\2\u00c0\u00be\3\2\2") buf.write(u"\2\u00c0\u00bf\3\2\2\2\u00c1\u00c2\3\2\2\2\u00c2\u00c3") buf.write(u"\7\27\2\2\u00c3\37\3\2\2\2\u00c4\u00c5\b\21\1\2\u00c5") buf.write(u"\u00c6\5$\23\2\u00c6\u00d5\3\2\2\2\u00c7\u00c8\f\4\2") buf.write(u"\2\u00c8\u00ce\7I\2\2\u00c9\u00cf\5,\27\2\u00ca\u00cb") buf.write(u"\7\26\2\2\u00cb\u00cc\5\b\5\2\u00cc\u00cd\7\27\2\2\u00cd") buf.write(u"\u00cf\3\2\2\2\u00ce\u00c9\3\2\2\2\u00ce\u00ca\3\2\2") buf.write(u"\2\u00cf\u00d1\3\2\2\2\u00d0\u00d2\5J&\2\u00d1\u00d0") buf.write(u"\3\2\2\2\u00d1\u00d2\3\2\2\2\u00d2\u00d4\3\2\2\2\u00d3") buf.write(u"\u00c7\3\2\2\2\u00d4\u00d7\3\2\2\2\u00d5\u00d3\3\2\2") buf.write(u"\2\u00d5\u00d6\3\2\2\2\u00d6!\3\2\2\2\u00d7\u00d5\3\2") buf.write(u"\2\2\u00d8\u00d9\b\22\1\2\u00d9\u00da\5&\24\2\u00da\u00e9") buf.write(u"\3\2\2\2\u00db\u00dc\f\4\2\2\u00dc\u00e2\7I\2\2\u00dd") buf.write(u"\u00e3\5,\27\2\u00de\u00df\7\26\2\2\u00df\u00e0\5\b\5") buf.write(u"\2\u00e0\u00e1\7\27\2\2\u00e1\u00e3\3\2\2\2\u00e2\u00dd") buf.write(u"\3\2\2\2\u00e2\u00de\3\2\2\2\u00e3\u00e5\3\2\2\2\u00e4") buf.write(u"\u00e6\5J&\2\u00e5\u00e4\3\2\2\2\u00e5\u00e6\3\2\2\2") buf.write(u"\u00e6\u00e8\3\2\2\2\u00e7\u00db\3\2\2\2\u00e8\u00eb") buf.write(u"\3\2\2\2\u00e9\u00e7\3\2\2\2\u00e9\u00ea\3\2\2\2\u00ea") buf.write(u"#\3\2\2\2\u00eb\u00e9\3\2\2\2\u00ec\u00f5\5(\25\2\u00ed") buf.write(u"\u00f5\5*\26\2\u00ee\u00f5\5@!\2\u00ef\u00f5\5,\27\2") buf.write(u"\u00f0\u00f5\5\66\34\2\u00f1\u00f5\58\35\2\u00f2\u00f5") buf.write(u"\5:\36\2\u00f3\u00f5\5<\37\2\u00f4\u00ec\3\2\2\2\u00f4") buf.write(u"\u00ed\3\2\2\2\u00f4\u00ee\3\2\2\2\u00f4\u00ef\3\2\2") buf.write(u"\2\u00f4\u00f0\3\2\2\2\u00f4\u00f1\3\2\2\2\u00f4\u00f2") buf.write(u"\3\2\2\2\u00f4\u00f3\3\2\2\2\u00f5%\3\2\2\2\u00f6\u00fe") buf.write(u"\5(\25\2\u00f7\u00fe\5*\26\2\u00f8\u00fe\5,\27\2\u00f9") buf.write(u"\u00fe\5\66\34\2\u00fa\u00fe\58\35\2\u00fb\u00fe\5:\36") buf.write(u"\2\u00fc\u00fe\5<\37\2\u00fd\u00f6\3\2\2\2\u00fd\u00f7") buf.write(u"\3\2\2\2\u00fd\u00f8\3\2\2\2\u00fd\u00f9\3\2\2\2\u00fd") buf.write(u"\u00fa\3\2\2\2\u00fd\u00fb\3\2\2\2\u00fd\u00fc\3\2\2") buf.write(u"\2\u00fe\'\3\2\2\2\u00ff\u0100\7\24\2\2\u0100\u0101\5") buf.write(u"\b\5\2\u0101\u0102\7\25\2\2\u0102\u0110\3\2\2\2\u0103") buf.write(u"\u0104\7\32\2\2\u0104\u0105\5\b\5\2\u0105\u0106\7\33") buf.write(u"\2\2\u0106\u0110\3\2\2\2\u0107\u0108\7\26\2\2\u0108\u0109") buf.write(u"\5\b\5\2\u0109\u010a\7\27\2\2\u010a\u0110\3\2\2\2\u010b") buf.write(u"\u010c\7\30\2\2\u010c\u010d\5\b\5\2\u010d\u010e\7\31") buf.write(u"\2\2\u010e\u0110\3\2\2\2\u010f\u00ff\3\2\2\2\u010f\u0103") buf.write(u"\3\2\2\2\u010f\u0107\3\2\2\2\u010f\u010b\3\2\2\2\u0110") buf.write(u")\3\2\2\2\u0111\u0112\7\34\2\2\u0112\u0113\5\b\5\2\u0113") buf.write(u"\u0114\7\34\2\2\u0114+\3\2\2\2\u0115\u0117\t\5\2\2\u0116") buf.write(u"\u0118\5J&\2\u0117\u0116\3\2\2\2\u0117\u0118\3\2\2\2") buf.write(u"\u0118\u011f\3\2\2\2\u0119\u011f\7M\2\2\u011a\u011f\7") buf.write(u"K\2\2\u011b\u011f\5\62\32\2\u011c\u011f\5.\30\2\u011d") buf.write(u"\u011f\5\60\31\2\u011e\u0115\3\2\2\2\u011e\u0119\3\2") buf.write(u"\2\2\u011e\u011a\3\2\2\2\u011e\u011b\3\2\2\2\u011e\u011c") buf.write(u"\3\2\2\2\u011e\u011d\3\2\2\2\u011f-\3\2\2\2\u0120\u0121") buf.write(u"\7\37\2\2\u0121\u0122\5\b\5\2\u0122\u0123\t\6\2\2\u0123") buf.write(u"/\3\2\2\2\u0124\u0125\t\7\2\2\u0125\u0126\5\b\5\2\u0126") buf.write(u"\u0127\7 \2\2\u0127\61\3\2\2\2\u0128\u0129\7G\2\2\u0129") buf.write(u"\u012a\7\26\2\2\u012a\u012b\5\64\33\2\u012b\u012c\7\27") buf.write(u"\2\2\u012c\63\3\2\2\2\u012d\u012f\7L\2\2\u012e\u012d") buf.write(u"\3\2\2\2\u012f\u0132\3\2\2\2\u0130\u012e\3\2\2\2\u0130") buf.write(u"\u0131\3\2\2\2\u0131\65\3\2\2\2\u0132\u0130\3\2\2\2\u0133") buf.write(u"\u0134\7C\2\2\u0134\u0135\7\26\2\2\u0135\u0136\5\b\5") buf.write(u"\2\u0136\u0137\7\27\2\2\u0137\u0138\7\26\2\2\u0138\u0139") buf.write(u"\5\b\5\2\u0139\u013a\7\27\2\2\u013a\67\3\2\2\2\u013b") buf.write(u"\u013c\t\b\2\2\u013c\u013d\7\26\2\2\u013d\u013e\5\b\5") buf.write(u"\2\u013e\u013f\7\27\2\2\u013f\u0140\7\26\2\2\u0140\u0141") buf.write(u"\5\b\5\2\u0141\u0142\7\27\2\2\u01429\3\2\2\2\u0143\u0144") buf.write(u"\7;\2\2\u0144\u0145\5\b\5\2\u0145\u0146\7<\2\2\u0146") buf.write(u";\3\2\2\2\u0147\u0148\7=\2\2\u0148\u0149\5\b\5\2\u0149") buf.write(u"\u014a\7>\2\2\u014a=\3\2\2\2\u014b\u014c\t\t\2\2\u014c") buf.write(u"?\3\2\2\2\u014d\u015a\5> \2\u014e\u0150\5J&\2\u014f\u014e") buf.write(u"\3\2\2\2\u014f\u0150\3\2\2\2\u0150\u0152\3\2\2\2\u0151") buf.write(u"\u0153\5L\'\2\u0152\u0151\3\2\2\2\u0152\u0153\3\2\2\2") buf.write(u"\u0153\u015b\3\2\2\2\u0154\u0156\5L\'\2\u0155\u0154\3") buf.write(u"\2\2\2\u0155\u0156\3\2\2\2\u0156\u0158\3\2\2\2\u0157") buf.write(u"\u0159\5J&\2\u0158\u0157\3\2\2\2\u0158\u0159\3\2\2\2") buf.write(u"\u0159\u015b\3\2\2\2\u015a\u014f\3\2\2\2\u015a\u0155") buf.write(u"\3\2\2\2\u015b\u0161\3\2\2\2\u015c\u015d\7\24\2\2\u015d") buf.write(u"\u015e\5F$\2\u015e\u015f\7\25\2\2\u015f\u0162\3\2\2\2") buf.write(u"\u0160\u0162\5H%\2\u0161\u015c\3\2\2\2\u0161\u0160\3") buf.write(u"\2\2\2\u0162\u0197\3\2\2\2\u0163\u0165\t\5\2\2\u0164") buf.write(u"\u0166\5J&\2\u0165\u0164\3\2\2\2\u0165\u0166\3\2\2\2") buf.write(u"\u0166\u0167\3\2\2\2\u0167\u0168\7\24\2\2\u0168\u0169") buf.write(u"\5B\"\2\u0169\u016a\7\25\2\2\u016a\u0197\3\2\2\2\u016b") buf.write(u"\u0172\7#\2\2\u016c\u016d\5J&\2\u016d\u016e\5L\'\2\u016e") buf.write(u"\u0173\3\2\2\2\u016f\u0170\5L\'\2\u0170\u0171\5J&\2\u0171") buf.write(u"\u0173\3\2\2\2\u0172\u016c\3\2\2\2\u0172\u016f\3\2\2") buf.write(u"\2\u0172\u0173\3\2\2\2\u0173\u017a\3\2\2\2\u0174\u0176") buf.write(u"\5\n\6\2\u0175\u0174\3\2\2\2\u0175\u0176\3\2\2\2\u0176") buf.write(u"\u0177\3\2\2\2\u0177\u017b\7K\2\2\u0178\u017b\5\66\34") buf.write(u"\2\u0179\u017b\5\n\6\2\u017a\u0175\3\2\2\2\u017a\u0178") buf.write(u"\3\2\2\2\u017a\u0179\3\2\2\2\u017b\u0197\3\2\2\2\u017c") buf.write(u"\u0181\7?\2\2\u017d\u017e\7\32\2\2\u017e\u017f\5\b\5") buf.write(u"\2\u017f\u0180\7\33\2\2\u0180\u0182\3\2\2\2\u0181\u017d") buf.write(u"\3\2\2\2\u0181\u0182\3\2\2\2\u0182\u0183\3\2\2\2\u0183") buf.write(u"\u0184\7\26\2\2\u0184\u0185\5\b\5\2\u0185\u0186\7\27") buf.write(u"\2\2\u0186\u0197\3\2\2\2\u0187\u018e\t\n\2\2\u0188\u0189") buf.write(u"\5N(\2\u0189\u018a\5L\'\2\u018a\u018f\3\2\2\2\u018b\u018c") buf.write(u"\5L\'\2\u018c\u018d\5N(\2\u018d\u018f\3\2\2\2\u018e\u0188") buf.write(u"\3\2\2\2\u018e\u018b\3\2\2\2\u018f\u0190\3\2\2\2\u0190") buf.write(u"\u0191\5\f\7\2\u0191\u0197\3\2\2\2\u0192\u0193\7!\2\2") buf.write(u"\u0193\u0194\5D#\2\u0194\u0195\5\f\7\2\u0195\u0197\3") buf.write(u"\2\2\2\u0196\u014d\3\2\2\2\u0196\u0163\3\2\2\2\u0196") buf.write(u"\u016b\3\2\2\2\u0196\u017c\3\2\2\2\u0196\u0187\3\2\2") buf.write(u"\2\u0196\u0192\3\2\2\2\u0197A\3\2\2\2\u0198\u0199\5\b") buf.write(u"\5\2\u0199\u019a\7\3\2\2\u019a\u019b\5B\"\2\u019b\u019e") buf.write(u"\3\2\2\2\u019c\u019e\5\b\5\2\u019d\u0198\3\2\2\2\u019d") buf.write(u"\u019c\3\2\2\2\u019eC\3\2\2\2\u019f\u01a0\7H\2\2\u01a0") buf.write(u"\u01a1\7\26\2\2\u01a1\u01a2\t\5\2\2\u01a2\u01a3\7\"\2") buf.write(u"\2\u01a3\u01a8\5\b\5\2\u01a4\u01a5\7I\2\2\u01a5\u01a6") buf.write(u"\7\26\2\2\u01a6\u01a7\t\3\2\2\u01a7\u01a9\7\27\2\2\u01a8") buf.write(u"\u01a4\3\2\2\2\u01a8\u01a9\3\2\2\2\u01a9\u01aa\3\2\2") buf.write(u"\2\u01aa\u01ab\7\27\2\2\u01abE\3\2\2\2\u01ac\u01b2\5") buf.write(u"\b\5\2\u01ad\u01ae\5\b\5\2\u01ae\u01af\7\3\2\2\u01af") buf.write(u"\u01b0\5F$\2\u01b0\u01b2\3\2\2\2\u01b1\u01ac\3\2\2\2") buf.write(u"\u01b1\u01ad\3\2\2\2\u01b2G\3\2\2\2\u01b3\u01b4\5\16") buf.write(u"\b\2\u01b4I\3\2\2\2\u01b5\u01bb\7H\2\2\u01b6\u01bc\5") buf.write(u",\27\2\u01b7\u01b8\7\26\2\2\u01b8\u01b9\5\b\5\2\u01b9") buf.write(u"\u01ba\7\27\2\2\u01ba\u01bc\3\2\2\2\u01bb\u01b6\3\2\2") buf.write(u"\2\u01bb\u01b7\3\2\2\2\u01bcK\3\2\2\2\u01bd\u01c3\7I") buf.write(u"\2\2\u01be\u01c4\5,\27\2\u01bf\u01c0\7\26\2\2\u01c0\u01c1") buf.write(u"\5\b\5\2\u01c1\u01c2\7\27\2\2\u01c2\u01c4\3\2\2\2\u01c3") buf.write(u"\u01be\3\2\2\2\u01c3\u01bf\3\2\2\2\u01c4M\3\2\2\2\u01c5") buf.write(u"\u01c6\7H\2\2\u01c6\u01c7\7\26\2\2\u01c7\u01c8\5\6\4") buf.write(u"\2\u01c8\u01c9\7\27\2\2\u01c9O\3\2\2\2\u01ca\u01cb\7") buf.write(u"H\2\2\u01cb\u01cc\7\26\2\2\u01cc\u01cd\5\6\4\2\u01cd") buf.write(u"\u01ce\7\27\2\2\u01ceQ\3\2\2\2.\\mx\u0083\u008b\u008d") buf.write(u"\u0095\u0098\u009e\u00a5\u00aa\u00b2\u00b8\u00c0\u00ce") buf.write(u"\u00d1\u00d5\u00e2\u00e5\u00e9\u00f4\u00fd\u010f\u0117") buf.write(u"\u011e\u0130\u014f\u0152\u0155\u0158\u015a\u0161\u0165") buf.write(u"\u0172\u0175\u017a\u0181\u018e\u0196\u019d\u01a8\u01b1") buf.write(u"\u01bb\u01c3") return buf.getvalue() class LaTeXParser ( Parser ): grammarFileName = "LaTeX.g4" atn = ATNDeserializer().deserialize(serializedATN()) decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ] sharedContextCache = PredictionContextCache() literalNames = [ u"<INVALID>", u"','", u"<INVALID>", u"<INVALID>", u"<INVALID>", u"<INVALID>", u"'\\quad'", u"'\\qquad'", u"<INVALID>", u"'\\negmedspace'", u"'\\negthickspace'", u"'\\left'", u"'\\right'", u"<INVALID>", u"'+'", u"'-'", u"'*'", u"'/'", u"'('", u"')'", u"'{'", u"'}'", u"'\\{'", u"'\\}'", u"'['", u"']'", u"'|'", u"'\\right|'", u"'\\left|'", u"'\\langle'", u"'\\rangle'", u"'\\lim'", u"<INVALID>", u"'\\int'", u"'\\sum'", u"'\\prod'", u"'\\exp'", u"'\\log'", u"'\\ln'", u"'\\sin'", u"'\\cos'", u"'\\tan'", u"'\\csc'", u"'\\sec'", u"'\\cot'", u"'\\arcsin'", u"'\\arccos'", u"'\\arctan'", u"'\\arccsc'", u"'\\arcsec'", u"'\\arccot'", u"'\\sinh'", u"'\\cosh'", u"'\\tanh'", u"'\\arsinh'", u"'\\arcosh'", u"'\\artanh'", u"'\\lfloor'", u"'\\rfloor'", u"'\\lceil'", u"'\\rceil'", u"'\\sqrt'", u"'\\times'", u"'\\cdot'", u"'\\div'", u"'\\frac'", u"'\\binom'", u"'\\dbinom'", u"'\\tbinom'", u"'\\mathit'", u"'_'", u"'^'", u"':'", u"<INVALID>", u"<INVALID>", u"<INVALID>", u"<INVALID>", u"'\\neq'", u"'<'", u"<INVALID>", u"'\\leqq'", u"'\\leqslant'", u"'>'", u"<INVALID>", u"'\\geqq'", u"'\\geqslant'", u"'!'" ] symbolicNames = [ u"<INVALID>", u"<INVALID>", u"WS", u"THINSPACE", u"MEDSPACE", u"THICKSPACE", u"QUAD", u"QQUAD", u"NEGTHINSPACE", u"NEGMEDSPACE", u"NEGTHICKSPACE", u"CMD_LEFT", u"CMD_RIGHT", u"IGNORE", u"ADD", u"SUB", u"MUL", u"DIV", u"L_PAREN", u"R_PAREN", u"L_BRACE", u"R_BRACE", u"L_BRACE_LITERAL", u"R_BRACE_LITERAL", u"L_BRACKET", u"R_BRACKET", u"BAR", u"R_BAR", u"L_BAR", u"L_ANGLE", u"R_ANGLE", u"FUNC_LIM", u"LIM_APPROACH_SYM", u"FUNC_INT", u"FUNC_SUM", u"FUNC_PROD", u"FUNC_EXP", u"FUNC_LOG", u"FUNC_LN", u"FUNC_SIN", u"FUNC_COS", u"FUNC_TAN", u"FUNC_CSC", u"FUNC_SEC", u"FUNC_COT", u"FUNC_ARCSIN", u"FUNC_ARCCOS", u"FUNC_ARCTAN", u"FUNC_ARCCSC", u"FUNC_ARCSEC", u"FUNC_ARCCOT", u"FUNC_SINH", u"FUNC_COSH", u"FUNC_TANH", u"FUNC_ARSINH", u"FUNC_ARCOSH", u"FUNC_ARTANH", u"L_FLOOR", u"R_FLOOR", u"L_CEIL", u"R_CEIL", u"FUNC_SQRT", u"CMD_TIMES", u"CMD_CDOT", u"CMD_DIV", u"CMD_FRAC", u"CMD_BINOM", u"CMD_DBINOM", u"CMD_TBINOM", u"CMD_MATHIT", u"UNDERSCORE", u"CARET", u"COLON", u"DIFFERENTIAL", u"LETTER", u"NUMBER", u"EQUAL", u"NEQ", u"LT", u"LTE", u"LTE_Q", u"LTE_S", u"GT", u"GTE", u"GTE_Q", u"GTE_S", u"BANG", u"SYMBOL" ] RULE_math = 0 RULE_relation = 1 RULE_equality = 2 RULE_expr = 3 RULE_additive = 4 RULE_mp = 5 RULE_mp_nofunc = 6 RULE_unary = 7 RULE_unary_nofunc = 8 RULE_postfix = 9 RULE_postfix_nofunc = 10 RULE_postfix_op = 11 RULE_eval_at = 12 RULE_eval_at_sub = 13 RULE_eval_at_sup = 14 RULE_exp = 15 RULE_exp_nofunc = 16 RULE_comp = 17 RULE_comp_nofunc = 18 RULE_group = 19 RULE_abs_group = 20 RULE_atom = 21 RULE_bra = 22 RULE_ket = 23 RULE_mathit = 24 RULE_mathit_text = 25 RULE_frac = 26 RULE_binom = 27 RULE_floor = 28 RULE_ceil = 29 RULE_func_normal = 30 RULE_func = 31 RULE_args = 32 RULE_limit_sub = 33 RULE_func_arg = 34 RULE_func_arg_noparens = 35 RULE_subexpr = 36 RULE_supexpr = 37 RULE_subeq = 38 RULE_supeq = 39 ruleNames = [ u"math", u"relation", u"equality", u"expr", u"additive", u"mp", u"mp_nofunc", u"unary", u"unary_nofunc", u"postfix", u"postfix_nofunc", u"postfix_op", u"eval_at", u"eval_at_sub", u"eval_at_sup", u"exp", u"exp_nofunc", u"comp", u"comp_nofunc", u"group", u"abs_group", u"atom", u"bra", u"ket", u"mathit", u"mathit_text", u"frac", u"binom", u"floor", u"ceil", u"func_normal", u"func", u"args", u"limit_sub", u"func_arg", u"func_arg_noparens", u"subexpr", u"supexpr", u"subeq", u"supeq" ] EOF = Token.EOF T__0=1 WS=2 THINSPACE=3 MEDSPACE=4 THICKSPACE=5 QUAD=6 QQUAD=7 NEGTHINSPACE=8 NEGMEDSPACE=9 NEGTHICKSPACE=10 CMD_LEFT=11 CMD_RIGHT=12 IGNORE=13 ADD=14 SUB=15 MUL=16 DIV=17 L_PAREN=18 R_PAREN=19 L_BRACE=20 R_BRACE=21 L_BRACE_LITERAL=22 R_BRACE_LITERAL=23 L_BRACKET=24 R_BRACKET=25 BAR=26 R_BAR=27 L_BAR=28 L_ANGLE=29 R_ANGLE=30 FUNC_LIM=31 LIM_APPROACH_SYM=32 FUNC_INT=33 FUNC_SUM=34 FUNC_PROD=35 FUNC_EXP=36 FUNC_LOG=37 FUNC_LN=38 FUNC_SIN=39 FUNC_COS=40 FUNC_TAN=41 FUNC_CSC=42 FUNC_SEC=43 FUNC_COT=44 FUNC_ARCSIN=45 FUNC_ARCCOS=46 FUNC_ARCTAN=47 FUNC_ARCCSC=48 FUNC_ARCSEC=49 FUNC_ARCCOT=50 FUNC_SINH=51 FUNC_COSH=52 FUNC_TANH=53 FUNC_ARSINH=54 FUNC_ARCOSH=55 FUNC_ARTANH=56 L_FLOOR=57 R_FLOOR=58 L_CEIL=59 R_CEIL=60 FUNC_SQRT=61 CMD_TIMES=62 CMD_CDOT=63 CMD_DIV=64 CMD_FRAC=65 CMD_BINOM=66 CMD_DBINOM=67 CMD_TBINOM=68 CMD_MATHIT=69 UNDERSCORE=70 CARET=71 COLON=72 DIFFERENTIAL=73 LETTER=74 NUMBER=75 EQUAL=76 NEQ=77 LT=78 LTE=79 LTE_Q=80 LTE_S=81 GT=82 GTE=83 GTE_Q=84 GTE_S=85 BANG=86 SYMBOL=87 def __init__(self, input, output=sys.stdout): super(LaTeXParser, self).__init__(input, output=output) self.checkVersion("4.7.2") self._interp = ParserATNSimulator(self, self.atn, self.decisionsToDFA, self.sharedContextCache) self._predicates = None class MathContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.MathContext, self).__init__(parent, invokingState) self.parser = parser def relation(self): return self.getTypedRuleContext(LaTeXParser.RelationContext,0) def getRuleIndex(self): return LaTeXParser.RULE_math def math(self): localctx = LaTeXParser.MathContext(self, self._ctx, self.state) self.enterRule(localctx, 0, self.RULE_math) try: self.enterOuterAlt(localctx, 1) self.state = 80 self.relation(0) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class RelationContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.RelationContext, self).__init__(parent, invokingState) self.parser = parser def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def relation(self, i=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.RelationContext) else: return self.getTypedRuleContext(LaTeXParser.RelationContext,i) def EQUAL(self): return self.getToken(LaTeXParser.EQUAL, 0) def LT(self): return self.getToken(LaTeXParser.LT, 0) def LTE(self): return self.getToken(LaTeXParser.LTE, 0) def GT(self): return self.getToken(LaTeXParser.GT, 0) def GTE(self): return self.getToken(LaTeXParser.GTE, 0) def NEQ(self): return self.getToken(LaTeXParser.NEQ, 0) def getRuleIndex(self): return LaTeXParser.RULE_relation def relation(self, _p=0): _parentctx = self._ctx _parentState = self.state localctx = LaTeXParser.RelationContext(self, self._ctx, _parentState) _prevctx = localctx _startState = 2 self.enterRecursionRule(localctx, 2, self.RULE_relation, _p) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 83 self.expr() self._ctx.stop = self._input.LT(-1) self.state = 90 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,0,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: if self._parseListeners is not None: self.triggerExitRuleEvent() _prevctx = localctx localctx = LaTeXParser.RelationContext(self, _parentctx, _parentState) self.pushNewRecursionContext(localctx, _startState, self.RULE_relation) self.state = 85 if not self.precpred(self._ctx, 2): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 2)") self.state = 86 _la = self._input.LA(1) if not(((((_la - 76)) & ~0x3f) == 0 and ((1 << (_la - 76)) & ((1 << (LaTeXParser.EQUAL - 76)) | (1 << (LaTeXParser.NEQ - 76)) | (1 << (LaTeXParser.LT - 76)) | (1 << (LaTeXParser.LTE - 76)) | (1 << (LaTeXParser.GT - 76)) | (1 << (LaTeXParser.GTE - 76)))) != 0)): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 87 self.relation(3) self.state = 92 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,0,self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.unrollRecursionContexts(_parentctx) return localctx class EqualityContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.EqualityContext, self).__init__(parent, invokingState) self.parser = parser def expr(self, i=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.ExprContext) else: return self.getTypedRuleContext(LaTeXParser.ExprContext,i) def EQUAL(self): return self.getToken(LaTeXParser.EQUAL, 0) def getRuleIndex(self): return LaTeXParser.RULE_equality def equality(self): localctx = LaTeXParser.EqualityContext(self, self._ctx, self.state) self.enterRule(localctx, 4, self.RULE_equality) try: self.enterOuterAlt(localctx, 1) self.state = 93 self.expr() self.state = 94 self.match(LaTeXParser.EQUAL) self.state = 95 self.expr() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ExprContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.ExprContext, self).__init__(parent, invokingState) self.parser = parser def additive(self): return self.getTypedRuleContext(LaTeXParser.AdditiveContext,0) def getRuleIndex(self): return LaTeXParser.RULE_expr def expr(self): localctx = LaTeXParser.ExprContext(self, self._ctx, self.state) self.enterRule(localctx, 6, self.RULE_expr) try: self.enterOuterAlt(localctx, 1) self.state = 97 self.additive(0) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class AdditiveContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.AdditiveContext, self).__init__(parent, invokingState) self.parser = parser def mp(self): return self.getTypedRuleContext(LaTeXParser.MpContext,0) def additive(self, i=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.AdditiveContext) else: return self.getTypedRuleContext(LaTeXParser.AdditiveContext,i) def ADD(self): return self.getToken(LaTeXParser.ADD, 0) def SUB(self): return self.getToken(LaTeXParser.SUB, 0) def getRuleIndex(self): return LaTeXParser.RULE_additive def additive(self, _p=0): _parentctx = self._ctx _parentState = self.state localctx = LaTeXParser.AdditiveContext(self, self._ctx, _parentState) _prevctx = localctx _startState = 8 self.enterRecursionRule(localctx, 8, self.RULE_additive, _p) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 100 self.mp(0) self._ctx.stop = self._input.LT(-1) self.state = 107 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,1,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: if self._parseListeners is not None: self.triggerExitRuleEvent() _prevctx = localctx localctx = LaTeXParser.AdditiveContext(self, _parentctx, _parentState) self.pushNewRecursionContext(localctx, _startState, self.RULE_additive) self.state = 102 if not self.precpred(self._ctx, 2): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 2)") self.state = 103 _la = self._input.LA(1) if not(_la==LaTeXParser.ADD or _la==LaTeXParser.SUB): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 104 self.additive(3) self.state = 109 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,1,self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.unrollRecursionContexts(_parentctx) return localctx class MpContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.MpContext, self).__init__(parent, invokingState) self.parser = parser def unary(self): return self.getTypedRuleContext(LaTeXParser.UnaryContext,0) def mp(self, i=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.MpContext) else: return self.getTypedRuleContext(LaTeXParser.MpContext,i) def MUL(self): return self.getToken(LaTeXParser.MUL, 0) def CMD_TIMES(self): return self.getToken(LaTeXParser.CMD_TIMES, 0) def CMD_CDOT(self): return self.getToken(LaTeXParser.CMD_CDOT, 0) def DIV(self): return self.getToken(LaTeXParser.DIV, 0) def CMD_DIV(self): return self.getToken(LaTeXParser.CMD_DIV, 0) def COLON(self): return self.getToken(LaTeXParser.COLON, 0) def getRuleIndex(self): return LaTeXParser.RULE_mp def mp(self, _p=0): _parentctx = self._ctx _parentState = self.state localctx = LaTeXParser.MpContext(self, self._ctx, _parentState) _prevctx = localctx _startState = 10 self.enterRecursionRule(localctx, 10, self.RULE_mp, _p) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 111 self.unary() self._ctx.stop = self._input.LT(-1) self.state = 118 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,2,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: if self._parseListeners is not None: self.triggerExitRuleEvent() _prevctx = localctx localctx = LaTeXParser.MpContext(self, _parentctx, _parentState) self.pushNewRecursionContext(localctx, _startState, self.RULE_mp) self.state = 113 if not self.precpred(self._ctx, 2): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 2)") self.state = 114 _la = self._input.LA(1) if not(((((_la - 16)) & ~0x3f) == 0 and ((1 << (_la - 16)) & ((1 << (LaTeXParser.MUL - 16)) | (1 << (LaTeXParser.DIV - 16)) | (1 << (LaTeXParser.CMD_TIMES - 16)) | (1 << (LaTeXParser.CMD_CDOT - 16)) | (1 << (LaTeXParser.CMD_DIV - 16)) | (1 << (LaTeXParser.COLON - 16)))) != 0)): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 115 self.mp(3) self.state = 120 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,2,self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.unrollRecursionContexts(_parentctx) return localctx class Mp_nofuncContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Mp_nofuncContext, self).__init__(parent, invokingState) self.parser = parser def unary_nofunc(self): return self.getTypedRuleContext(LaTeXParser.Unary_nofuncContext,0) def mp_nofunc(self, i=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.Mp_nofuncContext) else: return self.getTypedRuleContext(LaTeXParser.Mp_nofuncContext,i) def MUL(self): return self.getToken(LaTeXParser.MUL, 0) def CMD_TIMES(self): return self.getToken(LaTeXParser.CMD_TIMES, 0) def CMD_CDOT(self): return self.getToken(LaTeXParser.CMD_CDOT, 0) def DIV(self): return self.getToken(LaTeXParser.DIV, 0) def CMD_DIV(self): return self.getToken(LaTeXParser.CMD_DIV, 0) def COLON(self): return self.getToken(LaTeXParser.COLON, 0) def getRuleIndex(self): return LaTeXParser.RULE_mp_nofunc def mp_nofunc(self, _p=0): _parentctx = self._ctx _parentState = self.state localctx = LaTeXParser.Mp_nofuncContext(self, self._ctx, _parentState) _prevctx = localctx _startState = 12 self.enterRecursionRule(localctx, 12, self.RULE_mp_nofunc, _p) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 122 self.unary_nofunc() self._ctx.stop = self._input.LT(-1) self.state = 129 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,3,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: if self._parseListeners is not None: self.triggerExitRuleEvent() _prevctx = localctx localctx = LaTeXParser.Mp_nofuncContext(self, _parentctx, _parentState) self.pushNewRecursionContext(localctx, _startState, self.RULE_mp_nofunc) self.state = 124 if not self.precpred(self._ctx, 2): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 2)") self.state = 125 _la = self._input.LA(1) if not(((((_la - 16)) & ~0x3f) == 0 and ((1 << (_la - 16)) & ((1 << (LaTeXParser.MUL - 16)) | (1 << (LaTeXParser.DIV - 16)) | (1 << (LaTeXParser.CMD_TIMES - 16)) | (1 << (LaTeXParser.CMD_CDOT - 16)) | (1 << (LaTeXParser.CMD_DIV - 16)) | (1 << (LaTeXParser.COLON - 16)))) != 0)): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 126 self.mp_nofunc(3) self.state = 131 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,3,self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.unrollRecursionContexts(_parentctx) return localctx class UnaryContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.UnaryContext, self).__init__(parent, invokingState) self.parser = parser def unary(self): return self.getTypedRuleContext(LaTeXParser.UnaryContext,0) def ADD(self): return self.getToken(LaTeXParser.ADD, 0) def SUB(self): return self.getToken(LaTeXParser.SUB, 0) def postfix(self, i=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.PostfixContext) else: return self.getTypedRuleContext(LaTeXParser.PostfixContext,i) def getRuleIndex(self): return LaTeXParser.RULE_unary def unary(self): localctx = LaTeXParser.UnaryContext(self, self._ctx, self.state) self.enterRule(localctx, 14, self.RULE_unary) self._la = 0 # Token type try: self.state = 139 self._errHandler.sync(self) token = self._input.LA(1) if token in [LaTeXParser.ADD, LaTeXParser.SUB]: self.enterOuterAlt(localctx, 1) self.state = 132 _la = self._input.LA(1) if not(_la==LaTeXParser.ADD or _la==LaTeXParser.SUB): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 133 self.unary() pass elif token in [LaTeXParser.L_PAREN, LaTeXParser.L_BRACE, LaTeXParser.L_BRACE_LITERAL, LaTeXParser.L_BRACKET, LaTeXParser.BAR, LaTeXParser.L_BAR, LaTeXParser.L_ANGLE, LaTeXParser.FUNC_LIM, LaTeXParser.FUNC_INT, LaTeXParser.FUNC_SUM, LaTeXParser.FUNC_PROD, LaTeXParser.FUNC_EXP, LaTeXParser.FUNC_LOG, LaTeXParser.FUNC_LN, LaTeXParser.FUNC_SIN, LaTeXParser.FUNC_COS, LaTeXParser.FUNC_TAN, LaTeXParser.FUNC_CSC, LaTeXParser.FUNC_SEC, LaTeXParser.FUNC_COT, LaTeXParser.FUNC_ARCSIN, LaTeXParser.FUNC_ARCCOS, LaTeXParser.FUNC_ARCTAN, LaTeXParser.FUNC_ARCCSC, LaTeXParser.FUNC_ARCSEC, LaTeXParser.FUNC_ARCCOT, LaTeXParser.FUNC_SINH, LaTeXParser.FUNC_COSH, LaTeXParser.FUNC_TANH, LaTeXParser.FUNC_ARSINH, LaTeXParser.FUNC_ARCOSH, LaTeXParser.FUNC_ARTANH, LaTeXParser.L_FLOOR, LaTeXParser.L_CEIL, LaTeXParser.FUNC_SQRT, LaTeXParser.CMD_FRAC, LaTeXParser.CMD_BINOM, LaTeXParser.CMD_DBINOM, LaTeXParser.CMD_TBINOM, LaTeXParser.CMD_MATHIT, LaTeXParser.DIFFERENTIAL, LaTeXParser.LETTER, LaTeXParser.NUMBER, LaTeXParser.SYMBOL]: self.enterOuterAlt(localctx, 2) self.state = 135 self._errHandler.sync(self) _alt = 1 while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt == 1: self.state = 134 self.postfix() else: raise NoViableAltException(self) self.state = 137 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,4,self._ctx) pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Unary_nofuncContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Unary_nofuncContext, self).__init__(parent, invokingState) self.parser = parser def unary_nofunc(self): return self.getTypedRuleContext(LaTeXParser.Unary_nofuncContext,0) def ADD(self): return self.getToken(LaTeXParser.ADD, 0) def SUB(self): return self.getToken(LaTeXParser.SUB, 0) def postfix(self): return self.getTypedRuleContext(LaTeXParser.PostfixContext,0) def postfix_nofunc(self, i=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.Postfix_nofuncContext) else: return self.getTypedRuleContext(LaTeXParser.Postfix_nofuncContext,i) def getRuleIndex(self): return LaTeXParser.RULE_unary_nofunc def unary_nofunc(self): localctx = LaTeXParser.Unary_nofuncContext(self, self._ctx, self.state) self.enterRule(localctx, 16, self.RULE_unary_nofunc) self._la = 0 # Token type try: self.state = 150 self._errHandler.sync(self) token = self._input.LA(1) if token in [LaTeXParser.ADD, LaTeXParser.SUB]: self.enterOuterAlt(localctx, 1) self.state = 141 _la = self._input.LA(1) if not(_la==LaTeXParser.ADD or _la==LaTeXParser.SUB): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 142 self.unary_nofunc() pass elif token in [LaTeXParser.L_PAREN, LaTeXParser.L_BRACE, LaTeXParser.L_BRACE_LITERAL, LaTeXParser.L_BRACKET, LaTeXParser.BAR, LaTeXParser.L_BAR, LaTeXParser.L_ANGLE, LaTeXParser.FUNC_LIM, LaTeXParser.FUNC_INT, LaTeXParser.FUNC_SUM, LaTeXParser.FUNC_PROD, LaTeXParser.FUNC_EXP, LaTeXParser.FUNC_LOG, LaTeXParser.FUNC_LN, LaTeXParser.FUNC_SIN, LaTeXParser.FUNC_COS, LaTeXParser.FUNC_TAN, LaTeXParser.FUNC_CSC, LaTeXParser.FUNC_SEC, LaTeXParser.FUNC_COT, LaTeXParser.FUNC_ARCSIN, LaTeXParser.FUNC_ARCCOS, LaTeXParser.FUNC_ARCTAN, LaTeXParser.FUNC_ARCCSC, LaTeXParser.FUNC_ARCSEC, LaTeXParser.FUNC_ARCCOT, LaTeXParser.FUNC_SINH, LaTeXParser.FUNC_COSH, LaTeXParser.FUNC_TANH, LaTeXParser.FUNC_ARSINH, LaTeXParser.FUNC_ARCOSH, LaTeXParser.FUNC_ARTANH, LaTeXParser.L_FLOOR, LaTeXParser.L_CEIL, LaTeXParser.FUNC_SQRT, LaTeXParser.CMD_FRAC, LaTeXParser.CMD_BINOM, LaTeXParser.CMD_DBINOM, LaTeXParser.CMD_TBINOM, LaTeXParser.CMD_MATHIT, LaTeXParser.DIFFERENTIAL, LaTeXParser.LETTER, LaTeXParser.NUMBER, LaTeXParser.SYMBOL]: self.enterOuterAlt(localctx, 2) self.state = 143 self.postfix() self.state = 147 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,6,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: self.state = 144 self.postfix_nofunc() self.state = 149 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,6,self._ctx) pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class PostfixContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.PostfixContext, self).__init__(parent, invokingState) self.parser = parser def exp(self): return self.getTypedRuleContext(LaTeXParser.ExpContext,0) def postfix_op(self, i=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.Postfix_opContext) else: return self.getTypedRuleContext(LaTeXParser.Postfix_opContext,i) def getRuleIndex(self): return LaTeXParser.RULE_postfix def postfix(self): localctx = LaTeXParser.PostfixContext(self, self._ctx, self.state) self.enterRule(localctx, 18, self.RULE_postfix) try: self.enterOuterAlt(localctx, 1) self.state = 152 self.exp(0) self.state = 156 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,8,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: self.state = 153 self.postfix_op() self.state = 158 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,8,self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Postfix_nofuncContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Postfix_nofuncContext, self).__init__(parent, invokingState) self.parser = parser def exp_nofunc(self): return self.getTypedRuleContext(LaTeXParser.Exp_nofuncContext,0) def postfix_op(self, i=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.Postfix_opContext) else: return self.getTypedRuleContext(LaTeXParser.Postfix_opContext,i) def getRuleIndex(self): return LaTeXParser.RULE_postfix_nofunc def postfix_nofunc(self): localctx = LaTeXParser.Postfix_nofuncContext(self, self._ctx, self.state) self.enterRule(localctx, 20, self.RULE_postfix_nofunc) try: self.enterOuterAlt(localctx, 1) self.state = 159 self.exp_nofunc(0) self.state = 163 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,9,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: self.state = 160 self.postfix_op() self.state = 165 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,9,self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Postfix_opContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Postfix_opContext, self).__init__(parent, invokingState) self.parser = parser def BANG(self): return self.getToken(LaTeXParser.BANG, 0) def eval_at(self): return self.getTypedRuleContext(LaTeXParser.Eval_atContext,0) def getRuleIndex(self): return LaTeXParser.RULE_postfix_op def postfix_op(self): localctx = LaTeXParser.Postfix_opContext(self, self._ctx, self.state) self.enterRule(localctx, 22, self.RULE_postfix_op) try: self.state = 168 self._errHandler.sync(self) token = self._input.LA(1) if token in [LaTeXParser.BANG]: self.enterOuterAlt(localctx, 1) self.state = 166 self.match(LaTeXParser.BANG) pass elif token in [LaTeXParser.BAR]: self.enterOuterAlt(localctx, 2) self.state = 167 self.eval_at() pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Eval_atContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Eval_atContext, self).__init__(parent, invokingState) self.parser = parser def BAR(self): return self.getToken(LaTeXParser.BAR, 0) def eval_at_sup(self): return self.getTypedRuleContext(LaTeXParser.Eval_at_supContext,0) def eval_at_sub(self): return self.getTypedRuleContext(LaTeXParser.Eval_at_subContext,0) def getRuleIndex(self): return LaTeXParser.RULE_eval_at def eval_at(self): localctx = LaTeXParser.Eval_atContext(self, self._ctx, self.state) self.enterRule(localctx, 24, self.RULE_eval_at) try: self.enterOuterAlt(localctx, 1) self.state = 170 self.match(LaTeXParser.BAR) self.state = 176 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,11,self._ctx) if la_ == 1: self.state = 171 self.eval_at_sup() pass elif la_ == 2: self.state = 172 self.eval_at_sub() pass elif la_ == 3: self.state = 173 self.eval_at_sup() self.state = 174 self.eval_at_sub() pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Eval_at_subContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Eval_at_subContext, self).__init__(parent, invokingState) self.parser = parser def UNDERSCORE(self): return self.getToken(LaTeXParser.UNDERSCORE, 0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def equality(self): return self.getTypedRuleContext(LaTeXParser.EqualityContext,0) def getRuleIndex(self): return LaTeXParser.RULE_eval_at_sub def eval_at_sub(self): localctx = LaTeXParser.Eval_at_subContext(self, self._ctx, self.state) self.enterRule(localctx, 26, self.RULE_eval_at_sub) try: self.enterOuterAlt(localctx, 1) self.state = 178 self.match(LaTeXParser.UNDERSCORE) self.state = 179 self.match(LaTeXParser.L_BRACE) self.state = 182 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,12,self._ctx) if la_ == 1: self.state = 180 self.expr() pass elif la_ == 2: self.state = 181 self.equality() pass self.state = 184 self.match(LaTeXParser.R_BRACE) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Eval_at_supContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Eval_at_supContext, self).__init__(parent, invokingState) self.parser = parser def CARET(self): return self.getToken(LaTeXParser.CARET, 0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def equality(self): return self.getTypedRuleContext(LaTeXParser.EqualityContext,0) def getRuleIndex(self): return LaTeXParser.RULE_eval_at_sup def eval_at_sup(self): localctx = LaTeXParser.Eval_at_supContext(self, self._ctx, self.state) self.enterRule(localctx, 28, self.RULE_eval_at_sup) try: self.enterOuterAlt(localctx, 1) self.state = 186 self.match(LaTeXParser.CARET) self.state = 187 self.match(LaTeXParser.L_BRACE) self.state = 190 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,13,self._ctx) if la_ == 1: self.state = 188 self.expr() pass elif la_ == 2: self.state = 189 self.equality() pass self.state = 192 self.match(LaTeXParser.R_BRACE) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ExpContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.ExpContext, self).__init__(parent, invokingState) self.parser = parser def comp(self): return self.getTypedRuleContext(LaTeXParser.CompContext,0) def exp(self): return self.getTypedRuleContext(LaTeXParser.ExpContext,0) def CARET(self): return self.getToken(LaTeXParser.CARET, 0) def atom(self): return self.getTypedRuleContext(LaTeXParser.AtomContext,0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def subexpr(self): return self.getTypedRuleContext(LaTeXParser.SubexprContext,0) def getRuleIndex(self): return LaTeXParser.RULE_exp def exp(self, _p=0): _parentctx = self._ctx _parentState = self.state localctx = LaTeXParser.ExpContext(self, self._ctx, _parentState) _prevctx = localctx _startState = 30 self.enterRecursionRule(localctx, 30, self.RULE_exp, _p) try: self.enterOuterAlt(localctx, 1) self.state = 195 self.comp() self._ctx.stop = self._input.LT(-1) self.state = 211 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,16,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: if self._parseListeners is not None: self.triggerExitRuleEvent() _prevctx = localctx localctx = LaTeXParser.ExpContext(self, _parentctx, _parentState) self.pushNewRecursionContext(localctx, _startState, self.RULE_exp) self.state = 197 if not self.precpred(self._ctx, 2): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 2)") self.state = 198 self.match(LaTeXParser.CARET) self.state = 204 self._errHandler.sync(self) token = self._input.LA(1) if token in [LaTeXParser.BAR, LaTeXParser.L_BAR, LaTeXParser.L_ANGLE, LaTeXParser.CMD_MATHIT, LaTeXParser.DIFFERENTIAL, LaTeXParser.LETTER, LaTeXParser.NUMBER, LaTeXParser.SYMBOL]: self.state = 199 self.atom() pass elif token in [LaTeXParser.L_BRACE]: self.state = 200 self.match(LaTeXParser.L_BRACE) self.state = 201 self.expr() self.state = 202 self.match(LaTeXParser.R_BRACE) pass else: raise NoViableAltException(self) self.state = 207 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,15,self._ctx) if la_ == 1: self.state = 206 self.subexpr() self.state = 213 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,16,self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.unrollRecursionContexts(_parentctx) return localctx class Exp_nofuncContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Exp_nofuncContext, self).__init__(parent, invokingState) self.parser = parser def comp_nofunc(self): return self.getTypedRuleContext(LaTeXParser.Comp_nofuncContext,0) def exp_nofunc(self): return self.getTypedRuleContext(LaTeXParser.Exp_nofuncContext,0) def CARET(self): return self.getToken(LaTeXParser.CARET, 0) def atom(self): return self.getTypedRuleContext(LaTeXParser.AtomContext,0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def subexpr(self): return self.getTypedRuleContext(LaTeXParser.SubexprContext,0) def getRuleIndex(self): return LaTeXParser.RULE_exp_nofunc def exp_nofunc(self, _p=0): _parentctx = self._ctx _parentState = self.state localctx = LaTeXParser.Exp_nofuncContext(self, self._ctx, _parentState) _prevctx = localctx _startState = 32 self.enterRecursionRule(localctx, 32, self.RULE_exp_nofunc, _p) try: self.enterOuterAlt(localctx, 1) self.state = 215 self.comp_nofunc() self._ctx.stop = self._input.LT(-1) self.state = 231 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,19,self._ctx) while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER: if _alt==1: if self._parseListeners is not None: self.triggerExitRuleEvent() _prevctx = localctx localctx = LaTeXParser.Exp_nofuncContext(self, _parentctx, _parentState) self.pushNewRecursionContext(localctx, _startState, self.RULE_exp_nofunc) self.state = 217 if not self.precpred(self._ctx, 2): from antlr4.error.Errors import FailedPredicateException raise FailedPredicateException(self, "self.precpred(self._ctx, 2)") self.state = 218 self.match(LaTeXParser.CARET) self.state = 224 self._errHandler.sync(self) token = self._input.LA(1) if token in [LaTeXParser.BAR, LaTeXParser.L_BAR, LaTeXParser.L_ANGLE, LaTeXParser.CMD_MATHIT, LaTeXParser.DIFFERENTIAL, LaTeXParser.LETTER, LaTeXParser.NUMBER, LaTeXParser.SYMBOL]: self.state = 219 self.atom() pass elif token in [LaTeXParser.L_BRACE]: self.state = 220 self.match(LaTeXParser.L_BRACE) self.state = 221 self.expr() self.state = 222 self.match(LaTeXParser.R_BRACE) pass else: raise NoViableAltException(self) self.state = 227 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,18,self._ctx) if la_ == 1: self.state = 226 self.subexpr() self.state = 233 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input,19,self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.unrollRecursionContexts(_parentctx) return localctx class CompContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.CompContext, self).__init__(parent, invokingState) self.parser = parser def group(self): return self.getTypedRuleContext(LaTeXParser.GroupContext,0) def abs_group(self): return self.getTypedRuleContext(LaTeXParser.Abs_groupContext,0) def func(self): return self.getTypedRuleContext(LaTeXParser.FuncContext,0) def atom(self): return self.getTypedRuleContext(LaTeXParser.AtomContext,0) def frac(self): return self.getTypedRuleContext(LaTeXParser.FracContext,0) def binom(self): return self.getTypedRuleContext(LaTeXParser.BinomContext,0) def floor(self): return self.getTypedRuleContext(LaTeXParser.FloorContext,0) def ceil(self): return self.getTypedRuleContext(LaTeXParser.CeilContext,0) def getRuleIndex(self): return LaTeXParser.RULE_comp def comp(self): localctx = LaTeXParser.CompContext(self, self._ctx, self.state) self.enterRule(localctx, 34, self.RULE_comp) try: self.state = 242 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,20,self._ctx) if la_ == 1: self.enterOuterAlt(localctx, 1) self.state = 234 self.group() pass elif la_ == 2: self.enterOuterAlt(localctx, 2) self.state = 235 self.abs_group() pass elif la_ == 3: self.enterOuterAlt(localctx, 3) self.state = 236 self.func() pass elif la_ == 4: self.enterOuterAlt(localctx, 4) self.state = 237 self.atom() pass elif la_ == 5: self.enterOuterAlt(localctx, 5) self.state = 238 self.frac() pass elif la_ == 6: self.enterOuterAlt(localctx, 6) self.state = 239 self.binom() pass elif la_ == 7: self.enterOuterAlt(localctx, 7) self.state = 240 self.floor() pass elif la_ == 8: self.enterOuterAlt(localctx, 8) self.state = 241 self.ceil() pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Comp_nofuncContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Comp_nofuncContext, self).__init__(parent, invokingState) self.parser = parser def group(self): return self.getTypedRuleContext(LaTeXParser.GroupContext,0) def abs_group(self): return self.getTypedRuleContext(LaTeXParser.Abs_groupContext,0) def atom(self): return self.getTypedRuleContext(LaTeXParser.AtomContext,0) def frac(self): return self.getTypedRuleContext(LaTeXParser.FracContext,0) def binom(self): return self.getTypedRuleContext(LaTeXParser.BinomContext,0) def floor(self): return self.getTypedRuleContext(LaTeXParser.FloorContext,0) def ceil(self): return self.getTypedRuleContext(LaTeXParser.CeilContext,0) def getRuleIndex(self): return LaTeXParser.RULE_comp_nofunc def comp_nofunc(self): localctx = LaTeXParser.Comp_nofuncContext(self, self._ctx, self.state) self.enterRule(localctx, 36, self.RULE_comp_nofunc) try: self.state = 251 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,21,self._ctx) if la_ == 1: self.enterOuterAlt(localctx, 1) self.state = 244 self.group() pass elif la_ == 2: self.enterOuterAlt(localctx, 2) self.state = 245 self.abs_group() pass elif la_ == 3: self.enterOuterAlt(localctx, 3) self.state = 246 self.atom() pass elif la_ == 4: self.enterOuterAlt(localctx, 4) self.state = 247 self.frac() pass elif la_ == 5: self.enterOuterAlt(localctx, 5) self.state = 248 self.binom() pass elif la_ == 6: self.enterOuterAlt(localctx, 6) self.state = 249 self.floor() pass elif la_ == 7: self.enterOuterAlt(localctx, 7) self.state = 250 self.ceil() pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class GroupContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.GroupContext, self).__init__(parent, invokingState) self.parser = parser def L_PAREN(self): return self.getToken(LaTeXParser.L_PAREN, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def R_PAREN(self): return self.getToken(LaTeXParser.R_PAREN, 0) def L_BRACKET(self): return self.getToken(LaTeXParser.L_BRACKET, 0) def R_BRACKET(self): return self.getToken(LaTeXParser.R_BRACKET, 0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def L_BRACE_LITERAL(self): return self.getToken(LaTeXParser.L_BRACE_LITERAL, 0) def R_BRACE_LITERAL(self): return self.getToken(LaTeXParser.R_BRACE_LITERAL, 0) def getRuleIndex(self): return LaTeXParser.RULE_group def group(self): localctx = LaTeXParser.GroupContext(self, self._ctx, self.state) self.enterRule(localctx, 38, self.RULE_group) try: self.state = 269 self._errHandler.sync(self) token = self._input.LA(1) if token in [LaTeXParser.L_PAREN]: self.enterOuterAlt(localctx, 1) self.state = 253 self.match(LaTeXParser.L_PAREN) self.state = 254 self.expr() self.state = 255 self.match(LaTeXParser.R_PAREN) pass elif token in [LaTeXParser.L_BRACKET]: self.enterOuterAlt(localctx, 2) self.state = 257 self.match(LaTeXParser.L_BRACKET) self.state = 258 self.expr() self.state = 259 self.match(LaTeXParser.R_BRACKET) pass elif token in [LaTeXParser.L_BRACE]: self.enterOuterAlt(localctx, 3) self.state = 261 self.match(LaTeXParser.L_BRACE) self.state = 262 self.expr() self.state = 263 self.match(LaTeXParser.R_BRACE) pass elif token in [LaTeXParser.L_BRACE_LITERAL]: self.enterOuterAlt(localctx, 4) self.state = 265 self.match(LaTeXParser.L_BRACE_LITERAL) self.state = 266 self.expr() self.state = 267 self.match(LaTeXParser.R_BRACE_LITERAL) pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Abs_groupContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Abs_groupContext, self).__init__(parent, invokingState) self.parser = parser def BAR(self, i=None): if i is None: return self.getTokens(LaTeXParser.BAR) else: return self.getToken(LaTeXParser.BAR, i) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def getRuleIndex(self): return LaTeXParser.RULE_abs_group def abs_group(self): localctx = LaTeXParser.Abs_groupContext(self, self._ctx, self.state) self.enterRule(localctx, 40, self.RULE_abs_group) try: self.enterOuterAlt(localctx, 1) self.state = 271 self.match(LaTeXParser.BAR) self.state = 272 self.expr() self.state = 273 self.match(LaTeXParser.BAR) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class AtomContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.AtomContext, self).__init__(parent, invokingState) self.parser = parser def LETTER(self): return self.getToken(LaTeXParser.LETTER, 0) def SYMBOL(self): return self.getToken(LaTeXParser.SYMBOL, 0) def subexpr(self): return self.getTypedRuleContext(LaTeXParser.SubexprContext,0) def NUMBER(self): return self.getToken(LaTeXParser.NUMBER, 0) def DIFFERENTIAL(self): return self.getToken(LaTeXParser.DIFFERENTIAL, 0) def mathit(self): return self.getTypedRuleContext(LaTeXParser.MathitContext,0) def bra(self): return self.getTypedRuleContext(LaTeXParser.BraContext,0) def ket(self): return self.getTypedRuleContext(LaTeXParser.KetContext,0) def getRuleIndex(self): return LaTeXParser.RULE_atom def atom(self): localctx = LaTeXParser.AtomContext(self, self._ctx, self.state) self.enterRule(localctx, 42, self.RULE_atom) self._la = 0 # Token type try: self.state = 284 self._errHandler.sync(self) token = self._input.LA(1) if token in [LaTeXParser.LETTER, LaTeXParser.SYMBOL]: self.enterOuterAlt(localctx, 1) self.state = 275 _la = self._input.LA(1) if not(_la==LaTeXParser.LETTER or _la==LaTeXParser.SYMBOL): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 277 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,23,self._ctx) if la_ == 1: self.state = 276 self.subexpr() pass elif token in [LaTeXParser.NUMBER]: self.enterOuterAlt(localctx, 2) self.state = 279 self.match(LaTeXParser.NUMBER) pass elif token in [LaTeXParser.DIFFERENTIAL]: self.enterOuterAlt(localctx, 3) self.state = 280 self.match(LaTeXParser.DIFFERENTIAL) pass elif token in [LaTeXParser.CMD_MATHIT]: self.enterOuterAlt(localctx, 4) self.state = 281 self.mathit() pass elif token in [LaTeXParser.L_ANGLE]: self.enterOuterAlt(localctx, 5) self.state = 282 self.bra() pass elif token in [LaTeXParser.BAR, LaTeXParser.L_BAR]: self.enterOuterAlt(localctx, 6) self.state = 283 self.ket() pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class BraContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.BraContext, self).__init__(parent, invokingState) self.parser = parser def L_ANGLE(self): return self.getToken(LaTeXParser.L_ANGLE, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def R_BAR(self): return self.getToken(LaTeXParser.R_BAR, 0) def BAR(self): return self.getToken(LaTeXParser.BAR, 0) def getRuleIndex(self): return LaTeXParser.RULE_bra def bra(self): localctx = LaTeXParser.BraContext(self, self._ctx, self.state) self.enterRule(localctx, 44, self.RULE_bra) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 286 self.match(LaTeXParser.L_ANGLE) self.state = 287 self.expr() self.state = 288 _la = self._input.LA(1) if not(_la==LaTeXParser.BAR or _la==LaTeXParser.R_BAR): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class KetContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.KetContext, self).__init__(parent, invokingState) self.parser = parser def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def R_ANGLE(self): return self.getToken(LaTeXParser.R_ANGLE, 0) def L_BAR(self): return self.getToken(LaTeXParser.L_BAR, 0) def BAR(self): return self.getToken(LaTeXParser.BAR, 0) def getRuleIndex(self): return LaTeXParser.RULE_ket def ket(self): localctx = LaTeXParser.KetContext(self, self._ctx, self.state) self.enterRule(localctx, 46, self.RULE_ket) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 290 _la = self._input.LA(1) if not(_la==LaTeXParser.BAR or _la==LaTeXParser.L_BAR): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 291 self.expr() self.state = 292 self.match(LaTeXParser.R_ANGLE) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class MathitContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.MathitContext, self).__init__(parent, invokingState) self.parser = parser def CMD_MATHIT(self): return self.getToken(LaTeXParser.CMD_MATHIT, 0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def mathit_text(self): return self.getTypedRuleContext(LaTeXParser.Mathit_textContext,0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def getRuleIndex(self): return LaTeXParser.RULE_mathit def mathit(self): localctx = LaTeXParser.MathitContext(self, self._ctx, self.state) self.enterRule(localctx, 48, self.RULE_mathit) try: self.enterOuterAlt(localctx, 1) self.state = 294 self.match(LaTeXParser.CMD_MATHIT) self.state = 295 self.match(LaTeXParser.L_BRACE) self.state = 296 self.mathit_text() self.state = 297 self.match(LaTeXParser.R_BRACE) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Mathit_textContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Mathit_textContext, self).__init__(parent, invokingState) self.parser = parser def LETTER(self, i=None): if i is None: return self.getTokens(LaTeXParser.LETTER) else: return self.getToken(LaTeXParser.LETTER, i) def getRuleIndex(self): return LaTeXParser.RULE_mathit_text def mathit_text(self): localctx = LaTeXParser.Mathit_textContext(self, self._ctx, self.state) self.enterRule(localctx, 50, self.RULE_mathit_text) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 302 self._errHandler.sync(self) _la = self._input.LA(1) while _la==LaTeXParser.LETTER: self.state = 299 self.match(LaTeXParser.LETTER) self.state = 304 self._errHandler.sync(self) _la = self._input.LA(1) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class FracContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.FracContext, self).__init__(parent, invokingState) self.parser = parser self.upper = None # ExprContext self.lower = None # ExprContext def CMD_FRAC(self): return self.getToken(LaTeXParser.CMD_FRAC, 0) def L_BRACE(self, i=None): if i is None: return self.getTokens(LaTeXParser.L_BRACE) else: return self.getToken(LaTeXParser.L_BRACE, i) def R_BRACE(self, i=None): if i is None: return self.getTokens(LaTeXParser.R_BRACE) else: return self.getToken(LaTeXParser.R_BRACE, i) def expr(self, i=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.ExprContext) else: return self.getTypedRuleContext(LaTeXParser.ExprContext,i) def getRuleIndex(self): return LaTeXParser.RULE_frac def frac(self): localctx = LaTeXParser.FracContext(self, self._ctx, self.state) self.enterRule(localctx, 52, self.RULE_frac) try: self.enterOuterAlt(localctx, 1) self.state = 305 self.match(LaTeXParser.CMD_FRAC) self.state = 306 self.match(LaTeXParser.L_BRACE) self.state = 307 localctx.upper = self.expr() self.state = 308 self.match(LaTeXParser.R_BRACE) self.state = 309 self.match(LaTeXParser.L_BRACE) self.state = 310 localctx.lower = self.expr() self.state = 311 self.match(LaTeXParser.R_BRACE) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class BinomContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.BinomContext, self).__init__(parent, invokingState) self.parser = parser self.n = None # ExprContext self.k = None # ExprContext def L_BRACE(self, i=None): if i is None: return self.getTokens(LaTeXParser.L_BRACE) else: return self.getToken(LaTeXParser.L_BRACE, i) def R_BRACE(self, i=None): if i is None: return self.getTokens(LaTeXParser.R_BRACE) else: return self.getToken(LaTeXParser.R_BRACE, i) def CMD_BINOM(self): return self.getToken(LaTeXParser.CMD_BINOM, 0) def CMD_DBINOM(self): return self.getToken(LaTeXParser.CMD_DBINOM, 0) def CMD_TBINOM(self): return self.getToken(LaTeXParser.CMD_TBINOM, 0) def expr(self, i=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.ExprContext) else: return self.getTypedRuleContext(LaTeXParser.ExprContext,i) def getRuleIndex(self): return LaTeXParser.RULE_binom def binom(self): localctx = LaTeXParser.BinomContext(self, self._ctx, self.state) self.enterRule(localctx, 54, self.RULE_binom) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 313 _la = self._input.LA(1) if not(((((_la - 66)) & ~0x3f) == 0 and ((1 << (_la - 66)) & ((1 << (LaTeXParser.CMD_BINOM - 66)) | (1 << (LaTeXParser.CMD_DBINOM - 66)) | (1 << (LaTeXParser.CMD_TBINOM - 66)))) != 0)): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 314 self.match(LaTeXParser.L_BRACE) self.state = 315 localctx.n = self.expr() self.state = 316 self.match(LaTeXParser.R_BRACE) self.state = 317 self.match(LaTeXParser.L_BRACE) self.state = 318 localctx.k = self.expr() self.state = 319 self.match(LaTeXParser.R_BRACE) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class FloorContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.FloorContext, self).__init__(parent, invokingState) self.parser = parser self.val = None # ExprContext def L_FLOOR(self): return self.getToken(LaTeXParser.L_FLOOR, 0) def R_FLOOR(self): return self.getToken(LaTeXParser.R_FLOOR, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def getRuleIndex(self): return LaTeXParser.RULE_floor def floor(self): localctx = LaTeXParser.FloorContext(self, self._ctx, self.state) self.enterRule(localctx, 56, self.RULE_floor) try: self.enterOuterAlt(localctx, 1) self.state = 321 self.match(LaTeXParser.L_FLOOR) self.state = 322 localctx.val = self.expr() self.state = 323 self.match(LaTeXParser.R_FLOOR) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class CeilContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.CeilContext, self).__init__(parent, invokingState) self.parser = parser self.val = None # ExprContext def L_CEIL(self): return self.getToken(LaTeXParser.L_CEIL, 0) def R_CEIL(self): return self.getToken(LaTeXParser.R_CEIL, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def getRuleIndex(self): return LaTeXParser.RULE_ceil def ceil(self): localctx = LaTeXParser.CeilContext(self, self._ctx, self.state) self.enterRule(localctx, 58, self.RULE_ceil) try: self.enterOuterAlt(localctx, 1) self.state = 325 self.match(LaTeXParser.L_CEIL) self.state = 326 localctx.val = self.expr() self.state = 327 self.match(LaTeXParser.R_CEIL) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Func_normalContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Func_normalContext, self).__init__(parent, invokingState) self.parser = parser def FUNC_EXP(self): return self.getToken(LaTeXParser.FUNC_EXP, 0) def FUNC_LOG(self): return self.getToken(LaTeXParser.FUNC_LOG, 0) def FUNC_LN(self): return self.getToken(LaTeXParser.FUNC_LN, 0) def FUNC_SIN(self): return self.getToken(LaTeXParser.FUNC_SIN, 0) def FUNC_COS(self): return self.getToken(LaTeXParser.FUNC_COS, 0) def FUNC_TAN(self): return self.getToken(LaTeXParser.FUNC_TAN, 0) def FUNC_CSC(self): return self.getToken(LaTeXParser.FUNC_CSC, 0) def FUNC_SEC(self): return self.getToken(LaTeXParser.FUNC_SEC, 0) def FUNC_COT(self): return self.getToken(LaTeXParser.FUNC_COT, 0) def FUNC_ARCSIN(self): return self.getToken(LaTeXParser.FUNC_ARCSIN, 0) def FUNC_ARCCOS(self): return self.getToken(LaTeXParser.FUNC_ARCCOS, 0) def FUNC_ARCTAN(self): return self.getToken(LaTeXParser.FUNC_ARCTAN, 0) def FUNC_ARCCSC(self): return self.getToken(LaTeXParser.FUNC_ARCCSC, 0) def FUNC_ARCSEC(self): return self.getToken(LaTeXParser.FUNC_ARCSEC, 0) def FUNC_ARCCOT(self): return self.getToken(LaTeXParser.FUNC_ARCCOT, 0) def FUNC_SINH(self): return self.getToken(LaTeXParser.FUNC_SINH, 0) def FUNC_COSH(self): return self.getToken(LaTeXParser.FUNC_COSH, 0) def FUNC_TANH(self): return self.getToken(LaTeXParser.FUNC_TANH, 0) def FUNC_ARSINH(self): return self.getToken(LaTeXParser.FUNC_ARSINH, 0) def FUNC_ARCOSH(self): return self.getToken(LaTeXParser.FUNC_ARCOSH, 0) def FUNC_ARTANH(self): return self.getToken(LaTeXParser.FUNC_ARTANH, 0) def getRuleIndex(self): return LaTeXParser.RULE_func_normal def func_normal(self): localctx = LaTeXParser.Func_normalContext(self, self._ctx, self.state) self.enterRule(localctx, 60, self.RULE_func_normal) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 329 _la = self._input.LA(1) if not((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << LaTeXParser.FUNC_EXP) | (1 << LaTeXParser.FUNC_LOG) | (1 << LaTeXParser.FUNC_LN) | (1 << LaTeXParser.FUNC_SIN) | (1 << LaTeXParser.FUNC_COS) | (1 << LaTeXParser.FUNC_TAN) | (1 << LaTeXParser.FUNC_CSC) | (1 << LaTeXParser.FUNC_SEC) | (1 << LaTeXParser.FUNC_COT) | (1 << LaTeXParser.FUNC_ARCSIN) | (1 << LaTeXParser.FUNC_ARCCOS) | (1 << LaTeXParser.FUNC_ARCTAN) | (1 << LaTeXParser.FUNC_ARCCSC) | (1 << LaTeXParser.FUNC_ARCSEC) | (1 << LaTeXParser.FUNC_ARCCOT) | (1 << LaTeXParser.FUNC_SINH) | (1 << LaTeXParser.FUNC_COSH) | (1 << LaTeXParser.FUNC_TANH) | (1 << LaTeXParser.FUNC_ARSINH) | (1 << LaTeXParser.FUNC_ARCOSH) | (1 << LaTeXParser.FUNC_ARTANH))) != 0)): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class FuncContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.FuncContext, self).__init__(parent, invokingState) self.parser = parser self.root = None # ExprContext self.base = None # ExprContext def func_normal(self): return self.getTypedRuleContext(LaTeXParser.Func_normalContext,0) def L_PAREN(self): return self.getToken(LaTeXParser.L_PAREN, 0) def func_arg(self): return self.getTypedRuleContext(LaTeXParser.Func_argContext,0) def R_PAREN(self): return self.getToken(LaTeXParser.R_PAREN, 0) def func_arg_noparens(self): return self.getTypedRuleContext(LaTeXParser.Func_arg_noparensContext,0) def subexpr(self): return self.getTypedRuleContext(LaTeXParser.SubexprContext,0) def supexpr(self): return self.getTypedRuleContext(LaTeXParser.SupexprContext,0) def args(self): return self.getTypedRuleContext(LaTeXParser.ArgsContext,0) def LETTER(self): return self.getToken(LaTeXParser.LETTER, 0) def SYMBOL(self): return self.getToken(LaTeXParser.SYMBOL, 0) def FUNC_INT(self): return self.getToken(LaTeXParser.FUNC_INT, 0) def DIFFERENTIAL(self): return self.getToken(LaTeXParser.DIFFERENTIAL, 0) def frac(self): return self.getTypedRuleContext(LaTeXParser.FracContext,0) def additive(self): return self.getTypedRuleContext(LaTeXParser.AdditiveContext,0) def FUNC_SQRT(self): return self.getToken(LaTeXParser.FUNC_SQRT, 0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def expr(self, i=None): if i is None: return self.getTypedRuleContexts(LaTeXParser.ExprContext) else: return self.getTypedRuleContext(LaTeXParser.ExprContext,i) def L_BRACKET(self): return self.getToken(LaTeXParser.L_BRACKET, 0) def R_BRACKET(self): return self.getToken(LaTeXParser.R_BRACKET, 0) def mp(self): return self.getTypedRuleContext(LaTeXParser.MpContext,0) def FUNC_SUM(self): return self.getToken(LaTeXParser.FUNC_SUM, 0) def FUNC_PROD(self): return self.getToken(LaTeXParser.FUNC_PROD, 0) def subeq(self): return self.getTypedRuleContext(LaTeXParser.SubeqContext,0) def FUNC_LIM(self): return self.getToken(LaTeXParser.FUNC_LIM, 0) def limit_sub(self): return self.getTypedRuleContext(LaTeXParser.Limit_subContext,0) def getRuleIndex(self): return LaTeXParser.RULE_func def func(self): localctx = LaTeXParser.FuncContext(self, self._ctx, self.state) self.enterRule(localctx, 62, self.RULE_func) self._la = 0 # Token type try: self.state = 404 self._errHandler.sync(self) token = self._input.LA(1) if token in [LaTeXParser.FUNC_EXP, LaTeXParser.FUNC_LOG, LaTeXParser.FUNC_LN, LaTeXParser.FUNC_SIN, LaTeXParser.FUNC_COS, LaTeXParser.FUNC_TAN, LaTeXParser.FUNC_CSC, LaTeXParser.FUNC_SEC, LaTeXParser.FUNC_COT, LaTeXParser.FUNC_ARCSIN, LaTeXParser.FUNC_ARCCOS, LaTeXParser.FUNC_ARCTAN, LaTeXParser.FUNC_ARCCSC, LaTeXParser.FUNC_ARCSEC, LaTeXParser.FUNC_ARCCOT, LaTeXParser.FUNC_SINH, LaTeXParser.FUNC_COSH, LaTeXParser.FUNC_TANH, LaTeXParser.FUNC_ARSINH, LaTeXParser.FUNC_ARCOSH, LaTeXParser.FUNC_ARTANH]: self.enterOuterAlt(localctx, 1) self.state = 331 self.func_normal() self.state = 344 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,30,self._ctx) if la_ == 1: self.state = 333 self._errHandler.sync(self) _la = self._input.LA(1) if _la==LaTeXParser.UNDERSCORE: self.state = 332 self.subexpr() self.state = 336 self._errHandler.sync(self) _la = self._input.LA(1) if _la==LaTeXParser.CARET: self.state = 335 self.supexpr() pass elif la_ == 2: self.state = 339 self._errHandler.sync(self) _la = self._input.LA(1) if _la==LaTeXParser.CARET: self.state = 338 self.supexpr() self.state = 342 self._errHandler.sync(self) _la = self._input.LA(1) if _la==LaTeXParser.UNDERSCORE: self.state = 341 self.subexpr() pass self.state = 351 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,31,self._ctx) if la_ == 1: self.state = 346 self.match(LaTeXParser.L_PAREN) self.state = 347 self.func_arg() self.state = 348 self.match(LaTeXParser.R_PAREN) pass elif la_ == 2: self.state = 350 self.func_arg_noparens() pass pass elif token in [LaTeXParser.LETTER, LaTeXParser.SYMBOL]: self.enterOuterAlt(localctx, 2) self.state = 353 _la = self._input.LA(1) if not(_la==LaTeXParser.LETTER or _la==LaTeXParser.SYMBOL): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 355 self._errHandler.sync(self) _la = self._input.LA(1) if _la==LaTeXParser.UNDERSCORE: self.state = 354 self.subexpr() self.state = 357 self.match(LaTeXParser.L_PAREN) self.state = 358 self.args() self.state = 359 self.match(LaTeXParser.R_PAREN) pass elif token in [LaTeXParser.FUNC_INT]: self.enterOuterAlt(localctx, 3) self.state = 361 self.match(LaTeXParser.FUNC_INT) self.state = 368 self._errHandler.sync(self) token = self._input.LA(1) if token in [LaTeXParser.UNDERSCORE]: self.state = 362 self.subexpr() self.state = 363 self.supexpr() pass elif token in [LaTeXParser.CARET]: self.state = 365 self.supexpr() self.state = 366 self.subexpr() pass elif token in [LaTeXParser.ADD, LaTeXParser.SUB, LaTeXParser.L_PAREN, LaTeXParser.L_BRACE, LaTeXParser.L_BRACE_LITERAL, LaTeXParser.L_BRACKET, LaTeXParser.BAR, LaTeXParser.L_BAR, LaTeXParser.L_ANGLE, LaTeXParser.FUNC_LIM, LaTeXParser.FUNC_INT, LaTeXParser.FUNC_SUM, LaTeXParser.FUNC_PROD, LaTeXParser.FUNC_EXP, LaTeXParser.FUNC_LOG, LaTeXParser.FUNC_LN, LaTeXParser.FUNC_SIN, LaTeXParser.FUNC_COS, LaTeXParser.FUNC_TAN, LaTeXParser.FUNC_CSC, LaTeXParser.FUNC_SEC, LaTeXParser.FUNC_COT, LaTeXParser.FUNC_ARCSIN, LaTeXParser.FUNC_ARCCOS, LaTeXParser.FUNC_ARCTAN, LaTeXParser.FUNC_ARCCSC, LaTeXParser.FUNC_ARCSEC, LaTeXParser.FUNC_ARCCOT, LaTeXParser.FUNC_SINH, LaTeXParser.FUNC_COSH, LaTeXParser.FUNC_TANH, LaTeXParser.FUNC_ARSINH, LaTeXParser.FUNC_ARCOSH, LaTeXParser.FUNC_ARTANH, LaTeXParser.L_FLOOR, LaTeXParser.L_CEIL, LaTeXParser.FUNC_SQRT, LaTeXParser.CMD_FRAC, LaTeXParser.CMD_BINOM, LaTeXParser.CMD_DBINOM, LaTeXParser.CMD_TBINOM, LaTeXParser.CMD_MATHIT, LaTeXParser.DIFFERENTIAL, LaTeXParser.LETTER, LaTeXParser.NUMBER, LaTeXParser.SYMBOL]: pass else: pass self.state = 376 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,35,self._ctx) if la_ == 1: self.state = 371 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,34,self._ctx) if la_ == 1: self.state = 370 self.additive(0) self.state = 373 self.match(LaTeXParser.DIFFERENTIAL) pass elif la_ == 2: self.state = 374 self.frac() pass elif la_ == 3: self.state = 375 self.additive(0) pass pass elif token in [LaTeXParser.FUNC_SQRT]: self.enterOuterAlt(localctx, 4) self.state = 378 self.match(LaTeXParser.FUNC_SQRT) self.state = 383 self._errHandler.sync(self) _la = self._input.LA(1) if _la==LaTeXParser.L_BRACKET: self.state = 379 self.match(LaTeXParser.L_BRACKET) self.state = 380 localctx.root = self.expr() self.state = 381 self.match(LaTeXParser.R_BRACKET) self.state = 385 self.match(LaTeXParser.L_BRACE) self.state = 386 localctx.base = self.expr() self.state = 387 self.match(LaTeXParser.R_BRACE) pass elif token in [LaTeXParser.FUNC_SUM, LaTeXParser.FUNC_PROD]: self.enterOuterAlt(localctx, 5) self.state = 389 _la = self._input.LA(1) if not(_la==LaTeXParser.FUNC_SUM or _la==LaTeXParser.FUNC_PROD): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 396 self._errHandler.sync(self) token = self._input.LA(1) if token in [LaTeXParser.UNDERSCORE]: self.state = 390 self.subeq() self.state = 391 self.supexpr() pass elif token in [LaTeXParser.CARET]: self.state = 393 self.supexpr() self.state = 394 self.subeq() pass else: raise NoViableAltException(self) self.state = 398 self.mp(0) pass elif token in [LaTeXParser.FUNC_LIM]: self.enterOuterAlt(localctx, 6) self.state = 400 self.match(LaTeXParser.FUNC_LIM) self.state = 401 self.limit_sub() self.state = 402 self.mp(0) pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ArgsContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.ArgsContext, self).__init__(parent, invokingState) self.parser = parser def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def args(self): return self.getTypedRuleContext(LaTeXParser.ArgsContext,0) def getRuleIndex(self): return LaTeXParser.RULE_args def args(self): localctx = LaTeXParser.ArgsContext(self, self._ctx, self.state) self.enterRule(localctx, 64, self.RULE_args) try: self.state = 411 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,39,self._ctx) if la_ == 1: self.enterOuterAlt(localctx, 1) self.state = 406 self.expr() self.state = 407 self.match(LaTeXParser.T__0) self.state = 408 self.args() pass elif la_ == 2: self.enterOuterAlt(localctx, 2) self.state = 410 self.expr() pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Limit_subContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Limit_subContext, self).__init__(parent, invokingState) self.parser = parser def UNDERSCORE(self): return self.getToken(LaTeXParser.UNDERSCORE, 0) def L_BRACE(self, i=None): if i is None: return self.getTokens(LaTeXParser.L_BRACE) else: return self.getToken(LaTeXParser.L_BRACE, i) def LIM_APPROACH_SYM(self): return self.getToken(LaTeXParser.LIM_APPROACH_SYM, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def R_BRACE(self, i=None): if i is None: return self.getTokens(LaTeXParser.R_BRACE) else: return self.getToken(LaTeXParser.R_BRACE, i) def LETTER(self): return self.getToken(LaTeXParser.LETTER, 0) def SYMBOL(self): return self.getToken(LaTeXParser.SYMBOL, 0) def CARET(self): return self.getToken(LaTeXParser.CARET, 0) def ADD(self): return self.getToken(LaTeXParser.ADD, 0) def SUB(self): return self.getToken(LaTeXParser.SUB, 0) def getRuleIndex(self): return LaTeXParser.RULE_limit_sub def limit_sub(self): localctx = LaTeXParser.Limit_subContext(self, self._ctx, self.state) self.enterRule(localctx, 66, self.RULE_limit_sub) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 413 self.match(LaTeXParser.UNDERSCORE) self.state = 414 self.match(LaTeXParser.L_BRACE) self.state = 415 _la = self._input.LA(1) if not(_la==LaTeXParser.LETTER or _la==LaTeXParser.SYMBOL): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 416 self.match(LaTeXParser.LIM_APPROACH_SYM) self.state = 417 self.expr() self.state = 422 self._errHandler.sync(self) _la = self._input.LA(1) if _la==LaTeXParser.CARET: self.state = 418 self.match(LaTeXParser.CARET) self.state = 419 self.match(LaTeXParser.L_BRACE) self.state = 420 _la = self._input.LA(1) if not(_la==LaTeXParser.ADD or _la==LaTeXParser.SUB): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() self.state = 421 self.match(LaTeXParser.R_BRACE) self.state = 424 self.match(LaTeXParser.R_BRACE) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Func_argContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Func_argContext, self).__init__(parent, invokingState) self.parser = parser def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def func_arg(self): return self.getTypedRuleContext(LaTeXParser.Func_argContext,0) def getRuleIndex(self): return LaTeXParser.RULE_func_arg def func_arg(self): localctx = LaTeXParser.Func_argContext(self, self._ctx, self.state) self.enterRule(localctx, 68, self.RULE_func_arg) try: self.state = 431 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input,41,self._ctx) if la_ == 1: self.enterOuterAlt(localctx, 1) self.state = 426 self.expr() pass elif la_ == 2: self.enterOuterAlt(localctx, 2) self.state = 427 self.expr() self.state = 428 self.match(LaTeXParser.T__0) self.state = 429 self.func_arg() pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class Func_arg_noparensContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.Func_arg_noparensContext, self).__init__(parent, invokingState) self.parser = parser def mp_nofunc(self): return self.getTypedRuleContext(LaTeXParser.Mp_nofuncContext,0) def getRuleIndex(self): return LaTeXParser.RULE_func_arg_noparens def func_arg_noparens(self): localctx = LaTeXParser.Func_arg_noparensContext(self, self._ctx, self.state) self.enterRule(localctx, 70, self.RULE_func_arg_noparens) try: self.enterOuterAlt(localctx, 1) self.state = 433 self.mp_nofunc(0) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class SubexprContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.SubexprContext, self).__init__(parent, invokingState) self.parser = parser def UNDERSCORE(self): return self.getToken(LaTeXParser.UNDERSCORE, 0) def atom(self): return self.getTypedRuleContext(LaTeXParser.AtomContext,0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def getRuleIndex(self): return LaTeXParser.RULE_subexpr def subexpr(self): localctx = LaTeXParser.SubexprContext(self, self._ctx, self.state) self.enterRule(localctx, 72, self.RULE_subexpr) try: self.enterOuterAlt(localctx, 1) self.state = 435 self.match(LaTeXParser.UNDERSCORE) self.state = 441 self._errHandler.sync(self) token = self._input.LA(1) if token in [LaTeXParser.BAR, LaTeXParser.L_BAR, LaTeXParser.L_ANGLE, LaTeXParser.CMD_MATHIT, LaTeXParser.DIFFERENTIAL, LaTeXParser.LETTER, LaTeXParser.NUMBER, LaTeXParser.SYMBOL]: self.state = 436 self.atom() pass elif token in [LaTeXParser.L_BRACE]: self.state = 437 self.match(LaTeXParser.L_BRACE) self.state = 438 self.expr() self.state = 439 self.match(LaTeXParser.R_BRACE) pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class SupexprContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.SupexprContext, self).__init__(parent, invokingState) self.parser = parser def CARET(self): return self.getToken(LaTeXParser.CARET, 0) def atom(self): return self.getTypedRuleContext(LaTeXParser.AtomContext,0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def expr(self): return self.getTypedRuleContext(LaTeXParser.ExprContext,0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def getRuleIndex(self): return LaTeXParser.RULE_supexpr def supexpr(self): localctx = LaTeXParser.SupexprContext(self, self._ctx, self.state) self.enterRule(localctx, 74, self.RULE_supexpr) try: self.enterOuterAlt(localctx, 1) self.state = 443 self.match(LaTeXParser.CARET) self.state = 449 self._errHandler.sync(self) token = self._input.LA(1) if token in [LaTeXParser.BAR, LaTeXParser.L_BAR, LaTeXParser.L_ANGLE, LaTeXParser.CMD_MATHIT, LaTeXParser.DIFFERENTIAL, LaTeXParser.LETTER, LaTeXParser.NUMBER, LaTeXParser.SYMBOL]: self.state = 444 self.atom() pass elif token in [LaTeXParser.L_BRACE]: self.state = 445 self.match(LaTeXParser.L_BRACE) self.state = 446 self.expr() self.state = 447 self.match(LaTeXParser.R_BRACE) pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class SubeqContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.SubeqContext, self).__init__(parent, invokingState) self.parser = parser def UNDERSCORE(self): return self.getToken(LaTeXParser.UNDERSCORE, 0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def equality(self): return self.getTypedRuleContext(LaTeXParser.EqualityContext,0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def getRuleIndex(self): return LaTeXParser.RULE_subeq def subeq(self): localctx = LaTeXParser.SubeqContext(self, self._ctx, self.state) self.enterRule(localctx, 76, self.RULE_subeq) try: self.enterOuterAlt(localctx, 1) self.state = 451 self.match(LaTeXParser.UNDERSCORE) self.state = 452 self.match(LaTeXParser.L_BRACE) self.state = 453 self.equality() self.state = 454 self.match(LaTeXParser.R_BRACE) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class SupeqContext(ParserRuleContext): def __init__(self, parser, parent=None, invokingState=-1): super(LaTeXParser.SupeqContext, self).__init__(parent, invokingState) self.parser = parser def UNDERSCORE(self): return self.getToken(LaTeXParser.UNDERSCORE, 0) def L_BRACE(self): return self.getToken(LaTeXParser.L_BRACE, 0) def equality(self): return self.getTypedRuleContext(LaTeXParser.EqualityContext,0) def R_BRACE(self): return self.getToken(LaTeXParser.R_BRACE, 0) def getRuleIndex(self): return LaTeXParser.RULE_supeq def supeq(self): localctx = LaTeXParser.SupeqContext(self, self._ctx, self.state) self.enterRule(localctx, 78, self.RULE_supeq) try: self.enterOuterAlt(localctx, 1) self.state = 456 self.match(LaTeXParser.UNDERSCORE) self.state = 457 self.match(LaTeXParser.L_BRACE) self.state = 458 self.equality() self.state = 459 self.match(LaTeXParser.R_BRACE) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx def sempred(self, localctx, ruleIndex, predIndex): if self._predicates == None: self._predicates = dict() self._predicates[1] = self.relation_sempred self._predicates[4] = self.additive_sempred self._predicates[5] = self.mp_sempred self._predicates[6] = self.mp_nofunc_sempred self._predicates[15] = self.exp_sempred self._predicates[16] = self.exp_nofunc_sempred pred = self._predicates.get(ruleIndex, None) if pred is None: raise Exception("No predicate with index:" + str(ruleIndex)) else: return pred(localctx, predIndex) def relation_sempred(self, localctx, predIndex): if predIndex == 0: return self.precpred(self._ctx, 2) def additive_sempred(self, localctx, predIndex): if predIndex == 1: return self.precpred(self._ctx, 2) def mp_sempred(self, localctx, predIndex): if predIndex == 2: return self.precpred(self._ctx, 2) def mp_nofunc_sempred(self, localctx, predIndex): if predIndex == 3: return self.precpred(self._ctx, 2) def exp_sempred(self, localctx, predIndex): if predIndex == 4: return self.precpred(self._ctx, 2) def exp_nofunc_sempred(self, localctx, predIndex): if predIndex == 5: return self.precpred(self._ctx, 2)
05886da6b971b7df8883edf498320d81022aad5f76617894960ab15efb0f7227
from sympy import Basic, Mul, Pow, degree, Symbol, expand, cancel, Expr, exp, roots from sympy.core.evalf import EvalfMixin from sympy.core.logic import fuzzy_and from sympy.core.numbers import Integer from sympy.core.sympify import sympify, _sympify from sympy.polys import Poly, rootof from sympy.series import limit __all__ = ['TransferFunction', 'Series', 'Parallel', 'Feedback'] def _roots(poly, var): """ like roots, but works on higher-order polynomials. """ r = roots(poly, var, multiple=True) n = degree(poly) if len(r) != n: r = [rootof(poly, var, k) for k in range(n)] return r class TransferFunction(Basic, EvalfMixin): """ A class for representing LTI (Linear, time-invariant) systems that can be strictly described by ratio of polynomials in the Laplace Transform complex variable. The arguments are ``num``, ``den``, and ``var``, where ``num`` and ``den`` are numerator and denominator polynomials of the ``TransferFunction`` respectively, and the third argument is a complex variable of the Laplace transform used by these polynomials of the transfer function. ``num`` and ``den`` can be either polynomials or numbers, whereas ``var`` has to be a Symbol. Parameters ========== num : Expr, Number The numerator polynomial of the transfer function. den : Expr, Number The denominator polynomial of the transfer function. var : Symbol Complex variable of the Laplace transform used by the polynomials of the transfer function. Raises ====== TypeError When ``var`` is not a Symbol or when ``num`` or ``den`` is not a number or a polynomial. Also, when ``num`` or ``den`` has a time delay term. ValueError When ``den`` is zero. Examples ======== >>> from sympy.abc import s, p, a >>> from sympy.physics.control.lti import TransferFunction >>> tf1 = TransferFunction(s + a, s**2 + s + 1, s) >>> tf1 TransferFunction(a + s, s**2 + s + 1, s) >>> tf1.num a + s >>> tf1.den s**2 + s + 1 >>> tf1.var s >>> tf1.args (a + s, s**2 + s + 1, s) Any complex variable can be used for ``var``. >>> tf2 = TransferFunction(a*p**3 - a*p**2 + s*p, p + a**2, p) >>> tf2 TransferFunction(a*p**3 - a*p**2 + p*s, a**2 + p, p) >>> tf3 = TransferFunction((p + 3)*(p - 1), (p - 1)*(p + 5), p) >>> tf3 TransferFunction((p - 1)*(p + 3), (p - 1)*(p + 5), p) To negate a transfer function the ``-`` operator can be prepended: >>> tf4 = TransferFunction(-a + s, p**2 + s, p) >>> -tf4 TransferFunction(a - s, p**2 + s, p) >>> tf5 = TransferFunction(s**4 - 2*s**3 + 5*s + 4, s + 4, s) >>> -tf5 TransferFunction(-s**4 + 2*s**3 - 5*s - 4, s + 4, s) You can use a Float or an Integer (or other constants) as numerator and denominator: >>> tf6 = TransferFunction(1/2, 4, s) >>> tf6.num 0.500000000000000 >>> tf6.den 4 >>> tf6.var s >>> tf6.args (0.5, 4, s) You can take the integer power of a transfer function using the ``**`` operator: >>> tf7 = TransferFunction(s + a, s - a, s) >>> tf7**3 TransferFunction((a + s)**3, (-a + s)**3, s) >>> tf7**0 TransferFunction(1, 1, s) >>> tf8 = TransferFunction(p + 4, p - 3, p) >>> tf8**-1 TransferFunction(p - 3, p + 4, p) Addition, subtraction, and multiplication of transfer functions can form unevaluated ``Series`` or ``Parallel`` objects. >>> tf9 = TransferFunction(s + 1, s**2 + s + 1, s) >>> tf10 = TransferFunction(s - p, s + 3, s) >>> tf11 = TransferFunction(4*s**2 + 2*s - 4, s - 1, s) >>> tf12 = TransferFunction(1 - s, s**2 + 4, s) >>> tf9 + tf10 Parallel(TransferFunction(s + 1, s**2 + s + 1, s), TransferFunction(-p + s, s + 3, s)) >>> tf10 - tf11 Parallel(TransferFunction(-p + s, s + 3, s), TransferFunction(-4*s**2 - 2*s + 4, s - 1, s)) >>> tf9 * tf10 Series(TransferFunction(s + 1, s**2 + s + 1, s), TransferFunction(-p + s, s + 3, s)) >>> tf10 - (tf9 + tf12) Parallel(TransferFunction(-p + s, s + 3, s), TransferFunction(-s - 1, s**2 + s + 1, s), TransferFunction(s - 1, s**2 + 4, s)) >>> tf10 - (tf9 * tf12) Parallel(TransferFunction(-p + s, s + 3, s), Series(TransferFunction(-1, 1, s), Series(TransferFunction(s + 1, s**2 + s + 1, s), TransferFunction(1 - s, s**2 + 4, s)))) >>> tf11 * tf10 * tf9 Series(TransferFunction(4*s**2 + 2*s - 4, s - 1, s), TransferFunction(-p + s, s + 3, s), TransferFunction(s + 1, s**2 + s + 1, s)) >>> tf9 * tf11 + tf10 * tf12 Parallel(Series(TransferFunction(s + 1, s**2 + s + 1, s), TransferFunction(4*s**2 + 2*s - 4, s - 1, s)), Series(TransferFunction(-p + s, s + 3, s), TransferFunction(1 - s, s**2 + 4, s))) >>> (tf9 + tf12) * (tf10 + tf11) Series(Parallel(TransferFunction(s + 1, s**2 + s + 1, s), TransferFunction(1 - s, s**2 + 4, s)), Parallel(TransferFunction(-p + s, s + 3, s), TransferFunction(4*s**2 + 2*s - 4, s - 1, s))) These unevaluated ``Series`` or ``Parallel`` objects can convert into the resultant transfer function using ``.doit()`` method or by ``.rewrite(TransferFunction)``. >>> ((tf9 + tf10) * tf12).doit() TransferFunction((1 - s)*((-p + s)*(s**2 + s + 1) + (s + 1)*(s + 3)), (s + 3)*(s**2 + 4)*(s**2 + s + 1), s) >>> (tf9 * tf10 - tf11 * tf12).rewrite(TransferFunction) TransferFunction(-(1 - s)*(s + 3)*(s**2 + s + 1)*(4*s**2 + 2*s - 4) + (-p + s)*(s - 1)*(s + 1)*(s**2 + 4), (s - 1)*(s + 3)*(s**2 + 4)*(s**2 + s + 1), s) See Also ======== Feedback, Series, Parallel """ def __new__(cls, num, den, var): num, den = _sympify(num), _sympify(den) if not isinstance(var, Symbol): raise TypeError("Variable input must be a Symbol.") if den == 0: raise ValueError("TransferFunction can't have a zero denominator.") if (((isinstance(num, Expr) and num.has(Symbol) and not num.has(exp)) or num.is_number) and ((isinstance(den, Expr) and den.has(Symbol) and not den.has(exp)) or den.is_number)): obj = super().__new__(cls, num, den, var) obj._num = num obj._den = den obj._var = var return obj else: raise TypeError("Unsupported type for numerator or denominator of TransferFunction.") @property def num(self): """ Returns the numerator polynomial of the transfer function. Examples ======== >>> from sympy.abc import s, p >>> from sympy.physics.control.lti import TransferFunction >>> G1 = TransferFunction(s**2 + p*s + 3, s - 4, s) >>> G1.num p*s + s**2 + 3 >>> G2 = TransferFunction((p + 5)*(p - 3), (p - 3)*(p + 1), p) >>> G2.num (p - 3)*(p + 5) """ return self._num @property def den(self): """ Returns the denominator polynomial of the transfer function. Examples ======== >>> from sympy.abc import s, p >>> from sympy.physics.control.lti import TransferFunction >>> G1 = TransferFunction(s + 4, p**3 - 2*p + 4, s) >>> G1.den p**3 - 2*p + 4 >>> G2 = TransferFunction(3, 4, s) >>> G2.den 4 """ return self._den @property def var(self): """ Returns the complex variable of the Laplace transform used by the polynomials of the transfer function. Examples ======== >>> from sympy.abc import s, p >>> from sympy.physics.control.lti import TransferFunction >>> G1 = TransferFunction(p**2 + 2*p + 4, p - 6, p) >>> G1.var p >>> G2 = TransferFunction(0, s - 5, s) >>> G2.var s """ return self._var def _eval_subs(self, old, new): arg_num = self.num.subs(old, new) arg_den = self.den.subs(old, new) argnew = TransferFunction(arg_num, arg_den, self.var) return self if old == self.var else argnew def _eval_evalf(self, prec): return TransferFunction( self.num._eval_evalf(prec), self.den._eval_evalf(prec), self.var) def _eval_simplify(self, **kwargs): tf = cancel(Mul(self.num, 1/self.den, evaluate=False), expand=False).as_numer_denom() num_, den_ = tf[0], tf[1] return TransferFunction(num_, den_, self.var) def expand(self): """ Returns the transfer function with numerator and denominator in expanded form. Examples ======== >>> from sympy.abc import s, p, a, b >>> from sympy.physics.control.lti import TransferFunction >>> G1 = TransferFunction((a - s)**2, (s**2 + a)**2, s) >>> G1.expand() TransferFunction(a**2 - 2*a*s + s**2, a**2 + 2*a*s**2 + s**4, s) >>> G2 = TransferFunction((p + 3*b)*(p - b), (p - b)*(p + 2*b), p) >>> G2.expand() TransferFunction(-3*b**2 + 2*b*p + p**2, -2*b**2 + b*p + p**2, p) """ return TransferFunction(expand(self.num), expand(self.den), self.var) def dc_gain(self): """ Computes the gain of the response as the frequency approaches zero. The DC gain is infinite for systems with pure integrators. Examples ======== >>> from sympy.abc import s, p, a, b >>> from sympy.physics.control.lti import TransferFunction >>> tf1 = TransferFunction(s + 3, s**2 - 9, s) >>> tf1.dc_gain() -1/3 >>> tf2 = TransferFunction(p**2, p - 3 + p**3, p) >>> tf2.dc_gain() 0 >>> tf3 = TransferFunction(a*p**2 - b, s + b, s) >>> tf3.dc_gain() (a*p**2 - b)/b >>> tf4 = TransferFunction(1, s, s) >>> tf4.dc_gain() oo """ m = Mul(self.num, Pow(self.den, -1, evaluate=False), evaluate=False) return limit(m, self.var, 0) def poles(self): """ Returns the poles of a transfer function. Examples ======== >>> from sympy.abc import s, p, a >>> from sympy.physics.control.lti import TransferFunction >>> tf1 = TransferFunction((p + 3)*(p - 1), (p - 1)*(p + 5), p) >>> tf1.poles() [-5, 1] >>> tf2 = TransferFunction((1 - s)**2, (s**2 + 1)**2, s) >>> tf2.poles() [I, I, -I, -I] >>> tf3 = TransferFunction(s**2, a*s + p, s) >>> tf3.poles() [-p/a] """ return _roots(Poly(self.den, self.var), self.var) def zeros(self): """ Returns the zeros of a transfer function. Examples ======== >>> from sympy.abc import s, p, a >>> from sympy.physics.control.lti import TransferFunction >>> tf1 = TransferFunction((p + 3)*(p - 1), (p - 1)*(p + 5), p) >>> tf1.zeros() [-3, 1] >>> tf2 = TransferFunction((1 - s)**2, (s**2 + 1)**2, s) >>> tf2.zeros() [1, 1] >>> tf3 = TransferFunction(s**2, a*s + p, s) >>> tf3.zeros() [0, 0] """ return _roots(Poly(self.num, self.var), self.var) def is_stable(self): """ Returns True if the transfer function is asymptotically stable; else False. This would not check the marginal or conditional stability of the system. Examples ======== >>> from sympy.abc import s, p, a >>> from sympy.core.symbol import symbols >>> q, r = symbols('q, r', negative=True) >>> from sympy.physics.control.lti import TransferFunction >>> tf1 = TransferFunction((1 - s)**2, (s + 1)**2, s) >>> tf1.is_stable() True >>> tf2 = TransferFunction((1 - p)**2, (s**2 + 1)**2, s) >>> tf2.is_stable() False >>> tf3 = TransferFunction(4, q*s - r, s) >>> tf3.is_stable() False >>> tf4 = TransferFunction(p + 1, a*p - s**2, p) >>> tf4.is_stable() is None # Not enough info about the symbols to determine stability True """ return fuzzy_and(pole.as_real_imag()[0].is_negative for pole in self.poles()) def __add__(self, other): if isinstance(other, (TransferFunction, Series)): if not self.var == other.var: raise ValueError("All the transfer functions should use the same complex variable " "of the Laplace transform.") return Parallel(self, other) elif isinstance(other, Parallel): if not self.var == other.var: raise ValueError("All the transfer functions should use the same complex variable " "of the Laplace transform.") arg_list = list(other.args) return Parallel(self, *arg_list) else: raise ValueError("TransferFunction cannot be added with {}.". format(type(other))) def __radd__(self, other): return self + other def __sub__(self, other): if isinstance(other, (TransferFunction, Series)): if not self.var == other.var: raise ValueError("All the transfer functions should use the same complex variable " "of the Laplace transform.") return Parallel(self, -other) elif isinstance(other, Parallel): if not self.var == other.var: raise ValueError("All the transfer functions should use the same complex variable " "of the Laplace transform.") arg_list = [-i for i in list(other.args)] return Parallel(self, *arg_list) else: raise ValueError("{} cannot be subtracted from a TransferFunction." .format(type(other))) def __rsub__(self, other): return -self + other def __mul__(self, other): if isinstance(other, (TransferFunction, Parallel)): if not self.var == other.var: raise ValueError("All the transfer functions should use the same complex variable " "of the Laplace transform.") return Series(self, other) elif isinstance(other, Series): if not self.var == other.var: raise ValueError("All the transfer functions should use the same complex variable " "of the Laplace transform.") arg_list = list(other.args) return Series(self, *arg_list) else: raise ValueError("TransferFunction cannot be multiplied with {}." .format(type(other))) __rmul__ = __mul__ def __truediv__(self, other): if (isinstance(other, Parallel) and len(other.args) == 2 and isinstance(other.args[0], TransferFunction) and isinstance(other.args[1], (Series, TransferFunction))): if not self.var == other.var: raise ValueError("Both TransferFunction and Parallel should use the" " same complex variable of the Laplace transform.") if other.args[1] == self: # plant and controller with unit feedback. return Feedback(self, other.args[0]) other_arg_list = list(other.args[1].args) if isinstance(other.args[1], Series) else other.args[1] if other_arg_list == other.args[1]: return Feedback(self, other_arg_list) elif self in other_arg_list: other_arg_list.remove(self) else: return Feedback(self, Series(*other_arg_list)) if len(other_arg_list) == 1: return Feedback(self, *other_arg_list) else: return Feedback(self, Series(*other_arg_list)) else: raise ValueError("TransferFunction cannot be divided by {}.". format(type(other))) __rtruediv__ = __truediv__ def __pow__(self, p): p = sympify(p) if not isinstance(p, Integer): raise ValueError("Exponent must be an Integer.") if p == 0: return TransferFunction(1, 1, self.var) elif p > 0: num_, den_ = self.num**p, self.den**p else: p = abs(p) num_, den_ = self.den**p, self.num**p return TransferFunction(num_, den_, self.var) def __neg__(self): return TransferFunction(-self.num, self.den, self.var) @property def is_proper(self): """ Returns True if degree of the numerator polynomial is less than or equal to degree of the denominator polynomial, else False. Examples ======== >>> from sympy.abc import s, p, a, b >>> from sympy.physics.control.lti import TransferFunction >>> tf1 = TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s) >>> tf1.is_proper False >>> tf2 = TransferFunction(p**2 - 4*p, p**3 + 3*p + 2, p) >>> tf2.is_proper True """ return degree(self.num, self.var) <= degree(self.den, self.var) @property def is_strictly_proper(self): """ Returns True if degree of the numerator polynomial is strictly less than degree of the denominator polynomial, else False. Examples ======== >>> from sympy.abc import s, p, a, b >>> from sympy.physics.control.lti import TransferFunction >>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s) >>> tf1.is_strictly_proper False >>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s) >>> tf2.is_strictly_proper True """ return degree(self.num, self.var) < degree(self.den, self.var) @property def is_biproper(self): """ Returns True if degree of the numerator polynomial is equal to degree of the denominator polynomial, else False. Examples ======== >>> from sympy.abc import s, p, a, b >>> from sympy.physics.control.lti import TransferFunction >>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s) >>> tf1.is_biproper True >>> tf2 = TransferFunction(p**2, p + a, p) >>> tf2.is_biproper False """ return degree(self.num, self.var) == degree(self.den, self.var) class Series(Basic): """ A class for representing product of transfer functions or transfer functions in a series configuration. Examples ======== >>> from sympy.abc import s, p, a, b >>> from sympy.physics.control.lti import TransferFunction, Series, Parallel >>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s) >>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s) >>> tf3 = TransferFunction(p**2, p + s, s) >>> S1 = Series(tf1, tf2) >>> S1 Series(TransferFunction(a*p**2 + b*s, -p + s, s), TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)) >>> S1.var s >>> S2 = Series(tf2, Parallel(tf3, -tf1)) >>> S2 Series(TransferFunction(s**3 - 2, s**4 + 5*s + 6, s), Parallel(TransferFunction(p**2, p + s, s), TransferFunction(-a*p**2 - b*s, -p + s, s))) >>> S2.var s >>> S3 = Series(Parallel(tf1, tf2), Parallel(tf2, tf3)) >>> S3 Series(Parallel(TransferFunction(a*p**2 + b*s, -p + s, s), TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)), Parallel(TransferFunction(s**3 - 2, s**4 + 5*s + 6, s), TransferFunction(p**2, p + s, s))) >>> S3.var s You can get the resultant transfer function by using ``.doit()`` method: >>> S3 = Series(tf1, tf2, -tf3) >>> S3.doit() TransferFunction(-p**2*(s**3 - 2)*(a*p**2 + b*s), (-p + s)*(p + s)*(s**4 + 5*s + 6), s) >>> S4 = Series(tf2, Parallel(tf1, -tf3)) >>> S4.doit() TransferFunction((s**3 - 2)*(-p**2*(-p + s) + (p + s)*(a*p**2 + b*s)), (-p + s)*(p + s)*(s**4 + 5*s + 6), s) Notes ===== All the transfer functions should use the same complex variable ``var`` of the Laplace transform. See Also ======== Parallel, TransferFunction, Feedback """ def __new__(cls, *args, evaluate=False): if not all(isinstance(arg, (TransferFunction, Parallel, Series)) for arg in args): raise TypeError("Unsupported type of argument(s) for Series.") obj = super().__new__(cls, *args) obj._var = None for arg in args: if obj._var is None: obj._var = arg.var elif obj._var != arg.var: raise ValueError("All transfer functions should use the same complex" " variable of the Laplace transform.") if evaluate: return obj.doit() return obj @property def var(self): """ Returns the complex variable used by all the transfer functions. Examples ======== >>> from sympy.abc import p >>> from sympy.physics.control.lti import TransferFunction, Series, Parallel >>> G1 = TransferFunction(p**2 + 2*p + 4, p - 6, p) >>> G2 = TransferFunction(p, 4 - p, p) >>> G3 = TransferFunction(0, p**4 - 1, p) >>> Series(G1, G2).var p >>> Series(-G3, Parallel(G1, G2)).var p """ return self._var def doit(self, **kwargs): """ Returns the resultant transfer function obtained after evaluating the transfer functions in series configuration. Examples ======== >>> from sympy.abc import s, p, a, b >>> from sympy.physics.control.lti import TransferFunction, Series >>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s) >>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s) >>> Series(tf2, tf1).doit() TransferFunction((s**3 - 2)*(a*p**2 + b*s), (-p + s)*(s**4 + 5*s + 6), s) >>> Series(-tf1, -tf2).doit() TransferFunction((2 - s**3)*(-a*p**2 - b*s), (-p + s)*(s**4 + 5*s + 6), s) """ res = None for arg in self.args: arg = arg.doit() if res is None: res = arg else: num_ = arg.num * res.num den_ = arg.den * res.den res = TransferFunction(num_, den_, self.var) return res def _eval_rewrite_as_TransferFunction(self, *args, **kwargs): return self.doit() def __add__(self, other): if isinstance(other, (TransferFunction, Series)): if not self.var == other.var: raise ValueError("All the transfer functions should use the same complex variable " "of the Laplace transform.") return Parallel(self, other) elif isinstance(other, Parallel): if not self.var == other.var: raise ValueError("All the transfer functions should use the same complex variable " "of the Laplace transform.") arg_list = list(other.args) return Parallel(self, *arg_list) else: raise ValueError("This transfer function expression is invalid.") __radd__ = __add__ def __sub__(self, other): if isinstance(other, (TransferFunction, Series)): if not self.var == other.var: raise ValueError("All the transfer functions should use the same complex variable " "of the Laplace transform.") return Parallel(self, -other) elif isinstance(other, Parallel): if not self.var == other.var: raise ValueError("All the transfer functions should use the same complex variable " "of the Laplace transform.") arg_list = [-i for i in list(other.args)] return Parallel(self, *arg_list) else: raise ValueError("This transfer function expression is invalid.") def __rsub__(self, other): return -self + other def __mul__(self, other): if isinstance(other, (TransferFunction, Parallel)): if not self.var == other.var: raise ValueError("All the transfer functions should use the same complex variable " "of the Laplace transform.") arg_list = list(self.args) return Series(*arg_list, other) elif isinstance(other, Series): if not self.var == other.var: raise ValueError("All the transfer functions should use the same complex variable " "of the Laplace transform.") self_arg_list = list(self.args) other_arg_list = list(other.args) return Series(*self_arg_list, *other_arg_list) else: raise ValueError("This transfer function expression is invalid.") def __truediv__(self, other): if (isinstance(other, Parallel) and len(other.args) == 2 and isinstance(other.args[0], TransferFunction) and isinstance(other.args[1], Series)): if not self.var == other.var: raise ValueError("All the transfer functions should use the same complex variable " "of the Laplace transform.") self_arg_list = set(list(self.args)) other_arg_list = set(list(other.args[1].args)) res = list(self_arg_list ^ other_arg_list) if len(res) == 0: return Feedback(self, other.args[0]) elif len(res) == 1: return Feedback(self, *res) else: return Feedback(self, Series(*res)) else: raise ValueError("This transfer function expression is invalid.") def __neg__(self): return Series(TransferFunction(-1, 1, self.var), self) @property def is_proper(self): """ Returns True if degree of the numerator polynomial of the resultant transfer function is less than or equal to degree of the denominator polynomial of the same, else False. Examples ======== >>> from sympy.abc import s, p, a, b >>> from sympy.physics.control.lti import TransferFunction, Series >>> tf1 = TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s) >>> tf2 = TransferFunction(p**2 - 4*p, p**3 + 3*s + 2, s) >>> tf3 = TransferFunction(s, s**2 + s + 1, s) >>> S1 = Series(-tf2, tf1) >>> S1.is_proper False >>> S2 = Series(tf1, tf2, tf3) >>> S2.is_proper True """ return self.doit().is_proper @property def is_strictly_proper(self): """ Returns True if degree of the numerator polynomial of the resultant transfer function is strictly less than degree of the denominator polynomial of the same, else False. Examples ======== >>> from sympy.abc import s, p, a, b >>> from sympy.physics.control.lti import TransferFunction, Series >>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s) >>> tf2 = TransferFunction(s**3 - 2, s**2 + 5*s + 6, s) >>> tf3 = TransferFunction(1, s**2 + s + 1, s) >>> S1 = Series(tf1, tf2) >>> S1.is_strictly_proper False >>> S2 = Series(tf1, tf2, tf3) >>> S2.is_strictly_proper True """ return self.doit().is_strictly_proper @property def is_biproper(self): r""" Returns True if degree of the numerator polynomial of the resultant transfer function is equal to degree of the denominator polynomial of the same, else False. Examples ======== >>> from sympy.abc import s, p, a, b >>> from sympy.physics.control.lti import TransferFunction, Series >>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s) >>> tf2 = TransferFunction(p, s**2, s) >>> tf3 = TransferFunction(s**2, 1, s) >>> S1 = Series(tf1, -tf2) >>> S1.is_biproper False >>> S2 = Series(tf2, tf3) >>> S2.is_biproper True """ return self.doit().is_biproper class Parallel(Basic): """ A class for representing addition of transfer functions or transfer functions in a parallel configuration. Examples ======== >>> from sympy.abc import s, p, a, b >>> from sympy.physics.control.lti import TransferFunction, Parallel, Series >>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s) >>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s) >>> tf3 = TransferFunction(p**2, p + s, s) >>> P1 = Parallel(tf1, tf2) >>> P1 Parallel(TransferFunction(a*p**2 + b*s, -p + s, s), TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)) >>> P1.var s >>> P2 = Parallel(tf2, Series(tf3, -tf1)) >>> P2 Parallel(TransferFunction(s**3 - 2, s**4 + 5*s + 6, s), Series(TransferFunction(p**2, p + s, s), TransferFunction(-a*p**2 - b*s, -p + s, s))) >>> P2.var s >>> P3 = Parallel(Series(tf1, tf2), Series(tf2, tf3)) >>> P3 Parallel(Series(TransferFunction(a*p**2 + b*s, -p + s, s), TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)), Series(TransferFunction(s**3 - 2, s**4 + 5*s + 6, s), TransferFunction(p**2, p + s, s))) >>> P3.var s You can get the resultant transfer function by using ``.doit()`` method: >>> Parallel(tf1, tf2, -tf3).doit() TransferFunction(-p**2*(-p + s)*(s**4 + 5*s + 6) + (p + s)*((-p + s)*(s**3 - 2) + (a*p**2 + b*s)*(s**4 + 5*s + 6)), (-p + s)*(p + s)*(s**4 + 5*s + 6), s) >>> Parallel(tf2, Series(tf1, -tf3)).doit() TransferFunction(-p**2*(a*p**2 + b*s)*(s**4 + 5*s + 6) + (-p + s)*(p + s)*(s**3 - 2), (-p + s)*(p + s)*(s**4 + 5*s + 6), s) Notes ===== All the transfer functions should use the same complex variable ``var`` of the Laplace transform. See Also ======== Series, TransferFunction, Feedback """ def __new__(cls, *args, evaluate=False): if not all(isinstance(arg, (TransferFunction, Series, Parallel)) for arg in args): raise TypeError("Unsupported type of argument(s) for Parallel.") obj = super().__new__(cls, *args) obj._var = None for arg in args: if obj._var is None: obj._var = arg.var elif obj._var != arg.var: raise ValueError("All transfer functions should use the same complex" " variable of the Laplace transform.") if evaluate: return obj.doit() return obj @property def var(self): """ Returns the complex variable used by all the transfer functions. Examples ======== >>> from sympy.abc import p >>> from sympy.physics.control.lti import TransferFunction, Parallel, Series >>> G1 = TransferFunction(p**2 + 2*p + 4, p - 6, p) >>> G2 = TransferFunction(p, 4 - p, p) >>> G3 = TransferFunction(0, p**4 - 1, p) >>> Parallel(G1, G2).var p >>> Parallel(-G3, Series(G1, G2)).var p """ return self._var def doit(self, **kwargs): """ Returns the resultant transfer function obtained after evaluating the transfer functions in parallel configuration. Examples ======== >>> from sympy.abc import s, p, a, b >>> from sympy.physics.control.lti import TransferFunction, Parallel >>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s) >>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s) >>> Parallel(tf2, tf1).doit() TransferFunction((-p + s)*(s**3 - 2) + (a*p**2 + b*s)*(s**4 + 5*s + 6), (-p + s)*(s**4 + 5*s + 6), s) >>> Parallel(-tf1, -tf2).doit() TransferFunction((2 - s**3)*(-p + s) + (-a*p**2 - b*s)*(s**4 + 5*s + 6), (-p + s)*(s**4 + 5*s + 6), s) """ res = None for arg in self.args: arg = arg.doit() if res is None: res = arg else: num_ = res.num * arg.den + res.den * arg.num den_ = res.den * arg.den res = TransferFunction(num_, den_, self.var) return res def _eval_rewrite_as_TransferFunction(self, *args, **kwargs): return self.doit() def __add__(self, other): if isinstance(other, (TransferFunction, Series)): if not self.var == other.var: raise ValueError("All the transfer functions should use the same complex variable " "of the Laplace transform.") arg_list = list(self.args) arg_list.append(other) return Parallel(*arg_list) elif isinstance(other, Parallel): if not self.var == other.var: raise ValueError("All the transfer functions should use the same complex variable " "of the Laplace transform.") self_arg_list = list(self.args) other_arg_list = list(other.args) for elem in other_arg_list: self_arg_list.append(elem) return Parallel(*self_arg_list) else: raise ValueError("This transfer function expression is invalid.") def __sub__(self, other): if isinstance(other, (TransferFunction, Series)): if not self.var == other.var: raise ValueError("All the transfer functions should use the same complex variable " "of the Laplace transform.") arg_list = list(self.args) arg_list.append(-other) return Parallel(*arg_list) elif isinstance(other, Parallel): if not self.var == other.var: raise ValueError("All the transfer functions should use the same complex variable " "of the Laplace transform.") self_arg_list = list(self.args) other_arg_list = list(other.args) for elem in other_arg_list: self_arg_list.append(-elem) return Parallel(*self_arg_list) else: raise ValueError("This transfer function expression is invalid.") def __mul__(self, other): if isinstance(other, (TransferFunction, Parallel)): if not self.var == other.var: raise ValueError("All the transfer functions should use the same complex variable " "of the Laplace transform.") return Series(self, other) elif isinstance(other, Series): if not self.var == other.var: raise ValueError("All the transfer functions should use the same complex variable " "of the Laplace transform.") arg_list = list(other.args) return Series(self, *arg_list) else: raise ValueError("This transfer function expression is invalid.") def __neg__(self): return Series(TransferFunction(-1, 1, self.var), self) @property def is_proper(self): """ Returns True if degree of the numerator polynomial of the resultant transfer function is less than or equal to degree of the denominator polynomial of the same, else False. Examples ======== >>> from sympy.abc import s, p, a, b >>> from sympy.physics.control.lti import TransferFunction, Parallel >>> tf1 = TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s) >>> tf2 = TransferFunction(p**2 - 4*p, p**3 + 3*s + 2, s) >>> tf3 = TransferFunction(s, s**2 + s + 1, s) >>> P1 = Parallel(-tf2, tf1) >>> P1.is_proper False >>> P2 = Parallel(tf2, tf3) >>> P2.is_proper True """ return self.doit().is_proper @property def is_strictly_proper(self): """ Returns True if degree of the numerator polynomial of the resultant transfer function is strictly less than degree of the denominator polynomial of the same, else False. Examples ======== >>> from sympy.abc import s, p, a, b >>> from sympy.physics.control.lti import TransferFunction, Parallel >>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s) >>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s) >>> tf3 = TransferFunction(s, s**2 + s + 1, s) >>> P1 = Parallel(tf1, tf2) >>> P1.is_strictly_proper False >>> P2 = Parallel(tf2, tf3) >>> P2.is_strictly_proper True """ return self.doit().is_strictly_proper @property def is_biproper(self): """ Returns True if degree of the numerator polynomial of the resultant transfer function is equal to degree of the denominator polynomial of the same, else False. Examples ======== >>> from sympy.abc import s, p, a, b >>> from sympy.physics.control.lti import TransferFunction, Parallel >>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s) >>> tf2 = TransferFunction(p**2, p + s, s) >>> tf3 = TransferFunction(s, s**2 + s + 1, s) >>> P1 = Parallel(tf1, -tf2) >>> P1.is_biproper True >>> P2 = Parallel(tf2, tf3) >>> P2.is_biproper False """ return self.doit().is_biproper class Feedback(Basic): """ A class for representing negative feedback interconnection between two input/output systems. The first argument, ``num``, is called as the primary plant or the numerator, and the second argument, ``den``, is called as the feedback plant (which is often a feedback controller) or the denominator. Both ``num`` and ``den`` can either be ``Series`` or ``TransferFunction`` objects. Parameters ========== num : Series, TransferFunction The primary plant. den : Series, TransferFunction The feedback plant (often a feedback controller). Raises ====== ValueError When ``num`` is equal to ``den`` or when they are not using the same complex variable of the Laplace transform. TypeError When either ``num`` or ``den`` is not a ``Series`` or a ``TransferFunction`` object. Examples ======== >>> from sympy.abc import s >>> from sympy.physics.control.lti import TransferFunction, Feedback >>> plant = TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s) >>> controller = TransferFunction(5*s - 10, s + 7, s) >>> F1 = Feedback(plant, controller) >>> F1 Feedback(TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s), TransferFunction(5*s - 10, s + 7, s)) >>> F1.var s >>> F1.args (TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s), TransferFunction(5*s - 10, s + 7, s)) You can get the primary and the feedback plant using ``.num`` and ``.den`` respectively. >>> F1.num TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s) >>> F1.den TransferFunction(5*s - 10, s + 7, s) You can get the resultant closed loop transfer function obtained by negative feedback interconnection using ``.doit()`` method. >>> F1.doit() TransferFunction((s + 7)*(s**2 - 4*s + 2)*(3*s**2 + 7*s - 3), ((s + 7)*(s**2 - 4*s + 2) + (5*s - 10)*(3*s**2 + 7*s - 3))*(s**2 - 4*s + 2), s) >>> G = TransferFunction(2*s**2 + 5*s + 1, s**2 + 2*s + 3, s) >>> C = TransferFunction(5*s + 10, s + 10, s) >>> F2 = Feedback(G*C, TransferFunction(1, 1, s)) >>> F2.doit() TransferFunction((s + 10)*(5*s + 10)*(s**2 + 2*s + 3)*(2*s**2 + 5*s + 1), (s + 10)*((s + 10)*(s**2 + 2*s + 3) + (5*s + 10)*(2*s**2 + 5*s + 1))*(s**2 + 2*s + 3), s) To negate a ``Feedback`` object, the ``-`` operator can be prepended: >>> -F1 Feedback(TransferFunction(-3*s**2 - 7*s + 3, s**2 - 4*s + 2, s), TransferFunction(5*s - 10, s + 7, s)) >>> -F2 Feedback(Series(TransferFunction(-1, 1, s), Series(TransferFunction(2*s**2 + 5*s + 1, s**2 + 2*s + 3, s), TransferFunction(5*s + 10, s + 10, s))), TransferFunction(1, 1, s)) See Also ======== TransferFunction, Series, Parallel """ def __new__(cls, num, den): if not (isinstance(num, (TransferFunction, Series)) and isinstance(den, (TransferFunction, Series))): raise TypeError("Unsupported type for numerator or denominator of Feedback.") if num == den: raise ValueError("The numerator cannot be equal to the denominator.") if not num.var == den.var: raise ValueError("Both numerator and denominator should be using the" " same complex variable.") obj = super().__new__(cls, num, den) obj._num = num obj._den = den obj._var = num.var return obj @property def num(self): """ Returns the primary plant of the negative feedback closed loop. Examples ======== >>> from sympy.abc import s, p >>> from sympy.physics.control.lti import TransferFunction, Feedback >>> plant = TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s) >>> controller = TransferFunction(5*s - 10, s + 7, s) >>> F1 = Feedback(plant, controller) >>> F1.num TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s) >>> G = TransferFunction(2*s**2 + 5*s + 1, p**2 + 2*p + 3, p) >>> C = TransferFunction(5*p + 10, p + 10, p) >>> P = TransferFunction(1 - s, p + 2, p) >>> F2 = Feedback(TransferFunction(1, 1, p), G*C*P) >>> F2.num TransferFunction(1, 1, p) """ return self._num @property def den(self): """ Returns the feedback plant (often a feedback controller) of the negative feedback closed loop. Examples ======== >>> from sympy.abc import s, p >>> from sympy.physics.control.lti import TransferFunction, Feedback >>> plant = TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s) >>> controller = TransferFunction(5*s - 10, s + 7, s) >>> F1 = Feedback(plant, controller) >>> F1.den TransferFunction(5*s - 10, s + 7, s) >>> G = TransferFunction(2*s**2 + 5*s + 1, p**2 + 2*p + 3, p) >>> C = TransferFunction(5*p + 10, p + 10, p) >>> P = TransferFunction(1 - s, p + 2, p) >>> F2 = Feedback(TransferFunction(1, 1, p), G*C*P) >>> F2.den Series(TransferFunction(2*s**2 + 5*s + 1, p**2 + 2*p + 3, p), TransferFunction(5*p + 10, p + 10, p), TransferFunction(1 - s, p + 2, p)) """ return self._den @property def var(self): """ Returns the complex variable of the Laplace transform used by all the transfer functions involved in the negative feedback closed loop. Examples ======== >>> from sympy.abc import s, p >>> from sympy.physics.control.lti import TransferFunction, Feedback >>> plant = TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s) >>> controller = TransferFunction(5*s - 10, s + 7, s) >>> F1 = Feedback(plant, controller) >>> F1.var s >>> G = TransferFunction(2*s**2 + 5*s + 1, p**2 + 2*p + 3, p) >>> C = TransferFunction(5*p + 10, p + 10, p) >>> P = TransferFunction(1 - s, p + 2, p) >>> F2 = Feedback(TransferFunction(1, 1, p), G*C*P) >>> F2.var p """ return self._var def doit(self, **kwargs): """ Returns the resultant closed loop transfer function obtained by the negative feedback interconnection. Examples ======== >>> from sympy.abc import s >>> from sympy.physics.control.lti import TransferFunction, Feedback >>> plant = TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s) >>> controller = TransferFunction(5*s - 10, s + 7, s) >>> F1 = Feedback(plant, controller) >>> F1.doit() TransferFunction((s + 7)*(s**2 - 4*s + 2)*(3*s**2 + 7*s - 3), ((s + 7)*(s**2 - 4*s + 2) + (5*s - 10)*(3*s**2 + 7*s - 3))*(s**2 - 4*s + 2), s) >>> G = TransferFunction(2*s**2 + 5*s + 1, s**2 + 2*s + 3, s) >>> F2 = Feedback(G, TransferFunction(1, 1, s)) >>> F2.doit() TransferFunction((s**2 + 2*s + 3)*(2*s**2 + 5*s + 1), (s**2 + 2*s + 3)*(3*s**2 + 7*s + 4), s) """ arg_list = list(self.num.args) if isinstance(self.num, Series) else [self.num] # F_n and F_d are resultant TFs of num and den of Feedback. F_n, tf = self.num.doit(), TransferFunction(1, 1, self.num.var) F_d = Parallel(tf, Series(self.den, *arg_list)).doit() return TransferFunction(F_n.num*F_d.den, F_n.den*F_d.num, F_n.var) def _eval_rewrite_as_TransferFunction(self, num, den, **kwargs): return self.doit() def __neg__(self): return Feedback(-self.num, self.den)
e72412b374b53665566a4f0918c48fe1f13fcbbedc013c7206c67b1a6d374116
"""A cache for storing small matrices in multiple formats.""" from sympy import Matrix, I, Pow, Rational, exp, pi from sympy.physics.quantum.matrixutils import ( to_sympy, to_numpy, to_scipy_sparse ) class MatrixCache: """A cache for small matrices in different formats. This class takes small matrices in the standard ``sympy.Matrix`` format, and then converts these to both ``numpy.matrix`` and ``scipy.sparse.csr_matrix`` matrices. These matrices are then stored for future recovery. """ def __init__(self, dtype='complex'): self._cache = {} self.dtype = dtype def cache_matrix(self, name, m): """Cache a matrix by its name. Parameters ---------- name : str A descriptive name for the matrix, like "identity2". m : list of lists The raw matrix data as a sympy Matrix. """ try: self._sympy_matrix(name, m) except ImportError: pass try: self._numpy_matrix(name, m) except ImportError: pass try: self._scipy_sparse_matrix(name, m) except ImportError: pass def get_matrix(self, name, format): """Get a cached matrix by name and format. Parameters ---------- name : str A descriptive name for the matrix, like "identity2". format : str The format desired ('sympy', 'numpy', 'scipy.sparse') """ m = self._cache.get((name, format)) if m is not None: return m raise NotImplementedError( 'Matrix with name %s and format %s is not available.' % (name, format) ) def _store_matrix(self, name, format, m): self._cache[(name, format)] = m def _sympy_matrix(self, name, m): self._store_matrix(name, 'sympy', to_sympy(m)) def _numpy_matrix(self, name, m): m = to_numpy(m, dtype=self.dtype) self._store_matrix(name, 'numpy', m) def _scipy_sparse_matrix(self, name, m): # TODO: explore different sparse formats. But sparse.kron will use # coo in most cases, so we use that here. m = to_scipy_sparse(m, dtype=self.dtype) self._store_matrix(name, 'scipy.sparse', m) sqrt2_inv = Pow(2, Rational(-1, 2), evaluate=False) # Save the common matrices that we will need matrix_cache = MatrixCache() matrix_cache.cache_matrix('eye2', Matrix([[1, 0], [0, 1]])) matrix_cache.cache_matrix('op11', Matrix([[0, 0], [0, 1]])) # |1><1| matrix_cache.cache_matrix('op00', Matrix([[1, 0], [0, 0]])) # |0><0| matrix_cache.cache_matrix('op10', Matrix([[0, 0], [1, 0]])) # |1><0| matrix_cache.cache_matrix('op01', Matrix([[0, 1], [0, 0]])) # |0><1| matrix_cache.cache_matrix('X', Matrix([[0, 1], [1, 0]])) matrix_cache.cache_matrix('Y', Matrix([[0, -I], [I, 0]])) matrix_cache.cache_matrix('Z', Matrix([[1, 0], [0, -1]])) matrix_cache.cache_matrix('S', Matrix([[1, 0], [0, I]])) matrix_cache.cache_matrix('T', Matrix([[1, 0], [0, exp(I*pi/4)]])) matrix_cache.cache_matrix('H', sqrt2_inv*Matrix([[1, 1], [1, -1]])) matrix_cache.cache_matrix('Hsqrt2', Matrix([[1, 1], [1, -1]])) matrix_cache.cache_matrix( 'SWAP', Matrix([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]])) matrix_cache.cache_matrix('ZX', sqrt2_inv*Matrix([[1, 1], [1, -1]])) matrix_cache.cache_matrix('ZY', Matrix([[I, 0], [0, -I]]))
8e0f41fc7eb5e3fb91a45c3f782328eb37f2df862de569a1ee350b7c92016030
"""An implementation of qubits and gates acting on them. Todo: * Update docstrings. * Update tests. * Implement apply using decompose. * Implement represent using decompose or something smarter. For this to work we first have to implement represent for SWAP. * Decide if we want upper index to be inclusive in the constructor. * Fix the printing of Rk gates in plotting. """ from sympy import Expr, Matrix, exp, I, pi, Integer, Symbol from sympy.functions import sqrt from sympy.physics.quantum.qapply import qapply from sympy.physics.quantum.qexpr import QuantumError, QExpr from sympy.matrices import eye from sympy.physics.quantum.tensorproduct import matrix_tensor_product from sympy.physics.quantum.gate import ( Gate, HadamardGate, SwapGate, OneQubitGate, CGate, PhaseGate, TGate, ZGate ) __all__ = [ 'QFT', 'IQFT', 'RkGate', 'Rk' ] #----------------------------------------------------------------------------- # Fourier stuff #----------------------------------------------------------------------------- class RkGate(OneQubitGate): """This is the R_k gate of the QTF.""" gate_name = 'Rk' gate_name_latex = 'R' def __new__(cls, *args): if len(args) != 2: raise QuantumError( 'Rk gates only take two arguments, got: %r' % args ) # For small k, Rk gates simplify to other gates, using these # substitutions give us familiar results for the QFT for small numbers # of qubits. target = args[0] k = args[1] if k == 1: return ZGate(target) elif k == 2: return PhaseGate(target) elif k == 3: return TGate(target) args = cls._eval_args(args) inst = Expr.__new__(cls, *args) inst.hilbert_space = cls._eval_hilbert_space(args) return inst @classmethod def _eval_args(cls, args): # Fall back to this, because Gate._eval_args assumes that args is # all targets and can't contain duplicates. return QExpr._eval_args(args) @property def k(self): return self.label[1] @property def targets(self): return self.label[:1] @property def gate_name_plot(self): return r'$%s_%s$' % (self.gate_name_latex, str(self.k)) def get_target_matrix(self, format='sympy'): if format == 'sympy': return Matrix([[1, 0], [0, exp(Integer(2)*pi*I/(Integer(2)**self.k))]]) raise NotImplementedError( 'Invalid format for the R_k gate: %r' % format) Rk = RkGate class Fourier(Gate): """Superclass of Quantum Fourier and Inverse Quantum Fourier Gates.""" @classmethod def _eval_args(self, args): if len(args) != 2: raise QuantumError( 'QFT/IQFT only takes two arguments, got: %r' % args ) if args[0] >= args[1]: raise QuantumError("Start must be smaller than finish") return Gate._eval_args(args) def _represent_default_basis(self, **options): return self._represent_ZGate(None, **options) def _represent_ZGate(self, basis, **options): """ Represents the (I)QFT In the Z Basis """ nqubits = options.get('nqubits', 0) if nqubits == 0: raise QuantumError( 'The number of qubits must be given as nqubits.') if nqubits < self.min_qubits: raise QuantumError( 'The number of qubits %r is too small for the gate.' % nqubits ) size = self.size omega = self.omega #Make a matrix that has the basic Fourier Transform Matrix arrayFT = [[omega**( i*j % size)/sqrt(size) for i in range(size)] for j in range(size)] matrixFT = Matrix(arrayFT) #Embed the FT Matrix in a higher space, if necessary if self.label[0] != 0: matrixFT = matrix_tensor_product(eye(2**self.label[0]), matrixFT) if self.min_qubits < nqubits: matrixFT = matrix_tensor_product( matrixFT, eye(2**(nqubits - self.min_qubits))) return matrixFT @property def targets(self): return range(self.label[0], self.label[1]) @property def min_qubits(self): return self.label[1] @property def size(self): """Size is the size of the QFT matrix""" return 2**(self.label[1] - self.label[0]) @property def omega(self): return Symbol('omega') class QFT(Fourier): """The forward quantum Fourier transform.""" gate_name = 'QFT' gate_name_latex = 'QFT' def decompose(self): """Decomposes QFT into elementary gates.""" start = self.label[0] finish = self.label[1] circuit = 1 for level in reversed(range(start, finish)): circuit = HadamardGate(level)*circuit for i in range(level - start): circuit = CGate(level - i - 1, RkGate(level, i + 2))*circuit for i in range((finish - start)//2): circuit = SwapGate(i + start, finish - i - 1)*circuit return circuit def _apply_operator_Qubit(self, qubits, **options): return qapply(self.decompose()*qubits) def _eval_inverse(self): return IQFT(*self.args) @property def omega(self): return exp(2*pi*I/self.size) class IQFT(Fourier): """The inverse quantum Fourier transform.""" gate_name = 'IQFT' gate_name_latex = '{QFT^{-1}}' def decompose(self): """Decomposes IQFT into elementary gates.""" start = self.args[0] finish = self.args[1] circuit = 1 for i in range((finish - start)//2): circuit = SwapGate(i + start, finish - i - 1)*circuit for level in range(start, finish): for i in reversed(range(level - start)): circuit = CGate(level - i - 1, RkGate(level, -i - 2))*circuit circuit = HadamardGate(level)*circuit return circuit def _eval_inverse(self): return QFT(*self.args) @property def omega(self): return exp(-2*pi*I/self.size)
4ff43b30be1e85463bfaca0bb1314007c2e6fda544acce777277066369cdfa4c
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 * np.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
5bcad852b875ebb9e465ca1709316c719d59bc14fa59790c7e62b3464b3779d1
""" A module for mapping operators to their corresponding eigenstates and vice versa It contains a global dictionary with eigenstate-operator pairings. If a new state-operator pair is created, this dictionary should be updated as well. It also contains functions operators_to_state and state_to_operators for mapping between the two. These can handle both classes and instances of operators and states. See the individual function descriptions for details. TODO List: - Update the dictionary with a complete list of state-operator pairs """ from sympy.physics.quantum.cartesian import (XOp, YOp, ZOp, XKet, PxOp, PxKet, PositionKet3D) from sympy.physics.quantum.operator import Operator from sympy.physics.quantum.state import StateBase, BraBase, Ket from sympy.physics.quantum.spin import (JxOp, JyOp, JzOp, J2Op, JxKet, JyKet, JzKet) __all__ = [ 'operators_to_state', 'state_to_operators' ] #state_mapping stores the mappings between states and their associated #operators or tuples of operators. This should be updated when new #classes are written! Entries are of the form PxKet : PxOp or #something like 3DKet : (ROp, ThetaOp, PhiOp) #frozenset is used so that the reverse mapping can be made #(regular sets are not hashable because they are mutable state_mapping = { JxKet: frozenset((J2Op, JxOp)), JyKet: frozenset((J2Op, JyOp)), JzKet: frozenset((J2Op, JzOp)), Ket: Operator, PositionKet3D: frozenset((XOp, YOp, ZOp)), PxKet: PxOp, XKet: XOp } op_mapping = {v: k for k, v in state_mapping.items()} def operators_to_state(operators, **options): """ Returns the eigenstate of the given operator or set of operators A global function for mapping operator classes to their associated states. It takes either an Operator or a set of operators and returns the state associated with these. This function can handle both instances of a given operator or just the class itself (i.e. both XOp() and XOp) There are multiple use cases to consider: 1) A class or set of classes is passed: First, we try to instantiate default instances for these operators. If this fails, then the class is simply returned. If we succeed in instantiating default instances, then we try to call state._operators_to_state on the operator instances. If this fails, the class is returned. Otherwise, the instance returned by _operators_to_state is returned. 2) An instance or set of instances is passed: In this case, state._operators_to_state is called on the instances passed. If this fails, a state class is returned. If the method returns an instance, that instance is returned. In both cases, if the operator class or set does not exist in the state_mapping dictionary, None is returned. Parameters ========== arg: Operator or set The class or instance of the operator or set of operators to be mapped to a state Examples ======== >>> from sympy.physics.quantum.cartesian import XOp, PxOp >>> from sympy.physics.quantum.operatorset import operators_to_state >>> from sympy.physics.quantum.operator import Operator >>> operators_to_state(XOp) |x> >>> operators_to_state(XOp()) |x> >>> operators_to_state(PxOp) |px> >>> operators_to_state(PxOp()) |px> >>> operators_to_state(Operator) |psi> >>> operators_to_state(Operator()) |psi> """ if not (isinstance(operators, Operator) or isinstance(operators, set) or issubclass(operators, Operator)): raise NotImplementedError("Argument is not an Operator or a set!") if isinstance(operators, set): for s in operators: if not (isinstance(s, Operator) or issubclass(s, Operator)): raise NotImplementedError("Set is not all Operators!") ops = frozenset(operators) if ops in op_mapping: # ops is a list of classes in this case #Try to get an object from default instances of the #operators...if this fails, return the class try: op_instances = [op() for op in ops] ret = _get_state(op_mapping[ops], set(op_instances), **options) except NotImplementedError: ret = op_mapping[ops] return ret else: tmp = [type(o) for o in ops] classes = frozenset(tmp) if classes in op_mapping: ret = _get_state(op_mapping[classes], ops, **options) else: ret = None return ret else: if operators in op_mapping: try: op_instance = operators() ret = _get_state(op_mapping[operators], op_instance, **options) except NotImplementedError: ret = op_mapping[operators] return ret elif type(operators) in op_mapping: return _get_state(op_mapping[type(operators)], operators, **options) else: return None def state_to_operators(state, **options): """ Returns the operator or set of operators corresponding to the given eigenstate A global function for mapping state classes to their associated operators or sets of operators. It takes either a state class or instance. This function can handle both instances of a given state or just the class itself (i.e. both XKet() and XKet) There are multiple use cases to consider: 1) A state class is passed: In this case, we first try instantiating a default instance of the class. If this succeeds, then we try to call state._state_to_operators on that instance. If the creation of the default instance or if the calling of _state_to_operators fails, then either an operator class or set of operator classes is returned. Otherwise, the appropriate operator instances are returned. 2) A state instance is returned: Here, state._state_to_operators is called for the instance. If this fails, then a class or set of operator classes is returned. Otherwise, the instances are returned. In either case, if the state's class does not exist in state_mapping, None is returned. Parameters ========== arg: StateBase class or instance (or subclasses) The class or instance of the state to be mapped to an operator or set of operators Examples ======== >>> from sympy.physics.quantum.cartesian import XKet, PxKet, XBra, PxBra >>> from sympy.physics.quantum.operatorset import state_to_operators >>> from sympy.physics.quantum.state import Ket, Bra >>> state_to_operators(XKet) X >>> state_to_operators(XKet()) X >>> state_to_operators(PxKet) Px >>> state_to_operators(PxKet()) Px >>> state_to_operators(PxBra) Px >>> state_to_operators(XBra) X >>> state_to_operators(Ket) O >>> state_to_operators(Bra) O """ if not (isinstance(state, StateBase) or issubclass(state, StateBase)): raise NotImplementedError("Argument is not a state!") if state in state_mapping: # state is a class state_inst = _make_default(state) try: ret = _get_ops(state_inst, _make_set(state_mapping[state]), **options) except (NotImplementedError, TypeError): ret = state_mapping[state] elif type(state) in state_mapping: ret = _get_ops(state, _make_set(state_mapping[type(state)]), **options) elif isinstance(state, BraBase) and state.dual_class() in state_mapping: ret = _get_ops(state, _make_set(state_mapping[state.dual_class()])) elif issubclass(state, BraBase) and state.dual_class() in state_mapping: state_inst = _make_default(state) try: ret = _get_ops(state_inst, _make_set(state_mapping[state.dual_class()])) except (NotImplementedError, TypeError): ret = state_mapping[state.dual_class()] else: ret = None return _make_set(ret) def _make_default(expr): # XXX: Catching TypeError like this is a bad way of distinguishing between # classes and instances. The logic using this function should be rewritten # somehow. try: ret = expr() except TypeError: ret = expr return ret def _get_state(state_class, ops, **options): # Try to get a state instance from the operator INSTANCES. # If this fails, get the class try: ret = state_class._operators_to_state(ops, **options) except NotImplementedError: ret = _make_default(state_class) return ret def _get_ops(state_inst, op_classes, **options): # Try to get operator instances from the state INSTANCE. # If this fails, just return the classes try: ret = state_inst._state_to_operators(op_classes, **options) except NotImplementedError: if isinstance(op_classes, (set, tuple, frozenset)): ret = tuple(_make_default(x) for x in op_classes) else: ret = _make_default(op_classes) if isinstance(ret, set) and len(ret) == 1: return ret[0] return ret def _make_set(ops): if isinstance(ops, (tuple, list, frozenset)): return set(ops) else: return ops
fef54326295f7076269662e5acb298f0b4df3756aaa3414c58a534cca6096644
"""Abstract tensor product.""" from sympy import Expr, Add, Mul, Matrix, Pow, sympify from sympy.core.trace import Tr from sympy.printing.pretty.stringpict import prettyForm from sympy.physics.quantum.qexpr import QuantumError from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.commutator import Commutator from sympy.physics.quantum.anticommutator import AntiCommutator from sympy.physics.quantum.state import Ket, Bra from sympy.physics.quantum.matrixutils import ( numpy_ndarray, scipy_sparse_matrix, matrix_tensor_product ) __all__ = [ 'TensorProduct', 'tensor_product_simp' ] #----------------------------------------------------------------------------- # Tensor product #----------------------------------------------------------------------------- _combined_printing = False def combined_tensor_printing(combined): """Set flag controlling whether tensor products of states should be printed as a combined bra/ket or as an explicit tensor product of different bra/kets. This is a global setting for all TensorProduct class instances. Parameters ---------- combine : bool When true, tensor product states are combined into one ket/bra, and when false explicit tensor product notation is used between each ket/bra. """ global _combined_printing _combined_printing = combined class TensorProduct(Expr): """The tensor product of two or more arguments. For matrices, this uses ``matrix_tensor_product`` to compute the Kronecker or tensor product matrix. For other objects a symbolic ``TensorProduct`` instance is returned. The tensor product is a non-commutative multiplication that is used primarily with operators and states in quantum mechanics. Currently, the tensor product distinguishes between commutative and non-commutative arguments. Commutative arguments are assumed to be scalars and are pulled out in front of the ``TensorProduct``. Non-commutative arguments remain in the resulting ``TensorProduct``. Parameters ========== args : tuple A sequence of the objects to take the tensor product of. Examples ======== Start with a simple tensor product of sympy matrices:: >>> from sympy import Matrix >>> from sympy.physics.quantum import TensorProduct >>> m1 = Matrix([[1,2],[3,4]]) >>> m2 = Matrix([[1,0],[0,1]]) >>> TensorProduct(m1, m2) Matrix([ [1, 0, 2, 0], [0, 1, 0, 2], [3, 0, 4, 0], [0, 3, 0, 4]]) >>> TensorProduct(m2, m1) Matrix([ [1, 2, 0, 0], [3, 4, 0, 0], [0, 0, 1, 2], [0, 0, 3, 4]]) We can also construct tensor products of non-commutative symbols: >>> from sympy import Symbol >>> A = Symbol('A',commutative=False) >>> B = Symbol('B',commutative=False) >>> tp = TensorProduct(A, B) >>> tp AxB We can take the dagger of a tensor product (note the order does NOT reverse like the dagger of a normal product): >>> from sympy.physics.quantum import Dagger >>> Dagger(tp) Dagger(A)xDagger(B) Expand can be used to distribute a tensor product across addition: >>> C = Symbol('C',commutative=False) >>> tp = TensorProduct(A+B,C) >>> tp (A + B)xC >>> tp.expand(tensorproduct=True) AxC + BxC """ is_commutative = False def __new__(cls, *args): if isinstance(args[0], (Matrix, numpy_ndarray, scipy_sparse_matrix)): return matrix_tensor_product(*args) c_part, new_args = cls.flatten(sympify(args)) c_part = Mul(*c_part) if len(new_args) == 0: return c_part elif len(new_args) == 1: return c_part * new_args[0] else: tp = Expr.__new__(cls, *new_args) return c_part * tp @classmethod def flatten(cls, args): # TODO: disallow nested TensorProducts. c_part = [] nc_parts = [] for arg in args: cp, ncp = arg.args_cnc() c_part.extend(list(cp)) nc_parts.append(Mul._from_args(ncp)) return c_part, nc_parts def _eval_adjoint(self): return TensorProduct(*[Dagger(i) for i in self.args]) def _eval_rewrite(self, pattern, rule, **hints): sargs = self.args terms = [t._eval_rewrite(pattern, rule, **hints) for t in sargs] return TensorProduct(*terms).expand(tensorproduct=True) def _sympystr(self, printer, *args): length = len(self.args) s = '' for i in range(length): if isinstance(self.args[i], (Add, Pow, Mul)): s = s + '(' s = s + printer._print(self.args[i]) if isinstance(self.args[i], (Add, Pow, Mul)): s = s + ')' if i != length - 1: s = s + 'x' return s def _pretty(self, printer, *args): if (_combined_printing and (all([isinstance(arg, Ket) for arg in self.args]) or all([isinstance(arg, Bra) for arg in self.args]))): length = len(self.args) pform = printer._print('', *args) for i in range(length): next_pform = printer._print('', *args) length_i = len(self.args[i].args) for j in range(length_i): part_pform = printer._print(self.args[i].args[j], *args) next_pform = prettyForm(*next_pform.right(part_pform)) if j != length_i - 1: next_pform = prettyForm(*next_pform.right(', ')) if len(self.args[i].args) > 1: next_pform = prettyForm( *next_pform.parens(left='{', right='}')) pform = prettyForm(*pform.right(next_pform)) if i != length - 1: pform = prettyForm(*pform.right(',' + ' ')) pform = prettyForm(*pform.left(self.args[0].lbracket)) pform = prettyForm(*pform.right(self.args[0].rbracket)) return pform length = len(self.args) pform = printer._print('', *args) for i in range(length): next_pform = printer._print(self.args[i], *args) if isinstance(self.args[i], (Add, Mul)): next_pform = prettyForm( *next_pform.parens(left='(', right=')') ) pform = prettyForm(*pform.right(next_pform)) if i != length - 1: if printer._use_unicode: pform = prettyForm(*pform.right('\N{N-ARY CIRCLED TIMES OPERATOR}' + ' ')) else: pform = prettyForm(*pform.right('x' + ' ')) return pform def _latex(self, printer, *args): if (_combined_printing and (all([isinstance(arg, Ket) for arg in self.args]) or all([isinstance(arg, Bra) for arg in self.args]))): def _label_wrap(label, nlabels): return label if nlabels == 1 else r"\left\{%s\right\}" % label s = r", ".join([_label_wrap(arg._print_label_latex(printer, *args), len(arg.args)) for arg in self.args]) return r"{%s%s%s}" % (self.args[0].lbracket_latex, s, self.args[0].rbracket_latex) length = len(self.args) s = '' for i in range(length): if isinstance(self.args[i], (Add, Mul)): s = s + '\\left(' # The extra {} brackets are needed to get matplotlib's latex # rendered to render this properly. s = s + '{' + printer._print(self.args[i], *args) + '}' if isinstance(self.args[i], (Add, Mul)): s = s + '\\right)' if i != length - 1: s = s + '\\otimes ' return s def doit(self, **hints): return TensorProduct(*[item.doit(**hints) for item in self.args]) def _eval_expand_tensorproduct(self, **hints): """Distribute TensorProducts across addition.""" args = self.args add_args = [] for i in range(len(args)): if isinstance(args[i], Add): for aa in args[i].args: tp = TensorProduct(*args[:i] + (aa,) + args[i + 1:]) if isinstance(tp, TensorProduct): tp = tp._eval_expand_tensorproduct() add_args.append(tp) break if add_args: return Add(*add_args) else: return self def _eval_trace(self, **kwargs): indices = kwargs.get('indices', None) exp = tensor_product_simp(self) if indices is None or len(indices) == 0: return Mul(*[Tr(arg).doit() for arg in exp.args]) else: return Mul(*[Tr(value).doit() if idx in indices else value for idx, value in enumerate(exp.args)]) def tensor_product_simp_Mul(e): """Simplify a Mul with TensorProducts. Current the main use of this is to simplify a ``Mul`` of ``TensorProduct``s to a ``TensorProduct`` of ``Muls``. It currently only works for relatively simple cases where the initial ``Mul`` only has scalars and raw ``TensorProduct``s, not ``Add``, ``Pow``, ``Commutator``s of ``TensorProduct``s. Parameters ========== e : Expr A ``Mul`` of ``TensorProduct``s to be simplified. Returns ======= e : Expr A ``TensorProduct`` of ``Mul``s. Examples ======== This is an example of the type of simplification that this function performs:: >>> from sympy.physics.quantum.tensorproduct import \ tensor_product_simp_Mul, TensorProduct >>> from sympy import Symbol >>> A = Symbol('A',commutative=False) >>> B = Symbol('B',commutative=False) >>> C = Symbol('C',commutative=False) >>> D = Symbol('D',commutative=False) >>> e = TensorProduct(A,B)*TensorProduct(C,D) >>> e AxB*CxD >>> tensor_product_simp_Mul(e) (A*C)x(B*D) """ # TODO: This won't work with Muls that have other composites of # TensorProducts, like an Add, Commutator, etc. # TODO: This only works for the equivalent of single Qbit gates. if not isinstance(e, Mul): return e c_part, nc_part = e.args_cnc() n_nc = len(nc_part) if n_nc == 0: return e elif n_nc == 1: if isinstance(nc_part[0], Pow): return Mul(*c_part) * tensor_product_simp_Pow(nc_part[0]) return e elif e.has(TensorProduct): current = nc_part[0] if not isinstance(current, TensorProduct): if isinstance(current, Pow): if isinstance(current.base, TensorProduct): current = tensor_product_simp_Pow(current) else: raise TypeError('TensorProduct expected, got: %r' % current) n_terms = len(current.args) new_args = list(current.args) for next in nc_part[1:]: # TODO: check the hilbert spaces of next and current here. if isinstance(next, TensorProduct): if n_terms != len(next.args): raise QuantumError( 'TensorProducts of different lengths: %r and %r' % (current, next) ) for i in range(len(new_args)): new_args[i] = new_args[i] * next.args[i] else: if isinstance(next, Pow): if isinstance(next.base, TensorProduct): new_tp = tensor_product_simp_Pow(next) for i in range(len(new_args)): new_args[i] = new_args[i] * new_tp.args[i] else: raise TypeError('TensorProduct expected, got: %r' % next) else: raise TypeError('TensorProduct expected, got: %r' % next) current = next return Mul(*c_part) * TensorProduct(*new_args) elif e.has(Pow): new_args = [ tensor_product_simp_Pow(nc) for nc in nc_part ] return tensor_product_simp_Mul(Mul(*c_part) * TensorProduct(*new_args)) else: return e def tensor_product_simp_Pow(e): """Evaluates ``Pow`` expressions whose base is ``TensorProduct``""" if not isinstance(e, Pow): return e if isinstance(e.base, TensorProduct): return TensorProduct(*[ b**e.exp for b in e.base.args]) else: return e def tensor_product_simp(e, **hints): """Try to simplify and combine TensorProducts. In general this will try to pull expressions inside of ``TensorProducts``. It currently only works for relatively simple cases where the products have only scalars, raw ``TensorProducts``, not ``Add``, ``Pow``, ``Commutators`` of ``TensorProducts``. It is best to see what it does by showing examples. Examples ======== >>> from sympy.physics.quantum import tensor_product_simp >>> from sympy.physics.quantum import TensorProduct >>> from sympy import Symbol >>> A = Symbol('A',commutative=False) >>> B = Symbol('B',commutative=False) >>> C = Symbol('C',commutative=False) >>> D = Symbol('D',commutative=False) First see what happens to products of tensor products: >>> e = TensorProduct(A,B)*TensorProduct(C,D) >>> e AxB*CxD >>> tensor_product_simp(e) (A*C)x(B*D) This is the core logic of this function, and it works inside, powers, sums, commutators and anticommutators as well: >>> tensor_product_simp(e**2) (A*C)x(B*D)**2 """ if isinstance(e, Add): return Add(*[tensor_product_simp(arg) for arg in e.args]) elif isinstance(e, Pow): if isinstance(e.base, TensorProduct): return tensor_product_simp_Pow(e) else: return tensor_product_simp(e.base) ** e.exp elif isinstance(e, Mul): return tensor_product_simp_Mul(e) elif isinstance(e, Commutator): return Commutator(*[tensor_product_simp(arg) for arg in e.args]) elif isinstance(e, AntiCommutator): return AntiCommutator(*[tensor_product_simp(arg) for arg in e.args]) else: return e
3e8bf3d5f13d4395e34fcf2c97f8b88201f1c7c8689d60fea102b83331a95aed
"""The anti-commutator: ``{A,B} = A*B + B*A``.""" from sympy import S, Expr, Mul, Integer from sympy.printing.pretty.stringpict import prettyForm from sympy.physics.quantum.operator import Operator from sympy.physics.quantum.dagger import Dagger __all__ = [ 'AntiCommutator' ] #----------------------------------------------------------------------------- # Anti-commutator #----------------------------------------------------------------------------- class AntiCommutator(Expr): """The standard anticommutator, in an unevaluated state. Evaluating an anticommutator is defined [1]_ as: ``{A, B} = A*B + B*A``. This class returns the anticommutator in an unevaluated form. To evaluate the anticommutator, use the ``.doit()`` method. Canonical ordering of an anticommutator is ``{A, B}`` for ``A < B``. The arguments of the anticommutator are put into canonical order using ``__cmp__``. If ``B < A``, then ``{A, B}`` is returned as ``{B, A}``. Parameters ========== A : Expr The first argument of the anticommutator {A,B}. B : Expr The second argument of the anticommutator {A,B}. Examples ======== >>> from sympy import symbols >>> from sympy.physics.quantum import AntiCommutator >>> from sympy.physics.quantum import Operator, Dagger >>> x, y = symbols('x,y') >>> A = Operator('A') >>> B = Operator('B') Create an anticommutator and use ``doit()`` to multiply them out. >>> ac = AntiCommutator(A,B); ac {A,B} >>> ac.doit() A*B + B*A The commutator orders it arguments in canonical order: >>> ac = AntiCommutator(B,A); ac {A,B} Commutative constants are factored out: >>> AntiCommutator(3*x*A,x*y*B) 3*x**2*y*{A,B} Adjoint operations applied to the anticommutator are properly applied to the arguments: >>> Dagger(AntiCommutator(A,B)) {Dagger(A),Dagger(B)} References ========== .. [1] https://en.wikipedia.org/wiki/Commutator """ is_commutative = False def __new__(cls, A, B): r = cls.eval(A, B) if r is not None: return r obj = Expr.__new__(cls, A, B) return obj @classmethod def eval(cls, a, b): if not (a and b): return S.Zero if a == b: return Integer(2)*a**2 if a.is_commutative or b.is_commutative: return Integer(2)*a*b # [xA,yB] -> xy*[A,B] ca, nca = a.args_cnc() cb, ncb = b.args_cnc() c_part = ca + cb if c_part: return Mul(Mul(*c_part), cls(Mul._from_args(nca), Mul._from_args(ncb))) # Canonical ordering of arguments #The Commutator [A,B] is on canonical form if A < B. if a.compare(b) == 1: return cls(b, a) def doit(self, **hints): """ Evaluate anticommutator """ A = self.args[0] B = self.args[1] if isinstance(A, Operator) and isinstance(B, Operator): try: comm = A._eval_anticommutator(B, **hints) except NotImplementedError: try: comm = B._eval_anticommutator(A, **hints) except NotImplementedError: comm = None if comm is not None: return comm.doit(**hints) return (A*B + B*A).doit(**hints) def _eval_adjoint(self): return AntiCommutator(Dagger(self.args[0]), Dagger(self.args[1])) def _sympyrepr(self, printer, *args): return "%s(%s,%s)" % ( self.__class__.__name__, printer._print( self.args[0]), printer._print(self.args[1]) ) def _sympystr(self, printer, *args): return "{%s,%s}" % ( printer._print(self.args[0]), printer._print(self.args[1])) def _pretty(self, printer, *args): pform = printer._print(self.args[0], *args) pform = prettyForm(*pform.right(prettyForm(','))) pform = prettyForm(*pform.right(printer._print(self.args[1], *args))) pform = prettyForm(*pform.parens(left='{', right='}')) return pform def _latex(self, printer, *args): return "\\left\\{%s,%s\\right\\}" % tuple([ printer._print(arg, *args) for arg in self.args])
55b5bb505c06556e26168bf63629121c042a5b450c939f861ea698ebaf2015fa
"""Dirac notation for states.""" from sympy import (cacheit, conjugate, Expr, Function, integrate, oo, sqrt, Tuple) from sympy.printing.pretty.stringpict import stringPict from sympy.physics.quantum.qexpr import QExpr, dispatch_method __all__ = [ 'KetBase', 'BraBase', 'StateBase', 'State', 'Ket', 'Bra', 'TimeDepState', 'TimeDepBra', 'TimeDepKet', 'OrthogonalKet', 'OrthogonalBra', 'OrthogonalState', 'Wavefunction' ] #----------------------------------------------------------------------------- # States, bras and kets. #----------------------------------------------------------------------------- # ASCII brackets _lbracket = "<" _rbracket = ">" _straight_bracket = "|" # Unicode brackets # MATHEMATICAL ANGLE BRACKETS _lbracket_ucode = "\N{MATHEMATICAL LEFT ANGLE BRACKET}" _rbracket_ucode = "\N{MATHEMATICAL RIGHT ANGLE BRACKET}" # LIGHT VERTICAL BAR _straight_bracket_ucode = "\N{LIGHT VERTICAL BAR}" # Other options for unicode printing of <, > and | for Dirac notation. # LEFT-POINTING ANGLE BRACKET # _lbracket = "\u2329" # _rbracket = "\u232A" # LEFT ANGLE BRACKET # _lbracket = "\u3008" # _rbracket = "\u3009" # VERTICAL LINE # _straight_bracket = "\u007C" class StateBase(QExpr): """Abstract base class for general abstract states in quantum mechanics. All other state classes defined will need to inherit from this class. It carries the basic structure for all other states such as dual, _eval_adjoint and label. This is an abstract base class and you should not instantiate it directly, instead use State. """ @classmethod def _operators_to_state(self, ops, **options): """ Returns the eigenstate instance for the passed operators. This method should be overridden in subclasses. It will handle being passed either an Operator instance or set of Operator instances. It should return the corresponding state INSTANCE or simply raise a NotImplementedError. See cartesian.py for an example. """ raise NotImplementedError("Cannot map operators to states in this class. Method not implemented!") def _state_to_operators(self, op_classes, **options): """ Returns the operators which this state instance is an eigenstate of. This method should be overridden in subclasses. It will be called on state instances and be passed the operator classes that we wish to make into instances. The state instance will then transform the classes appropriately, or raise a NotImplementedError if it cannot return operator instances. See cartesian.py for examples, """ raise NotImplementedError( "Cannot map this state to operators. Method not implemented!") @property def operators(self): """Return the operator(s) that this state is an eigenstate of""" from .operatorset import state_to_operators # import internally to avoid circular import errors return state_to_operators(self) def _enumerate_state(self, num_states, **options): raise NotImplementedError("Cannot enumerate this state!") def _represent_default_basis(self, **options): return self._represent(basis=self.operators) #------------------------------------------------------------------------- # Dagger/dual #------------------------------------------------------------------------- @property def dual(self): """Return the dual state of this one.""" return self.dual_class()._new_rawargs(self.hilbert_space, *self.args) @classmethod def dual_class(self): """Return the class used to construct the dual.""" raise NotImplementedError( 'dual_class must be implemented in a subclass' ) def _eval_adjoint(self): """Compute the dagger of this state using the dual.""" return self.dual #------------------------------------------------------------------------- # Printing #------------------------------------------------------------------------- def _pretty_brackets(self, height, use_unicode=True): # Return pretty printed brackets for the state # Ideally, this could be done by pform.parens but it does not support the angled < and > # Setup for unicode vs ascii if use_unicode: lbracket, rbracket = self.lbracket_ucode, self.rbracket_ucode slash, bslash, vert = '\N{BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT}', \ '\N{BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT}', \ '\N{BOX DRAWINGS LIGHT VERTICAL}' else: lbracket, rbracket = self.lbracket, self.rbracket slash, bslash, vert = '/', '\\', '|' # If height is 1, just return brackets if height == 1: return stringPict(lbracket), stringPict(rbracket) # Make height even height += (height % 2) brackets = [] for bracket in lbracket, rbracket: # Create left bracket if bracket in {_lbracket, _lbracket_ucode}: bracket_args = [ ' ' * (height//2 - i - 1) + slash for i in range(height // 2)] bracket_args.extend( [ ' ' * i + bslash for i in range(height // 2)]) # Create right bracket elif bracket in {_rbracket, _rbracket_ucode}: bracket_args = [ ' ' * i + bslash for i in range(height // 2)] bracket_args.extend([ ' ' * ( height//2 - i - 1) + slash for i in range(height // 2)]) # Create straight bracket elif bracket in {_straight_bracket, _straight_bracket_ucode}: bracket_args = [vert for i in range(height)] else: raise ValueError(bracket) brackets.append( stringPict('\n'.join(bracket_args), baseline=height//2)) return brackets def _sympystr(self, printer, *args): contents = self._print_contents(printer, *args) return '%s%s%s' % (self.lbracket, contents, self.rbracket) def _pretty(self, printer, *args): from sympy.printing.pretty.stringpict import prettyForm # Get brackets pform = self._print_contents_pretty(printer, *args) lbracket, rbracket = self._pretty_brackets( pform.height(), printer._use_unicode) # Put together state pform = prettyForm(*pform.left(lbracket)) pform = prettyForm(*pform.right(rbracket)) return pform def _latex(self, printer, *args): contents = self._print_contents_latex(printer, *args) # The extra {} brackets are needed to get matplotlib's latex # rendered to render this properly. return '{%s%s%s}' % (self.lbracket_latex, contents, self.rbracket_latex) class KetBase(StateBase): """Base class for Kets. This class defines the dual property and the brackets for printing. This is an abstract base class and you should not instantiate it directly, instead use Ket. """ lbracket = _straight_bracket rbracket = _rbracket lbracket_ucode = _straight_bracket_ucode rbracket_ucode = _rbracket_ucode lbracket_latex = r'\left|' rbracket_latex = r'\right\rangle ' @classmethod def default_args(self): return ("psi",) @classmethod def dual_class(self): return BraBase def __mul__(self, other): """KetBase*other""" from sympy.physics.quantum.operator import OuterProduct if isinstance(other, BraBase): return OuterProduct(self, other) else: return Expr.__mul__(self, other) def __rmul__(self, other): """other*KetBase""" from sympy.physics.quantum.innerproduct import InnerProduct if isinstance(other, BraBase): return InnerProduct(other, self) else: return Expr.__rmul__(self, other) #------------------------------------------------------------------------- # _eval_* methods #------------------------------------------------------------------------- def _eval_innerproduct(self, bra, **hints): """Evaluate the inner product between this ket and a bra. This is called to compute <bra|ket>, where the ket is ``self``. This method will dispatch to sub-methods having the format:: ``def _eval_innerproduct_BraClass(self, **hints):`` Subclasses should define these methods (one for each BraClass) to teach the ket how to take inner products with bras. """ return dispatch_method(self, '_eval_innerproduct', bra, **hints) def _apply_operator(self, op, **options): """Apply an Operator to this Ket. This method will dispatch to methods having the format:: ``def _apply_operator_OperatorName(op, **options):`` Subclasses should define these methods (one for each OperatorName) to teach the Ket how operators act on it. Parameters ========== op : Operator The Operator that is acting on the Ket. options : dict A dict of key/value pairs that control how the operator is applied to the Ket. """ return dispatch_method(self, '_apply_operator', op, **options) class BraBase(StateBase): """Base class for Bras. This class defines the dual property and the brackets for printing. This is an abstract base class and you should not instantiate it directly, instead use Bra. """ lbracket = _lbracket rbracket = _straight_bracket lbracket_ucode = _lbracket_ucode rbracket_ucode = _straight_bracket_ucode lbracket_latex = r'\left\langle ' rbracket_latex = r'\right|' @classmethod def _operators_to_state(self, ops, **options): state = self.dual_class()._operators_to_state(ops, **options) return state.dual def _state_to_operators(self, op_classes, **options): return self.dual._state_to_operators(op_classes, **options) def _enumerate_state(self, num_states, **options): dual_states = self.dual._enumerate_state(num_states, **options) return [x.dual for x in dual_states] @classmethod def default_args(self): return self.dual_class().default_args() @classmethod def dual_class(self): return KetBase def __mul__(self, other): """BraBase*other""" from sympy.physics.quantum.innerproduct import InnerProduct if isinstance(other, KetBase): return InnerProduct(self, other) else: return Expr.__mul__(self, other) def __rmul__(self, other): """other*BraBase""" from sympy.physics.quantum.operator import OuterProduct if isinstance(other, KetBase): return OuterProduct(other, self) else: return Expr.__rmul__(self, other) def _represent(self, **options): """A default represent that uses the Ket's version.""" from sympy.physics.quantum.dagger import Dagger return Dagger(self.dual._represent(**options)) class State(StateBase): """General abstract quantum state used as a base class for Ket and Bra.""" pass class Ket(State, KetBase): """A general time-independent Ket in quantum mechanics. Inherits from State and KetBase. This class should be used as the base class for all physical, time-independent Kets in a system. This class and its subclasses will be the main classes that users will use for expressing Kets in Dirac notation [1]_. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the ket. This will usually be its symbol or its quantum numbers. For time-dependent state, this will include the time. Examples ======== Create a simple Ket and looking at its properties:: >>> from sympy.physics.quantum import Ket >>> from sympy import symbols, I >>> k = Ket('psi') >>> k |psi> >>> k.hilbert_space H >>> k.is_commutative False >>> k.label (psi,) Ket's know about their associated bra:: >>> k.dual <psi| >>> k.dual_class() <class 'sympy.physics.quantum.state.Bra'> Take a linear combination of two kets:: >>> k0 = Ket(0) >>> k1 = Ket(1) >>> 2*I*k0 - 4*k1 2*I*|0> - 4*|1> Compound labels are passed as tuples:: >>> n, m = symbols('n,m') >>> k = Ket(n,m) >>> k |nm> References ========== .. [1] https://en.wikipedia.org/wiki/Bra-ket_notation """ @classmethod def dual_class(self): return Bra class Bra(State, BraBase): """A general time-independent Bra in quantum mechanics. Inherits from State and BraBase. A Bra is the dual of a Ket [1]_. This class and its subclasses will be the main classes that users will use for expressing Bras in Dirac notation. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the ket. This will usually be its symbol or its quantum numbers. For time-dependent state, this will include the time. Examples ======== Create a simple Bra and look at its properties:: >>> from sympy.physics.quantum import Bra >>> from sympy import symbols, I >>> b = Bra('psi') >>> b <psi| >>> b.hilbert_space H >>> b.is_commutative False Bra's know about their dual Ket's:: >>> b.dual |psi> >>> b.dual_class() <class 'sympy.physics.quantum.state.Ket'> Like Kets, Bras can have compound labels and be manipulated in a similar manner:: >>> n, m = symbols('n,m') >>> b = Bra(n,m) - I*Bra(m,n) >>> b -I*<mn| + <nm| Symbols in a Bra can be substituted using ``.subs``:: >>> b.subs(n,m) <mm| - I*<mm| References ========== .. [1] https://en.wikipedia.org/wiki/Bra-ket_notation """ @classmethod def dual_class(self): return Ket #----------------------------------------------------------------------------- # Time dependent states, bras and kets. #----------------------------------------------------------------------------- class TimeDepState(StateBase): """Base class for a general time-dependent quantum state. This class is used as a base class for any time-dependent state. The main difference between this class and the time-independent state is that this class takes a second argument that is the time in addition to the usual label argument. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the ket. This will usually be its symbol or its quantum numbers. For time-dependent state, this will include the time as the final argument. """ #------------------------------------------------------------------------- # Initialization #------------------------------------------------------------------------- @classmethod def default_args(self): return ("psi", "t") #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def label(self): """The label of the state.""" return self.args[:-1] @property def time(self): """The time of the state.""" return self.args[-1] #------------------------------------------------------------------------- # Printing #------------------------------------------------------------------------- def _print_time(self, printer, *args): return printer._print(self.time, *args) _print_time_repr = _print_time _print_time_latex = _print_time def _print_time_pretty(self, printer, *args): pform = printer._print(self.time, *args) return pform def _print_contents(self, printer, *args): label = self._print_label(printer, *args) time = self._print_time(printer, *args) return '%s;%s' % (label, time) def _print_label_repr(self, printer, *args): label = self._print_sequence(self.label, ',', printer, *args) time = self._print_time_repr(printer, *args) return '%s,%s' % (label, time) def _print_contents_pretty(self, printer, *args): label = self._print_label_pretty(printer, *args) time = self._print_time_pretty(printer, *args) return printer._print_seq((label, time), delimiter=';') def _print_contents_latex(self, printer, *args): label = self._print_sequence( self.label, self._label_separator, printer, *args) time = self._print_time_latex(printer, *args) return '%s;%s' % (label, time) class TimeDepKet(TimeDepState, KetBase): """General time-dependent Ket in quantum mechanics. This inherits from ``TimeDepState`` and ``KetBase`` and is the main class that should be used for Kets that vary with time. Its dual is a ``TimeDepBra``. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the ket. This will usually be its symbol or its quantum numbers. For time-dependent state, this will include the time as the final argument. Examples ======== Create a TimeDepKet and look at its attributes:: >>> from sympy.physics.quantum import TimeDepKet >>> k = TimeDepKet('psi', 't') >>> k |psi;t> >>> k.time t >>> k.label (psi,) >>> k.hilbert_space H TimeDepKets know about their dual bra:: >>> k.dual <psi;t| >>> k.dual_class() <class 'sympy.physics.quantum.state.TimeDepBra'> """ @classmethod def dual_class(self): return TimeDepBra class TimeDepBra(TimeDepState, BraBase): """General time-dependent Bra in quantum mechanics. This inherits from TimeDepState and BraBase and is the main class that should be used for Bras that vary with time. Its dual is a TimeDepBra. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the ket. This will usually be its symbol or its quantum numbers. For time-dependent state, this will include the time as the final argument. Examples ======== >>> from sympy.physics.quantum import TimeDepBra >>> b = TimeDepBra('psi', 't') >>> b <psi;t| >>> b.time t >>> b.label (psi,) >>> b.hilbert_space H >>> b.dual |psi;t> """ @classmethod def dual_class(self): return TimeDepKet class OrthogonalState(State, StateBase): """General abstract quantum state used as a base class for Ket and Bra.""" pass class OrthogonalKet(OrthogonalState, KetBase): """Orthogonal Ket in quantum mechanics. The inner product of two states with different labels will give zero, states with the same label will give one. >>> from sympy.physics.quantum import OrthogonalBra, OrthogonalKet >>> from sympy.abc import m, n >>> (OrthogonalBra(n)*OrthogonalKet(n)).doit() 1 >>> (OrthogonalBra(n)*OrthogonalKet(n+1)).doit() 0 >>> (OrthogonalBra(n)*OrthogonalKet(m)).doit() <n|m> """ @classmethod def dual_class(self): return OrthogonalBra def _eval_innerproduct(self, bra, **hints): if len(self.args) != len(bra.args): raise ValueError('Cannot multiply a ket that has a different number of labels.') for i in range(len(self.args)): diff = self.args[i] - bra.args[i] diff = diff.expand() if diff.is_zero is False: return 0 if diff.is_zero is None: return None return 1 class OrthogonalBra(OrthogonalState, BraBase): """Orthogonal Bra in quantum mechanics. """ @classmethod def dual_class(self): return OrthogonalKet class Wavefunction(Function): """Class for representations in continuous bases This class takes an expression and coordinates in its constructor. It can be used to easily calculate normalizations and probabilities. Parameters ========== expr : Expr The expression representing the functional form of the w.f. coords : Symbol or tuple The coordinates to be integrated over, and their bounds Examples ======== Particle in a box, specifying bounds in the more primitive way of using Piecewise: >>> from sympy import Symbol, Piecewise, pi, N >>> from sympy.functions import sqrt, sin >>> from sympy.physics.quantum.state import Wavefunction >>> x = Symbol('x', real=True) >>> n = 1 >>> L = 1 >>> g = Piecewise((0, x < 0), (0, x > L), (sqrt(2//L)*sin(n*pi*x/L), True)) >>> f = Wavefunction(g, x) >>> f.norm 1 >>> f.is_normalized True >>> p = f.prob() >>> p(0) 0 >>> p(L) 0 >>> p(0.5) 2 >>> p(0.85*L) 2*sin(0.85*pi)**2 >>> N(p(0.85*L)) 0.412214747707527 Additionally, you can specify the bounds of the function and the indices in a more compact way: >>> from sympy import symbols, pi, diff >>> from sympy.functions import sqrt, sin >>> from sympy.physics.quantum.state import Wavefunction >>> x, L = symbols('x,L', positive=True) >>> n = symbols('n', integer=True, positive=True) >>> g = sqrt(2/L)*sin(n*pi*x/L) >>> f = Wavefunction(g, (x, 0, L)) >>> f.norm 1 >>> f(L+1) 0 >>> f(L-1) sqrt(2)*sin(pi*n*(L - 1)/L)/sqrt(L) >>> f(-1) 0 >>> f(0.85) sqrt(2)*sin(0.85*pi*n/L)/sqrt(L) >>> f(0.85, n=1, L=1) sqrt(2)*sin(0.85*pi) >>> f.is_commutative False All arguments are automatically sympified, so you can define the variables as strings rather than symbols: >>> expr = x**2 >>> f = Wavefunction(expr, 'x') >>> type(f.variables[0]) <class 'sympy.core.symbol.Symbol'> Derivatives of Wavefunctions will return Wavefunctions: >>> diff(f, x) Wavefunction(2*x, x) """ #Any passed tuples for coordinates and their bounds need to be #converted to Tuples before Function's constructor is called, to #avoid errors from calling is_Float in the constructor def __new__(cls, *args, **options): new_args = [None for i in args] ct = 0 for arg in args: if isinstance(arg, tuple): new_args[ct] = Tuple(*arg) else: new_args[ct] = arg ct += 1 return super().__new__(cls, *new_args, **options) def __call__(self, *args, **options): var = self.variables if len(args) != len(var): raise NotImplementedError( "Incorrect number of arguments to function!") ct = 0 #If the passed value is outside the specified bounds, return 0 for v in var: lower, upper = self.limits[v] #Do the comparison to limits only if the passed symbol is actually #a symbol present in the limits; #Had problems with a comparison of x > L if isinstance(args[ct], Expr) and \ not (lower in args[ct].free_symbols or upper in args[ct].free_symbols): continue if (args[ct] < lower) == True or (args[ct] > upper) == True: return 0 ct += 1 expr = self.expr #Allows user to make a call like f(2, 4, m=1, n=1) for symbol in list(expr.free_symbols): if str(symbol) in options.keys(): val = options[str(symbol)] expr = expr.subs(symbol, val) return expr.subs(zip(var, args)) def _eval_derivative(self, symbol): expr = self.expr deriv = expr._eval_derivative(symbol) return Wavefunction(deriv, *self.args[1:]) def _eval_conjugate(self): return Wavefunction(conjugate(self.expr), *self.args[1:]) def _eval_transpose(self): return self @property def free_symbols(self): return self.expr.free_symbols @property def is_commutative(self): """ Override Function's is_commutative so that order is preserved in represented expressions """ return False @classmethod def eval(self, *args): return None @property def variables(self): """ Return the coordinates which the wavefunction depends on Examples ======== >>> from sympy.physics.quantum.state import Wavefunction >>> from sympy import symbols >>> x,y = symbols('x,y') >>> f = Wavefunction(x*y, x, y) >>> f.variables (x, y) >>> g = Wavefunction(x*y, x) >>> g.variables (x,) """ var = [g[0] if isinstance(g, Tuple) else g for g in self._args[1:]] return tuple(var) @property def limits(self): """ Return the limits of the coordinates which the w.f. depends on If no limits are specified, defaults to ``(-oo, oo)``. Examples ======== >>> from sympy.physics.quantum.state import Wavefunction >>> from sympy import symbols >>> x, y = symbols('x, y') >>> f = Wavefunction(x**2, (x, 0, 1)) >>> f.limits {x: (0, 1)} >>> f = Wavefunction(x**2, x) >>> f.limits {x: (-oo, oo)} >>> f = Wavefunction(x**2 + y**2, x, (y, -1, 2)) >>> f.limits {x: (-oo, oo), y: (-1, 2)} """ limits = [(g[1], g[2]) if isinstance(g, Tuple) else (-oo, oo) for g in self._args[1:]] return dict(zip(self.variables, tuple(limits))) @property def expr(self): """ Return the expression which is the functional form of the Wavefunction Examples ======== >>> from sympy.physics.quantum.state import Wavefunction >>> from sympy import symbols >>> x, y = symbols('x, y') >>> f = Wavefunction(x**2, x) >>> f.expr x**2 """ return self._args[0] @property def is_normalized(self): """ Returns true if the Wavefunction is properly normalized Examples ======== >>> from sympy import symbols, pi >>> from sympy.functions import sqrt, sin >>> from sympy.physics.quantum.state import Wavefunction >>> x, L = symbols('x,L', positive=True) >>> n = symbols('n', integer=True, positive=True) >>> g = sqrt(2/L)*sin(n*pi*x/L) >>> f = Wavefunction(g, (x, 0, L)) >>> f.is_normalized True """ return (self.norm == 1.0) @property # type: ignore @cacheit def norm(self): """ Return the normalization of the specified functional form. This function integrates over the coordinates of the Wavefunction, with the bounds specified. Examples ======== >>> from sympy import symbols, pi >>> from sympy.functions import sqrt, sin >>> from sympy.physics.quantum.state import Wavefunction >>> x, L = symbols('x,L', positive=True) >>> n = symbols('n', integer=True, positive=True) >>> g = sqrt(2/L)*sin(n*pi*x/L) >>> f = Wavefunction(g, (x, 0, L)) >>> f.norm 1 >>> g = sin(n*pi*x/L) >>> f = Wavefunction(g, (x, 0, L)) >>> f.norm sqrt(2)*sqrt(L)/2 """ exp = self.expr*conjugate(self.expr) var = self.variables limits = self.limits for v in var: curr_limits = limits[v] exp = integrate(exp, (v, curr_limits[0], curr_limits[1])) return sqrt(exp) def normalize(self): """ Return a normalized version of the Wavefunction Examples ======== >>> from sympy import symbols, pi >>> from sympy.functions import sin >>> from sympy.physics.quantum.state import Wavefunction >>> x = symbols('x', real=True) >>> L = symbols('L', positive=True) >>> n = symbols('n', integer=True, positive=True) >>> g = sin(n*pi*x/L) >>> f = Wavefunction(g, (x, 0, L)) >>> f.normalize() Wavefunction(sqrt(2)*sin(pi*n*x/L)/sqrt(L), (x, 0, L)) """ const = self.norm if const is oo: raise NotImplementedError("The function is not normalizable!") else: return Wavefunction((const)**(-1)*self.expr, *self.args[1:]) def prob(self): r""" Return the absolute magnitude of the w.f., `|\psi(x)|^2` Examples ======== >>> from sympy import symbols, pi >>> from sympy.functions import sin >>> from sympy.physics.quantum.state import Wavefunction >>> x, L = symbols('x,L', real=True) >>> n = symbols('n', integer=True) >>> g = sin(n*pi*x/L) >>> f = Wavefunction(g, (x, 0, L)) >>> f.prob() Wavefunction(sin(pi*n*x/L)**2, x) """ return Wavefunction(self.expr*conjugate(self.expr), *self.variables)
60c92c111e3d64bb6adb5e0d3d4dae0318b0e4f6b9fffdbf208c14f51692423a
"""Operators and states for 1D cartesian position and momentum. TODO: * Add 3D classes to mappings in operatorset.py """ from sympy import DiracDelta, exp, I, Interval, pi, S, sqrt from sympy.physics.quantum.constants import hbar from sympy.physics.quantum.hilbert import L2 from sympy.physics.quantum.operator import DifferentialOperator, HermitianOperator from sympy.physics.quantum.state import Ket, Bra, State __all__ = [ 'XOp', 'YOp', 'ZOp', 'PxOp', 'X', 'Y', 'Z', 'Px', 'XKet', 'XBra', 'PxKet', 'PxBra', 'PositionState3D', 'PositionKet3D', 'PositionBra3D' ] #------------------------------------------------------------------------- # Position operators #------------------------------------------------------------------------- class XOp(HermitianOperator): """1D cartesian position operator.""" @classmethod def default_args(self): return ("X",) @classmethod def _eval_hilbert_space(self, args): return L2(Interval(S.NegativeInfinity, S.Infinity)) def _eval_commutator_PxOp(self, other): return I*hbar def _apply_operator_XKet(self, ket): return ket.position*ket def _apply_operator_PositionKet3D(self, ket): return ket.position_x*ket def _represent_PxKet(self, basis, *, index=1, **options): states = basis._enumerate_state(2, start_index=index) coord1 = states[0].momentum coord2 = states[1].momentum d = DifferentialOperator(coord1) delta = DiracDelta(coord1 - coord2) return I*hbar*(d*delta) class YOp(HermitianOperator): """ Y cartesian coordinate operator (for 2D or 3D systems) """ @classmethod def default_args(self): return ("Y",) @classmethod def _eval_hilbert_space(self, args): return L2(Interval(S.NegativeInfinity, S.Infinity)) def _apply_operator_PositionKet3D(self, ket): return ket.position_y*ket class ZOp(HermitianOperator): """ Z cartesian coordinate operator (for 3D systems) """ @classmethod def default_args(self): return ("Z",) @classmethod def _eval_hilbert_space(self, args): return L2(Interval(S.NegativeInfinity, S.Infinity)) def _apply_operator_PositionKet3D(self, ket): return ket.position_z*ket #------------------------------------------------------------------------- # Momentum operators #------------------------------------------------------------------------- class PxOp(HermitianOperator): """1D cartesian momentum operator.""" @classmethod def default_args(self): return ("Px",) @classmethod def _eval_hilbert_space(self, args): return L2(Interval(S.NegativeInfinity, S.Infinity)) def _apply_operator_PxKet(self, ket): return ket.momentum*ket def _represent_XKet(self, basis, *, index=1, **options): states = basis._enumerate_state(2, start_index=index) coord1 = states[0].position coord2 = states[1].position d = DifferentialOperator(coord1) delta = DiracDelta(coord1 - coord2) return -I*hbar*(d*delta) X = XOp('X') Y = YOp('Y') Z = ZOp('Z') Px = PxOp('Px') #------------------------------------------------------------------------- # Position eigenstates #------------------------------------------------------------------------- class XKet(Ket): """1D cartesian position eigenket.""" @classmethod def _operators_to_state(self, op, **options): return self.__new__(self, *_lowercase_labels(op), **options) def _state_to_operators(self, op_class, **options): return op_class.__new__(op_class, *_uppercase_labels(self), **options) @classmethod def default_args(self): return ("x",) @classmethod def dual_class(self): return XBra @property def position(self): """The position of the state.""" return self.label[0] def _enumerate_state(self, num_states, **options): return _enumerate_continuous_1D(self, num_states, **options) def _eval_innerproduct_XBra(self, bra, **hints): return DiracDelta(self.position - bra.position) def _eval_innerproduct_PxBra(self, bra, **hints): return exp(-I*self.position*bra.momentum/hbar)/sqrt(2*pi*hbar) class XBra(Bra): """1D cartesian position eigenbra.""" @classmethod def default_args(self): return ("x",) @classmethod def dual_class(self): return XKet @property def position(self): """The position of the state.""" return self.label[0] class PositionState3D(State): """ Base class for 3D cartesian position eigenstates """ @classmethod def _operators_to_state(self, op, **options): return self.__new__(self, *_lowercase_labels(op), **options) def _state_to_operators(self, op_class, **options): return op_class.__new__(op_class, *_uppercase_labels(self), **options) @classmethod def default_args(self): return ("x", "y", "z") @property def position_x(self): """ The x coordinate of the state """ return self.label[0] @property def position_y(self): """ The y coordinate of the state """ return self.label[1] @property def position_z(self): """ The z coordinate of the state """ return self.label[2] class PositionKet3D(Ket, PositionState3D): """ 3D cartesian position eigenket """ def _eval_innerproduct_PositionBra3D(self, bra, **options): x_diff = self.position_x - bra.position_x y_diff = self.position_y - bra.position_y z_diff = self.position_z - bra.position_z return DiracDelta(x_diff)*DiracDelta(y_diff)*DiracDelta(z_diff) @classmethod def dual_class(self): return PositionBra3D # XXX: The type:ignore here is because mypy gives Definition of # "_state_to_operators" in base class "PositionState3D" is incompatible with # definition in base class "BraBase" class PositionBra3D(Bra, PositionState3D): # type: ignore """ 3D cartesian position eigenbra """ @classmethod def dual_class(self): return PositionKet3D #------------------------------------------------------------------------- # Momentum eigenstates #------------------------------------------------------------------------- class PxKet(Ket): """1D cartesian momentum eigenket.""" @classmethod def _operators_to_state(self, op, **options): return self.__new__(self, *_lowercase_labels(op), **options) def _state_to_operators(self, op_class, **options): return op_class.__new__(op_class, *_uppercase_labels(self), **options) @classmethod def default_args(self): return ("px",) @classmethod def dual_class(self): return PxBra @property def momentum(self): """The momentum of the state.""" return self.label[0] def _enumerate_state(self, *args, **options): return _enumerate_continuous_1D(self, *args, **options) def _eval_innerproduct_XBra(self, bra, **hints): return exp(I*self.momentum*bra.position/hbar)/sqrt(2*pi*hbar) def _eval_innerproduct_PxBra(self, bra, **hints): return DiracDelta(self.momentum - bra.momentum) class PxBra(Bra): """1D cartesian momentum eigenbra.""" @classmethod def default_args(self): return ("px",) @classmethod def dual_class(self): return PxKet @property def momentum(self): """The momentum of the state.""" return self.label[0] #------------------------------------------------------------------------- # Global helper functions #------------------------------------------------------------------------- def _enumerate_continuous_1D(*args, **options): state = args[0] num_states = args[1] state_class = state.__class__ index_list = options.pop('index_list', []) if len(index_list) == 0: start_index = options.pop('start_index', 1) index_list = list(range(start_index, start_index + num_states)) enum_states = [0 for i in range(len(index_list))] for i, ind in enumerate(index_list): label = state.args[0] enum_states[i] = state_class(str(label) + "_" + str(ind), **options) return enum_states def _lowercase_labels(ops): if not isinstance(ops, set): ops = [ops] return [str(arg.label[0]).lower() for arg in ops] def _uppercase_labels(ops): if not isinstance(ops, set): ops = [ops] new_args = [str(arg.label[0])[0].upper() + str(arg.label[0])[1:] for arg in ops] return new_args
80af97569d065fd3e587bb289970d8d4ac1d7224811dce0aaf8a0b436708539d
"""Utilities to deal with sympy.Matrix, numpy and scipy.sparse.""" from sympy import MatrixBase, I, Expr, Integer from sympy.matrices import eye, zeros from sympy.external import import_module __all__ = [ 'numpy_ndarray', 'scipy_sparse_matrix', 'sympy_to_numpy', 'sympy_to_scipy_sparse', 'numpy_to_sympy', 'scipy_sparse_to_sympy', 'flatten_scalar', 'matrix_dagger', 'to_sympy', 'to_numpy', 'to_scipy_sparse', 'matrix_tensor_product', 'matrix_zeros' ] # Conditionally define the base classes for numpy and scipy.sparse arrays # for use in isinstance tests. np = import_module('numpy') if not np: class numpy_ndarray: pass else: numpy_ndarray = np.ndarray # type: ignore scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']}) if not scipy: class scipy_sparse_matrix: pass sparse = None else: sparse = scipy.sparse # Try to find spmatrix. if hasattr(sparse, 'base'): # Newer versions have it under scipy.sparse.base. scipy_sparse_matrix = sparse.base.spmatrix # type: ignore elif hasattr(sparse, 'sparse'): # Older versions have it under scipy.sparse.sparse. scipy_sparse_matrix = sparse.sparse.spmatrix # type: ignore def sympy_to_numpy(m, **options): """Convert a sympy Matrix/complex number to a numpy matrix or scalar.""" if not np: raise ImportError dtype = options.get('dtype', 'complex') if isinstance(m, MatrixBase): return np.matrix(m.tolist(), dtype=dtype) elif isinstance(m, Expr): if m.is_Number or m.is_NumberSymbol or m == I: return complex(m) raise TypeError('Expected MatrixBase or complex scalar, got: %r' % m) def sympy_to_scipy_sparse(m, **options): """Convert a sympy Matrix/complex number to a numpy matrix or scalar.""" if not np or not sparse: raise ImportError dtype = options.get('dtype', 'complex') if isinstance(m, MatrixBase): return sparse.csr_matrix(np.matrix(m.tolist(), dtype=dtype)) elif isinstance(m, Expr): if m.is_Number or m.is_NumberSymbol or m == I: return complex(m) raise TypeError('Expected MatrixBase or complex scalar, got: %r' % m) def scipy_sparse_to_sympy(m, **options): """Convert a scipy.sparse matrix to a sympy matrix.""" return MatrixBase(m.todense()) def numpy_to_sympy(m, **options): """Convert a numpy matrix to a sympy matrix.""" return MatrixBase(m) def to_sympy(m, **options): """Convert a numpy/scipy.sparse matrix to a sympy matrix.""" if isinstance(m, MatrixBase): return m elif isinstance(m, numpy_ndarray): return numpy_to_sympy(m) elif isinstance(m, scipy_sparse_matrix): return scipy_sparse_to_sympy(m) elif isinstance(m, Expr): return m raise TypeError('Expected sympy/numpy/scipy.sparse matrix, got: %r' % m) def to_numpy(m, **options): """Convert a sympy/scipy.sparse matrix to a numpy matrix.""" dtype = options.get('dtype', 'complex') if isinstance(m, (MatrixBase, Expr)): return sympy_to_numpy(m, dtype=dtype) elif isinstance(m, numpy_ndarray): return m elif isinstance(m, scipy_sparse_matrix): return m.todense() raise TypeError('Expected sympy/numpy/scipy.sparse matrix, got: %r' % m) def to_scipy_sparse(m, **options): """Convert a sympy/numpy matrix to a scipy.sparse matrix.""" dtype = options.get('dtype', 'complex') if isinstance(m, (MatrixBase, Expr)): return sympy_to_scipy_sparse(m, dtype=dtype) elif isinstance(m, numpy_ndarray): if not sparse: raise ImportError return sparse.csr_matrix(m) elif isinstance(m, scipy_sparse_matrix): return m raise TypeError('Expected sympy/numpy/scipy.sparse matrix, got: %r' % m) def flatten_scalar(e): """Flatten a 1x1 matrix to a scalar, return larger matrices unchanged.""" if isinstance(e, MatrixBase): if e.shape == (1, 1): e = e[0] if isinstance(e, (numpy_ndarray, scipy_sparse_matrix)): if e.shape == (1, 1): e = complex(e[0, 0]) return e def matrix_dagger(e): """Return the dagger of a sympy/numpy/scipy.sparse matrix.""" if isinstance(e, MatrixBase): return e.H elif isinstance(e, (numpy_ndarray, scipy_sparse_matrix)): return e.conjugate().transpose() raise TypeError('Expected sympy/numpy/scipy.sparse matrix, got: %r' % e) # TODO: Move this into sympy.matricies. def _sympy_tensor_product(*matrices): """Compute the kronecker product of a sequence of sympy Matrices. """ from sympy.matrices.expressions.kronecker import matrix_kronecker_product return matrix_kronecker_product(*matrices) def _numpy_tensor_product(*product): """numpy version of tensor product of multiple arguments.""" if not np: raise ImportError answer = product[0] for item in product[1:]: answer = np.kron(answer, item) return answer def _scipy_sparse_tensor_product(*product): """scipy.sparse version of tensor product of multiple arguments.""" if not sparse: raise ImportError answer = product[0] for item in product[1:]: answer = sparse.kron(answer, item) # The final matrices will just be multiplied, so csr is a good final # sparse format. return sparse.csr_matrix(answer) def matrix_tensor_product(*product): """Compute the matrix tensor product of sympy/numpy/scipy.sparse matrices.""" if isinstance(product[0], MatrixBase): return _sympy_tensor_product(*product) elif isinstance(product[0], numpy_ndarray): return _numpy_tensor_product(*product) elif isinstance(product[0], scipy_sparse_matrix): return _scipy_sparse_tensor_product(*product) def _numpy_eye(n): """numpy version of complex eye.""" if not np: raise ImportError return np.matrix(np.eye(n, dtype='complex')) def _scipy_sparse_eye(n): """scipy.sparse version of complex eye.""" if not sparse: raise ImportError return sparse.eye(n, n, dtype='complex') def matrix_eye(n, **options): """Get the version of eye and tensor_product for a given format.""" format = options.get('format', 'sympy') if format == 'sympy': return eye(n) elif format == 'numpy': return _numpy_eye(n) elif format == 'scipy.sparse': return _scipy_sparse_eye(n) raise NotImplementedError('Invalid format: %r' % format) def _numpy_zeros(m, n, **options): """numpy version of zeros.""" dtype = options.get('dtype', 'float64') if not np: raise ImportError return np.zeros((m, n), dtype=dtype) def _scipy_sparse_zeros(m, n, **options): """scipy.sparse version of zeros.""" spmatrix = options.get('spmatrix', 'csr') dtype = options.get('dtype', 'float64') if not sparse: raise ImportError if spmatrix == 'lil': return sparse.lil_matrix((m, n), dtype=dtype) elif spmatrix == 'csr': return sparse.csr_matrix((m, n), dtype=dtype) def matrix_zeros(m, n, **options): """"Get a zeros matrix for a given format.""" format = options.get('format', 'sympy') if format == 'sympy': return zeros(m, n) elif format == 'numpy': return _numpy_zeros(m, n, **options) elif format == 'scipy.sparse': return _scipy_sparse_zeros(m, n, **options) raise NotImplementedError('Invaild format: %r' % format) def _numpy_matrix_to_zero(e): """Convert a numpy zero matrix to the zero scalar.""" if not np: raise ImportError test = np.zeros_like(e) if np.allclose(e, test): return 0.0 else: return e def _scipy_sparse_matrix_to_zero(e): """Convert a scipy.sparse zero matrix to the zero scalar.""" if not np: raise ImportError edense = e.todense() test = np.zeros_like(edense) if np.allclose(edense, test): return 0.0 else: return e def matrix_to_zero(e): """Convert a zero matrix to the scalar zero.""" if isinstance(e, MatrixBase): if zeros(*e.shape) == e: e = Integer(0) elif isinstance(e, numpy_ndarray): e = _numpy_matrix_to_zero(e) elif isinstance(e, scipy_sparse_matrix): e = _scipy_sparse_matrix_to_zero(e) return e
04ea7d00b589ffe43b08ce35ef9e11aba9a96f4a66b75140b5bdf46da92ecf80
"""An implementation of gates that act on qubits. Gates are unitary operators that act on the space of qubits. Medium Term Todo: * Optimize Gate._apply_operators_Qubit to remove the creation of many intermediate Qubit objects. * Add commutation relationships to all operators and use this in gate_sort. * Fix gate_sort and gate_simp. * Get multi-target UGates plotting properly. * Get UGate to work with either sympy/numpy matrices and output either format. This should also use the matrix slots. """ from itertools import chain import random from sympy import Add, I, Integer, Mul, Pow, sqrt, Tuple from sympy.core.numbers import Number from sympy.core.compatibility import is_sequence from sympy.printing.pretty.stringpict import prettyForm, stringPict from sympy.physics.quantum.anticommutator import AntiCommutator from sympy.physics.quantum.commutator import Commutator from sympy.physics.quantum.qexpr import QuantumError from sympy.physics.quantum.hilbert import ComplexSpace from sympy.physics.quantum.operator import (UnitaryOperator, Operator, HermitianOperator) from sympy.physics.quantum.matrixutils import matrix_tensor_product, matrix_eye from sympy.physics.quantum.matrixcache import matrix_cache from sympy.matrices.matrices import MatrixBase from sympy.utilities import default_sort_key __all__ = [ 'Gate', 'CGate', 'UGate', 'OneQubitGate', 'TwoQubitGate', 'IdentityGate', 'HadamardGate', 'XGate', 'YGate', 'ZGate', 'TGate', 'PhaseGate', 'SwapGate', 'CNotGate', # Aliased gate names 'CNOT', 'SWAP', 'H', 'X', 'Y', 'Z', 'T', 'S', 'Phase', 'normalized', 'gate_sort', 'gate_simp', 'random_circuit', 'CPHASE', 'CGateS', ] #----------------------------------------------------------------------------- # Gate Super-Classes #----------------------------------------------------------------------------- _normalized = True def _max(*args, **kwargs): if "key" not in kwargs: kwargs["key"] = default_sort_key return max(*args, **kwargs) def _min(*args, **kwargs): if "key" not in kwargs: kwargs["key"] = default_sort_key return min(*args, **kwargs) def normalized(normalize): """Set flag controlling normalization of Hadamard gates by 1/sqrt(2). This is a global setting that can be used to simplify the look of various expressions, by leaving off the leading 1/sqrt(2) of the Hadamard gate. Parameters ---------- normalize : bool Should the Hadamard gate include the 1/sqrt(2) normalization factor? When True, the Hadamard gate will have the 1/sqrt(2). When False, the Hadamard gate will not have this factor. """ global _normalized _normalized = normalize def _validate_targets_controls(tandc): tandc = list(tandc) # Check for integers for bit in tandc: if not bit.is_Integer and not bit.is_Symbol: raise TypeError('Integer expected, got: %r' % tandc[bit]) # Detect duplicates if len(list(set(tandc))) != len(tandc): raise QuantumError( 'Target/control qubits in a gate cannot be duplicated' ) class Gate(UnitaryOperator): """Non-controlled unitary gate operator that acts on qubits. This is a general abstract gate that needs to be subclassed to do anything useful. Parameters ---------- label : tuple, int A list of the target qubits (as ints) that the gate will apply to. Examples ======== """ _label_separator = ',' gate_name = 'G' gate_name_latex = 'G' #------------------------------------------------------------------------- # Initialization/creation #------------------------------------------------------------------------- @classmethod def _eval_args(cls, args): args = Tuple(*UnitaryOperator._eval_args(args)) _validate_targets_controls(args) return args @classmethod def _eval_hilbert_space(cls, args): """This returns the smallest possible Hilbert space.""" return ComplexSpace(2)**(_max(args) + 1) #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def nqubits(self): """The total number of qubits this gate acts on. For controlled gate subclasses this includes both target and control qubits, so that, for examples the CNOT gate acts on 2 qubits. """ return len(self.targets) @property def min_qubits(self): """The minimum number of qubits this gate needs to act on.""" return _max(self.targets) + 1 @property def targets(self): """A tuple of target qubits.""" return self.label @property def gate_name_plot(self): return r'$%s$' % self.gate_name_latex #------------------------------------------------------------------------- # Gate methods #------------------------------------------------------------------------- def get_target_matrix(self, format='sympy'): """The matrix rep. of the target part of the gate. Parameters ---------- format : str The format string ('sympy','numpy', etc.) """ raise NotImplementedError( 'get_target_matrix is not implemented in Gate.') #------------------------------------------------------------------------- # Apply #------------------------------------------------------------------------- def _apply_operator_IntQubit(self, qubits, **options): """Redirect an apply from IntQubit to Qubit""" return self._apply_operator_Qubit(qubits, **options) def _apply_operator_Qubit(self, qubits, **options): """Apply this gate to a Qubit.""" # Check number of qubits this gate acts on. if qubits.nqubits < self.min_qubits: raise QuantumError( 'Gate needs a minimum of %r qubits to act on, got: %r' % (self.min_qubits, qubits.nqubits) ) # If the controls are not met, just return if isinstance(self, CGate): if not self.eval_controls(qubits): return qubits targets = self.targets target_matrix = self.get_target_matrix(format='sympy') # Find which column of the target matrix this applies to. column_index = 0 n = 1 for target in targets: column_index += n*qubits[target] n = n << 1 column = target_matrix[:, int(column_index)] # Now apply each column element to the qubit. result = 0 for index in range(column.rows): # TODO: This can be optimized to reduce the number of Qubit # creations. We should simply manipulate the raw list of qubit # values and then build the new Qubit object once. # Make a copy of the incoming qubits. new_qubit = qubits.__class__(*qubits.args) # Flip the bits that need to be flipped. for bit in range(len(targets)): if new_qubit[targets[bit]] != (index >> bit) & 1: new_qubit = new_qubit.flip(targets[bit]) # The value in that row and column times the flipped-bit qubit # is the result for that part. result += column[index]*new_qubit return result #------------------------------------------------------------------------- # Represent #------------------------------------------------------------------------- def _represent_default_basis(self, **options): return self._represent_ZGate(None, **options) def _represent_ZGate(self, basis, **options): format = options.get('format', 'sympy') nqubits = options.get('nqubits', 0) if nqubits == 0: raise QuantumError( 'The number of qubits must be given as nqubits.') # Make sure we have enough qubits for the gate. if nqubits < self.min_qubits: raise QuantumError( 'The number of qubits %r is too small for the gate.' % nqubits ) target_matrix = self.get_target_matrix(format) targets = self.targets if isinstance(self, CGate): controls = self.controls else: controls = [] m = represent_zbasis( controls, targets, target_matrix, nqubits, format ) return m #------------------------------------------------------------------------- # Print methods #------------------------------------------------------------------------- def _sympystr(self, printer, *args): label = self._print_label(printer, *args) return '%s(%s)' % (self.gate_name, label) def _pretty(self, printer, *args): a = stringPict(self.gate_name) b = self._print_label_pretty(printer, *args) return self._print_subscript_pretty(a, b) def _latex(self, printer, *args): label = self._print_label(printer, *args) return '%s_{%s}' % (self.gate_name_latex, label) def plot_gate(self, axes, gate_idx, gate_grid, wire_grid): raise NotImplementedError('plot_gate is not implemented.') class CGate(Gate): """A general unitary gate with control qubits. A general control gate applies a target gate to a set of targets if all of the control qubits have a particular values (set by ``CGate.control_value``). Parameters ---------- label : tuple The label in this case has the form (controls, gate), where controls is a tuple/list of control qubits (as ints) and gate is a ``Gate`` instance that is the target operator. Examples ======== """ gate_name = 'C' gate_name_latex = 'C' # The values this class controls for. control_value = Integer(1) simplify_cgate=False #------------------------------------------------------------------------- # Initialization #------------------------------------------------------------------------- @classmethod def _eval_args(cls, args): # _eval_args has the right logic for the controls argument. controls = args[0] gate = args[1] if not is_sequence(controls): controls = (controls,) controls = UnitaryOperator._eval_args(controls) _validate_targets_controls(chain(controls, gate.targets)) return (Tuple(*controls), gate) @classmethod def _eval_hilbert_space(cls, args): """This returns the smallest possible Hilbert space.""" return ComplexSpace(2)**_max(_max(args[0]) + 1, args[1].min_qubits) #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def nqubits(self): """The total number of qubits this gate acts on. For controlled gate subclasses this includes both target and control qubits, so that, for examples the CNOT gate acts on 2 qubits. """ return len(self.targets) + len(self.controls) @property def min_qubits(self): """The minimum number of qubits this gate needs to act on.""" return _max(_max(self.controls), _max(self.targets)) + 1 @property def targets(self): """A tuple of target qubits.""" return self.gate.targets @property def controls(self): """A tuple of control qubits.""" return tuple(self.label[0]) @property def gate(self): """The non-controlled gate that will be applied to the targets.""" return self.label[1] #------------------------------------------------------------------------- # Gate methods #------------------------------------------------------------------------- def get_target_matrix(self, format='sympy'): return self.gate.get_target_matrix(format) def eval_controls(self, qubit): """Return True/False to indicate if the controls are satisfied.""" return all(qubit[bit] == self.control_value for bit in self.controls) def decompose(self, **options): """Decompose the controlled gate into CNOT and single qubits gates.""" if len(self.controls) == 1: c = self.controls[0] t = self.gate.targets[0] if isinstance(self.gate, YGate): g1 = PhaseGate(t) g2 = CNotGate(c, t) g3 = PhaseGate(t) g4 = ZGate(t) return g1*g2*g3*g4 if isinstance(self.gate, ZGate): g1 = HadamardGate(t) g2 = CNotGate(c, t) g3 = HadamardGate(t) return g1*g2*g3 else: return self #------------------------------------------------------------------------- # Print methods #------------------------------------------------------------------------- def _print_label(self, printer, *args): controls = self._print_sequence(self.controls, ',', printer, *args) gate = printer._print(self.gate, *args) return '(%s),%s' % (controls, gate) def _pretty(self, printer, *args): controls = self._print_sequence_pretty( self.controls, ',', printer, *args) gate = printer._print(self.gate) gate_name = stringPict(self.gate_name) first = self._print_subscript_pretty(gate_name, controls) gate = self._print_parens_pretty(gate) final = prettyForm(*first.right(gate)) return final def _latex(self, printer, *args): controls = self._print_sequence(self.controls, ',', printer, *args) gate = printer._print(self.gate, *args) return r'%s_{%s}{\left(%s\right)}' % \ (self.gate_name_latex, controls, gate) def plot_gate(self, circ_plot, gate_idx): """ Plot the controlled gate. If *simplify_cgate* is true, simplify C-X and C-Z gates into their more familiar forms. """ min_wire = int(_min(chain(self.controls, self.targets))) max_wire = int(_max(chain(self.controls, self.targets))) circ_plot.control_line(gate_idx, min_wire, max_wire) for c in self.controls: circ_plot.control_point(gate_idx, int(c)) if self.simplify_cgate: if self.gate.gate_name == 'X': self.gate.plot_gate_plus(circ_plot, gate_idx) elif self.gate.gate_name == 'Z': circ_plot.control_point(gate_idx, self.targets[0]) else: self.gate.plot_gate(circ_plot, gate_idx) else: self.gate.plot_gate(circ_plot, gate_idx) #------------------------------------------------------------------------- # Miscellaneous #------------------------------------------------------------------------- def _eval_dagger(self): if isinstance(self.gate, HermitianOperator): return self else: return Gate._eval_dagger(self) def _eval_inverse(self): if isinstance(self.gate, HermitianOperator): return self else: return Gate._eval_inverse(self) def _eval_power(self, exp): if isinstance(self.gate, HermitianOperator): if exp == -1: return Gate._eval_power(self, exp) elif abs(exp) % 2 == 0: return self*(Gate._eval_inverse(self)) else: return self else: return Gate._eval_power(self, exp) class CGateS(CGate): """Version of CGate that allows gate simplifications. I.e. cnot looks like an oplus, cphase has dots, etc. """ simplify_cgate=True class UGate(Gate): """General gate specified by a set of targets and a target matrix. Parameters ---------- label : tuple A tuple of the form (targets, U), where targets is a tuple of the target qubits and U is a unitary matrix with dimension of len(targets). """ gate_name = 'U' gate_name_latex = 'U' #------------------------------------------------------------------------- # Initialization #------------------------------------------------------------------------- @classmethod def _eval_args(cls, args): targets = args[0] if not is_sequence(targets): targets = (targets,) targets = Gate._eval_args(targets) _validate_targets_controls(targets) mat = args[1] if not isinstance(mat, MatrixBase): raise TypeError('Matrix expected, got: %r' % mat) dim = 2**len(targets) if not all(dim == shape for shape in mat.shape): raise IndexError( 'Number of targets must match the matrix size: %r %r' % (targets, mat) ) return (targets, mat) @classmethod def _eval_hilbert_space(cls, args): """This returns the smallest possible Hilbert space.""" return ComplexSpace(2)**(_max(args[0]) + 1) #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def targets(self): """A tuple of target qubits.""" return tuple(self.label[0]) #------------------------------------------------------------------------- # Gate methods #------------------------------------------------------------------------- def get_target_matrix(self, format='sympy'): """The matrix rep. of the target part of the gate. Parameters ---------- format : str The format string ('sympy','numpy', etc.) """ return self.label[1] #------------------------------------------------------------------------- # Print methods #------------------------------------------------------------------------- def _pretty(self, printer, *args): targets = self._print_sequence_pretty( self.targets, ',', printer, *args) gate_name = stringPict(self.gate_name) return self._print_subscript_pretty(gate_name, targets) def _latex(self, printer, *args): targets = self._print_sequence(self.targets, ',', printer, *args) return r'%s_{%s}' % (self.gate_name_latex, targets) def plot_gate(self, circ_plot, gate_idx): circ_plot.one_qubit_box( self.gate_name_plot, gate_idx, int(self.targets[0]) ) class OneQubitGate(Gate): """A single qubit unitary gate base class.""" nqubits = Integer(1) def plot_gate(self, circ_plot, gate_idx): circ_plot.one_qubit_box( self.gate_name_plot, gate_idx, int(self.targets[0]) ) def _eval_commutator(self, other, **hints): if isinstance(other, OneQubitGate): if self.targets != other.targets or self.__class__ == other.__class__: return Integer(0) return Operator._eval_commutator(self, other, **hints) def _eval_anticommutator(self, other, **hints): if isinstance(other, OneQubitGate): if self.targets != other.targets or self.__class__ == other.__class__: return Integer(2)*self*other return Operator._eval_anticommutator(self, other, **hints) class TwoQubitGate(Gate): """A two qubit unitary gate base class.""" nqubits = Integer(2) #----------------------------------------------------------------------------- # Single Qubit Gates #----------------------------------------------------------------------------- class IdentityGate(OneQubitGate): """The single qubit identity gate. Parameters ---------- target : int The target qubit this gate will apply to. Examples ======== """ gate_name = '1' gate_name_latex = '1' def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('eye2', format) def _eval_commutator(self, other, **hints): return Integer(0) def _eval_anticommutator(self, other, **hints): return Integer(2)*other class HadamardGate(HermitianOperator, OneQubitGate): """The single qubit Hadamard gate. Parameters ---------- target : int The target qubit this gate will apply to. Examples ======== >>> from sympy import sqrt >>> from sympy.physics.quantum.qubit import Qubit >>> from sympy.physics.quantum.gate import HadamardGate >>> from sympy.physics.quantum.qapply import qapply >>> qapply(HadamardGate(0)*Qubit('1')) sqrt(2)*|0>/2 - sqrt(2)*|1>/2 >>> # Hadamard on bell state, applied on 2 qubits. >>> psi = 1/sqrt(2)*(Qubit('00')+Qubit('11')) >>> qapply(HadamardGate(0)*HadamardGate(1)*psi) sqrt(2)*|00>/2 + sqrt(2)*|11>/2 """ gate_name = 'H' gate_name_latex = 'H' def get_target_matrix(self, format='sympy'): if _normalized: return matrix_cache.get_matrix('H', format) else: return matrix_cache.get_matrix('Hsqrt2', format) def _eval_commutator_XGate(self, other, **hints): return I*sqrt(2)*YGate(self.targets[0]) def _eval_commutator_YGate(self, other, **hints): return I*sqrt(2)*(ZGate(self.targets[0]) - XGate(self.targets[0])) def _eval_commutator_ZGate(self, other, **hints): return -I*sqrt(2)*YGate(self.targets[0]) def _eval_anticommutator_XGate(self, other, **hints): return sqrt(2)*IdentityGate(self.targets[0]) def _eval_anticommutator_YGate(self, other, **hints): return Integer(0) def _eval_anticommutator_ZGate(self, other, **hints): return sqrt(2)*IdentityGate(self.targets[0]) class XGate(HermitianOperator, OneQubitGate): """The single qubit X, or NOT, gate. Parameters ---------- target : int The target qubit this gate will apply to. Examples ======== """ gate_name = 'X' gate_name_latex = 'X' def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('X', format) def plot_gate(self, circ_plot, gate_idx): OneQubitGate.plot_gate(self,circ_plot,gate_idx) def plot_gate_plus(self, circ_plot, gate_idx): circ_plot.not_point( gate_idx, int(self.label[0]) ) def _eval_commutator_YGate(self, other, **hints): return Integer(2)*I*ZGate(self.targets[0]) def _eval_anticommutator_XGate(self, other, **hints): return Integer(2)*IdentityGate(self.targets[0]) def _eval_anticommutator_YGate(self, other, **hints): return Integer(0) def _eval_anticommutator_ZGate(self, other, **hints): return Integer(0) class YGate(HermitianOperator, OneQubitGate): """The single qubit Y gate. Parameters ---------- target : int The target qubit this gate will apply to. Examples ======== """ gate_name = 'Y' gate_name_latex = 'Y' def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('Y', format) def _eval_commutator_ZGate(self, other, **hints): return Integer(2)*I*XGate(self.targets[0]) def _eval_anticommutator_YGate(self, other, **hints): return Integer(2)*IdentityGate(self.targets[0]) def _eval_anticommutator_ZGate(self, other, **hints): return Integer(0) class ZGate(HermitianOperator, OneQubitGate): """The single qubit Z gate. Parameters ---------- target : int The target qubit this gate will apply to. Examples ======== """ gate_name = 'Z' gate_name_latex = 'Z' def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('Z', format) def _eval_commutator_XGate(self, other, **hints): return Integer(2)*I*YGate(self.targets[0]) def _eval_anticommutator_YGate(self, other, **hints): return Integer(0) class PhaseGate(OneQubitGate): """The single qubit phase, or S, gate. This gate rotates the phase of the state by pi/2 if the state is ``|1>`` and does nothing if the state is ``|0>``. Parameters ---------- target : int The target qubit this gate will apply to. Examples ======== """ gate_name = 'S' gate_name_latex = 'S' def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('S', format) def _eval_commutator_ZGate(self, other, **hints): return Integer(0) def _eval_commutator_TGate(self, other, **hints): return Integer(0) class TGate(OneQubitGate): """The single qubit pi/8 gate. This gate rotates the phase of the state by pi/4 if the state is ``|1>`` and does nothing if the state is ``|0>``. Parameters ---------- target : int The target qubit this gate will apply to. Examples ======== """ gate_name = 'T' gate_name_latex = 'T' def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('T', format) def _eval_commutator_ZGate(self, other, **hints): return Integer(0) def _eval_commutator_PhaseGate(self, other, **hints): return Integer(0) # Aliases for gate names. H = HadamardGate X = XGate Y = YGate Z = ZGate T = TGate Phase = S = PhaseGate #----------------------------------------------------------------------------- # 2 Qubit Gates #----------------------------------------------------------------------------- class CNotGate(HermitianOperator, CGate, TwoQubitGate): """Two qubit controlled-NOT. This gate performs the NOT or X gate on the target qubit if the control qubits all have the value 1. Parameters ---------- label : tuple A tuple of the form (control, target). Examples ======== >>> from sympy.physics.quantum.gate import CNOT >>> from sympy.physics.quantum.qapply import qapply >>> from sympy.physics.quantum.qubit import Qubit >>> c = CNOT(1,0) >>> qapply(c*Qubit('10')) # note that qubits are indexed from right to left |11> """ gate_name = 'CNOT' gate_name_latex = 'CNOT' simplify_cgate = True #------------------------------------------------------------------------- # Initialization #------------------------------------------------------------------------- @classmethod def _eval_args(cls, args): args = Gate._eval_args(args) return args @classmethod def _eval_hilbert_space(cls, args): """This returns the smallest possible Hilbert space.""" return ComplexSpace(2)**(_max(args) + 1) #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def min_qubits(self): """The minimum number of qubits this gate needs to act on.""" return _max(self.label) + 1 @property def targets(self): """A tuple of target qubits.""" return (self.label[1],) @property def controls(self): """A tuple of control qubits.""" return (self.label[0],) @property def gate(self): """The non-controlled gate that will be applied to the targets.""" return XGate(self.label[1]) #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- # The default printing of Gate works better than those of CGate, so we # go around the overridden methods in CGate. def _print_label(self, printer, *args): return Gate._print_label(self, printer, *args) def _pretty(self, printer, *args): return Gate._pretty(self, printer, *args) def _latex(self, printer, *args): return Gate._latex(self, printer, *args) #------------------------------------------------------------------------- # Commutator/AntiCommutator #------------------------------------------------------------------------- def _eval_commutator_ZGate(self, other, **hints): """[CNOT(i, j), Z(i)] == 0.""" if self.controls[0] == other.targets[0]: return Integer(0) else: raise NotImplementedError('Commutator not implemented: %r' % other) def _eval_commutator_TGate(self, other, **hints): """[CNOT(i, j), T(i)] == 0.""" return self._eval_commutator_ZGate(other, **hints) def _eval_commutator_PhaseGate(self, other, **hints): """[CNOT(i, j), S(i)] == 0.""" return self._eval_commutator_ZGate(other, **hints) def _eval_commutator_XGate(self, other, **hints): """[CNOT(i, j), X(j)] == 0.""" if self.targets[0] == other.targets[0]: return Integer(0) else: raise NotImplementedError('Commutator not implemented: %r' % other) def _eval_commutator_CNotGate(self, other, **hints): """[CNOT(i, j), CNOT(i,k)] == 0.""" if self.controls[0] == other.controls[0]: return Integer(0) else: raise NotImplementedError('Commutator not implemented: %r' % other) class SwapGate(TwoQubitGate): """Two qubit SWAP gate. This gate swap the values of the two qubits. Parameters ---------- label : tuple A tuple of the form (target1, target2). Examples ======== """ gate_name = 'SWAP' gate_name_latex = 'SWAP' def get_target_matrix(self, format='sympy'): return matrix_cache.get_matrix('SWAP', format) def decompose(self, **options): """Decompose the SWAP gate into CNOT gates.""" i, j = self.targets[0], self.targets[1] g1 = CNotGate(i, j) g2 = CNotGate(j, i) return g1*g2*g1 def plot_gate(self, circ_plot, gate_idx): min_wire = int(_min(self.targets)) max_wire = int(_max(self.targets)) circ_plot.control_line(gate_idx, min_wire, max_wire) circ_plot.swap_point(gate_idx, min_wire) circ_plot.swap_point(gate_idx, max_wire) def _represent_ZGate(self, basis, **options): """Represent the SWAP gate in the computational basis. The following representation is used to compute this: SWAP = |1><1|x|1><1| + |0><0|x|0><0| + |1><0|x|0><1| + |0><1|x|1><0| """ format = options.get('format', 'sympy') targets = [int(t) for t in self.targets] min_target = _min(targets) max_target = _max(targets) nqubits = options.get('nqubits', self.min_qubits) op01 = matrix_cache.get_matrix('op01', format) op10 = matrix_cache.get_matrix('op10', format) op11 = matrix_cache.get_matrix('op11', format) op00 = matrix_cache.get_matrix('op00', format) eye2 = matrix_cache.get_matrix('eye2', format) result = None for i, j in ((op01, op10), (op10, op01), (op00, op00), (op11, op11)): product = nqubits*[eye2] product[nqubits - min_target - 1] = i product[nqubits - max_target - 1] = j new_result = matrix_tensor_product(*product) if result is None: result = new_result else: result = result + new_result return result # Aliases for gate names. CNOT = CNotGate SWAP = SwapGate def CPHASE(a,b): return CGateS((a,),Z(b)) #----------------------------------------------------------------------------- # Represent #----------------------------------------------------------------------------- def represent_zbasis(controls, targets, target_matrix, nqubits, format='sympy'): """Represent a gate with controls, targets and target_matrix. This function does the low-level work of representing gates as matrices in the standard computational basis (ZGate). Currently, we support two main cases: 1. One target qubit and no control qubits. 2. One target qubits and multiple control qubits. For the base of multiple controls, we use the following expression [1]: 1_{2**n} + (|1><1|)^{(n-1)} x (target-matrix - 1_{2}) Parameters ---------- controls : list, tuple A sequence of control qubits. targets : list, tuple A sequence of target qubits. target_matrix : sympy.Matrix, numpy.matrix, scipy.sparse The matrix form of the transformation to be performed on the target qubits. The format of this matrix must match that passed into the `format` argument. nqubits : int The total number of qubits used for the representation. format : str The format of the final matrix ('sympy', 'numpy', 'scipy.sparse'). Examples ======== References ---------- [1] http://www.johnlapeyre.com/qinf/qinf_html/node6.html. """ controls = [int(x) for x in controls] targets = [int(x) for x in targets] nqubits = int(nqubits) # This checks for the format as well. op11 = matrix_cache.get_matrix('op11', format) eye2 = matrix_cache.get_matrix('eye2', format) # Plain single qubit case if len(controls) == 0 and len(targets) == 1: product = [] bit = targets[0] # Fill product with [I1,Gate,I2] such that the unitaries, # I, cause the gate to be applied to the correct Qubit if bit != nqubits - 1: product.append(matrix_eye(2**(nqubits - bit - 1), format=format)) product.append(target_matrix) if bit != 0: product.append(matrix_eye(2**bit, format=format)) return matrix_tensor_product(*product) # Single target, multiple controls. elif len(targets) == 1 and len(controls) >= 1: target = targets[0] # Build the non-trivial part. product2 = [] for i in range(nqubits): product2.append(matrix_eye(2, format=format)) for control in controls: product2[nqubits - 1 - control] = op11 product2[nqubits - 1 - target] = target_matrix - eye2 return matrix_eye(2**nqubits, format=format) + \ matrix_tensor_product(*product2) # Multi-target, multi-control is not yet implemented. else: raise NotImplementedError( 'The representation of multi-target, multi-control gates ' 'is not implemented.' ) #----------------------------------------------------------------------------- # Gate manipulation functions. #----------------------------------------------------------------------------- def gate_simp(circuit): """Simplifies gates symbolically It first sorts gates using gate_sort. It then applies basic simplification rules to the circuit, e.g., XGate**2 = Identity """ # Bubble sort out gates that commute. circuit = gate_sort(circuit) # Do simplifications by subing a simplification into the first element # which can be simplified. We recursively call gate_simp with new circuit # as input more simplifications exist. if isinstance(circuit, Add): return sum(gate_simp(t) for t in circuit.args) elif isinstance(circuit, Mul): circuit_args = circuit.args elif isinstance(circuit, Pow): b, e = circuit.as_base_exp() circuit_args = (gate_simp(b)**e,) else: return circuit # Iterate through each element in circuit, simplify if possible. for i in range(len(circuit_args)): # H,X,Y or Z squared is 1. # T**2 = S, S**2 = Z if isinstance(circuit_args[i], Pow): if isinstance(circuit_args[i].base, (HadamardGate, XGate, YGate, ZGate)) \ and isinstance(circuit_args[i].exp, Number): # Build a new circuit taking replacing the # H,X,Y,Z squared with one. newargs = (circuit_args[:i] + (circuit_args[i].base**(circuit_args[i].exp % 2),) + circuit_args[i + 1:]) # Recursively simplify the new circuit. circuit = gate_simp(Mul(*newargs)) break elif isinstance(circuit_args[i].base, PhaseGate): # Build a new circuit taking old circuit but splicing # in simplification. newargs = circuit_args[:i] # Replace PhaseGate**2 with ZGate. newargs = newargs + (ZGate(circuit_args[i].base.args[0])** (Integer(circuit_args[i].exp/2)), circuit_args[i].base** (circuit_args[i].exp % 2)) # Append the last elements. newargs = newargs + circuit_args[i + 1:] # Recursively simplify the new circuit. circuit = gate_simp(Mul(*newargs)) break elif isinstance(circuit_args[i].base, TGate): # Build a new circuit taking all the old elements. newargs = circuit_args[:i] # Put an Phasegate in place of any TGate**2. newargs = newargs + (PhaseGate(circuit_args[i].base.args[0])** Integer(circuit_args[i].exp/2), circuit_args[i].base** (circuit_args[i].exp % 2)) # Append the last elements. newargs = newargs + circuit_args[i + 1:] # Recursively simplify the new circuit. circuit = gate_simp(Mul(*newargs)) break return circuit def gate_sort(circuit): """Sorts the gates while keeping track of commutation relations This function uses a bubble sort to rearrange the order of gate application. Keeps track of Quantum computations special commutation relations (e.g. things that apply to the same Qubit do not commute with each other) circuit is the Mul of gates that are to be sorted. """ # Make sure we have an Add or Mul. if isinstance(circuit, Add): return sum(gate_sort(t) for t in circuit.args) if isinstance(circuit, Pow): return gate_sort(circuit.base)**circuit.exp elif isinstance(circuit, Gate): return circuit if not isinstance(circuit, Mul): return circuit changes = True while changes: changes = False circ_array = circuit.args for i in range(len(circ_array) - 1): # Go through each element and switch ones that are in wrong order if isinstance(circ_array[i], (Gate, Pow)) and \ isinstance(circ_array[i + 1], (Gate, Pow)): # If we have a Pow object, look at only the base first_base, first_exp = circ_array[i].as_base_exp() second_base, second_exp = circ_array[i + 1].as_base_exp() # Use sympy's hash based sorting. This is not mathematical # sorting, but is rather based on comparing hashes of objects. # See Basic.compare for details. if first_base.compare(second_base) > 0: if Commutator(first_base, second_base).doit() == 0: new_args = (circuit.args[:i] + (circuit.args[i + 1],) + (circuit.args[i],) + circuit.args[i + 2:]) circuit = Mul(*new_args) changes = True break if AntiCommutator(first_base, second_base).doit() == 0: new_args = (circuit.args[:i] + (circuit.args[i + 1],) + (circuit.args[i],) + circuit.args[i + 2:]) sign = Integer(-1)**(first_exp*second_exp) circuit = sign*Mul(*new_args) changes = True break return circuit #----------------------------------------------------------------------------- # Utility functions #----------------------------------------------------------------------------- def random_circuit(ngates, nqubits, gate_space=(X, Y, Z, S, T, H, CNOT, SWAP)): """Return a random circuit of ngates and nqubits. This uses an equally weighted sample of (X, Y, Z, S, T, H, CNOT, SWAP) gates. Parameters ---------- ngates : int The number of gates in the circuit. nqubits : int The number of qubits in the circuit. gate_space : tuple A tuple of the gate classes that will be used in the circuit. Repeating gate classes multiple times in this tuple will increase the frequency they appear in the random circuit. """ qubit_space = range(nqubits) result = [] for i in range(ngates): g = random.choice(gate_space) if g == CNotGate or g == SwapGate: qubits = random.sample(qubit_space, 2) g = g(*qubits) else: qubit = random.choice(qubit_space) g = g(qubit) result.append(g) return Mul(*result) def zx_basis_transform(self, format='sympy'): """Transformation matrix from Z to X basis.""" return matrix_cache.get_matrix('ZX', format) def zy_basis_transform(self, format='sympy'): """Transformation matrix from Z to Y basis.""" return matrix_cache.get_matrix('ZY', format)
e7ad5774274b1bc8be126ad1af847659becd05d29f9671f1c476ef46e18a920c
"""Logic for representing operators in state in various bases. TODO: * Get represent working with continuous hilbert spaces. * Document default basis functionality. """ from sympy import Add, Expr, I, integrate, Mul, Pow from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.commutator import Commutator from sympy.physics.quantum.anticommutator import AntiCommutator from sympy.physics.quantum.innerproduct import InnerProduct from sympy.physics.quantum.qexpr import QExpr from sympy.physics.quantum.tensorproduct import TensorProduct from sympy.physics.quantum.matrixutils import flatten_scalar from sympy.physics.quantum.state import KetBase, BraBase, StateBase from sympy.physics.quantum.operator import Operator, OuterProduct from sympy.physics.quantum.qapply import qapply from sympy.physics.quantum.operatorset import operators_to_state, state_to_operators __all__ = [ 'represent', 'rep_innerproduct', 'rep_expectation', 'integrate_result', 'get_basis', 'enumerate_states' ] #----------------------------------------------------------------------------- # Represent #----------------------------------------------------------------------------- def _sympy_to_scalar(e): """Convert from a sympy scalar to a Python scalar.""" if isinstance(e, Expr): if e.is_Integer: return int(e) elif e.is_Float: return float(e) elif e.is_Rational: return float(e) elif e.is_Number or e.is_NumberSymbol or e == I: return complex(e) raise TypeError('Expected number, got: %r' % e) def represent(expr, **options): """Represent the quantum expression in the given basis. In quantum mechanics abstract states and operators can be represented in various basis sets. Under this operation the follow transforms happen: * Ket -> column vector or function * Bra -> row vector of function * Operator -> matrix or differential operator This function is the top-level interface for this action. This function walks the sympy expression tree looking for ``QExpr`` instances that have a ``_represent`` method. This method is then called and the object is replaced by the representation returned by this method. By default, the ``_represent`` method will dispatch to other methods that handle the representation logic for a particular basis set. The naming convention for these methods is the following:: def _represent_FooBasis(self, e, basis, **options) This function will have the logic for representing instances of its class in the basis set having a class named ``FooBasis``. Parameters ========== expr : Expr The expression to represent. basis : Operator, basis set An object that contains the information about the basis set. If an operator is used, the basis is assumed to be the orthonormal eigenvectors of that operator. In general though, the basis argument can be any object that contains the basis set information. options : dict Key/value pairs of options that are passed to the underlying method that finds the representation. These options can be used to control how the representation is done. For example, this is where the size of the basis set would be set. Returns ======= e : Expr The SymPy expression of the represented quantum expression. Examples ======== Here we subclass ``Operator`` and ``Ket`` to create the z-spin operator and its spin 1/2 up eigenstate. By defining the ``_represent_SzOp`` method, the ket can be represented in the z-spin basis. >>> from sympy.physics.quantum import Operator, represent, Ket >>> from sympy import Matrix >>> class SzUpKet(Ket): ... def _represent_SzOp(self, basis, **options): ... return Matrix([1,0]) ... >>> class SzOp(Operator): ... pass ... >>> sz = SzOp('Sz') >>> up = SzUpKet('up') >>> represent(up, basis=sz) Matrix([ [1], [0]]) Here we see an example of representations in a continuous basis. We see that the result of representing various combinations of cartesian position operators and kets give us continuous expressions involving DiracDelta functions. >>> from sympy.physics.quantum.cartesian import XOp, XKet, XBra >>> X = XOp() >>> x = XKet() >>> y = XBra('y') >>> represent(X*x) x*DiracDelta(x - x_2) >>> represent(X*x*y) x*DiracDelta(x - x_3)*DiracDelta(x_1 - y) """ format = options.get('format', 'sympy') if isinstance(expr, QExpr) and not isinstance(expr, OuterProduct): options['replace_none'] = False temp_basis = get_basis(expr, **options) if temp_basis is not None: options['basis'] = temp_basis try: return expr._represent(**options) except NotImplementedError as strerr: #If no _represent_FOO method exists, map to the #appropriate basis state and try #the other methods of representation options['replace_none'] = True if isinstance(expr, (KetBase, BraBase)): try: return rep_innerproduct(expr, **options) except NotImplementedError: raise NotImplementedError(strerr) elif isinstance(expr, Operator): try: return rep_expectation(expr, **options) except NotImplementedError: raise NotImplementedError(strerr) else: raise NotImplementedError(strerr) elif isinstance(expr, Add): result = represent(expr.args[0], **options) for args in expr.args[1:]: # scipy.sparse doesn't support += so we use plain = here. result = result + represent(args, **options) return result elif isinstance(expr, Pow): base, exp = expr.as_base_exp() if format == 'numpy' or format == 'scipy.sparse': exp = _sympy_to_scalar(exp) base = represent(base, **options) # scipy.sparse doesn't support negative exponents # and warns when inverting a matrix in csr format. if format == 'scipy.sparse' and exp < 0: from scipy.sparse.linalg import inv exp = - exp base = inv(base.tocsc()).tocsr() return base ** exp elif isinstance(expr, TensorProduct): new_args = [represent(arg, **options) for arg in expr.args] return TensorProduct(*new_args) elif isinstance(expr, Dagger): return Dagger(represent(expr.args[0], **options)) elif isinstance(expr, Commutator): A = represent(expr.args[0], **options) B = represent(expr.args[1], **options) return A*B - B*A elif isinstance(expr, AntiCommutator): A = represent(expr.args[0], **options) B = represent(expr.args[1], **options) return A*B + B*A elif isinstance(expr, InnerProduct): return represent(Mul(expr.bra, expr.ket), **options) elif not (isinstance(expr, Mul) or isinstance(expr, OuterProduct)): # For numpy and scipy.sparse, we can only handle numerical prefactors. if format == 'numpy' or format == 'scipy.sparse': return _sympy_to_scalar(expr) return expr if not (isinstance(expr, Mul) or isinstance(expr, OuterProduct)): raise TypeError('Mul expected, got: %r' % expr) if "index" in options: options["index"] += 1 else: options["index"] = 1 if not "unities" in options: options["unities"] = [] result = represent(expr.args[-1], **options) last_arg = expr.args[-1] for arg in reversed(expr.args[:-1]): if isinstance(last_arg, Operator): options["index"] += 1 options["unities"].append(options["index"]) elif isinstance(last_arg, BraBase) and isinstance(arg, KetBase): options["index"] += 1 elif isinstance(last_arg, KetBase) and isinstance(arg, Operator): options["unities"].append(options["index"]) elif isinstance(last_arg, KetBase) and isinstance(arg, BraBase): options["unities"].append(options["index"]) result = represent(arg, **options)*result last_arg = arg # All three matrix formats create 1 by 1 matrices when inner products of # vectors are taken. In these cases, we simply return a scalar. result = flatten_scalar(result) result = integrate_result(expr, result, **options) return result def rep_innerproduct(expr, **options): """ Returns an innerproduct like representation (e.g. ``<x'|x>``) for the given state. Attempts to calculate inner product with a bra from the specified basis. Should only be passed an instance of KetBase or BraBase Parameters ========== expr : KetBase or BraBase The expression to be represented Examples ======== >>> from sympy.physics.quantum.represent import rep_innerproduct >>> from sympy.physics.quantum.cartesian import XOp, XKet, PxOp, PxKet >>> rep_innerproduct(XKet()) DiracDelta(x - x_1) >>> rep_innerproduct(XKet(), basis=PxOp()) sqrt(2)*exp(-I*px_1*x/hbar)/(2*sqrt(hbar)*sqrt(pi)) >>> rep_innerproduct(PxKet(), basis=XOp()) sqrt(2)*exp(I*px*x_1/hbar)/(2*sqrt(hbar)*sqrt(pi)) """ if not isinstance(expr, (KetBase, BraBase)): raise TypeError("expr passed is not a Bra or Ket") basis = get_basis(expr, **options) if not isinstance(basis, StateBase): raise NotImplementedError("Can't form this representation!") if not "index" in options: options["index"] = 1 basis_kets = enumerate_states(basis, options["index"], 2) if isinstance(expr, BraBase): bra = expr ket = (basis_kets[1] if basis_kets[0].dual == expr else basis_kets[0]) else: bra = (basis_kets[1].dual if basis_kets[0] == expr else basis_kets[0].dual) ket = expr prod = InnerProduct(bra, ket) result = prod.doit() format = options.get('format', 'sympy') return expr._format_represent(result, format) def rep_expectation(expr, **options): """ Returns an ``<x'|A|x>`` type representation for the given operator. Parameters ========== expr : Operator Operator to be represented in the specified basis Examples ======== >>> from sympy.physics.quantum.cartesian import XOp, PxOp, PxKet >>> from sympy.physics.quantum.represent import rep_expectation >>> rep_expectation(XOp()) x_1*DiracDelta(x_1 - x_2) >>> rep_expectation(XOp(), basis=PxOp()) <px_2|*X*|px_1> >>> rep_expectation(XOp(), basis=PxKet()) <px_2|*X*|px_1> """ if not "index" in options: options["index"] = 1 if not isinstance(expr, Operator): raise TypeError("The passed expression is not an operator") basis_state = get_basis(expr, **options) if basis_state is None or not isinstance(basis_state, StateBase): raise NotImplementedError("Could not get basis kets for this operator") basis_kets = enumerate_states(basis_state, options["index"], 2) bra = basis_kets[1].dual ket = basis_kets[0] return qapply(bra*expr*ket) def integrate_result(orig_expr, result, **options): """ Returns the result of integrating over any unities ``(|x><x|)`` in the given expression. Intended for integrating over the result of representations in continuous bases. This function integrates over any unities that may have been inserted into the quantum expression and returns the result. It uses the interval of the Hilbert space of the basis state passed to it in order to figure out the limits of integration. The unities option must be specified for this to work. Note: This is mostly used internally by represent(). Examples are given merely to show the use cases. Parameters ========== orig_expr : quantum expression The original expression which was to be represented result: Expr The resulting representation that we wish to integrate over Examples ======== >>> from sympy import symbols, DiracDelta >>> from sympy.physics.quantum.represent import integrate_result >>> from sympy.physics.quantum.cartesian import XOp, XKet >>> x_ket = XKet() >>> X_op = XOp() >>> x, x_1, x_2 = symbols('x, x_1, x_2') >>> integrate_result(X_op*x_ket, x*DiracDelta(x-x_1)*DiracDelta(x_1-x_2)) x*DiracDelta(x - x_1)*DiracDelta(x_1 - x_2) >>> integrate_result(X_op*x_ket, x*DiracDelta(x-x_1)*DiracDelta(x_1-x_2), ... unities=[1]) x*DiracDelta(x - x_2) """ if not isinstance(result, Expr): return result options['replace_none'] = True if not "basis" in options: arg = orig_expr.args[-1] options["basis"] = get_basis(arg, **options) elif not isinstance(options["basis"], StateBase): options["basis"] = get_basis(orig_expr, **options) basis = options.pop("basis", None) if basis is None: return result unities = options.pop("unities", []) if len(unities) == 0: return result kets = enumerate_states(basis, unities) coords = [k.label[0] for k in kets] for coord in coords: if coord in result.free_symbols: #TODO: Add support for sets of operators basis_op = state_to_operators(basis) start = basis_op.hilbert_space.interval.start end = basis_op.hilbert_space.interval.end result = integrate(result, (coord, start, end)) return result def get_basis(expr, *, basis=None, replace_none=True, **options): """ Returns a basis state instance corresponding to the basis specified in options=s. If no basis is specified, the function tries to form a default basis state of the given expression. There are three behaviors: 1. The basis specified in options is already an instance of StateBase. If this is the case, it is simply returned. If the class is specified but not an instance, a default instance is returned. 2. The basis specified is an operator or set of operators. If this is the case, the operator_to_state mapping method is used. 3. No basis is specified. If expr is a state, then a default instance of its class is returned. If expr is an operator, then it is mapped to the corresponding state. If it is neither, then we cannot obtain the basis state. If the basis cannot be mapped, then it is not changed. This will be called from within represent, and represent will only pass QExpr's. TODO (?): Support for Muls and other types of expressions? Parameters ========== expr : Operator or StateBase Expression whose basis is sought Examples ======== >>> from sympy.physics.quantum.represent import get_basis >>> from sympy.physics.quantum.cartesian import XOp, XKet, PxOp, PxKet >>> x = XKet() >>> X = XOp() >>> get_basis(x) |x> >>> get_basis(X) |x> >>> get_basis(x, basis=PxOp()) |px> >>> get_basis(x, basis=PxKet) |px> """ if basis is None and not replace_none: return None if basis is None: if isinstance(expr, KetBase): return _make_default(expr.__class__) elif isinstance(expr, BraBase): return _make_default(expr.dual_class()) elif isinstance(expr, Operator): state_inst = operators_to_state(expr) return (state_inst if state_inst is not None else None) else: return None elif (isinstance(basis, Operator) or (not isinstance(basis, StateBase) and issubclass(basis, Operator))): state = operators_to_state(basis) if state is None: return None elif isinstance(state, StateBase): return state else: return _make_default(state) elif isinstance(basis, StateBase): return basis elif issubclass(basis, StateBase): return _make_default(basis) else: return None def _make_default(expr): # XXX: Catching TypeError like this is a bad way of distinguishing # instances from classes. The logic using this function should be # rewritten somehow. try: expr = expr() except TypeError: return expr return expr def enumerate_states(*args, **options): """ Returns instances of the given state with dummy indices appended Operates in two different modes: 1. Two arguments are passed to it. The first is the base state which is to be indexed, and the second argument is a list of indices to append. 2. Three arguments are passed. The first is again the base state to be indexed. The second is the start index for counting. The final argument is the number of kets you wish to receive. Tries to call state._enumerate_state. If this fails, returns an empty list Parameters ========== args : list See list of operation modes above for explanation Examples ======== >>> from sympy.physics.quantum.cartesian import XBra, XKet >>> from sympy.physics.quantum.represent import enumerate_states >>> test = XKet('foo') >>> enumerate_states(test, 1, 3) [|foo_1>, |foo_2>, |foo_3>] >>> test2 = XBra('bar') >>> enumerate_states(test2, [4, 5, 10]) [<bar_4|, <bar_5|, <bar_10|] """ state = args[0] if not (len(args) == 2 or len(args) == 3): raise NotImplementedError("Wrong number of arguments!") if not isinstance(state, StateBase): raise TypeError("First argument is not a state!") if len(args) == 3: num_states = args[2] options['start_index'] = args[1] else: num_states = len(args[1]) options['index_list'] = args[1] try: ret = state._enumerate_state(num_states, **options) except NotImplementedError: ret = [] return ret
2a4d62b36519ccb44c91b9f150416ae8c6d57411d9b0fef3743db89121b918a3
"""Quantum mechanical operators. TODO: * Fix early 0 in apply_operators. * Debug and test apply_operators. * Get cse working with classes in this file. * Doctests and documentation of special methods for InnerProduct, Commutator, AntiCommutator, represent, apply_operators. """ from sympy import Derivative, Expr, Integer, oo, Mul, expand, Add from sympy.printing.pretty.stringpict import prettyForm from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.qexpr import QExpr, dispatch_method from sympy.matrices import eye __all__ = [ 'Operator', 'HermitianOperator', 'UnitaryOperator', 'IdentityOperator', 'OuterProduct', 'DifferentialOperator' ] #----------------------------------------------------------------------------- # Operators and outer products #----------------------------------------------------------------------------- class Operator(QExpr): """Base class for non-commuting quantum operators. An operator maps between quantum states [1]_. In quantum mechanics, observables (including, but not limited to, measured physical values) are represented as Hermitian operators [2]_. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the operator. For time-dependent operators, this will include the time. Examples ======== Create an operator and examine its attributes:: >>> from sympy.physics.quantum import Operator >>> from sympy import I >>> A = Operator('A') >>> A A >>> A.hilbert_space H >>> A.label (A,) >>> A.is_commutative False Create another operator and do some arithmetic operations:: >>> B = Operator('B') >>> C = 2*A*A + I*B >>> C 2*A**2 + I*B Operators don't commute:: >>> A.is_commutative False >>> B.is_commutative False >>> A*B == B*A False Polymonials of operators respect the commutation properties:: >>> e = (A+B)**3 >>> e.expand() A*B*A + A*B**2 + A**2*B + A**3 + B*A*B + B*A**2 + B**2*A + B**3 Operator inverses are handle symbolically:: >>> A.inv() A**(-1) >>> A*A.inv() 1 References ========== .. [1] https://en.wikipedia.org/wiki/Operator_%28physics%29 .. [2] https://en.wikipedia.org/wiki/Observable """ @classmethod def default_args(self): return ("O",) #------------------------------------------------------------------------- # Printing #------------------------------------------------------------------------- _label_separator = ',' def _print_operator_name(self, printer, *args): return self.__class__.__name__ _print_operator_name_latex = _print_operator_name def _print_operator_name_pretty(self, printer, *args): return prettyForm(self.__class__.__name__) def _print_contents(self, printer, *args): if len(self.label) == 1: return self._print_label(printer, *args) else: return '%s(%s)' % ( self._print_operator_name(printer, *args), self._print_label(printer, *args) ) def _print_contents_pretty(self, printer, *args): if len(self.label) == 1: return self._print_label_pretty(printer, *args) else: pform = self._print_operator_name_pretty(printer, *args) label_pform = self._print_label_pretty(printer, *args) label_pform = prettyForm( *label_pform.parens(left='(', right=')') ) pform = prettyForm(*pform.right(label_pform)) return pform def _print_contents_latex(self, printer, *args): if len(self.label) == 1: return self._print_label_latex(printer, *args) else: return r'%s\left(%s\right)' % ( self._print_operator_name_latex(printer, *args), self._print_label_latex(printer, *args) ) #------------------------------------------------------------------------- # _eval_* methods #------------------------------------------------------------------------- def _eval_commutator(self, other, **options): """Evaluate [self, other] if known, return None if not known.""" return dispatch_method(self, '_eval_commutator', other, **options) def _eval_anticommutator(self, other, **options): """Evaluate [self, other] if known.""" return dispatch_method(self, '_eval_anticommutator', other, **options) #------------------------------------------------------------------------- # Operator application #------------------------------------------------------------------------- def _apply_operator(self, ket, **options): return dispatch_method(self, '_apply_operator', ket, **options) def matrix_element(self, *args): raise NotImplementedError('matrix_elements is not defined') def inverse(self): return self._eval_inverse() inv = inverse def _eval_inverse(self): return self**(-1) def __mul__(self, other): if isinstance(other, IdentityOperator): return self return Mul(self, other) class HermitianOperator(Operator): """A Hermitian operator that satisfies H == Dagger(H). Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the operator. For time-dependent operators, this will include the time. Examples ======== >>> from sympy.physics.quantum import Dagger, HermitianOperator >>> H = HermitianOperator('H') >>> Dagger(H) H """ is_hermitian = True def _eval_inverse(self): if isinstance(self, UnitaryOperator): return self else: return Operator._eval_inverse(self) def _eval_power(self, exp): if isinstance(self, UnitaryOperator): if exp == -1: return Operator._eval_power(self, exp) elif abs(exp) % 2 == 0: return self*(Operator._eval_inverse(self)) else: return self else: return Operator._eval_power(self, exp) class UnitaryOperator(Operator): """A unitary operator that satisfies U*Dagger(U) == 1. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the operator. For time-dependent operators, this will include the time. Examples ======== >>> from sympy.physics.quantum import Dagger, UnitaryOperator >>> U = UnitaryOperator('U') >>> U*Dagger(U) 1 """ def _eval_adjoint(self): return self._eval_inverse() class IdentityOperator(Operator): """An identity operator I that satisfies op * I == I * op == op for any operator op. Parameters ========== N : Integer Optional parameter that specifies the dimension of the Hilbert space of operator. This is used when generating a matrix representation. Examples ======== >>> from sympy.physics.quantum import IdentityOperator >>> IdentityOperator() I """ @property def dimension(self): return self.N @classmethod def default_args(self): return (oo,) def __init__(self, *args, **hints): if not len(args) in [0, 1]: raise ValueError('0 or 1 parameters expected, got %s' % args) self.N = args[0] if (len(args) == 1 and args[0]) else oo def _eval_commutator(self, other, **hints): return Integer(0) def _eval_anticommutator(self, other, **hints): return 2 * other def _eval_inverse(self): return self def _eval_adjoint(self): return self def _apply_operator(self, ket, **options): return ket def _eval_power(self, exp): return self def _print_contents(self, printer, *args): return 'I' def _print_contents_pretty(self, printer, *args): return prettyForm('I') def _print_contents_latex(self, printer, *args): return r'{\mathcal{I}}' def __mul__(self, other): if isinstance(other, (Operator, Dagger)): return other return Mul(self, other) def _represent_default_basis(self, **options): if not self.N or self.N == oo: raise NotImplementedError('Cannot represent infinite dimensional' + ' identity operator as a matrix') format = options.get('format', 'sympy') if format != 'sympy': raise NotImplementedError('Representation in format ' + '%s not implemented.' % format) return eye(self.N) class OuterProduct(Operator): """An unevaluated outer product between a ket and bra. This constructs an outer product between any subclass of ``KetBase`` and ``BraBase`` as ``|a><b|``. An ``OuterProduct`` inherits from Operator as they act as operators in quantum expressions. For reference see [1]_. Parameters ========== ket : KetBase The ket on the left side of the outer product. bar : BraBase The bra on the right side of the outer product. Examples ======== Create a simple outer product by hand and take its dagger:: >>> from sympy.physics.quantum import Ket, Bra, OuterProduct, Dagger >>> from sympy.physics.quantum import Operator >>> k = Ket('k') >>> b = Bra('b') >>> op = OuterProduct(k, b) >>> op |k><b| >>> op.hilbert_space H >>> op.ket |k> >>> op.bra <b| >>> Dagger(op) |b><k| In simple products of kets and bras outer products will be automatically identified and created:: >>> k*b |k><b| But in more complex expressions, outer products are not automatically created:: >>> A = Operator('A') >>> A*k*b A*|k>*<b| A user can force the creation of an outer product in a complex expression by using parentheses to group the ket and bra:: >>> A*(k*b) A*|k><b| References ========== .. [1] https://en.wikipedia.org/wiki/Outer_product """ is_commutative = False def __new__(cls, *args, **old_assumptions): from sympy.physics.quantum.state import KetBase, BraBase if len(args) != 2: raise ValueError('2 parameters expected, got %d' % len(args)) ket_expr = expand(args[0]) bra_expr = expand(args[1]) if (isinstance(ket_expr, (KetBase, Mul)) and isinstance(bra_expr, (BraBase, Mul))): ket_c, kets = ket_expr.args_cnc() bra_c, bras = bra_expr.args_cnc() if len(kets) != 1 or not isinstance(kets[0], KetBase): raise TypeError('KetBase subclass expected' ', got: %r' % Mul(*kets)) if len(bras) != 1 or not isinstance(bras[0], BraBase): raise TypeError('BraBase subclass expected' ', got: %r' % Mul(*bras)) if not kets[0].dual_class() == bras[0].__class__: raise TypeError( 'ket and bra are not dual classes: %r, %r' % (kets[0].__class__, bras[0].__class__) ) # TODO: make sure the hilbert spaces of the bra and ket are # compatible obj = Expr.__new__(cls, *(kets[0], bras[0]), **old_assumptions) obj.hilbert_space = kets[0].hilbert_space return Mul(*(ket_c + bra_c)) * obj op_terms = [] if isinstance(ket_expr, Add) and isinstance(bra_expr, Add): for ket_term in ket_expr.args: for bra_term in bra_expr.args: op_terms.append(OuterProduct(ket_term, bra_term, **old_assumptions)) elif isinstance(ket_expr, Add): for ket_term in ket_expr.args: op_terms.append(OuterProduct(ket_term, bra_expr, **old_assumptions)) elif isinstance(bra_expr, Add): for bra_term in bra_expr.args: op_terms.append(OuterProduct(ket_expr, bra_term, **old_assumptions)) else: raise TypeError( 'Expected ket and bra expression, got: %r, %r' % (ket_expr, bra_expr) ) return Add(*op_terms) @property def ket(self): """Return the ket on the left side of the outer product.""" return self.args[0] @property def bra(self): """Return the bra on the right side of the outer product.""" return self.args[1] def _eval_adjoint(self): return OuterProduct(Dagger(self.bra), Dagger(self.ket)) def _sympystr(self, printer, *args): return printer._print(self.ket) + printer._print(self.bra) def _sympyrepr(self, printer, *args): return '%s(%s,%s)' % (self.__class__.__name__, printer._print(self.ket, *args), printer._print(self.bra, *args)) def _pretty(self, printer, *args): pform = self.ket._pretty(printer, *args) return prettyForm(*pform.right(self.bra._pretty(printer, *args))) def _latex(self, printer, *args): k = printer._print(self.ket, *args) b = printer._print(self.bra, *args) return k + b def _represent(self, **options): k = self.ket._represent(**options) b = self.bra._represent(**options) return k*b def _eval_trace(self, **kwargs): # TODO if operands are tensorproducts this may be will be handled # differently. return self.ket._eval_trace(self.bra, **kwargs) class DifferentialOperator(Operator): """An operator for representing the differential operator, i.e. d/dx It is initialized by passing two arguments. The first is an arbitrary expression that involves a function, such as ``Derivative(f(x), x)``. The second is the function (e.g. ``f(x)``) which we are to replace with the ``Wavefunction`` that this ``DifferentialOperator`` is applied to. Parameters ========== expr : Expr The arbitrary expression which the appropriate Wavefunction is to be substituted into func : Expr A function (e.g. f(x)) which is to be replaced with the appropriate Wavefunction when this DifferentialOperator is applied Examples ======== You can define a completely arbitrary expression and specify where the Wavefunction is to be substituted >>> from sympy import Derivative, Function, Symbol >>> from sympy.physics.quantum.operator import DifferentialOperator >>> from sympy.physics.quantum.state import Wavefunction >>> from sympy.physics.quantum.qapply import qapply >>> f = Function('f') >>> x = Symbol('x') >>> d = DifferentialOperator(1/x*Derivative(f(x), x), f(x)) >>> w = Wavefunction(x**2, x) >>> d.function f(x) >>> d.variables (x,) >>> qapply(d*w) Wavefunction(2, x) """ @property def variables(self): """ Returns the variables with which the function in the specified arbitrary expression is evaluated Examples ======== >>> from sympy.physics.quantum.operator import DifferentialOperator >>> from sympy import Symbol, Function, Derivative >>> x = Symbol('x') >>> f = Function('f') >>> d = DifferentialOperator(1/x*Derivative(f(x), x), f(x)) >>> d.variables (x,) >>> y = Symbol('y') >>> d = DifferentialOperator(Derivative(f(x, y), x) + ... Derivative(f(x, y), y), f(x, y)) >>> d.variables (x, y) """ return self.args[-1].args @property def function(self): """ Returns the function which is to be replaced with the Wavefunction Examples ======== >>> from sympy.physics.quantum.operator import DifferentialOperator >>> from sympy import Function, Symbol, Derivative >>> x = Symbol('x') >>> f = Function('f') >>> d = DifferentialOperator(Derivative(f(x), x), f(x)) >>> d.function f(x) >>> y = Symbol('y') >>> d = DifferentialOperator(Derivative(f(x, y), x) + ... Derivative(f(x, y), y), f(x, y)) >>> d.function f(x, y) """ return self.args[-1] @property def expr(self): """ Returns the arbitrary expression which is to have the Wavefunction substituted into it Examples ======== >>> from sympy.physics.quantum.operator import DifferentialOperator >>> from sympy import Function, Symbol, Derivative >>> x = Symbol('x') >>> f = Function('f') >>> d = DifferentialOperator(Derivative(f(x), x), f(x)) >>> d.expr Derivative(f(x), x) >>> y = Symbol('y') >>> d = DifferentialOperator(Derivative(f(x, y), x) + ... Derivative(f(x, y), y), f(x, y)) >>> d.expr Derivative(f(x, y), x) + Derivative(f(x, y), y) """ return self.args[0] @property def free_symbols(self): """ Return the free symbols of the expression. """ return self.expr.free_symbols def _apply_operator_Wavefunction(self, func): from sympy.physics.quantum.state import Wavefunction var = self.variables wf_vars = func.args[1:] f = self.function new_expr = self.expr.subs(f, func(*var)) new_expr = new_expr.doit() return Wavefunction(new_expr, *wf_vars) def _eval_derivative(self, symbol): new_expr = Derivative(self.expr, symbol) return DifferentialOperator(new_expr, self.args[-1]) #------------------------------------------------------------------------- # Printing #------------------------------------------------------------------------- def _print(self, printer, *args): return '%s(%s)' % ( self._print_operator_name(printer, *args), self._print_label(printer, *args) ) def _print_pretty(self, printer, *args): pform = self._print_operator_name_pretty(printer, *args) label_pform = self._print_label_pretty(printer, *args) label_pform = prettyForm( *label_pform.parens(left='(', right=')') ) pform = prettyForm(*pform.right(label_pform)) return pform
11a397f1564938e14c4c08312b5df34f5fd54b7b83e380ff058af2c658d878a3
"""Qubits for quantum computing. Todo: * Finish implementing measurement logic. This should include POVM. * Update docstrings. * Update tests. """ import math from sympy import Integer, log, Mul, Add, Pow, conjugate from sympy.core.basic import sympify from sympy.core.compatibility import SYMPY_INTS from sympy.matrices import Matrix, zeros from sympy.printing.pretty.stringpict import prettyForm from sympy.physics.quantum.hilbert import ComplexSpace from sympy.physics.quantum.state import Ket, Bra, State from sympy.physics.quantum.qexpr import QuantumError from sympy.physics.quantum.represent import represent from sympy.physics.quantum.matrixutils import ( numpy_ndarray, scipy_sparse_matrix ) from mpmath.libmp.libintmath import bitcount __all__ = [ 'Qubit', 'QubitBra', 'IntQubit', 'IntQubitBra', 'qubit_to_matrix', 'matrix_to_qubit', 'matrix_to_density', 'measure_all', 'measure_partial', 'measure_partial_oneshot', 'measure_all_oneshot' ] #----------------------------------------------------------------------------- # Qubit Classes #----------------------------------------------------------------------------- class QubitState(State): """Base class for Qubit and QubitBra.""" #------------------------------------------------------------------------- # Initialization/creation #------------------------------------------------------------------------- @classmethod def _eval_args(cls, args): # If we are passed a QubitState or subclass, we just take its qubit # values directly. if len(args) == 1 and isinstance(args[0], QubitState): return args[0].qubit_values # Turn strings into tuple of strings if len(args) == 1 and isinstance(args[0], str): args = tuple(args[0]) args = sympify(args) # Validate input (must have 0 or 1 input) for element in args: if not (element == 1 or element == 0): raise ValueError( "Qubit values must be 0 or 1, got: %r" % element) return args @classmethod def _eval_hilbert_space(cls, args): return ComplexSpace(2)**len(args) #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def dimension(self): """The number of Qubits in the state.""" return len(self.qubit_values) @property def nqubits(self): return self.dimension @property def qubit_values(self): """Returns the values of the qubits as a tuple.""" return self.label #------------------------------------------------------------------------- # Special methods #------------------------------------------------------------------------- def __len__(self): return self.dimension def __getitem__(self, bit): return self.qubit_values[int(self.dimension - bit - 1)] #------------------------------------------------------------------------- # Utility methods #------------------------------------------------------------------------- def flip(self, *bits): """Flip the bit(s) given.""" newargs = list(self.qubit_values) for i in bits: bit = int(self.dimension - i - 1) if newargs[bit] == 1: newargs[bit] = 0 else: newargs[bit] = 1 return self.__class__(*tuple(newargs)) class Qubit(QubitState, Ket): """A multi-qubit ket in the computational (z) basis. We use the normal convention that the least significant qubit is on the right, so ``|00001>`` has a 1 in the least significant qubit. Parameters ========== values : list, str The qubit values as a list of ints ([0,0,0,1,1,]) or a string ('011'). Examples ======== Create a qubit in a couple of different ways and look at their attributes: >>> from sympy.physics.quantum.qubit import Qubit >>> Qubit(0,0,0) |000> >>> q = Qubit('0101') >>> q |0101> >>> q.nqubits 4 >>> len(q) 4 >>> q.dimension 4 >>> q.qubit_values (0, 1, 0, 1) We can flip the value of an individual qubit: >>> q.flip(1) |0111> We can take the dagger of a Qubit to get a bra: >>> from sympy.physics.quantum.dagger import Dagger >>> Dagger(q) <0101| >>> type(Dagger(q)) <class 'sympy.physics.quantum.qubit.QubitBra'> Inner products work as expected: >>> ip = Dagger(q)*q >>> ip <0101|0101> >>> ip.doit() 1 """ @classmethod def dual_class(self): return QubitBra def _eval_innerproduct_QubitBra(self, bra, **hints): if self.label == bra.label: return Integer(1) else: return Integer(0) def _represent_default_basis(self, **options): return self._represent_ZGate(None, **options) def _represent_ZGate(self, basis, **options): """Represent this qubits in the computational basis (ZGate). """ _format = options.get('format', 'sympy') n = 1 definite_state = 0 for it in reversed(self.qubit_values): definite_state += n*it n = n*2 result = [0]*(2**self.dimension) result[int(definite_state)] = 1 if _format == 'sympy': return Matrix(result) elif _format == 'numpy': import numpy as np return np.matrix(result, dtype='complex').transpose() elif _format == 'scipy.sparse': from scipy import sparse return sparse.csr_matrix(result, dtype='complex').transpose() def _eval_trace(self, bra, **kwargs): indices = kwargs.get('indices', []) #sort index list to begin trace from most-significant #qubit sorted_idx = list(indices) if len(sorted_idx) == 0: sorted_idx = list(range(0, self.nqubits)) sorted_idx.sort() #trace out for each of index new_mat = self*bra for i in range(len(sorted_idx) - 1, -1, -1): # start from tracing out from leftmost qubit new_mat = self._reduced_density(new_mat, int(sorted_idx[i])) if (len(sorted_idx) == self.nqubits): #in case full trace was requested return new_mat[0] else: return matrix_to_density(new_mat) def _reduced_density(self, matrix, qubit, **options): """Compute the reduced density matrix by tracing out one qubit. The qubit argument should be of type python int, since it is used in bit operations """ def find_index_that_is_projected(j, k, qubit): bit_mask = 2**qubit - 1 return ((j >> qubit) << (1 + qubit)) + (j & bit_mask) + (k << qubit) old_matrix = represent(matrix, **options) old_size = old_matrix.cols #we expect the old_size to be even new_size = old_size//2 new_matrix = Matrix().zeros(new_size) for i in range(new_size): for j in range(new_size): for k in range(2): col = find_index_that_is_projected(j, k, qubit) row = find_index_that_is_projected(i, k, qubit) new_matrix[i, j] += old_matrix[row, col] return new_matrix class QubitBra(QubitState, Bra): """A multi-qubit bra in the computational (z) basis. We use the normal convention that the least significant qubit is on the right, so ``|00001>`` has a 1 in the least significant qubit. Parameters ========== values : list, str The qubit values as a list of ints ([0,0,0,1,1,]) or a string ('011'). See also ======== Qubit: Examples using qubits """ @classmethod def dual_class(self): return Qubit class IntQubitState(QubitState): """A base class for qubits that work with binary representations.""" @classmethod def _eval_args(cls, args, nqubits=None): # The case of a QubitState instance if len(args) == 1 and isinstance(args[0], QubitState): return QubitState._eval_args(args) # otherwise, args should be integer elif not all(isinstance(a, (int, Integer)) for a in args): raise ValueError('values must be integers, got (%s)' % (tuple(type(a) for a in args),)) # use nqubits if specified if nqubits is not None: if not isinstance(nqubits, (int, Integer)): raise ValueError('nqubits must be an integer, got (%s)' % type(nqubits)) if len(args) != 1: raise ValueError( 'too many positional arguments (%s). should be (number, nqubits=n)' % (args,)) return cls._eval_args_with_nqubits(args[0], nqubits) # For a single argument, we construct the binary representation of # that integer with the minimal number of bits. if len(args) == 1 and args[0] > 1: #rvalues is the minimum number of bits needed to express the number rvalues = reversed(range(bitcount(abs(args[0])))) qubit_values = [(args[0] >> i) & 1 for i in rvalues] return QubitState._eval_args(qubit_values) # For two numbers, the second number is the number of bits # on which it is expressed, so IntQubit(0,5) == |00000>. elif len(args) == 2 and args[1] > 1: return cls._eval_args_with_nqubits(args[0], args[1]) else: return QubitState._eval_args(args) @classmethod def _eval_args_with_nqubits(cls, number, nqubits): need = bitcount(abs(number)) if nqubits < need: raise ValueError( 'cannot represent %s with %s bits' % (number, nqubits)) qubit_values = [(number >> i) & 1 for i in reversed(range(nqubits))] return QubitState._eval_args(qubit_values) def as_int(self): """Return the numerical value of the qubit.""" number = 0 n = 1 for i in reversed(self.qubit_values): number += n*i n = n << 1 return number def _print_label(self, printer, *args): return str(self.as_int()) def _print_label_pretty(self, printer, *args): label = self._print_label(printer, *args) return prettyForm(label) _print_label_repr = _print_label _print_label_latex = _print_label class IntQubit(IntQubitState, Qubit): """A qubit ket that store integers as binary numbers in qubit values. The differences between this class and ``Qubit`` are: * The form of the constructor. * The qubit values are printed as their corresponding integer, rather than the raw qubit values. The internal storage format of the qubit values in the same as ``Qubit``. Parameters ========== values : int, tuple If a single argument, the integer we want to represent in the qubit values. This integer will be represented using the fewest possible number of qubits. If a pair of integers and the second value is more than one, the first integer gives the integer to represent in binary form and the second integer gives the number of qubits to use. List of zeros and ones is also accepted to generate qubit by bit pattern. nqubits : int The integer that represents the number of qubits. This number should be passed with keyword ``nqubits=N``. You can use this in order to avoid ambiguity of Qubit-style tuple of bits. Please see the example below for more details. Examples ======== Create a qubit for the integer 5: >>> from sympy.physics.quantum.qubit import IntQubit >>> from sympy.physics.quantum.qubit import Qubit >>> q = IntQubit(5) >>> q |5> We can also create an ``IntQubit`` by passing a ``Qubit`` instance. >>> q = IntQubit(Qubit('101')) >>> q |5> >>> q.as_int() 5 >>> q.nqubits 3 >>> q.qubit_values (1, 0, 1) We can go back to the regular qubit form. >>> Qubit(q) |101> Please note that ``IntQubit`` also accepts a ``Qubit``-style list of bits. So, the code below yields qubits 3, not a single bit ``1``. >>> IntQubit(1, 1) |3> To avoid ambiguity, use ``nqubits`` parameter. Use of this keyword is recommended especially when you provide the values by variables. >>> IntQubit(1, nqubits=1) |1> >>> a = 1 >>> IntQubit(a, nqubits=1) |1> """ @classmethod def dual_class(self): return IntQubitBra def _eval_innerproduct_IntQubitBra(self, bra, **hints): return Qubit._eval_innerproduct_QubitBra(self, bra) class IntQubitBra(IntQubitState, QubitBra): """A qubit bra that store integers as binary numbers in qubit values.""" @classmethod def dual_class(self): return IntQubit #----------------------------------------------------------------------------- # Qubit <---> Matrix conversion functions #----------------------------------------------------------------------------- def matrix_to_qubit(matrix): """Convert from the matrix repr. to a sum of Qubit objects. Parameters ---------- matrix : Matrix, numpy.matrix, scipy.sparse The matrix to build the Qubit representation of. This works with sympy matrices, numpy matrices and scipy.sparse sparse matrices. Examples ======== Represent a state and then go back to its qubit form: >>> from sympy.physics.quantum.qubit import matrix_to_qubit, Qubit >>> from sympy.physics.quantum.represent import represent >>> q = Qubit('01') >>> matrix_to_qubit(represent(q)) |01> """ # Determine the format based on the type of the input matrix format = 'sympy' if isinstance(matrix, numpy_ndarray): format = 'numpy' if isinstance(matrix, scipy_sparse_matrix): format = 'scipy.sparse' # Make sure it is of correct dimensions for a Qubit-matrix representation. # This logic should work with sympy, numpy or scipy.sparse matrices. if matrix.shape[0] == 1: mlistlen = matrix.shape[1] nqubits = log(mlistlen, 2) ket = False cls = QubitBra elif matrix.shape[1] == 1: mlistlen = matrix.shape[0] nqubits = log(mlistlen, 2) ket = True cls = Qubit else: raise QuantumError( 'Matrix must be a row/column vector, got %r' % matrix ) if not isinstance(nqubits, Integer): raise QuantumError('Matrix must be a row/column vector of size ' '2**nqubits, got: %r' % matrix) # Go through each item in matrix, if element is non-zero, make it into a # Qubit item times the element. result = 0 for i in range(mlistlen): if ket: element = matrix[i, 0] else: element = matrix[0, i] if format == 'numpy' or format == 'scipy.sparse': element = complex(element) if element != 0.0: # Form Qubit array; 0 in bit-locations where i is 0, 1 in # bit-locations where i is 1 qubit_array = [int(i & (1 << x) != 0) for x in range(nqubits)] qubit_array.reverse() result = result + element*cls(*qubit_array) # If sympy simplified by pulling out a constant coefficient, undo that. if isinstance(result, (Mul, Add, Pow)): result = result.expand() return result def matrix_to_density(mat): """ Works by finding the eigenvectors and eigenvalues of the matrix. We know we can decompose rho by doing: sum(EigenVal*|Eigenvect><Eigenvect|) """ from sympy.physics.quantum.density import Density eigen = mat.eigenvects() args = [[matrix_to_qubit(Matrix( [vector, ])), x[0]] for x in eigen for vector in x[2] if x[0] != 0] if (len(args) == 0): return 0 else: return Density(*args) def qubit_to_matrix(qubit, format='sympy'): """Converts an Add/Mul of Qubit objects into it's matrix representation This function is the inverse of ``matrix_to_qubit`` and is a shorthand for ``represent(qubit)``. """ return represent(qubit, format=format) #----------------------------------------------------------------------------- # Measurement #----------------------------------------------------------------------------- def measure_all(qubit, format='sympy', normalize=True): """Perform an ensemble measurement of all qubits. Parameters ========== qubit : Qubit, Add The qubit to measure. This can be any Qubit or a linear combination of them. format : str The format of the intermediate matrices to use. Possible values are ('sympy','numpy','scipy.sparse'). Currently only 'sympy' is implemented. Returns ======= result : list A list that consists of primitive states and their probabilities. Examples ======== >>> from sympy.physics.quantum.qubit import Qubit, measure_all >>> from sympy.physics.quantum.gate import H >>> from sympy.physics.quantum.qapply import qapply >>> c = H(0)*H(1)*Qubit('00') >>> c H(0)*H(1)*|00> >>> q = qapply(c) >>> measure_all(q) [(|00>, 1/4), (|01>, 1/4), (|10>, 1/4), (|11>, 1/4)] """ m = qubit_to_matrix(qubit, format) if format == 'sympy': results = [] if normalize: m = m.normalized() size = max(m.shape) # Max of shape to account for bra or ket nqubits = int(math.log(size)/math.log(2)) for i in range(size): if m[i] != 0.0: results.append( (Qubit(IntQubit(i, nqubits=nqubits)), m[i]*conjugate(m[i])) ) return results else: raise NotImplementedError( "This function can't handle non-sympy matrix formats yet" ) def measure_partial(qubit, bits, format='sympy', normalize=True): """Perform a partial ensemble measure on the specified qubits. Parameters ========== qubits : Qubit The qubit to measure. This can be any Qubit or a linear combination of them. bits : tuple The qubits to measure. format : str The format of the intermediate matrices to use. Possible values are ('sympy','numpy','scipy.sparse'). Currently only 'sympy' is implemented. Returns ======= result : list A list that consists of primitive states and their probabilities. Examples ======== >>> from sympy.physics.quantum.qubit import Qubit, measure_partial >>> from sympy.physics.quantum.gate import H >>> from sympy.physics.quantum.qapply import qapply >>> c = H(0)*H(1)*Qubit('00') >>> c H(0)*H(1)*|00> >>> q = qapply(c) >>> measure_partial(q, (0,)) [(sqrt(2)*|00>/2 + sqrt(2)*|10>/2, 1/2), (sqrt(2)*|01>/2 + sqrt(2)*|11>/2, 1/2)] """ m = qubit_to_matrix(qubit, format) if isinstance(bits, (SYMPY_INTS, Integer)): bits = (int(bits),) if format == 'sympy': if normalize: m = m.normalized() possible_outcomes = _get_possible_outcomes(m, bits) # Form output from function. output = [] for outcome in possible_outcomes: # Calculate probability of finding the specified bits with # given values. prob_of_outcome = 0 prob_of_outcome += (outcome.H*outcome)[0] # If the output has a chance, append it to output with found # probability. if prob_of_outcome != 0: if normalize: next_matrix = matrix_to_qubit(outcome.normalized()) else: next_matrix = matrix_to_qubit(outcome) output.append(( next_matrix, prob_of_outcome )) return output else: raise NotImplementedError( "This function can't handle non-sympy matrix formats yet" ) def measure_partial_oneshot(qubit, bits, format='sympy'): """Perform a partial oneshot measurement on the specified qubits. A oneshot measurement is equivalent to performing a measurement on a quantum system. This type of measurement does not return the probabilities like an ensemble measurement does, but rather returns *one* of the possible resulting states. The exact state that is returned is determined by picking a state randomly according to the ensemble probabilities. Parameters ---------- qubits : Qubit The qubit to measure. This can be any Qubit or a linear combination of them. bits : tuple The qubits to measure. format : str The format of the intermediate matrices to use. Possible values are ('sympy','numpy','scipy.sparse'). Currently only 'sympy' is implemented. Returns ------- result : Qubit The qubit that the system collapsed to upon measurement. """ import random m = qubit_to_matrix(qubit, format) if format == 'sympy': m = m.normalized() possible_outcomes = _get_possible_outcomes(m, bits) # Form output from function random_number = random.random() total_prob = 0 for outcome in possible_outcomes: # Calculate probability of finding the specified bits # with given values total_prob += (outcome.H*outcome)[0] if total_prob >= random_number: return matrix_to_qubit(outcome.normalized()) else: raise NotImplementedError( "This function can't handle non-sympy matrix formats yet" ) def _get_possible_outcomes(m, bits): """Get the possible states that can be produced in a measurement. Parameters ---------- m : Matrix The matrix representing the state of the system. bits : tuple, list Which bits will be measured. Returns ------- result : list The list of possible states which can occur given this measurement. These are un-normalized so we can derive the probability of finding this state by taking the inner product with itself """ # This is filled with loads of dirty binary tricks...You have been warned size = max(m.shape) # Max of shape to account for bra or ket nqubits = int(math.log(size, 2) + .1) # Number of qubits possible # Make the output states and put in output_matrices, nothing in them now. # Each state will represent a possible outcome of the measurement # Thus, output_matrices[0] is the matrix which we get when all measured # bits return 0. and output_matrices[1] is the matrix for only the 0th # bit being true output_matrices = [] for i in range(1 << len(bits)): output_matrices.append(zeros(2**nqubits, 1)) # Bitmasks will help sort how to determine possible outcomes. # When the bit mask is and-ed with a matrix-index, # it will determine which state that index belongs to bit_masks = [] for bit in bits: bit_masks.append(1 << bit) # Make possible outcome states for i in range(2**nqubits): trueness = 0 # This tells us to which output_matrix this value belongs # Find trueness for j in range(len(bit_masks)): if i & bit_masks[j]: trueness += j + 1 # Put the value in the correct output matrix output_matrices[trueness][i] = m[i] return output_matrices def measure_all_oneshot(qubit, format='sympy'): """Perform a oneshot ensemble measurement on all qubits. A oneshot measurement is equivalent to performing a measurement on a quantum system. This type of measurement does not return the probabilities like an ensemble measurement does, but rather returns *one* of the possible resulting states. The exact state that is returned is determined by picking a state randomly according to the ensemble probabilities. Parameters ---------- qubits : Qubit The qubit to measure. This can be any Qubit or a linear combination of them. format : str The format of the intermediate matrices to use. Possible values are ('sympy','numpy','scipy.sparse'). Currently only 'sympy' is implemented. Returns ------- result : Qubit The qubit that the system collapsed to upon measurement. """ import random m = qubit_to_matrix(qubit) if format == 'sympy': m = m.normalized() random_number = random.random() total = 0 result = 0 for i in m: total += i*i.conjugate() if total > random_number: break result += 1 return Qubit(IntQubit(result, int(math.log(max(m.shape), 2) + .1))) else: raise NotImplementedError( "This function can't handle non-sympy matrix formats yet" )
132eb6497382dac59e72695b08bc2d72343e02a06f8a10891505ec54a90c814a
"""Symbolic inner product.""" from sympy import Expr, conjugate from sympy.printing.pretty.stringpict import prettyForm from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.state import KetBase, BraBase __all__ = [ 'InnerProduct' ] # InnerProduct is not an QExpr because it is really just a regular commutative # number. We have gone back and forth about this, but we gain a lot by having # it subclass Expr. The main challenges were getting Dagger to work # (we use _eval_conjugate) and represent (we can use atoms and subs). Having # it be an Expr, mean that there are no commutative QExpr subclasses, # which simplifies the design of everything. class InnerProduct(Expr): """An unevaluated inner product between a Bra and a Ket [1]. Parameters ========== bra : BraBase or subclass The bra on the left side of the inner product. ket : KetBase or subclass The ket on the right side of the inner product. Examples ======== Create an InnerProduct and check its properties: >>> from sympy.physics.quantum import Bra, Ket >>> b = Bra('b') >>> k = Ket('k') >>> ip = b*k >>> ip <b|k> >>> ip.bra <b| >>> ip.ket |k> In simple products of kets and bras inner products will be automatically identified and created:: >>> b*k <b|k> But in more complex expressions, there is ambiguity in whether inner or outer products should be created:: >>> k*b*k*b |k><b|*|k>*<b| A user can force the creation of a inner products in a complex expression by using parentheses to group the bra and ket:: >>> k*(b*k)*b <b|k>*|k>*<b| Notice how the inner product <b|k> moved to the left of the expression because inner products are commutative complex numbers. References ========== .. [1] https://en.wikipedia.org/wiki/Inner_product """ is_complex = True def __new__(cls, bra, ket): if not isinstance(ket, KetBase): raise TypeError('KetBase subclass expected, got: %r' % ket) if not isinstance(bra, BraBase): raise TypeError('BraBase subclass expected, got: %r' % ket) obj = Expr.__new__(cls, bra, ket) return obj @property def bra(self): return self.args[0] @property def ket(self): return self.args[1] def _eval_conjugate(self): return InnerProduct(Dagger(self.ket), Dagger(self.bra)) def _sympyrepr(self, printer, *args): return '%s(%s,%s)' % (self.__class__.__name__, printer._print(self.bra, *args), printer._print(self.ket, *args)) def _sympystr(self, printer, *args): sbra = printer._print(self.bra) sket = printer._print(self.ket) return '%s|%s' % (sbra[:-1], sket[1:]) def _pretty(self, printer, *args): # Print state contents bra = self.bra._print_contents_pretty(printer, *args) ket = self.ket._print_contents_pretty(printer, *args) # Print brackets height = max(bra.height(), ket.height()) use_unicode = printer._use_unicode lbracket, _ = self.bra._pretty_brackets(height, use_unicode) cbracket, rbracket = self.ket._pretty_brackets(height, use_unicode) # Build innerproduct pform = prettyForm(*bra.left(lbracket)) pform = prettyForm(*pform.right(cbracket)) pform = prettyForm(*pform.right(ket)) pform = prettyForm(*pform.right(rbracket)) return pform def _latex(self, printer, *args): bra_label = self.bra._print_contents_latex(printer, *args) ket = printer._print(self.ket, *args) return r'\left\langle %s \right. %s' % (bra_label, ket) def doit(self, **hints): try: r = self.ket._eval_innerproduct(self.bra, **hints) except NotImplementedError: try: r = conjugate( self.bra.dual._eval_innerproduct(self.ket.dual, **hints) ) except NotImplementedError: r = None if r is not None: return r return self
315068cf8b80f369ee275201a0d7785cdc5fb91a21e0428772af5e848f1931ae
from sympy import Expr, sympify, Symbol, Matrix from sympy.printing.pretty.stringpict import prettyForm from sympy.core.containers import Tuple from sympy.core.compatibility import is_sequence from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.matrixutils import ( numpy_ndarray, scipy_sparse_matrix, to_sympy, to_numpy, to_scipy_sparse ) __all__ = [ 'QuantumError', 'QExpr' ] #----------------------------------------------------------------------------- # Error handling #----------------------------------------------------------------------------- class QuantumError(Exception): pass def _qsympify_sequence(seq): """Convert elements of a sequence to standard form. This is like sympify, but it performs special logic for arguments passed to QExpr. The following conversions are done: * (list, tuple, Tuple) => _qsympify_sequence each element and convert sequence to a Tuple. * basestring => Symbol * Matrix => Matrix * other => sympify Strings are passed to Symbol, not sympify to make sure that variables like 'pi' are kept as Symbols, not the SymPy built-in number subclasses. Examples ======== >>> from sympy.physics.quantum.qexpr import _qsympify_sequence >>> _qsympify_sequence((1,2,[3,4,[1,]])) (1, 2, (3, 4, (1,))) """ return tuple(__qsympify_sequence_helper(seq)) def __qsympify_sequence_helper(seq): """ Helper function for _qsympify_sequence This function does the actual work. """ #base case. If not a list, do Sympification if not is_sequence(seq): if isinstance(seq, Matrix): return seq elif isinstance(seq, str): return Symbol(seq) else: return sympify(seq) # base condition, when seq is QExpr and also # is iterable. if isinstance(seq, QExpr): return seq #if list, recurse on each item in the list result = [__qsympify_sequence_helper(item) for item in seq] return Tuple(*result) #----------------------------------------------------------------------------- # Basic Quantum Expression from which all objects descend #----------------------------------------------------------------------------- class QExpr(Expr): """A base class for all quantum object like operators and states.""" # In sympy, slots are for instance attributes that are computed # dynamically by the __new__ method. They are not part of args, but they # derive from args. # The Hilbert space a quantum Object belongs to. __slots__ = ('hilbert_space') is_commutative = False # The separator used in printing the label. _label_separator = '' @property def free_symbols(self): return {self} def __new__(cls, *args, **kwargs): """Construct a new quantum object. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the quantum object. For a state, this will be its symbol or its set of quantum numbers. Examples ======== >>> from sympy.physics.quantum.qexpr import QExpr >>> q = QExpr(0) >>> q 0 >>> q.label (0,) >>> q.hilbert_space H >>> q.args (0,) >>> q.is_commutative False """ # First compute args and call Expr.__new__ to create the instance args = cls._eval_args(args, **kwargs) if len(args) == 0: args = cls._eval_args(tuple(cls.default_args()), **kwargs) inst = Expr.__new__(cls, *args) # Now set the slots on the instance inst.hilbert_space = cls._eval_hilbert_space(args) return inst @classmethod def _new_rawargs(cls, hilbert_space, *args, **old_assumptions): """Create new instance of this class with hilbert_space and args. This is used to bypass the more complex logic in the ``__new__`` method in cases where you already have the exact ``hilbert_space`` and ``args``. This should be used when you are positive these arguments are valid, in their final, proper form and want to optimize the creation of the object. """ obj = Expr.__new__(cls, *args, **old_assumptions) obj.hilbert_space = hilbert_space return obj #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def label(self): """The label is the unique set of identifiers for the object. Usually, this will include all of the information about the state *except* the time (in the case of time-dependent objects). This must be a tuple, rather than a Tuple. """ if len(self.args) == 0: # If there is no label specified, return the default return self._eval_args(list(self.default_args())) else: return self.args @property def is_symbolic(self): return True @classmethod def default_args(self): """If no arguments are specified, then this will return a default set of arguments to be run through the constructor. NOTE: Any classes that override this MUST return a tuple of arguments. Should be overridden by subclasses to specify the default arguments for kets and operators """ raise NotImplementedError("No default arguments for this class!") #------------------------------------------------------------------------- # _eval_* methods #------------------------------------------------------------------------- def _eval_adjoint(self): obj = Expr._eval_adjoint(self) if obj is None: obj = Expr.__new__(Dagger, self) if isinstance(obj, QExpr): obj.hilbert_space = self.hilbert_space return obj @classmethod def _eval_args(cls, args): """Process the args passed to the __new__ method. This simply runs args through _qsympify_sequence. """ return _qsympify_sequence(args) @classmethod def _eval_hilbert_space(cls, args): """Compute the Hilbert space instance from the args. """ from sympy.physics.quantum.hilbert import HilbertSpace return HilbertSpace() #------------------------------------------------------------------------- # Printing #------------------------------------------------------------------------- # Utilities for printing: these operate on raw sympy objects def _print_sequence(self, seq, sep, printer, *args): result = [] for item in seq: result.append(printer._print(item, *args)) return sep.join(result) def _print_sequence_pretty(self, seq, sep, printer, *args): pform = printer._print(seq[0], *args) for item in seq[1:]: pform = prettyForm(*pform.right(sep)) pform = prettyForm(*pform.right(printer._print(item, *args))) return pform # Utilities for printing: these operate prettyForm objects def _print_subscript_pretty(self, a, b): top = prettyForm(*b.left(' '*a.width())) bot = prettyForm(*a.right(' '*b.width())) return prettyForm(binding=prettyForm.POW, *bot.below(top)) def _print_superscript_pretty(self, a, b): return a**b def _print_parens_pretty(self, pform, left='(', right=')'): return prettyForm(*pform.parens(left=left, right=right)) # Printing of labels (i.e. args) def _print_label(self, printer, *args): """Prints the label of the QExpr This method prints self.label, using self._label_separator to separate the elements. This method should not be overridden, instead, override _print_contents to change printing behavior. """ return self._print_sequence( self.label, self._label_separator, printer, *args ) def _print_label_repr(self, printer, *args): return self._print_sequence( self.label, ',', printer, *args ) def _print_label_pretty(self, printer, *args): return self._print_sequence_pretty( self.label, self._label_separator, printer, *args ) def _print_label_latex(self, printer, *args): return self._print_sequence( self.label, self._label_separator, printer, *args ) # Printing of contents (default to label) def _print_contents(self, printer, *args): """Printer for contents of QExpr Handles the printing of any unique identifying contents of a QExpr to print as its contents, such as any variables or quantum numbers. The default is to print the label, which is almost always the args. This should not include printing of any brackets or parenteses. """ return self._print_label(printer, *args) def _print_contents_pretty(self, printer, *args): return self._print_label_pretty(printer, *args) def _print_contents_latex(self, printer, *args): return self._print_label_latex(printer, *args) # Main printing methods def _sympystr(self, printer, *args): """Default printing behavior of QExpr objects Handles the default printing of a QExpr. To add other things to the printing of the object, such as an operator name to operators or brackets to states, the class should override the _print/_pretty/_latex functions directly and make calls to _print_contents where appropriate. This allows things like InnerProduct to easily control its printing the printing of contents. """ return self._print_contents(printer, *args) def _sympyrepr(self, printer, *args): classname = self.__class__.__name__ label = self._print_label_repr(printer, *args) return '%s(%s)' % (classname, label) def _pretty(self, printer, *args): pform = self._print_contents_pretty(printer, *args) return pform def _latex(self, printer, *args): return self._print_contents_latex(printer, *args) #------------------------------------------------------------------------- # Methods from Basic and Expr #------------------------------------------------------------------------- def doit(self, **kw_args): return self #------------------------------------------------------------------------- # Represent #------------------------------------------------------------------------- def _represent_default_basis(self, **options): raise NotImplementedError('This object does not have a default basis') def _represent(self, *, basis=None, **options): """Represent this object in a given basis. This method dispatches to the actual methods that perform the representation. Subclases of QExpr should define various methods to determine how the object will be represented in various bases. The format of these methods is:: def _represent_BasisName(self, basis, **options): Thus to define how a quantum object is represented in the basis of the operator Position, you would define:: def _represent_Position(self, basis, **options): Usually, basis object will be instances of Operator subclasses, but there is a chance we will relax this in the future to accommodate other types of basis sets that are not associated with an operator. If the ``format`` option is given it can be ("sympy", "numpy", "scipy.sparse"). This will ensure that any matrices that result from representing the object are returned in the appropriate matrix format. Parameters ========== basis : Operator The Operator whose basis functions will be used as the basis for representation. options : dict A dictionary of key/value pairs that give options and hints for the representation, such as the number of basis functions to be used. """ if basis is None: result = self._represent_default_basis(**options) else: result = dispatch_method(self, '_represent', basis, **options) # If we get a matrix representation, convert it to the right format. format = options.get('format', 'sympy') result = self._format_represent(result, format) return result def _format_represent(self, result, format): if format == 'sympy' and not isinstance(result, Matrix): return to_sympy(result) elif format == 'numpy' and not isinstance(result, numpy_ndarray): return to_numpy(result) elif format == 'scipy.sparse' and \ not isinstance(result, scipy_sparse_matrix): return to_scipy_sparse(result) return result def split_commutative_parts(e): """Split into commutative and non-commutative parts.""" c_part, nc_part = e.args_cnc() c_part = list(c_part) return c_part, nc_part def split_qexpr_parts(e): """Split an expression into Expr and noncommutative QExpr parts.""" expr_part = [] qexpr_part = [] for arg in e.args: if not isinstance(arg, QExpr): expr_part.append(arg) else: qexpr_part.append(arg) return expr_part, qexpr_part def dispatch_method(self, basename, arg, **options): """Dispatch a method to the proper handlers.""" method_name = '%s_%s' % (basename, arg.__class__.__name__) if hasattr(self, method_name): f = getattr(self, method_name) # This can raise and we will allow it to propagate. result = f(arg, **options) if result is not None: return result raise NotImplementedError( "%s.%s can't handle: %r" % (self.__class__.__name__, basename, arg) )
fd47c1cf3fda746edf8e6ce5d8410342a9874aa2eb4aa20a623b8f84938945b3
"""Grover's algorithm and helper functions. Todo: * W gate construction (or perhaps -W gate based on Mermin's book) * Generalize the algorithm for an unknown function that returns 1 on multiple qubit states, not just one. * Implement _represent_ZGate in OracleGate """ from sympy import floor, pi, sqrt, sympify, eye from sympy.core.numbers import NegativeOne from sympy.physics.quantum.qapply import qapply from sympy.physics.quantum.qexpr import QuantumError from sympy.physics.quantum.hilbert import ComplexSpace from sympy.physics.quantum.operator import UnitaryOperator from sympy.physics.quantum.gate import Gate from sympy.physics.quantum.qubit import IntQubit __all__ = [ 'OracleGate', 'WGate', 'superposition_basis', 'grover_iteration', 'apply_grover' ] def superposition_basis(nqubits): """Creates an equal superposition of the computational basis. Parameters ========== nqubits : int The number of qubits. Returns ======= state : Qubit An equal superposition of the computational basis with nqubits. Examples ======== Create an equal superposition of 2 qubits:: >>> from sympy.physics.quantum.grover import superposition_basis >>> superposition_basis(2) |0>/2 + |1>/2 + |2>/2 + |3>/2 """ amp = 1/sqrt(2**nqubits) return sum([amp*IntQubit(n, nqubits=nqubits) for n in range(2**nqubits)]) class OracleGate(Gate): """A black box gate. The gate marks the desired qubits of an unknown function by flipping the sign of the qubits. The unknown function returns true when it finds its desired qubits and false otherwise. Parameters ========== qubits : int Number of qubits. oracle : callable A callable function that returns a boolean on a computational basis. Examples ======== Apply an Oracle gate that flips the sign of ``|2>`` on different qubits:: >>> from sympy.physics.quantum.qubit import IntQubit >>> from sympy.physics.quantum.qapply import qapply >>> from sympy.physics.quantum.grover import OracleGate >>> f = lambda qubits: qubits == IntQubit(2) >>> v = OracleGate(2, f) >>> qapply(v*IntQubit(2)) -|2> >>> qapply(v*IntQubit(3)) |3> """ gate_name = 'V' gate_name_latex = 'V' #------------------------------------------------------------------------- # Initialization/creation #------------------------------------------------------------------------- @classmethod def _eval_args(cls, args): # TODO: args[1] is not a subclass of Basic if len(args) != 2: raise QuantumError( 'Insufficient/excessive arguments to Oracle. Please ' + 'supply the number of qubits and an unknown function.' ) sub_args = (args[0],) sub_args = UnitaryOperator._eval_args(sub_args) if not sub_args[0].is_Integer: raise TypeError('Integer expected, got: %r' % sub_args[0]) if not callable(args[1]): raise TypeError('Callable expected, got: %r' % args[1]) return (sub_args[0], args[1]) @classmethod def _eval_hilbert_space(cls, args): """This returns the smallest possible Hilbert space.""" return ComplexSpace(2)**args[0] #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def search_function(self): """The unknown function that helps find the sought after qubits.""" return self.label[1] @property def targets(self): """A tuple of target qubits.""" return sympify(tuple(range(self.args[0]))) #------------------------------------------------------------------------- # Apply #------------------------------------------------------------------------- def _apply_operator_Qubit(self, qubits, **options): """Apply this operator to a Qubit subclass. Parameters ========== qubits : Qubit The qubit subclass to apply this operator to. Returns ======= state : Expr The resulting quantum state. """ if qubits.nqubits != self.nqubits: raise QuantumError( 'OracleGate operates on %r qubits, got: %r' % (self.nqubits, qubits.nqubits) ) # If function returns 1 on qubits # return the negative of the qubits (flip the sign) if self.search_function(qubits): return -qubits else: return qubits #------------------------------------------------------------------------- # Represent #------------------------------------------------------------------------- def _represent_ZGate(self, basis, **options): """ Represent the OracleGate in the computational basis. """ nbasis = 2**self.nqubits # compute it only once matrixOracle = eye(nbasis) # Flip the sign given the output of the oracle function for i in range(nbasis): if self.search_function(IntQubit(i, nqubits=self.nqubits)): matrixOracle[i, i] = NegativeOne() return matrixOracle class WGate(Gate): """General n qubit W Gate in Grover's algorithm. The gate performs the operation ``2|phi><phi| - 1`` on some qubits. ``|phi> = (tensor product of n Hadamards)*(|0> with n qubits)`` Parameters ========== nqubits : int The number of qubits to operate on """ gate_name = 'W' gate_name_latex = 'W' @classmethod def _eval_args(cls, args): if len(args) != 1: raise QuantumError( 'Insufficient/excessive arguments to W gate. Please ' + 'supply the number of qubits to operate on.' ) args = UnitaryOperator._eval_args(args) if not args[0].is_Integer: raise TypeError('Integer expected, got: %r' % args[0]) return args #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def targets(self): return sympify(tuple(reversed(range(self.args[0])))) #------------------------------------------------------------------------- # Apply #------------------------------------------------------------------------- def _apply_operator_Qubit(self, qubits, **options): """ qubits: a set of qubits (Qubit) Returns: quantum object (quantum expression - QExpr) """ if qubits.nqubits != self.nqubits: raise QuantumError( 'WGate operates on %r qubits, got: %r' % (self.nqubits, qubits.nqubits) ) # See 'Quantum Computer Science' by David Mermin p.92 -> W|a> result # Return (2/(sqrt(2^n)))|phi> - |a> where |a> is the current basis # state and phi is the superposition of basis states (see function # create_computational_basis above) basis_states = superposition_basis(self.nqubits) change_to_basis = (2/sqrt(2**self.nqubits))*basis_states return change_to_basis - qubits def grover_iteration(qstate, oracle): """Applies one application of the Oracle and W Gate, WV. Parameters ========== qstate : Qubit A superposition of qubits. oracle : OracleGate The black box operator that flips the sign of the desired basis qubits. Returns ======= Qubit : The qubits after applying the Oracle and W gate. Examples ======== Perform one iteration of grover's algorithm to see a phase change:: >>> from sympy.physics.quantum.qapply import qapply >>> from sympy.physics.quantum.qubit import IntQubit >>> from sympy.physics.quantum.grover import OracleGate >>> from sympy.physics.quantum.grover import superposition_basis >>> from sympy.physics.quantum.grover import grover_iteration >>> numqubits = 2 >>> basis_states = superposition_basis(numqubits) >>> f = lambda qubits: qubits == IntQubit(2) >>> v = OracleGate(numqubits, f) >>> qapply(grover_iteration(basis_states, v)) |2> """ wgate = WGate(oracle.nqubits) return wgate*oracle*qstate def apply_grover(oracle, nqubits, iterations=None): """Applies grover's algorithm. Parameters ========== oracle : callable The unknown callable function that returns true when applied to the desired qubits and false otherwise. Returns ======= state : Expr The resulting state after Grover's algorithm has been iterated. Examples ======== Apply grover's algorithm to an even superposition of 2 qubits:: >>> from sympy.physics.quantum.qapply import qapply >>> from sympy.physics.quantum.qubit import IntQubit >>> from sympy.physics.quantum.grover import apply_grover >>> f = lambda qubits: qubits == IntQubit(2) >>> qapply(apply_grover(f, 2)) |2> """ if nqubits <= 0: raise QuantumError( 'Grover\'s algorithm needs nqubits > 0, received %r qubits' % nqubits ) if iterations is None: iterations = floor(sqrt(2**nqubits)*(pi/4)) v = OracleGate(nqubits, oracle) iterated = superposition_basis(nqubits) for iter in range(iterations): iterated = grover_iteration(iterated, v) iterated = qapply(iterated) return iterated
d4859204d2d253ce3d6a6a9baeedde4e76b06c5a6bd44498f14c32de597954ee
from itertools import product from sympy import Tuple, Add, Mul, Matrix, log, expand, S from sympy.core.trace import Tr from sympy.printing.pretty.stringpict import prettyForm from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.operator import HermitianOperator from sympy.physics.quantum.represent import represent from sympy.physics.quantum.matrixutils import numpy_ndarray, scipy_sparse_matrix, to_numpy from sympy.physics.quantum.tensorproduct import TensorProduct, tensor_product_simp class Density(HermitianOperator): """Density operator for representing mixed states. TODO: Density operator support for Qubits Parameters ========== values : tuples/lists Each tuple/list should be of form (state, prob) or [state,prob] Examples ======== Create a density operator with 2 states represented by Kets. >>> from sympy.physics.quantum.state import Ket >>> from sympy.physics.quantum.density import Density >>> d = Density([Ket(0), 0.5], [Ket(1),0.5]) >>> d Density((|0>, 0.5),(|1>, 0.5)) """ @classmethod def _eval_args(cls, args): # call this to qsympify the args args = super()._eval_args(args) for arg in args: # Check if arg is a tuple if not (isinstance(arg, Tuple) and len(arg) == 2): raise ValueError("Each argument should be of form [state,prob]" " or ( state, prob )") return args def states(self): """Return list of all states. Examples ======== >>> from sympy.physics.quantum.state import Ket >>> from sympy.physics.quantum.density import Density >>> d = Density([Ket(0), 0.5], [Ket(1),0.5]) >>> d.states() (|0>, |1>) """ return Tuple(*[arg[0] for arg in self.args]) def probs(self): """Return list of all probabilities. Examples ======== >>> from sympy.physics.quantum.state import Ket >>> from sympy.physics.quantum.density import Density >>> d = Density([Ket(0), 0.5], [Ket(1),0.5]) >>> d.probs() (0.5, 0.5) """ return Tuple(*[arg[1] for arg in self.args]) def get_state(self, index): """Return specific state by index. Parameters ========== index : index of state to be returned Examples ======== >>> from sympy.physics.quantum.state import Ket >>> from sympy.physics.quantum.density import Density >>> d = Density([Ket(0), 0.5], [Ket(1),0.5]) >>> d.states()[1] |1> """ state = self.args[index][0] return state def get_prob(self, index): """Return probability of specific state by index. Parameters =========== index : index of states whose probability is returned. Examples ======== >>> from sympy.physics.quantum.state import Ket >>> from sympy.physics.quantum.density import Density >>> d = Density([Ket(0), 0.5], [Ket(1),0.5]) >>> d.probs()[1] 0.500000000000000 """ prob = self.args[index][1] return prob def apply_op(self, op): """op will operate on each individual state. Parameters ========== op : Operator Examples ======== >>> from sympy.physics.quantum.state import Ket >>> from sympy.physics.quantum.density import Density >>> from sympy.physics.quantum.operator import Operator >>> A = Operator('A') >>> d = Density([Ket(0), 0.5], [Ket(1),0.5]) >>> d.apply_op(A) Density((A*|0>, 0.5),(A*|1>, 0.5)) """ new_args = [(op*state, prob) for (state, prob) in self.args] return Density(*new_args) def doit(self, **hints): """Expand the density operator into an outer product format. Examples ======== >>> from sympy.physics.quantum.state import Ket >>> from sympy.physics.quantum.density import Density >>> from sympy.physics.quantum.operator import Operator >>> A = Operator('A') >>> d = Density([Ket(0), 0.5], [Ket(1),0.5]) >>> d.doit() 0.5*|0><0| + 0.5*|1><1| """ terms = [] for (state, prob) in self.args: state = state.expand() # needed to break up (a+b)*c if (isinstance(state, Add)): for arg in product(state.args, repeat=2): terms.append(prob*self._generate_outer_prod(arg[0], arg[1])) else: terms.append(prob*self._generate_outer_prod(state, state)) return Add(*terms) def _generate_outer_prod(self, arg1, arg2): c_part1, nc_part1 = arg1.args_cnc() c_part2, nc_part2 = arg2.args_cnc() if (len(nc_part1) == 0 or len(nc_part2) == 0): raise ValueError('Atleast one-pair of' ' Non-commutative instance required' ' for outer product.') # Muls of Tensor Products should be expanded # before this function is called if (isinstance(nc_part1[0], TensorProduct) and len(nc_part1) == 1 and len(nc_part2) == 1): op = tensor_product_simp(nc_part1[0]*Dagger(nc_part2[0])) else: op = Mul(*nc_part1)*Dagger(Mul(*nc_part2)) return Mul(*c_part1)*Mul(*c_part2) * op def _represent(self, **options): return represent(self.doit(), **options) def _print_operator_name_latex(self, printer, *args): return r'\rho' def _print_operator_name_pretty(self, printer, *args): return prettyForm('\N{GREEK SMALL LETTER RHO}') def _eval_trace(self, **kwargs): indices = kwargs.get('indices', []) return Tr(self.doit(), indices).doit() def entropy(self): """ Compute the entropy of a density matrix. Refer to density.entropy() method for examples. """ return entropy(self) def entropy(density): """Compute the entropy of a matrix/density object. This computes -Tr(density*ln(density)) using the eigenvalue decomposition of density, which is given as either a Density instance or a matrix (numpy.ndarray, sympy.Matrix or scipy.sparse). Parameters ========== density : density matrix of type Density, sympy matrix, scipy.sparse or numpy.ndarray Examples ======== >>> from sympy.physics.quantum.density import Density, entropy >>> from sympy.physics.quantum.spin import JzKet >>> from sympy import S >>> up = JzKet(S(1)/2,S(1)/2) >>> down = JzKet(S(1)/2,-S(1)/2) >>> d = Density((up,S(1)/2),(down,S(1)/2)) >>> entropy(d) log(2)/2 """ if isinstance(density, Density): density = represent(density) # represent in Matrix if isinstance(density, scipy_sparse_matrix): density = to_numpy(density) if isinstance(density, Matrix): eigvals = density.eigenvals().keys() return expand(-sum(e*log(e) for e in eigvals)) elif isinstance(density, numpy_ndarray): import numpy as np eigvals = np.linalg.eigvals(density) return -np.sum(eigvals*np.log(eigvals)) else: raise ValueError( "numpy.ndarray, scipy.sparse or sympy matrix expected") def fidelity(state1, state2): """ Computes the fidelity [1]_ between two quantum states The arguments provided to this function should be a square matrix or a Density object. If it is a square matrix, it is assumed to be diagonalizable. Parameters ========== state1, state2 : a density matrix or Matrix Examples ======== >>> from sympy import S, sqrt >>> from sympy.physics.quantum.dagger import Dagger >>> from sympy.physics.quantum.spin import JzKet >>> from sympy.physics.quantum.density import fidelity >>> from sympy.physics.quantum.represent import represent >>> >>> up = JzKet(S(1)/2,S(1)/2) >>> down = JzKet(S(1)/2,-S(1)/2) >>> amp = 1/sqrt(2) >>> updown = (amp*up) + (amp*down) >>> >>> # represent turns Kets into matrices >>> up_dm = represent(up*Dagger(up)) >>> down_dm = represent(down*Dagger(down)) >>> updown_dm = represent(updown*Dagger(updown)) >>> >>> fidelity(up_dm, up_dm) 1 >>> fidelity(up_dm, down_dm) #orthogonal states 0 >>> fidelity(up_dm, updown_dm).evalf().round(3) 0.707 References ========== .. [1] https://en.wikipedia.org/wiki/Fidelity_of_quantum_states """ state1 = represent(state1) if isinstance(state1, Density) else state1 state2 = represent(state2) if isinstance(state2, Density) else state2 if not isinstance(state1, Matrix) or not isinstance(state2, Matrix): raise ValueError("state1 and state2 must be of type Density or Matrix " "received type=%s for state1 and type=%s for state2" % (type(state1), type(state2))) if state1.shape != state2.shape and state1.is_square: raise ValueError("The dimensions of both args should be equal and the " "matrix obtained should be a square matrix") sqrt_state1 = state1**S.Half return Tr((sqrt_state1*state2*sqrt_state1)**S.Half).doit()
db7c2f26f4f45d723842df7fbcdca01f61419eb6dfc56f3165db5e3b2f4a943c
""" qasm.py - Functions to parse a set of qasm commands into a Sympy Circuit. Examples taken from Chuang's page: http://www.media.mit.edu/quanta/qasm2circ/ The code returns a circuit and an associated list of labels. >>> from sympy.physics.quantum.qasm import Qasm >>> q = Qasm('qubit q0', 'qubit q1', 'h q0', 'cnot q0,q1') >>> q.get_circuit() CNOT(1,0)*H(1) >>> q = Qasm('qubit q0', 'qubit q1', 'cnot q0,q1', 'cnot q1,q0', 'cnot q0,q1') >>> q.get_circuit() CNOT(1,0)*CNOT(0,1)*CNOT(1,0) """ __all__ = [ 'Qasm', ] from sympy.physics.quantum.gate import H, CNOT, X, Z, CGate, CGateS, SWAP, S, T,CPHASE from sympy.physics.quantum.circuitplot import Mz def read_qasm(lines): return Qasm(*lines.splitlines()) def read_qasm_file(filename): return Qasm(*open(filename).readlines()) def prod(c): p = 1 for ci in c: p *= ci return p def flip_index(i, n): """Reorder qubit indices from largest to smallest. >>> from sympy.physics.quantum.qasm import flip_index >>> flip_index(0, 2) 1 >>> flip_index(1, 2) 0 """ return n-i-1 def trim(line): """Remove everything following comment # characters in line. >>> from sympy.physics.quantum.qasm import trim >>> trim('nothing happens here') 'nothing happens here' >>> trim('something #happens here') 'something ' """ if not '#' in line: return line return line.split('#')[0] def get_index(target, labels): """Get qubit labels from the rest of the line,and return indices >>> from sympy.physics.quantum.qasm import get_index >>> get_index('q0', ['q0', 'q1']) 1 >>> get_index('q1', ['q0', 'q1']) 0 """ nq = len(labels) return flip_index(labels.index(target), nq) def get_indices(targets, labels): return [get_index(t, labels) for t in targets] def nonblank(args): for line in args: line = trim(line) if line.isspace(): continue yield line return def fullsplit(line): words = line.split() rest = ' '.join(words[1:]) return fixcommand(words[0]), [s.strip() for s in rest.split(',')] def fixcommand(c): """Fix Qasm command names. Remove all of forbidden characters from command c, and replace 'def' with 'qdef'. """ forbidden_characters = ['-'] c = c.lower() for char in forbidden_characters: c = c.replace(char, '') if c == 'def': return 'qdef' return c def stripquotes(s): """Replace explicit quotes in a string. >>> from sympy.physics.quantum.qasm import stripquotes >>> stripquotes("'S'") == 'S' True >>> stripquotes('"S"') == 'S' True >>> stripquotes('S') == 'S' True """ s = s.replace('"', '') # Remove second set of quotes? s = s.replace("'", '') return s class Qasm: """Class to form objects from Qasm lines >>> from sympy.physics.quantum.qasm import Qasm >>> q = Qasm('qubit q0', 'qubit q1', 'h q0', 'cnot q0,q1') >>> q.get_circuit() CNOT(1,0)*H(1) >>> q = Qasm('qubit q0', 'qubit q1', 'cnot q0,q1', 'cnot q1,q0', 'cnot q0,q1') >>> q.get_circuit() CNOT(1,0)*CNOT(0,1)*CNOT(1,0) """ def __init__(self, *args, **kwargs): self.defs = {} self.circuit = [] self.labels = [] self.inits = {} self.add(*args) self.kwargs = kwargs def add(self, *lines): for line in nonblank(lines): command, rest = fullsplit(line) if self.defs.get(command): #defs come first, since you can override built-in function = self.defs.get(command) indices = self.indices(rest) if len(indices) == 1: self.circuit.append(function(indices[0])) else: self.circuit.append(function(indices[:-1], indices[-1])) elif hasattr(self, command): function = getattr(self, command) function(*rest) else: print("Function %s not defined. Skipping" % command) def get_circuit(self): return prod(reversed(self.circuit)) def get_labels(self): return list(reversed(self.labels)) def plot(self): from sympy.physics.quantum.circuitplot import CircuitPlot circuit, labels = self.get_circuit(), self.get_labels() CircuitPlot(circuit, len(labels), labels=labels, inits=self.inits) def qubit(self, arg, init=None): self.labels.append(arg) if init: self.inits[arg] = init def indices(self, args): return get_indices(args, self.labels) def index(self, arg): return get_index(arg, self.labels) def nop(self, *args): pass def x(self, arg): self.circuit.append(X(self.index(arg))) def z(self, arg): self.circuit.append(Z(self.index(arg))) def h(self, arg): self.circuit.append(H(self.index(arg))) def s(self, arg): self.circuit.append(S(self.index(arg))) def t(self, arg): self.circuit.append(T(self.index(arg))) def measure(self, arg): self.circuit.append(Mz(self.index(arg))) def cnot(self, a1, a2): self.circuit.append(CNOT(*self.indices([a1, a2]))) def swap(self, a1, a2): self.circuit.append(SWAP(*self.indices([a1, a2]))) def cphase(self, a1, a2): self.circuit.append(CPHASE(*self.indices([a1, a2]))) def toffoli(self, a1, a2, a3): i1, i2, i3 = self.indices([a1, a2, a3]) self.circuit.append(CGateS((i1, i2), X(i3))) def cx(self, a1, a2): fi, fj = self.indices([a1, a2]) self.circuit.append(CGate(fi, X(fj))) def cz(self, a1, a2): fi, fj = self.indices([a1, a2]) self.circuit.append(CGate(fi, Z(fj))) def defbox(self, *args): print("defbox not supported yet. Skipping: ", args) def qdef(self, name, ncontrols, symbol): from sympy.physics.quantum.circuitplot import CreateOneQubitGate, CreateCGate ncontrols = int(ncontrols) command = fixcommand(name) symbol = stripquotes(symbol) if ncontrols > 0: self.defs[command] = CreateCGate(symbol) else: self.defs[command] = CreateOneQubitGate(symbol)
76923ee69cdc8bb8e5794cfbfdfa1eae88cfa870ef2020289e82982992f787a7
"""1D quantum particle in a box.""" from sympy import Symbol, pi, sqrt, sin, Interval, S from sympy.physics.quantum.operator import HermitianOperator from sympy.physics.quantum.state import Ket, Bra from sympy.physics.quantum.constants import hbar from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.physics.quantum.hilbert import L2 m = Symbol('m') L = Symbol('L') __all__ = [ 'PIABHamiltonian', 'PIABKet', 'PIABBra' ] class PIABHamiltonian(HermitianOperator): """Particle in a box Hamiltonian operator.""" @classmethod def _eval_hilbert_space(cls, label): return L2(Interval(S.NegativeInfinity, S.Infinity)) def _apply_operator_PIABKet(self, ket, **options): n = ket.label[0] return (n**2*pi**2*hbar**2)/(2*m*L**2)*ket class PIABKet(Ket): """Particle in a box eigenket.""" @classmethod def _eval_hilbert_space(cls, args): return L2(Interval(S.NegativeInfinity, S.Infinity)) @classmethod def dual_class(self): return PIABBra def _represent_default_basis(self, **options): return self._represent_XOp(None, **options) def _represent_XOp(self, basis, **options): x = Symbol('x') n = Symbol('n') subs_info = options.get('subs', {}) return sqrt(2/L)*sin(n*pi*x/L).subs(subs_info) def _eval_innerproduct_PIABBra(self, bra): return KroneckerDelta(bra.label[0], self.label[0]) class PIABBra(Bra): """Particle in a box eigenbra.""" @classmethod def _eval_hilbert_space(cls, label): return L2(Interval(S.NegativeInfinity, S.Infinity)) @classmethod def dual_class(self): return PIABKet
7ac2a14b8a6682a4590ba13cde301c24369f92876c3375aa33edcacd2b87c2e5
"""The commutator: [A,B] = A*B - B*A.""" from sympy import S, Expr, Mul, Add, Pow from sympy.printing.pretty.stringpict import prettyForm from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.operator import Operator __all__ = [ 'Commutator' ] #----------------------------------------------------------------------------- # Commutator #----------------------------------------------------------------------------- class Commutator(Expr): """The standard commutator, in an unevaluated state. Evaluating a commutator is defined [1]_ as: ``[A, B] = A*B - B*A``. This class returns the commutator in an unevaluated form. To evaluate the commutator, use the ``.doit()`` method. Canonical ordering of a commutator is ``[A, B]`` for ``A < B``. The arguments of the commutator are put into canonical order using ``__cmp__``. If ``B < A``, then ``[B, A]`` is returned as ``-[A, B]``. Parameters ========== A : Expr The first argument of the commutator [A,B]. B : Expr The second argument of the commutator [A,B]. Examples ======== >>> from sympy.physics.quantum import Commutator, Dagger, Operator >>> from sympy.abc import x, y >>> A = Operator('A') >>> B = Operator('B') >>> C = Operator('C') Create a commutator and use ``.doit()`` to evaluate it: >>> comm = Commutator(A, B) >>> comm [A,B] >>> comm.doit() A*B - B*A The commutator orders it arguments in canonical order: >>> comm = Commutator(B, A); comm -[A,B] Commutative constants are factored out: >>> Commutator(3*x*A, x*y*B) 3*x**2*y*[A,B] Using ``.expand(commutator=True)``, the standard commutator expansion rules can be applied: >>> Commutator(A+B, C).expand(commutator=True) [A,C] + [B,C] >>> Commutator(A, B+C).expand(commutator=True) [A,B] + [A,C] >>> Commutator(A*B, C).expand(commutator=True) [A,C]*B + A*[B,C] >>> Commutator(A, B*C).expand(commutator=True) [A,B]*C + B*[A,C] Adjoint operations applied to the commutator are properly applied to the arguments: >>> Dagger(Commutator(A, B)) -[Dagger(A),Dagger(B)] References ========== .. [1] https://en.wikipedia.org/wiki/Commutator """ is_commutative = False def __new__(cls, A, B): r = cls.eval(A, B) if r is not None: return r obj = Expr.__new__(cls, A, B) return obj @classmethod def eval(cls, a, b): if not (a and b): return S.Zero if a == b: return S.Zero if a.is_commutative or b.is_commutative: return S.Zero # [xA,yB] -> xy*[A,B] ca, nca = a.args_cnc() cb, ncb = b.args_cnc() c_part = ca + cb if c_part: return Mul(Mul(*c_part), cls(Mul._from_args(nca), Mul._from_args(ncb))) # Canonical ordering of arguments # The Commutator [A, B] is in canonical form if A < B. if a.compare(b) == 1: return S.NegativeOne*cls(b, a) def _expand_pow(self, A, B, sign): exp = A.exp if not exp.is_integer or not exp.is_constant() or abs(exp) <= 1: # nothing to do return self base = A.base if exp.is_negative: base = A.base**-1 exp = -exp comm = Commutator(base, B).expand(commutator=True) result = base**(exp - 1) * comm for i in range(1, exp): result += base**(exp - 1 - i) * comm * base**i return sign*result.expand() def _eval_expand_commutator(self, **hints): A = self.args[0] B = self.args[1] if isinstance(A, Add): # [A + B, C] -> [A, C] + [B, C] sargs = [] for term in A.args: comm = Commutator(term, B) if isinstance(comm, Commutator): comm = comm._eval_expand_commutator() sargs.append(comm) return Add(*sargs) elif isinstance(B, Add): # [A, B + C] -> [A, B] + [A, C] sargs = [] for term in B.args: comm = Commutator(A, term) if isinstance(comm, Commutator): comm = comm._eval_expand_commutator() sargs.append(comm) return Add(*sargs) elif isinstance(A, Mul): # [A*B, C] -> A*[B, C] + [A, C]*B a = A.args[0] b = Mul(*A.args[1:]) c = B comm1 = Commutator(b, c) comm2 = Commutator(a, c) if isinstance(comm1, Commutator): comm1 = comm1._eval_expand_commutator() if isinstance(comm2, Commutator): comm2 = comm2._eval_expand_commutator() first = Mul(a, comm1) second = Mul(comm2, b) return Add(first, second) elif isinstance(B, Mul): # [A, B*C] -> [A, B]*C + B*[A, C] a = A b = B.args[0] c = Mul(*B.args[1:]) comm1 = Commutator(a, b) comm2 = Commutator(a, c) if isinstance(comm1, Commutator): comm1 = comm1._eval_expand_commutator() if isinstance(comm2, Commutator): comm2 = comm2._eval_expand_commutator() first = Mul(comm1, c) second = Mul(b, comm2) return Add(first, second) elif isinstance(A, Pow): # [A**n, C] -> A**(n - 1)*[A, C] + A**(n - 2)*[A, C]*A + ... + [A, C]*A**(n-1) return self._expand_pow(A, B, 1) elif isinstance(B, Pow): # [A, C**n] -> C**(n - 1)*[C, A] + C**(n - 2)*[C, A]*C + ... + [C, A]*C**(n-1) return self._expand_pow(B, A, -1) # No changes, so return self return self def doit(self, **hints): """ Evaluate commutator """ A = self.args[0] B = self.args[1] if isinstance(A, Operator) and isinstance(B, Operator): try: comm = A._eval_commutator(B, **hints) except NotImplementedError: try: comm = -1*B._eval_commutator(A, **hints) except NotImplementedError: comm = None if comm is not None: return comm.doit(**hints) return (A*B - B*A).doit(**hints) def _eval_adjoint(self): return Commutator(Dagger(self.args[1]), Dagger(self.args[0])) def _sympyrepr(self, printer, *args): return "%s(%s,%s)" % ( self.__class__.__name__, printer._print( self.args[0]), printer._print(self.args[1]) ) def _sympystr(self, printer, *args): return "[%s,%s]" % ( printer._print(self.args[0]), printer._print(self.args[1])) def _pretty(self, printer, *args): pform = printer._print(self.args[0], *args) pform = prettyForm(*pform.right(prettyForm(','))) pform = prettyForm(*pform.right(printer._print(self.args[1], *args))) pform = prettyForm(*pform.parens(left='[', right=']')) return pform def _latex(self, printer, *args): return "\\left[%s,%s\\right]" % tuple([ printer._print(arg, *args) for arg in self.args])
756b227868e5f1da4f2685d35684f5531ff3628bec3c86e58be104abcffe6da8
"""Quantum mechanical angular momemtum.""" from sympy import (Add, binomial, cos, exp, Expr, factorial, I, Integer, Mul, pi, Rational, S, sin, simplify, sqrt, Sum, symbols, sympify, Tuple, Dummy) from sympy.matrices import zeros from sympy.printing.pretty.stringpict import prettyForm, stringPict from sympy.printing.pretty.pretty_symbology import pretty_symbol from sympy.physics.quantum.qexpr import QExpr from sympy.physics.quantum.operator import (HermitianOperator, Operator, UnitaryOperator) from sympy.physics.quantum.state import Bra, Ket, State from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.physics.quantum.constants import hbar from sympy.physics.quantum.hilbert import ComplexSpace, DirectSumHilbertSpace from sympy.physics.quantum.tensorproduct import TensorProduct from sympy.physics.quantum.cg import CG from sympy.physics.quantum.qapply import qapply __all__ = [ 'm_values', 'Jplus', 'Jminus', 'Jx', 'Jy', 'Jz', 'J2', 'Rotation', 'WignerD', 'JxKet', 'JxBra', 'JyKet', 'JyBra', 'JzKet', 'JzBra', 'JzOp', 'J2Op', 'JxKetCoupled', 'JxBraCoupled', 'JyKetCoupled', 'JyBraCoupled', 'JzKetCoupled', 'JzBraCoupled', 'couple', 'uncouple' ] def m_values(j): j = sympify(j) size = 2*j + 1 if not size.is_Integer or not size > 0: raise ValueError( 'Only integer or half-integer values allowed for j, got: : %r' % j ) return size, [j - i for i in range(int(2*j + 1))] #----------------------------------------------------------------------------- # Spin Operators #----------------------------------------------------------------------------- class SpinOpBase: """Base class for spin operators.""" @classmethod def _eval_hilbert_space(cls, label): # We consider all j values so our space is infinite. return ComplexSpace(S.Infinity) @property def name(self): return self.args[0] def _print_contents(self, printer, *args): return '%s%s' % (self.name, self._coord) def _print_contents_pretty(self, printer, *args): a = stringPict(str(self.name)) b = stringPict(self._coord) return self._print_subscript_pretty(a, b) def _print_contents_latex(self, printer, *args): return r'%s_%s' % ((self.name, self._coord)) def _represent_base(self, basis, **options): j = options.get('j', S.Half) size, mvals = m_values(j) result = zeros(size, size) for p in range(size): for q in range(size): me = self.matrix_element(j, mvals[p], j, mvals[q]) result[p, q] = me return result def _apply_op(self, ket, orig_basis, **options): state = ket.rewrite(self.basis) # If the state has only one term if isinstance(state, State): ret = (hbar*state.m)*state # state is a linear combination of states elif isinstance(state, Sum): ret = self._apply_operator_Sum(state, **options) else: ret = qapply(self*state) if ret == self*state: raise NotImplementedError return ret.rewrite(orig_basis) def _apply_operator_JxKet(self, ket, **options): return self._apply_op(ket, 'Jx', **options) def _apply_operator_JxKetCoupled(self, ket, **options): return self._apply_op(ket, 'Jx', **options) def _apply_operator_JyKet(self, ket, **options): return self._apply_op(ket, 'Jy', **options) def _apply_operator_JyKetCoupled(self, ket, **options): return self._apply_op(ket, 'Jy', **options) def _apply_operator_JzKet(self, ket, **options): return self._apply_op(ket, 'Jz', **options) def _apply_operator_JzKetCoupled(self, ket, **options): return self._apply_op(ket, 'Jz', **options) def _apply_operator_TensorProduct(self, tp, **options): # Uncoupling operator is only easily found for coordinate basis spin operators # TODO: add methods for uncoupling operators if not (isinstance(self, JxOp) or isinstance(self, JyOp) or isinstance(self, JzOp)): raise NotImplementedError result = [] for n in range(len(tp.args)): arg = [] arg.extend(tp.args[:n]) arg.append(self._apply_operator(tp.args[n])) arg.extend(tp.args[n + 1:]) result.append(tp.__class__(*arg)) return Add(*result).expand() # TODO: move this to qapply_Mul def _apply_operator_Sum(self, s, **options): new_func = qapply(self*s.function) if new_func == self*s.function: raise NotImplementedError return Sum(new_func, *s.limits) def _eval_trace(self, **options): #TODO: use options to use different j values #For now eval at default basis # is it efficient to represent each time # to do a trace? return self._represent_default_basis().trace() class JplusOp(SpinOpBase, Operator): """The J+ operator.""" _coord = '+' basis = 'Jz' def _eval_commutator_JminusOp(self, other): return 2*hbar*JzOp(self.name) def _apply_operator_JzKet(self, ket, **options): j = ket.j m = ket.m if m.is_Number and j.is_Number: if m >= j: return S.Zero return hbar*sqrt(j*(j + S.One) - m*(m + S.One))*JzKet(j, m + S.One) def _apply_operator_JzKetCoupled(self, ket, **options): j = ket.j m = ket.m jn = ket.jn coupling = ket.coupling if m.is_Number and j.is_Number: if m >= j: return S.Zero return hbar*sqrt(j*(j + S.One) - m*(m + S.One))*JzKetCoupled(j, m + S.One, jn, coupling) def matrix_element(self, j, m, jp, mp): result = hbar*sqrt(j*(j + S.One) - mp*(mp + S.One)) result *= KroneckerDelta(m, mp + 1) result *= KroneckerDelta(j, jp) return result def _represent_default_basis(self, **options): return self._represent_JzOp(None, **options) def _represent_JzOp(self, basis, **options): return self._represent_base(basis, **options) def _eval_rewrite_as_xyz(self, *args, **kwargs): return JxOp(args[0]) + I*JyOp(args[0]) class JminusOp(SpinOpBase, Operator): """The J- operator.""" _coord = '-' basis = 'Jz' def _apply_operator_JzKet(self, ket, **options): j = ket.j m = ket.m if m.is_Number and j.is_Number: if m <= -j: return S.Zero return hbar*sqrt(j*(j + S.One) - m*(m - S.One))*JzKet(j, m - S.One) def _apply_operator_JzKetCoupled(self, ket, **options): j = ket.j m = ket.m jn = ket.jn coupling = ket.coupling if m.is_Number and j.is_Number: if m <= -j: return S.Zero return hbar*sqrt(j*(j + S.One) - m*(m - S.One))*JzKetCoupled(j, m - S.One, jn, coupling) def matrix_element(self, j, m, jp, mp): result = hbar*sqrt(j*(j + S.One) - mp*(mp - S.One)) result *= KroneckerDelta(m, mp - 1) result *= KroneckerDelta(j, jp) return result def _represent_default_basis(self, **options): return self._represent_JzOp(None, **options) def _represent_JzOp(self, basis, **options): return self._represent_base(basis, **options) def _eval_rewrite_as_xyz(self, *args, **kwargs): return JxOp(args[0]) - I*JyOp(args[0]) class JxOp(SpinOpBase, HermitianOperator): """The Jx operator.""" _coord = 'x' basis = 'Jx' def _eval_commutator_JyOp(self, other): return I*hbar*JzOp(self.name) def _eval_commutator_JzOp(self, other): return -I*hbar*JyOp(self.name) def _apply_operator_JzKet(self, ket, **options): jp = JplusOp(self.name)._apply_operator_JzKet(ket, **options) jm = JminusOp(self.name)._apply_operator_JzKet(ket, **options) return (jp + jm)/Integer(2) def _apply_operator_JzKetCoupled(self, ket, **options): jp = JplusOp(self.name)._apply_operator_JzKetCoupled(ket, **options) jm = JminusOp(self.name)._apply_operator_JzKetCoupled(ket, **options) return (jp + jm)/Integer(2) def _represent_default_basis(self, **options): return self._represent_JzOp(None, **options) def _represent_JzOp(self, basis, **options): jp = JplusOp(self.name)._represent_JzOp(basis, **options) jm = JminusOp(self.name)._represent_JzOp(basis, **options) return (jp + jm)/Integer(2) def _eval_rewrite_as_plusminus(self, *args, **kwargs): return (JplusOp(args[0]) + JminusOp(args[0]))/2 class JyOp(SpinOpBase, HermitianOperator): """The Jy operator.""" _coord = 'y' basis = 'Jy' def _eval_commutator_JzOp(self, other): return I*hbar*JxOp(self.name) def _eval_commutator_JxOp(self, other): return -I*hbar*J2Op(self.name) def _apply_operator_JzKet(self, ket, **options): jp = JplusOp(self.name)._apply_operator_JzKet(ket, **options) jm = JminusOp(self.name)._apply_operator_JzKet(ket, **options) return (jp - jm)/(Integer(2)*I) def _apply_operator_JzKetCoupled(self, ket, **options): jp = JplusOp(self.name)._apply_operator_JzKetCoupled(ket, **options) jm = JminusOp(self.name)._apply_operator_JzKetCoupled(ket, **options) return (jp - jm)/(Integer(2)*I) def _represent_default_basis(self, **options): return self._represent_JzOp(None, **options) def _represent_JzOp(self, basis, **options): jp = JplusOp(self.name)._represent_JzOp(basis, **options) jm = JminusOp(self.name)._represent_JzOp(basis, **options) return (jp - jm)/(Integer(2)*I) def _eval_rewrite_as_plusminus(self, *args, **kwargs): return (JplusOp(args[0]) - JminusOp(args[0]))/(2*I) class JzOp(SpinOpBase, HermitianOperator): """The Jz operator.""" _coord = 'z' basis = 'Jz' def _eval_commutator_JxOp(self, other): return I*hbar*JyOp(self.name) def _eval_commutator_JyOp(self, other): return -I*hbar*JxOp(self.name) def _eval_commutator_JplusOp(self, other): return hbar*JplusOp(self.name) def _eval_commutator_JminusOp(self, other): return -hbar*JminusOp(self.name) def matrix_element(self, j, m, jp, mp): result = hbar*mp result *= KroneckerDelta(m, mp) result *= KroneckerDelta(j, jp) return result def _represent_default_basis(self, **options): return self._represent_JzOp(None, **options) def _represent_JzOp(self, basis, **options): return self._represent_base(basis, **options) class J2Op(SpinOpBase, HermitianOperator): """The J^2 operator.""" _coord = '2' def _eval_commutator_JxOp(self, other): return S.Zero def _eval_commutator_JyOp(self, other): return S.Zero def _eval_commutator_JzOp(self, other): return S.Zero def _eval_commutator_JplusOp(self, other): return S.Zero def _eval_commutator_JminusOp(self, other): return S.Zero def _apply_operator_JxKet(self, ket, **options): j = ket.j return hbar**2*j*(j + 1)*ket def _apply_operator_JxKetCoupled(self, ket, **options): j = ket.j return hbar**2*j*(j + 1)*ket def _apply_operator_JyKet(self, ket, **options): j = ket.j return hbar**2*j*(j + 1)*ket def _apply_operator_JyKetCoupled(self, ket, **options): j = ket.j return hbar**2*j*(j + 1)*ket def _apply_operator_JzKet(self, ket, **options): j = ket.j return hbar**2*j*(j + 1)*ket def _apply_operator_JzKetCoupled(self, ket, **options): j = ket.j return hbar**2*j*(j + 1)*ket def matrix_element(self, j, m, jp, mp): result = (hbar**2)*j*(j + 1) result *= KroneckerDelta(m, mp) result *= KroneckerDelta(j, jp) return result def _represent_default_basis(self, **options): return self._represent_JzOp(None, **options) def _represent_JzOp(self, basis, **options): return self._represent_base(basis, **options) def _print_contents_pretty(self, printer, *args): a = prettyForm(str(self.name)) b = prettyForm('2') return a**b def _print_contents_latex(self, printer, *args): return r'%s^2' % str(self.name) def _eval_rewrite_as_xyz(self, *args, **kwargs): return JxOp(args[0])**2 + JyOp(args[0])**2 + JzOp(args[0])**2 def _eval_rewrite_as_plusminus(self, *args, **kwargs): a = args[0] return JzOp(a)**2 + \ S.Half*(JplusOp(a)*JminusOp(a) + JminusOp(a)*JplusOp(a)) class Rotation(UnitaryOperator): """Wigner D operator in terms of Euler angles. Defines the rotation operator in terms of the Euler angles defined by the z-y-z convention for a passive transformation. That is the coordinate axes are rotated first about the z-axis, giving the new x'-y'-z' axes. Then this new coordinate system is rotated about the new y'-axis, giving new x''-y''-z'' axes. Then this new coordinate system is rotated about the z''-axis. Conventions follow those laid out in [1]_. Parameters ========== alpha : Number, Symbol First Euler Angle beta : Number, Symbol Second Euler angle gamma : Number, Symbol Third Euler angle Examples ======== A simple example rotation operator: >>> from sympy import pi >>> from sympy.physics.quantum.spin import Rotation >>> Rotation(pi, 0, pi/2) R(pi,0,pi/2) With symbolic Euler angles and calculating the inverse rotation operator: >>> from sympy import symbols >>> a, b, c = symbols('a b c') >>> Rotation(a, b, c) R(a,b,c) >>> Rotation(a, b, c).inverse() R(-c,-b,-a) See Also ======== WignerD: Symbolic Wigner-D function D: Wigner-D function d: Wigner small-d function References ========== .. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988. """ @classmethod def _eval_args(cls, args): args = QExpr._eval_args(args) if len(args) != 3: raise ValueError('3 Euler angles required, got: %r' % args) return args @classmethod def _eval_hilbert_space(cls, label): # We consider all j values so our space is infinite. return ComplexSpace(S.Infinity) @property def alpha(self): return self.label[0] @property def beta(self): return self.label[1] @property def gamma(self): return self.label[2] def _print_operator_name(self, printer, *args): return 'R' def _print_operator_name_pretty(self, printer, *args): if printer._use_unicode: return prettyForm('\N{SCRIPT CAPITAL R}' + ' ') else: return prettyForm("R ") def _print_operator_name_latex(self, printer, *args): return r'\mathcal{R}' def _eval_inverse(self): return Rotation(-self.gamma, -self.beta, -self.alpha) @classmethod def D(cls, j, m, mp, alpha, beta, gamma): """Wigner D-function. Returns an instance of the WignerD class corresponding to the Wigner-D function specified by the parameters. Parameters =========== j : Number Total angular momentum m : Number Eigenvalue of angular momentum along axis after rotation mp : Number Eigenvalue of angular momentum along rotated axis alpha : Number, Symbol First Euler angle of rotation beta : Number, Symbol Second Euler angle of rotation gamma : Number, Symbol Third Euler angle of rotation Examples ======== Return the Wigner-D matrix element for a defined rotation, both numerical and symbolic: >>> from sympy.physics.quantum.spin import Rotation >>> from sympy import pi, symbols >>> alpha, beta, gamma = symbols('alpha beta gamma') >>> Rotation.D(1, 1, 0,pi, pi/2,-pi) WignerD(1, 1, 0, pi, pi/2, -pi) See Also ======== WignerD: Symbolic Wigner-D function """ return WignerD(j, m, mp, alpha, beta, gamma) @classmethod def d(cls, j, m, mp, beta): """Wigner small-d function. Returns an instance of the WignerD class corresponding to the Wigner-D function specified by the parameters with the alpha and gamma angles given as 0. Parameters =========== j : Number Total angular momentum m : Number Eigenvalue of angular momentum along axis after rotation mp : Number Eigenvalue of angular momentum along rotated axis beta : Number, Symbol Second Euler angle of rotation Examples ======== Return the Wigner-D matrix element for a defined rotation, both numerical and symbolic: >>> from sympy.physics.quantum.spin import Rotation >>> from sympy import pi, symbols >>> beta = symbols('beta') >>> Rotation.d(1, 1, 0, pi/2) WignerD(1, 1, 0, 0, pi/2, 0) See Also ======== WignerD: Symbolic Wigner-D function """ return WignerD(j, m, mp, 0, beta, 0) def matrix_element(self, j, m, jp, mp): result = self.__class__.D( jp, m, mp, self.alpha, self.beta, self.gamma ) result *= KroneckerDelta(j, jp) return result def _represent_base(self, basis, **options): j = sympify(options.get('j', S.Half)) # TODO: move evaluation up to represent function/implement elsewhere evaluate = sympify(options.get('doit')) size, mvals = m_values(j) result = zeros(size, size) for p in range(size): for q in range(size): me = self.matrix_element(j, mvals[p], j, mvals[q]) if evaluate: result[p, q] = me.doit() else: result[p, q] = me return result def _represent_default_basis(self, **options): return self._represent_JzOp(None, **options) def _represent_JzOp(self, basis, **options): return self._represent_base(basis, **options) def _apply_operator_uncoupled(self, state, ket, *, dummy=True, **options): a = self.alpha b = self.beta g = self.gamma j = ket.j m = ket.m if j.is_number: s = [] size = m_values(j) sz = size[1] for mp in sz: r = Rotation.D(j, m, mp, a, b, g) z = r.doit() s.append(z*state(j, mp)) return Add(*s) else: if dummy: mp = Dummy('mp') else: mp = symbols('mp') return Sum(Rotation.D(j, m, mp, a, b, g)*state(j, mp), (mp, -j, j)) def _apply_operator_JxKet(self, ket, **options): return self._apply_operator_uncoupled(JxKet, ket, **options) def _apply_operator_JyKet(self, ket, **options): return self._apply_operator_uncoupled(JyKet, ket, **options) def _apply_operator_JzKet(self, ket, **options): return self._apply_operator_uncoupled(JzKet, ket, **options) def _apply_operator_coupled(self, state, ket, *, dummy=True, **options): a = self.alpha b = self.beta g = self.gamma j = ket.j m = ket.m jn = ket.jn coupling = ket.coupling if j.is_number: s = [] size = m_values(j) sz = size[1] for mp in sz: r = Rotation.D(j, m, mp, a, b, g) z = r.doit() s.append(z*state(j, mp, jn, coupling)) return Add(*s) else: if dummy: mp = Dummy('mp') else: mp = symbols('mp') return Sum(Rotation.D(j, m, mp, a, b, g)*state( j, mp, jn, coupling), (mp, -j, j)) def _apply_operator_JxKetCoupled(self, ket, **options): return self._apply_operator_coupled(JxKetCoupled, ket, **options) def _apply_operator_JyKetCoupled(self, ket, **options): return self._apply_operator_coupled(JyKetCoupled, ket, **options) def _apply_operator_JzKetCoupled(self, ket, **options): return self._apply_operator_coupled(JzKetCoupled, ket, **options) class WignerD(Expr): r"""Wigner-D function The Wigner D-function gives the matrix elements of the rotation operator in the jm-representation. For the Euler angles `\alpha`, `\beta`, `\gamma`, the D-function is defined such that: .. math :: <j,m| \mathcal{R}(\alpha, \beta, \gamma ) |j',m'> = \delta_{jj'} D(j, m, m', \alpha, \beta, \gamma) Where the rotation operator is as defined by the Rotation class [1]_. The Wigner D-function defined in this way gives: .. math :: D(j, m, m', \alpha, \beta, \gamma) = e^{-i m \alpha} d(j, m, m', \beta) e^{-i m' \gamma} Where d is the Wigner small-d function, which is given by Rotation.d. The Wigner small-d function gives the component of the Wigner D-function that is determined by the second Euler angle. That is the Wigner D-function is: .. math :: D(j, m, m', \alpha, \beta, \gamma) = e^{-i m \alpha} d(j, m, m', \beta) e^{-i m' \gamma} Where d is the small-d function. The Wigner D-function is given by Rotation.D. Note that to evaluate the D-function, the j, m and mp parameters must be integer or half integer numbers. Parameters ========== j : Number Total angular momentum m : Number Eigenvalue of angular momentum along axis after rotation mp : Number Eigenvalue of angular momentum along rotated axis alpha : Number, Symbol First Euler angle of rotation beta : Number, Symbol Second Euler angle of rotation gamma : Number, Symbol Third Euler angle of rotation Examples ======== Evaluate the Wigner-D matrix elements of a simple rotation: >>> from sympy.physics.quantum.spin import Rotation >>> from sympy import pi >>> rot = Rotation.D(1, 1, 0, pi, pi/2, 0) >>> rot WignerD(1, 1, 0, pi, pi/2, 0) >>> rot.doit() sqrt(2)/2 Evaluate the Wigner-d matrix elements of a simple rotation >>> rot = Rotation.d(1, 1, 0, pi/2) >>> rot WignerD(1, 1, 0, 0, pi/2, 0) >>> rot.doit() -sqrt(2)/2 See Also ======== Rotation: Rotation operator References ========== .. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988. """ is_commutative = True def __new__(cls, *args, **hints): if not len(args) == 6: raise ValueError('6 parameters expected, got %s' % args) args = sympify(args) evaluate = hints.get('evaluate', False) if evaluate: return Expr.__new__(cls, *args)._eval_wignerd() return Expr.__new__(cls, *args) @property def j(self): return self.args[0] @property def m(self): return self.args[1] @property def mp(self): return self.args[2] @property def alpha(self): return self.args[3] @property def beta(self): return self.args[4] @property def gamma(self): return self.args[5] def _latex(self, printer, *args): if self.alpha == 0 and self.gamma == 0: return r'd^{%s}_{%s,%s}\left(%s\right)' % \ ( printer._print(self.j), printer._print( self.m), printer._print(self.mp), printer._print(self.beta) ) return r'D^{%s}_{%s,%s}\left(%s,%s,%s\right)' % \ ( printer._print( self.j), printer._print(self.m), printer._print(self.mp), printer._print(self.alpha), printer._print(self.beta), printer._print(self.gamma) ) def _pretty(self, printer, *args): top = printer._print(self.j) bot = printer._print(self.m) bot = prettyForm(*bot.right(',')) bot = prettyForm(*bot.right(printer._print(self.mp))) pad = max(top.width(), bot.width()) top = prettyForm(*top.left(' ')) bot = prettyForm(*bot.left(' ')) if pad > top.width(): top = prettyForm(*top.right(' '*(pad - top.width()))) if pad > bot.width(): bot = prettyForm(*bot.right(' '*(pad - bot.width()))) if self.alpha == 0 and self.gamma == 0: args = printer._print(self.beta) s = stringPict('d' + ' '*pad) else: args = printer._print(self.alpha) args = prettyForm(*args.right(',')) args = prettyForm(*args.right(printer._print(self.beta))) args = prettyForm(*args.right(',')) args = prettyForm(*args.right(printer._print(self.gamma))) s = stringPict('D' + ' '*pad) args = prettyForm(*args.parens()) s = prettyForm(*s.above(top)) s = prettyForm(*s.below(bot)) s = prettyForm(*s.right(args)) return s def doit(self, **hints): hints['evaluate'] = True return WignerD(*self.args, **hints) def _eval_wignerd(self): j = sympify(self.j) m = sympify(self.m) mp = sympify(self.mp) alpha = sympify(self.alpha) beta = sympify(self.beta) gamma = sympify(self.gamma) if not j.is_number: raise ValueError( 'j parameter must be numerical to evaluate, got %s' % j) r = 0 if beta == pi/2: # Varshalovich Equation (5), Section 4.16, page 113, setting # alpha=gamma=0. for k in range(2*j + 1): if k > j + mp or k > j - m or k < mp - m: continue r += (S.NegativeOne)**k*binomial(j + mp, k)*binomial(j - mp, k + m - mp) r *= (S.NegativeOne)**(m - mp) / 2**j*sqrt(factorial(j + m) * factorial(j - m) / (factorial(j + mp)*factorial(j - mp))) else: # Varshalovich Equation(5), Section 4.7.2, page 87, where we set # beta1=beta2=pi/2, and we get alpha=gamma=pi/2 and beta=phi+pi, # then we use the Eq. (1), Section 4.4. page 79, to simplify: # d(j, m, mp, beta+pi) = (-1)**(j-mp)*d(j, m, -mp, beta) # This happens to be almost the same as in Eq.(10), Section 4.16, # except that we need to substitute -mp for mp. size, mvals = m_values(j) for mpp in mvals: r += Rotation.d(j, m, mpp, pi/2).doit()*(cos(-mpp*beta) + I*sin(-mpp*beta))*\ Rotation.d(j, mpp, -mp, pi/2).doit() # Empirical normalization factor so results match Varshalovich # Tables 4.3-4.12 # Note that this exact normalization does not follow from the # above equations r = r*I**(2*j - m - mp)*(-1)**(2*m) # Finally, simplify the whole expression r = simplify(r) r *= exp(-I*m*alpha)*exp(-I*mp*gamma) return r Jx = JxOp('J') Jy = JyOp('J') Jz = JzOp('J') J2 = J2Op('J') Jplus = JplusOp('J') Jminus = JminusOp('J') #----------------------------------------------------------------------------- # Spin States #----------------------------------------------------------------------------- class SpinState(State): """Base class for angular momentum states.""" _label_separator = ',' def __new__(cls, j, m): j = sympify(j) m = sympify(m) if j.is_number: if 2*j != int(2*j): raise ValueError( 'j must be integer or half-integer, got: %s' % j) if j < 0: raise ValueError('j must be >= 0, got: %s' % j) if m.is_number: if 2*m != int(2*m): raise ValueError( 'm must be integer or half-integer, got: %s' % m) if j.is_number and m.is_number: if abs(m) > j: raise ValueError('Allowed values for m are -j <= m <= j, got j, m: %s, %s' % (j, m)) if int(j - m) != j - m: raise ValueError('Both j and m must be integer or half-integer, got j, m: %s, %s' % (j, m)) return State.__new__(cls, j, m) @property def j(self): return self.label[0] @property def m(self): return self.label[1] @classmethod def _eval_hilbert_space(cls, label): return ComplexSpace(2*label[0] + 1) def _represent_base(self, **options): j = self.j m = self.m alpha = sympify(options.get('alpha', 0)) beta = sympify(options.get('beta', 0)) gamma = sympify(options.get('gamma', 0)) size, mvals = m_values(j) result = zeros(size, 1) # TODO: Use KroneckerDelta if all Euler angles == 0 # breaks finding angles on L930 for p, mval in enumerate(mvals): if m.is_number: result[p, 0] = Rotation.D( self.j, mval, self.m, alpha, beta, gamma).doit() else: result[p, 0] = Rotation.D(self.j, mval, self.m, alpha, beta, gamma) return result def _eval_rewrite_as_Jx(self, *args, **options): if isinstance(self, Bra): return self._rewrite_basis(Jx, JxBra, **options) return self._rewrite_basis(Jx, JxKet, **options) def _eval_rewrite_as_Jy(self, *args, **options): if isinstance(self, Bra): return self._rewrite_basis(Jy, JyBra, **options) return self._rewrite_basis(Jy, JyKet, **options) def _eval_rewrite_as_Jz(self, *args, **options): if isinstance(self, Bra): return self._rewrite_basis(Jz, JzBra, **options) return self._rewrite_basis(Jz, JzKet, **options) def _rewrite_basis(self, basis, evect, **options): from sympy.physics.quantum.represent import represent j = self.j args = self.args[2:] if j.is_number: if isinstance(self, CoupledSpinState): if j == int(j): start = j**2 else: start = (2*j - 1)*(2*j + 1)/4 else: start = 0 vect = represent(self, basis=basis, **options) result = Add( *[vect[start + i]*evect(j, j - i, *args) for i in range(2*j + 1)]) if isinstance(self, CoupledSpinState) and options.get('coupled') is False: return uncouple(result) return result else: i = 0 mi = symbols('mi') # make sure not to introduce a symbol already in the state while self.subs(mi, 0) != self: i += 1 mi = symbols('mi%d' % i) break # TODO: better way to get angles of rotation if isinstance(self, CoupledSpinState): test_args = (0, mi, (0, 0)) else: test_args = (0, mi) if isinstance(self, Ket): angles = represent( self.__class__(*test_args), basis=basis)[0].args[3:6] else: angles = represent(self.__class__( *test_args), basis=basis)[0].args[0].args[3:6] if angles == (0, 0, 0): return self else: state = evect(j, mi, *args) lt = Rotation.D(j, mi, self.m, *angles) return Sum(lt*state, (mi, -j, j)) def _eval_innerproduct_JxBra(self, bra, **hints): result = KroneckerDelta(self.j, bra.j) if bra.dual_class() is not self.__class__: result *= self._represent_JxOp(None)[bra.j - bra.m] else: result *= KroneckerDelta( self.j, bra.j)*KroneckerDelta(self.m, bra.m) return result def _eval_innerproduct_JyBra(self, bra, **hints): result = KroneckerDelta(self.j, bra.j) if bra.dual_class() is not self.__class__: result *= self._represent_JyOp(None)[bra.j - bra.m] else: result *= KroneckerDelta( self.j, bra.j)*KroneckerDelta(self.m, bra.m) return result def _eval_innerproduct_JzBra(self, bra, **hints): result = KroneckerDelta(self.j, bra.j) if bra.dual_class() is not self.__class__: result *= self._represent_JzOp(None)[bra.j - bra.m] else: result *= KroneckerDelta( self.j, bra.j)*KroneckerDelta(self.m, bra.m) return result def _eval_trace(self, bra, **hints): # One way to implement this method is to assume the basis set k is # passed. # Then we can apply the discrete form of Trace formula here # Tr(|i><j| ) = \Sum_k <k|i><j|k> #then we do qapply() on each each inner product and sum over them. # OR # Inner product of |i><j| = Trace(Outer Product). # we could just use this unless there are cases when this is not true return (bra*self).doit() class JxKet(SpinState, Ket): """Eigenket of Jx. See JzKet for the usage of spin eigenstates. See Also ======== JzKet: Usage of spin states """ @classmethod def dual_class(self): return JxBra @classmethod def coupled_class(self): return JxKetCoupled def _represent_default_basis(self, **options): return self._represent_JxOp(None, **options) def _represent_JxOp(self, basis, **options): return self._represent_base(**options) def _represent_JyOp(self, basis, **options): return self._represent_base(alpha=pi*Rational(3, 2), **options) def _represent_JzOp(self, basis, **options): return self._represent_base(beta=pi/2, **options) class JxBra(SpinState, Bra): """Eigenbra of Jx. See JzKet for the usage of spin eigenstates. See Also ======== JzKet: Usage of spin states """ @classmethod def dual_class(self): return JxKet @classmethod def coupled_class(self): return JxBraCoupled class JyKet(SpinState, Ket): """Eigenket of Jy. See JzKet for the usage of spin eigenstates. See Also ======== JzKet: Usage of spin states """ @classmethod def dual_class(self): return JyBra @classmethod def coupled_class(self): return JyKetCoupled def _represent_default_basis(self, **options): return self._represent_JyOp(None, **options) def _represent_JxOp(self, basis, **options): return self._represent_base(gamma=pi/2, **options) def _represent_JyOp(self, basis, **options): return self._represent_base(**options) def _represent_JzOp(self, basis, **options): return self._represent_base(alpha=pi*Rational(3, 2), beta=-pi/2, gamma=pi/2, **options) class JyBra(SpinState, Bra): """Eigenbra of Jy. See JzKet for the usage of spin eigenstates. See Also ======== JzKet: Usage of spin states """ @classmethod def dual_class(self): return JyKet @classmethod def coupled_class(self): return JyBraCoupled class JzKet(SpinState, Ket): """Eigenket of Jz. Spin state which is an eigenstate of the Jz operator. Uncoupled states, that is states representing the interaction of multiple separate spin states, are defined as a tensor product of states. Parameters ========== j : Number, Symbol Total spin angular momentum m : Number, Symbol Eigenvalue of the Jz spin operator Examples ======== *Normal States:* Defining simple spin states, both numerical and symbolic: >>> from sympy.physics.quantum.spin import JzKet, JxKet >>> from sympy import symbols >>> JzKet(1, 0) |1,0> >>> j, m = symbols('j m') >>> JzKet(j, m) |j,m> Rewriting the JzKet in terms of eigenkets of the Jx operator: Note: that the resulting eigenstates are JxKet's >>> JzKet(1,1).rewrite("Jx") |1,-1>/2 - sqrt(2)*|1,0>/2 + |1,1>/2 Get the vector representation of a state in terms of the basis elements of the Jx operator: >>> from sympy.physics.quantum.represent import represent >>> from sympy.physics.quantum.spin import Jx, Jz >>> represent(JzKet(1,-1), basis=Jx) Matrix([ [ 1/2], [sqrt(2)/2], [ 1/2]]) Apply innerproducts between states: >>> from sympy.physics.quantum.innerproduct import InnerProduct >>> from sympy.physics.quantum.spin import JxBra >>> i = InnerProduct(JxBra(1,1), JzKet(1,1)) >>> i <1,1|1,1> >>> i.doit() 1/2 *Uncoupled States:* Define an uncoupled state as a TensorProduct between two Jz eigenkets: >>> from sympy.physics.quantum.tensorproduct import TensorProduct >>> j1,m1,j2,m2 = symbols('j1 m1 j2 m2') >>> TensorProduct(JzKet(1,0), JzKet(1,1)) |1,0>x|1,1> >>> TensorProduct(JzKet(j1,m1), JzKet(j2,m2)) |j1,m1>x|j2,m2> A TensorProduct can be rewritten, in which case the eigenstates that make up the tensor product is rewritten to the new basis: >>> TensorProduct(JzKet(1,1),JxKet(1,1)).rewrite('Jz') |1,1>x|1,-1>/2 + sqrt(2)*|1,1>x|1,0>/2 + |1,1>x|1,1>/2 The represent method for TensorProduct's gives the vector representation of the state. Note that the state in the product basis is the equivalent of the tensor product of the vector representation of the component eigenstates: >>> represent(TensorProduct(JzKet(1,0),JzKet(1,1))) Matrix([ [0], [0], [0], [1], [0], [0], [0], [0], [0]]) >>> represent(TensorProduct(JzKet(1,1),JxKet(1,1)), basis=Jz) Matrix([ [ 1/2], [sqrt(2)/2], [ 1/2], [ 0], [ 0], [ 0], [ 0], [ 0], [ 0]]) See Also ======== JzKetCoupled: Coupled eigenstates sympy.physics.quantum.tensorproduct.TensorProduct: Used to specify uncoupled states uncouple: Uncouples states given coupling parameters couple: Couples uncoupled states """ @classmethod def dual_class(self): return JzBra @classmethod def coupled_class(self): return JzKetCoupled def _represent_default_basis(self, **options): return self._represent_JzOp(None, **options) def _represent_JxOp(self, basis, **options): return self._represent_base(beta=pi*Rational(3, 2), **options) def _represent_JyOp(self, basis, **options): return self._represent_base(alpha=pi*Rational(3, 2), beta=pi/2, gamma=pi/2, **options) def _represent_JzOp(self, basis, **options): return self._represent_base(**options) class JzBra(SpinState, Bra): """Eigenbra of Jz. See the JzKet for the usage of spin eigenstates. See Also ======== JzKet: Usage of spin states """ @classmethod def dual_class(self): return JzKet @classmethod def coupled_class(self): return JzBraCoupled # Method used primarily to create coupled_n and coupled_jn by __new__ in # CoupledSpinState # This same method is also used by the uncouple method, and is separated from # the CoupledSpinState class to maintain consistency in defining coupling def _build_coupled(jcoupling, length): n_list = [ [n + 1] for n in range(length) ] coupled_jn = [] coupled_n = [] for n1, n2, j_new in jcoupling: coupled_jn.append(j_new) coupled_n.append( (n_list[n1 - 1], n_list[n2 - 1]) ) n_sort = sorted(n_list[n1 - 1] + n_list[n2 - 1]) n_list[n_sort[0] - 1] = n_sort return coupled_n, coupled_jn class CoupledSpinState(SpinState): """Base class for coupled angular momentum states.""" def __new__(cls, j, m, jn, *jcoupling): # Check j and m values using SpinState SpinState(j, m) # Build and check coupling scheme from arguments if len(jcoupling) == 0: # Use default coupling scheme jcoupling = [] for n in range(2, len(jn)): jcoupling.append( (1, n, Add(*[jn[i] for i in range(n)])) ) jcoupling.append( (1, len(jn), j) ) elif len(jcoupling) == 1: # Use specified coupling scheme jcoupling = jcoupling[0] else: raise TypeError("CoupledSpinState only takes 3 or 4 arguments, got: %s" % (len(jcoupling) + 3) ) # Check arguments have correct form if not (isinstance(jn, list) or isinstance(jn, tuple) or isinstance(jn, Tuple)): raise TypeError('jn must be Tuple, list or tuple, got %s' % jn.__class__.__name__) if not (isinstance(jcoupling, list) or isinstance(jcoupling, tuple) or isinstance(jcoupling, Tuple)): raise TypeError('jcoupling must be Tuple, list or tuple, got %s' % jcoupling.__class__.__name__) if not all(isinstance(term, list) or isinstance(term, tuple) or isinstance(term, Tuple) for term in jcoupling): raise TypeError( 'All elements of jcoupling must be list, tuple or Tuple') if not len(jn) - 1 == len(jcoupling): raise ValueError('jcoupling must have length of %d, got %d' % (len(jn) - 1, len(jcoupling))) if not all(len(x) == 3 for x in jcoupling): raise ValueError('All elements of jcoupling must have length 3') # Build sympified args j = sympify(j) m = sympify(m) jn = Tuple( *[sympify(ji) for ji in jn] ) jcoupling = Tuple( *[Tuple(sympify( n1), sympify(n2), sympify(ji)) for (n1, n2, ji) in jcoupling] ) # Check values in coupling scheme give physical state if any(2*ji != int(2*ji) for ji in jn if ji.is_number): raise ValueError('All elements of jn must be integer or half-integer, got: %s' % jn) if any(n1 != int(n1) or n2 != int(n2) for (n1, n2, _) in jcoupling): raise ValueError('Indices in jcoupling must be integers') if any(n1 < 1 or n2 < 1 or n1 > len(jn) or n2 > len(jn) for (n1, n2, _) in jcoupling): raise ValueError('Indices must be between 1 and the number of coupled spin spaces') if any(2*ji != int(2*ji) for (_, _, ji) in jcoupling if ji.is_number): raise ValueError('All coupled j values in coupling scheme must be integer or half-integer') coupled_n, coupled_jn = _build_coupled(jcoupling, len(jn)) jvals = list(jn) for n, (n1, n2) in enumerate(coupled_n): j1 = jvals[min(n1) - 1] j2 = jvals[min(n2) - 1] j3 = coupled_jn[n] if sympify(j1).is_number and sympify(j2).is_number and sympify(j3).is_number: if j1 + j2 < j3: raise ValueError('All couplings must have j1+j2 >= j3, ' 'in coupling number %d got j1,j2,j3: %d,%d,%d' % (n + 1, j1, j2, j3)) if abs(j1 - j2) > j3: raise ValueError("All couplings must have |j1+j2| <= j3, " "in coupling number %d got j1,j2,j3: %d,%d,%d" % (n + 1, j1, j2, j3)) if int(j1 + j2) == j1 + j2: pass jvals[min(n1 + n2) - 1] = j3 if len(jcoupling) > 0 and jcoupling[-1][2] != j: raise ValueError('Last j value coupled together must be the final j of the state') # Return state return State.__new__(cls, j, m, jn, jcoupling) def _print_label(self, printer, *args): label = [printer._print(self.j), printer._print(self.m)] for i, ji in enumerate(self.jn, start=1): label.append('j%d=%s' % ( i, printer._print(ji) )) for jn, (n1, n2) in zip(self.coupled_jn[:-1], self.coupled_n[:-1]): label.append('j(%s)=%s' % ( ','.join(str(i) for i in sorted(n1 + n2)), printer._print(jn) )) return ','.join(label) def _print_label_pretty(self, printer, *args): label = [self.j, self.m] for i, ji in enumerate(self.jn, start=1): symb = 'j%d' % i symb = pretty_symbol(symb) symb = prettyForm(symb + '=') item = prettyForm(*symb.right(printer._print(ji))) label.append(item) for jn, (n1, n2) in zip(self.coupled_jn[:-1], self.coupled_n[:-1]): n = ','.join(pretty_symbol("j%d" % i)[-1] for i in sorted(n1 + n2)) symb = prettyForm('j' + n + '=') item = prettyForm(*symb.right(printer._print(jn))) label.append(item) return self._print_sequence_pretty( label, self._label_separator, printer, *args ) def _print_label_latex(self, printer, *args): label = [ printer._print(self.j, *args), printer._print(self.m, *args) ] for i, ji in enumerate(self.jn, start=1): label.append('j_{%d}=%s' % (i, printer._print(ji, *args)) ) for jn, (n1, n2) in zip(self.coupled_jn[:-1], self.coupled_n[:-1]): n = ','.join(str(i) for i in sorted(n1 + n2)) label.append('j_{%s}=%s' % (n, printer._print(jn, *args)) ) return self._label_separator.join(label) @property def jn(self): return self.label[2] @property def coupling(self): return self.label[3] @property def coupled_jn(self): return _build_coupled(self.label[3], len(self.label[2]))[1] @property def coupled_n(self): return _build_coupled(self.label[3], len(self.label[2]))[0] @classmethod def _eval_hilbert_space(cls, label): j = Add(*label[2]) if j.is_number: return DirectSumHilbertSpace(*[ ComplexSpace(x) for x in range(int(2*j + 1), 0, -2) ]) else: # TODO: Need hilbert space fix, see issue 5732 # Desired behavior: #ji = symbols('ji') #ret = Sum(ComplexSpace(2*ji + 1), (ji, 0, j)) # Temporary fix: return ComplexSpace(2*j + 1) def _represent_coupled_base(self, **options): evect = self.uncoupled_class() if not self.j.is_number: raise ValueError( 'State must not have symbolic j value to represent') if not self.hilbert_space.dimension.is_number: raise ValueError( 'State must not have symbolic j values to represent') result = zeros(self.hilbert_space.dimension, 1) if self.j == int(self.j): start = self.j**2 else: start = (2*self.j - 1)*(1 + 2*self.j)/4 result[start:start + 2*self.j + 1, 0] = evect( self.j, self.m)._represent_base(**options) return result def _eval_rewrite_as_Jx(self, *args, **options): if isinstance(self, Bra): return self._rewrite_basis(Jx, JxBraCoupled, **options) return self._rewrite_basis(Jx, JxKetCoupled, **options) def _eval_rewrite_as_Jy(self, *args, **options): if isinstance(self, Bra): return self._rewrite_basis(Jy, JyBraCoupled, **options) return self._rewrite_basis(Jy, JyKetCoupled, **options) def _eval_rewrite_as_Jz(self, *args, **options): if isinstance(self, Bra): return self._rewrite_basis(Jz, JzBraCoupled, **options) return self._rewrite_basis(Jz, JzKetCoupled, **options) class JxKetCoupled(CoupledSpinState, Ket): """Coupled eigenket of Jx. See JzKetCoupled for the usage of coupled spin eigenstates. See Also ======== JzKetCoupled: Usage of coupled spin states """ @classmethod def dual_class(self): return JxBraCoupled @classmethod def uncoupled_class(self): return JxKet def _represent_default_basis(self, **options): return self._represent_JzOp(None, **options) def _represent_JxOp(self, basis, **options): return self._represent_coupled_base(**options) def _represent_JyOp(self, basis, **options): return self._represent_coupled_base(alpha=pi*Rational(3, 2), **options) def _represent_JzOp(self, basis, **options): return self._represent_coupled_base(beta=pi/2, **options) class JxBraCoupled(CoupledSpinState, Bra): """Coupled eigenbra of Jx. See JzKetCoupled for the usage of coupled spin eigenstates. See Also ======== JzKetCoupled: Usage of coupled spin states """ @classmethod def dual_class(self): return JxKetCoupled @classmethod def uncoupled_class(self): return JxBra class JyKetCoupled(CoupledSpinState, Ket): """Coupled eigenket of Jy. See JzKetCoupled for the usage of coupled spin eigenstates. See Also ======== JzKetCoupled: Usage of coupled spin states """ @classmethod def dual_class(self): return JyBraCoupled @classmethod def uncoupled_class(self): return JyKet def _represent_default_basis(self, **options): return self._represent_JzOp(None, **options) def _represent_JxOp(self, basis, **options): return self._represent_coupled_base(gamma=pi/2, **options) def _represent_JyOp(self, basis, **options): return self._represent_coupled_base(**options) def _represent_JzOp(self, basis, **options): return self._represent_coupled_base(alpha=pi*Rational(3, 2), beta=-pi/2, gamma=pi/2, **options) class JyBraCoupled(CoupledSpinState, Bra): """Coupled eigenbra of Jy. See JzKetCoupled for the usage of coupled spin eigenstates. See Also ======== JzKetCoupled: Usage of coupled spin states """ @classmethod def dual_class(self): return JyKetCoupled @classmethod def uncoupled_class(self): return JyBra class JzKetCoupled(CoupledSpinState, Ket): r"""Coupled eigenket of Jz Spin state that is an eigenket of Jz which represents the coupling of separate spin spaces. The arguments for creating instances of JzKetCoupled are ``j``, ``m``, ``jn`` and an optional ``jcoupling`` argument. The ``j`` and ``m`` options are the total angular momentum quantum numbers, as used for normal states (e.g. JzKet). The other required parameter in ``jn``, which is a tuple defining the `j_n` angular momentum quantum numbers of the product spaces. So for example, if a state represented the coupling of the product basis state `\left|j_1,m_1\right\rangle\times\left|j_2,m_2\right\rangle`, the ``jn`` for this state would be ``(j1,j2)``. The final option is ``jcoupling``, which is used to define how the spaces specified by ``jn`` are coupled, which includes both the order these spaces are coupled together and the quantum numbers that arise from these couplings. The ``jcoupling`` parameter itself is a list of lists, such that each of the sublists defines a single coupling between the spin spaces. If there are N coupled angular momentum spaces, that is ``jn`` has N elements, then there must be N-1 sublists. Each of these sublists making up the ``jcoupling`` parameter have length 3. The first two elements are the indices of the product spaces that are considered to be coupled together. For example, if we want to couple `j_1` and `j_4`, the indices would be 1 and 4. If a state has already been coupled, it is referenced by the smallest index that is coupled, so if `j_2` and `j_4` has already been coupled to some `j_{24}`, then this value can be coupled by referencing it with index 2. The final element of the sublist is the quantum number of the coupled state. So putting everything together, into a valid sublist for ``jcoupling``, if `j_1` and `j_2` are coupled to an angular momentum space with quantum number `j_{12}` with the value ``j12``, the sublist would be ``(1,2,j12)``, N-1 of these sublists are used in the list for ``jcoupling``. Note the ``jcoupling`` parameter is optional, if it is not specified, the default coupling is taken. This default value is to coupled the spaces in order and take the quantum number of the coupling to be the maximum value. For example, if the spin spaces are `j_1`, `j_2`, `j_3`, `j_4`, then the default coupling couples `j_1` and `j_2` to `j_{12}=j_1+j_2`, then, `j_{12}` and `j_3` are coupled to `j_{123}=j_{12}+j_3`, and finally `j_{123}` and `j_4` to `j=j_{123}+j_4`. The jcoupling value that would correspond to this is: ``((1,2,j1+j2),(1,3,j1+j2+j3))`` Parameters ========== args : tuple The arguments that must be passed are ``j``, ``m``, ``jn``, and ``jcoupling``. The ``j`` value is the total angular momentum. The ``m`` value is the eigenvalue of the Jz spin operator. The ``jn`` list are the j values of argular momentum spaces coupled together. The ``jcoupling`` parameter is an optional parameter defining how the spaces are coupled together. See the above description for how these coupling parameters are defined. Examples ======== Defining simple spin states, both numerical and symbolic: >>> from sympy.physics.quantum.spin import JzKetCoupled >>> from sympy import symbols >>> JzKetCoupled(1, 0, (1, 1)) |1,0,j1=1,j2=1> >>> j, m, j1, j2 = symbols('j m j1 j2') >>> JzKetCoupled(j, m, (j1, j2)) |j,m,j1=j1,j2=j2> Defining coupled spin states for more than 2 coupled spaces with various coupling parameters: >>> JzKetCoupled(2, 1, (1, 1, 1)) |2,1,j1=1,j2=1,j3=1,j(1,2)=2> >>> JzKetCoupled(2, 1, (1, 1, 1), ((1,2,2),(1,3,2)) ) |2,1,j1=1,j2=1,j3=1,j(1,2)=2> >>> JzKetCoupled(2, 1, (1, 1, 1), ((2,3,1),(1,2,2)) ) |2,1,j1=1,j2=1,j3=1,j(2,3)=1> Rewriting the JzKetCoupled in terms of eigenkets of the Jx operator: Note: that the resulting eigenstates are JxKetCoupled >>> JzKetCoupled(1,1,(1,1)).rewrite("Jx") |1,-1,j1=1,j2=1>/2 - sqrt(2)*|1,0,j1=1,j2=1>/2 + |1,1,j1=1,j2=1>/2 The rewrite method can be used to convert a coupled state to an uncoupled state. This is done by passing coupled=False to the rewrite function: >>> JzKetCoupled(1, 0, (1, 1)).rewrite('Jz', coupled=False) -sqrt(2)*|1,-1>x|1,1>/2 + sqrt(2)*|1,1>x|1,-1>/2 Get the vector representation of a state in terms of the basis elements of the Jx operator: >>> from sympy.physics.quantum.represent import represent >>> from sympy.physics.quantum.spin import Jx >>> from sympy import S >>> represent(JzKetCoupled(1,-1,(S(1)/2,S(1)/2)), basis=Jx) Matrix([ [ 0], [ 1/2], [sqrt(2)/2], [ 1/2]]) See Also ======== JzKet: Normal spin eigenstates uncouple: Uncoupling of coupling spin states couple: Coupling of uncoupled spin states """ @classmethod def dual_class(self): return JzBraCoupled @classmethod def uncoupled_class(self): return JzKet def _represent_default_basis(self, **options): return self._represent_JzOp(None, **options) def _represent_JxOp(self, basis, **options): return self._represent_coupled_base(beta=pi*Rational(3, 2), **options) def _represent_JyOp(self, basis, **options): return self._represent_coupled_base(alpha=pi*Rational(3, 2), beta=pi/2, gamma=pi/2, **options) def _represent_JzOp(self, basis, **options): return self._represent_coupled_base(**options) class JzBraCoupled(CoupledSpinState, Bra): """Coupled eigenbra of Jz. See the JzKetCoupled for the usage of coupled spin eigenstates. See Also ======== JzKetCoupled: Usage of coupled spin states """ @classmethod def dual_class(self): return JzKetCoupled @classmethod def uncoupled_class(self): return JzBra #----------------------------------------------------------------------------- # Coupling/uncoupling #----------------------------------------------------------------------------- def couple(expr, jcoupling_list=None): """ Couple a tensor product of spin states This function can be used to couple an uncoupled tensor product of spin states. All of the eigenstates to be coupled must be of the same class. It will return a linear combination of eigenstates that are subclasses of CoupledSpinState determined by Clebsch-Gordan angular momentum coupling coefficients. Parameters ========== expr : Expr An expression involving TensorProducts of spin states to be coupled. Each state must be a subclass of SpinState and they all must be the same class. jcoupling_list : list or tuple Elements of this list are sub-lists of length 2 specifying the order of the coupling of the spin spaces. The length of this must be N-1, where N is the number of states in the tensor product to be coupled. The elements of this sublist are the same as the first two elements of each sublist in the ``jcoupling`` parameter defined for JzKetCoupled. If this parameter is not specified, the default value is taken, which couples the first and second product basis spaces, then couples this new coupled space to the third product space, etc Examples ======== Couple a tensor product of numerical states for two spaces: >>> from sympy.physics.quantum.spin import JzKet, couple >>> from sympy.physics.quantum.tensorproduct import TensorProduct >>> couple(TensorProduct(JzKet(1,0), JzKet(1,1))) -sqrt(2)*|1,1,j1=1,j2=1>/2 + sqrt(2)*|2,1,j1=1,j2=1>/2 Numerical coupling of three spaces using the default coupling method, i.e. first and second spaces couple, then this couples to the third space: >>> couple(TensorProduct(JzKet(1,1), JzKet(1,1), JzKet(1,0))) sqrt(6)*|2,2,j1=1,j2=1,j3=1,j(1,2)=2>/3 + sqrt(3)*|3,2,j1=1,j2=1,j3=1,j(1,2)=2>/3 Perform this same coupling, but we define the coupling to first couple the first and third spaces: >>> couple(TensorProduct(JzKet(1,1), JzKet(1,1), JzKet(1,0)), ((1,3),(1,2)) ) sqrt(2)*|2,2,j1=1,j2=1,j3=1,j(1,3)=1>/2 - sqrt(6)*|2,2,j1=1,j2=1,j3=1,j(1,3)=2>/6 + sqrt(3)*|3,2,j1=1,j2=1,j3=1,j(1,3)=2>/3 Couple a tensor product of symbolic states: >>> from sympy import symbols >>> j1,m1,j2,m2 = symbols('j1 m1 j2 m2') >>> couple(TensorProduct(JzKet(j1,m1), JzKet(j2,m2))) Sum(CG(j1, m1, j2, m2, j, m1 + m2)*|j,m1 + m2,j1=j1,j2=j2>, (j, m1 + m2, j1 + j2)) """ a = expr.atoms(TensorProduct) for tp in a: # Allow other tensor products to be in expression if not all([ isinstance(state, SpinState) for state in tp.args]): continue # If tensor product has all spin states, raise error for invalid tensor product state if not all([state.__class__ is tp.args[0].__class__ for state in tp.args]): raise TypeError('All states must be the same basis') expr = expr.subs(tp, _couple(tp, jcoupling_list)) return expr def _couple(tp, jcoupling_list): states = tp.args coupled_evect = states[0].coupled_class() # Define default coupling if none is specified if jcoupling_list is None: jcoupling_list = [] for n in range(1, len(states)): jcoupling_list.append( (1, n + 1) ) # Check jcoupling_list valid if not len(jcoupling_list) == len(states) - 1: raise TypeError('jcoupling_list must be length %d, got %d' % (len(states) - 1, len(jcoupling_list))) if not all( len(coupling) == 2 for coupling in jcoupling_list): raise ValueError('Each coupling must define 2 spaces') if any([n1 == n2 for n1, n2 in jcoupling_list]): raise ValueError('Spin spaces cannot couple to themselves') if all([sympify(n1).is_number and sympify(n2).is_number for n1, n2 in jcoupling_list]): j_test = [0]*len(states) for n1, n2 in jcoupling_list: if j_test[n1 - 1] == -1 or j_test[n2 - 1] == -1: raise ValueError('Spaces coupling j_n\'s are referenced by smallest n value') j_test[max(n1, n2) - 1] = -1 # j values of states to be coupled together jn = [state.j for state in states] mn = [state.m for state in states] # Create coupling_list, which defines all the couplings between all # the spaces from jcoupling_list coupling_list = [] n_list = [ [i + 1] for i in range(len(states)) ] for j_coupling in jcoupling_list: # Least n for all j_n which is coupled as first and second spaces n1, n2 = j_coupling # List of all n's coupled in first and second spaces j1_n = list(n_list[n1 - 1]) j2_n = list(n_list[n2 - 1]) coupling_list.append( (j1_n, j2_n) ) # Set new j_n to be coupling of all j_n in both first and second spaces n_list[ min(n1, n2) - 1 ] = sorted(j1_n + j2_n) if all(state.j.is_number and state.m.is_number for state in states): # Numerical coupling # Iterate over difference between maximum possible j value of each coupling and the actual value diff_max = [ Add( *[ jn[n - 1] - mn[n - 1] for n in coupling[0] + coupling[1] ] ) for coupling in coupling_list ] result = [] for diff in range(diff_max[-1] + 1): # Determine available configurations n = len(coupling_list) tot = binomial(diff + n - 1, diff) for config_num in range(tot): diff_list = _confignum_to_difflist(config_num, diff, n) # Skip the configuration if non-physical # This is a lazy check for physical states given the loose restrictions of diff_max if any( [ d > m for d, m in zip(diff_list, diff_max) ] ): continue # Determine term cg_terms = [] coupled_j = list(jn) jcoupling = [] for (j1_n, j2_n), coupling_diff in zip(coupling_list, diff_list): j1 = coupled_j[ min(j1_n) - 1 ] j2 = coupled_j[ min(j2_n) - 1 ] j3 = j1 + j2 - coupling_diff coupled_j[ min(j1_n + j2_n) - 1 ] = j3 m1 = Add( *[ mn[x - 1] for x in j1_n] ) m2 = Add( *[ mn[x - 1] for x in j2_n] ) m3 = m1 + m2 cg_terms.append( (j1, m1, j2, m2, j3, m3) ) jcoupling.append( (min(j1_n), min(j2_n), j3) ) # Better checks that state is physical if any([ abs(term[5]) > term[4] for term in cg_terms ]): continue if any([ term[0] + term[2] < term[4] for term in cg_terms ]): continue if any([ abs(term[0] - term[2]) > term[4] for term in cg_terms ]): continue coeff = Mul( *[ CG(*term).doit() for term in cg_terms] ) state = coupled_evect(j3, m3, jn, jcoupling) result.append(coeff*state) return Add(*result) else: # Symbolic coupling cg_terms = [] jcoupling = [] sum_terms = [] coupled_j = list(jn) for j1_n, j2_n in coupling_list: j1 = coupled_j[ min(j1_n) - 1 ] j2 = coupled_j[ min(j2_n) - 1 ] if len(j1_n + j2_n) == len(states): j3 = symbols('j') else: j3_name = 'j' + ''.join(["%s" % n for n in j1_n + j2_n]) j3 = symbols(j3_name) coupled_j[ min(j1_n + j2_n) - 1 ] = j3 m1 = Add( *[ mn[x - 1] for x in j1_n] ) m2 = Add( *[ mn[x - 1] for x in j2_n] ) m3 = m1 + m2 cg_terms.append( (j1, m1, j2, m2, j3, m3) ) jcoupling.append( (min(j1_n), min(j2_n), j3) ) sum_terms.append((j3, m3, j1 + j2)) coeff = Mul( *[ CG(*term) for term in cg_terms] ) state = coupled_evect(j3, m3, jn, jcoupling) return Sum(coeff*state, *sum_terms) def uncouple(expr, jn=None, jcoupling_list=None): """ Uncouple a coupled spin state Gives the uncoupled representation of a coupled spin state. Arguments must be either a spin state that is a subclass of CoupledSpinState or a spin state that is a subclass of SpinState and an array giving the j values of the spaces that are to be coupled Parameters ========== expr : Expr The expression containing states that are to be coupled. If the states are a subclass of SpinState, the ``jn`` and ``jcoupling`` parameters must be defined. If the states are a subclass of CoupledSpinState, ``jn`` and ``jcoupling`` will be taken from the state. jn : list or tuple The list of the j-values that are coupled. If state is a CoupledSpinState, this parameter is ignored. This must be defined if state is not a subclass of CoupledSpinState. The syntax of this parameter is the same as the ``jn`` parameter of JzKetCoupled. jcoupling_list : list or tuple The list defining how the j-values are coupled together. If state is a CoupledSpinState, this parameter is ignored. This must be defined if state is not a subclass of CoupledSpinState. The syntax of this parameter is the same as the ``jcoupling`` parameter of JzKetCoupled. Examples ======== Uncouple a numerical state using a CoupledSpinState state: >>> from sympy.physics.quantum.spin import JzKetCoupled, uncouple >>> from sympy import S >>> uncouple(JzKetCoupled(1, 0, (S(1)/2, S(1)/2))) sqrt(2)*|1/2,-1/2>x|1/2,1/2>/2 + sqrt(2)*|1/2,1/2>x|1/2,-1/2>/2 Perform the same calculation using a SpinState state: >>> from sympy.physics.quantum.spin import JzKet >>> uncouple(JzKet(1, 0), (S(1)/2, S(1)/2)) sqrt(2)*|1/2,-1/2>x|1/2,1/2>/2 + sqrt(2)*|1/2,1/2>x|1/2,-1/2>/2 Uncouple a numerical state of three coupled spaces using a CoupledSpinState state: >>> uncouple(JzKetCoupled(1, 1, (1, 1, 1), ((1,3,1),(1,2,1)) )) |1,-1>x|1,1>x|1,1>/2 - |1,0>x|1,0>x|1,1>/2 + |1,1>x|1,0>x|1,0>/2 - |1,1>x|1,1>x|1,-1>/2 Perform the same calculation using a SpinState state: >>> uncouple(JzKet(1, 1), (1, 1, 1), ((1,3,1),(1,2,1)) ) |1,-1>x|1,1>x|1,1>/2 - |1,0>x|1,0>x|1,1>/2 + |1,1>x|1,0>x|1,0>/2 - |1,1>x|1,1>x|1,-1>/2 Uncouple a symbolic state using a CoupledSpinState state: >>> from sympy import symbols >>> j,m,j1,j2 = symbols('j m j1 j2') >>> uncouple(JzKetCoupled(j, m, (j1, j2))) Sum(CG(j1, m1, j2, m2, j, m)*|j1,m1>x|j2,m2>, (m1, -j1, j1), (m2, -j2, j2)) Perform the same calculation using a SpinState state >>> uncouple(JzKet(j, m), (j1, j2)) Sum(CG(j1, m1, j2, m2, j, m)*|j1,m1>x|j2,m2>, (m1, -j1, j1), (m2, -j2, j2)) """ a = expr.atoms(SpinState) for state in a: expr = expr.subs(state, _uncouple(state, jn, jcoupling_list)) return expr def _uncouple(state, jn, jcoupling_list): if isinstance(state, CoupledSpinState): jn = state.jn coupled_n = state.coupled_n coupled_jn = state.coupled_jn evect = state.uncoupled_class() elif isinstance(state, SpinState): if jn is None: raise ValueError("Must specify j-values for coupled state") if not (isinstance(jn, list) or isinstance(jn, tuple)): raise TypeError("jn must be list or tuple") if jcoupling_list is None: # Use default jcoupling_list = [] for i in range(1, len(jn)): jcoupling_list.append( (1, 1 + i, Add(*[jn[j] for j in range(i + 1)])) ) if not (isinstance(jcoupling_list, list) or isinstance(jcoupling_list, tuple)): raise TypeError("jcoupling must be a list or tuple") if not len(jcoupling_list) == len(jn) - 1: raise ValueError("Must specify 2 fewer coupling terms than the number of j values") coupled_n, coupled_jn = _build_coupled(jcoupling_list, len(jn)) evect = state.__class__ else: raise TypeError("state must be a spin state") j = state.j m = state.m coupling_list = [] j_list = list(jn) # Create coupling, which defines all the couplings between all the spaces for j3, (n1, n2) in zip(coupled_jn, coupled_n): # j's which are coupled as first and second spaces j1 = j_list[n1[0] - 1] j2 = j_list[n2[0] - 1] # Build coupling list coupling_list.append( (n1, n2, j1, j2, j3) ) # Set new value in j_list j_list[min(n1 + n2) - 1] = j3 if j.is_number and m.is_number: diff_max = [ 2*x for x in jn ] diff = Add(*jn) - m n = len(jn) tot = binomial(diff + n - 1, diff) result = [] for config_num in range(tot): diff_list = _confignum_to_difflist(config_num, diff, n) if any( [ d > p for d, p in zip(diff_list, diff_max) ] ): continue cg_terms = [] for coupling in coupling_list: j1_n, j2_n, j1, j2, j3 = coupling m1 = Add( *[ jn[x - 1] - diff_list[x - 1] for x in j1_n ] ) m2 = Add( *[ jn[x - 1] - diff_list[x - 1] for x in j2_n ] ) m3 = m1 + m2 cg_terms.append( (j1, m1, j2, m2, j3, m3) ) coeff = Mul( *[ CG(*term).doit() for term in cg_terms ] ) state = TensorProduct( *[ evect(j, j - d) for j, d in zip(jn, diff_list) ] ) result.append(coeff*state) return Add(*result) else: # Symbolic coupling m_str = "m1:%d" % (len(jn) + 1) mvals = symbols(m_str) cg_terms = [(j1, Add(*[mvals[n - 1] for n in j1_n]), j2, Add(*[mvals[n - 1] for n in j2_n]), j3, Add(*[mvals[n - 1] for n in j1_n + j2_n])) for j1_n, j2_n, j1, j2, j3 in coupling_list[:-1] ] cg_terms.append(*[(j1, Add(*[mvals[n - 1] for n in j1_n]), j2, Add(*[mvals[n - 1] for n in j2_n]), j, m) for j1_n, j2_n, j1, j2, j3 in [coupling_list[-1]] ]) cg_coeff = Mul(*[CG(*cg_term) for cg_term in cg_terms]) sum_terms = [ (m, -j, j) for j, m in zip(jn, mvals) ] state = TensorProduct( *[ evect(j, m) for j, m in zip(jn, mvals) ] ) return Sum(cg_coeff*state, *sum_terms) def _confignum_to_difflist(config_num, diff, list_len): # Determines configuration of diffs into list_len number of slots diff_list = [] for n in range(list_len): prev_diff = diff # Number of spots after current one rem_spots = list_len - n - 1 # Number of configurations of distributing diff among the remaining spots rem_configs = binomial(diff + rem_spots - 1, diff) while config_num >= rem_configs: config_num -= rem_configs diff -= 1 rem_configs = binomial(diff + rem_spots - 1, diff) diff_list.append(prev_diff - diff) return diff_list
db45510130a44a9ad29c6151e5e8ef3046255b011cbf507e744dd13ea3d343d9
"""Constants (like hbar) related to quantum mechanics.""" from sympy.core.numbers import NumberSymbol from sympy.core.singleton import Singleton from sympy.printing.pretty.stringpict import prettyForm import mpmath.libmp as mlib #----------------------------------------------------------------------------- # Constants #----------------------------------------------------------------------------- __all__ = [ 'hbar', 'HBar', ] class HBar(NumberSymbol, metaclass=Singleton): """Reduced Plank's constant in numerical and symbolic form [1]_. Examples ======== >>> from sympy.physics.quantum.constants import hbar >>> hbar.evalf() 1.05457162000000e-34 References ========== .. [1] https://en.wikipedia.org/wiki/Planck_constant """ is_real = True is_positive = True is_negative = False is_irrational = True __slots__ = () def _as_mpf_val(self, prec): return mlib.from_float(1.05457162e-34, prec) def _sympyrepr(self, printer, *args): return 'HBar()' def _sympystr(self, printer, *args): return 'hbar' def _pretty(self, printer, *args): if printer._use_unicode: return prettyForm('\N{PLANCK CONSTANT OVER TWO PI}') return prettyForm('hbar') def _latex(self, printer, *args): return r'\hbar' # Create an instance for everyone to use. hbar = HBar()
84b08f16c888394718551bd239385a14db509f49509850d6539b8c612bc11b55
"""Matplotlib based plotting of quantum circuits. Todo: * Optimize printing of large circuits. * Get this to work with single gates. * Do a better job checking the form of circuits to make sure it is a Mul of Gates. * Get multi-target gates plotting. * Get initial and final states to plot. * Get measurements to plot. Might need to rethink measurement as a gate issue. * Get scale and figsize to be handled in a better way. * Write some tests/examples! """ from typing import List, Dict from sympy import Mul from sympy.external import import_module from sympy.physics.quantum.gate import Gate, OneQubitGate, CGate, CGateS from sympy.core.core import BasicMeta from sympy.core.assumptions import ManagedProperties __all__ = [ 'CircuitPlot', 'circuit_plot', 'labeller', 'Mz', 'Mx', 'CreateOneQubitGate', 'CreateCGate', ] np = import_module('numpy') matplotlib = import_module( 'matplotlib', import_kwargs={'fromlist': ['pyplot']}, catch=(RuntimeError,)) # This is raised in environments that have no display. if np and matplotlib: pyplot = matplotlib.pyplot Line2D = matplotlib.lines.Line2D Circle = matplotlib.patches.Circle #from matplotlib import rc #rc('text',usetex=True) class CircuitPlot: """A class for managing a circuit plot.""" scale = 1.0 fontsize = 20.0 linewidth = 1.0 control_radius = 0.05 not_radius = 0.15 swap_delta = 0.05 labels = [] # type: List[str] inits = {} # type: Dict[str, str] label_buffer = 0.5 def __init__(self, c, nqubits, **kwargs): if not np or not matplotlib: raise ImportError('numpy or matplotlib not available.') self.circuit = c self.ngates = len(self.circuit.args) self.nqubits = nqubits self.update(kwargs) self._create_grid() self._create_figure() self._plot_wires() self._plot_gates() self._finish() def update(self, kwargs): """Load the kwargs into the instance dict.""" self.__dict__.update(kwargs) def _create_grid(self): """Create the grid of wires.""" scale = self.scale wire_grid = np.arange(0.0, self.nqubits*scale, scale, dtype=float) gate_grid = np.arange(0.0, self.ngates*scale, scale, dtype=float) self._wire_grid = wire_grid self._gate_grid = gate_grid def _create_figure(self): """Create the main matplotlib figure.""" self._figure = pyplot.figure( figsize=(self.ngates*self.scale, self.nqubits*self.scale), facecolor='w', edgecolor='w' ) ax = self._figure.add_subplot( 1, 1, 1, frameon=True ) ax.set_axis_off() offset = 0.5*self.scale ax.set_xlim(self._gate_grid[0] - offset, self._gate_grid[-1] + offset) ax.set_ylim(self._wire_grid[0] - offset, self._wire_grid[-1] + offset) ax.set_aspect('equal') self._axes = ax def _plot_wires(self): """Plot the wires of the circuit diagram.""" xstart = self._gate_grid[0] xstop = self._gate_grid[-1] xdata = (xstart - self.scale, xstop + self.scale) for i in range(self.nqubits): ydata = (self._wire_grid[i], self._wire_grid[i]) line = Line2D( xdata, ydata, color='k', lw=self.linewidth ) self._axes.add_line(line) if self.labels: init_label_buffer = 0 if self.inits.get(self.labels[i]): init_label_buffer = 0.25 self._axes.text( xdata[0]-self.label_buffer-init_label_buffer,ydata[0], render_label(self.labels[i],self.inits), size=self.fontsize, color='k',ha='center',va='center') self._plot_measured_wires() def _plot_measured_wires(self): ismeasured = self._measurements() xstop = self._gate_grid[-1] dy = 0.04 # amount to shift wires when doubled # Plot doubled wires after they are measured for im in ismeasured: xdata = (self._gate_grid[ismeasured[im]],xstop+self.scale) ydata = (self._wire_grid[im]+dy,self._wire_grid[im]+dy) line = Line2D( xdata, ydata, color='k', lw=self.linewidth ) self._axes.add_line(line) # Also double any controlled lines off these wires for i,g in enumerate(self._gates()): if isinstance(g, CGate) or isinstance(g, CGateS): wires = g.controls + g.targets for wire in wires: if wire in ismeasured and \ self._gate_grid[i] > self._gate_grid[ismeasured[wire]]: ydata = min(wires), max(wires) xdata = self._gate_grid[i]-dy, self._gate_grid[i]-dy line = Line2D( xdata, ydata, color='k', lw=self.linewidth ) self._axes.add_line(line) def _gates(self): """Create a list of all gates in the circuit plot.""" gates = [] if isinstance(self.circuit, Mul): for g in reversed(self.circuit.args): if isinstance(g, Gate): gates.append(g) elif isinstance(self.circuit, Gate): gates.append(self.circuit) return gates def _plot_gates(self): """Iterate through the gates and plot each of them.""" for i, gate in enumerate(self._gates()): gate.plot_gate(self, i) def _measurements(self): """Return a dict {i:j} where i is the index of the wire that has been measured, and j is the gate where the wire is measured. """ ismeasured = {} for i,g in enumerate(self._gates()): if getattr(g,'measurement',False): for target in g.targets: if target in ismeasured: if ismeasured[target] > i: ismeasured[target] = i else: ismeasured[target] = i return ismeasured def _finish(self): # Disable clipping to make panning work well for large circuits. for o in self._figure.findobj(): o.set_clip_on(False) def one_qubit_box(self, t, gate_idx, wire_idx): """Draw a box for a single qubit gate.""" x = self._gate_grid[gate_idx] y = self._wire_grid[wire_idx] self._axes.text( x, y, t, color='k', ha='center', va='center', bbox=dict(ec='k', fc='w', fill=True, lw=self.linewidth), size=self.fontsize ) def two_qubit_box(self, t, gate_idx, wire_idx): """Draw a box for a two qubit gate. Doesn't work yet. """ # x = self._gate_grid[gate_idx] # y = self._wire_grid[wire_idx]+0.5 print(self._gate_grid) print(self._wire_grid) # unused: # obj = self._axes.text( # x, y, t, # color='k', # ha='center', # va='center', # bbox=dict(ec='k', fc='w', fill=True, lw=self.linewidth), # size=self.fontsize # ) def control_line(self, gate_idx, min_wire, max_wire): """Draw a vertical control line.""" xdata = (self._gate_grid[gate_idx], self._gate_grid[gate_idx]) ydata = (self._wire_grid[min_wire], self._wire_grid[max_wire]) line = Line2D( xdata, ydata, color='k', lw=self.linewidth ) self._axes.add_line(line) def control_point(self, gate_idx, wire_idx): """Draw a control point.""" x = self._gate_grid[gate_idx] y = self._wire_grid[wire_idx] radius = self.control_radius c = Circle( (x, y), radius*self.scale, ec='k', fc='k', fill=True, lw=self.linewidth ) self._axes.add_patch(c) def not_point(self, gate_idx, wire_idx): """Draw a NOT gates as the circle with plus in the middle.""" x = self._gate_grid[gate_idx] y = self._wire_grid[wire_idx] radius = self.not_radius c = Circle( (x, y), radius, ec='k', fc='w', fill=False, lw=self.linewidth ) self._axes.add_patch(c) l = Line2D( (x, x), (y - radius, y + radius), color='k', lw=self.linewidth ) self._axes.add_line(l) def swap_point(self, gate_idx, wire_idx): """Draw a swap point as a cross.""" x = self._gate_grid[gate_idx] y = self._wire_grid[wire_idx] d = self.swap_delta l1 = Line2D( (x - d, x + d), (y - d, y + d), color='k', lw=self.linewidth ) l2 = Line2D( (x - d, x + d), (y + d, y - d), color='k', lw=self.linewidth ) self._axes.add_line(l1) self._axes.add_line(l2) def circuit_plot(c, nqubits, **kwargs): """Draw the circuit diagram for the circuit with nqubits. Parameters ========== c : circuit The circuit to plot. Should be a product of Gate instances. nqubits : int The number of qubits to include in the circuit. Must be at least as big as the largest `min_qubits`` of the gates. """ return CircuitPlot(c, nqubits, **kwargs) def render_label(label, inits={}): """Slightly more flexible way to render labels. >>> from sympy.physics.quantum.circuitplot import render_label >>> render_label('q0') '$\\\\left|q0\\\\right\\\\rangle$' >>> render_label('q0', {'q0':'0'}) '$\\\\left|q0\\\\right\\\\rangle=\\\\left|0\\\\right\\\\rangle$' """ init = inits.get(label) if init: return r'$\left|%s\right\rangle=\left|%s\right\rangle$' % (label, init) return r'$\left|%s\right\rangle$' % label def labeller(n, symbol='q'): """Autogenerate labels for wires of quantum circuits. Parameters ========== n : int number of qubits in the circuit symbol : string A character string to precede all gate labels. E.g. 'q_0', 'q_1', etc. >>> from sympy.physics.quantum.circuitplot import labeller >>> labeller(2) ['q_1', 'q_0'] >>> labeller(3,'j') ['j_2', 'j_1', 'j_0'] """ return ['%s_%d' % (symbol,n-i-1) for i in range(n)] class Mz(OneQubitGate): """Mock-up of a z measurement gate. This is in circuitplot rather than gate.py because it's not a real gate, it just draws one. """ measurement = True gate_name='Mz' gate_name_latex='M_z' class Mx(OneQubitGate): """Mock-up of an x measurement gate. This is in circuitplot rather than gate.py because it's not a real gate, it just draws one. """ measurement = True gate_name='Mx' gate_name_latex='M_x' class CreateOneQubitGate(ManagedProperties): def __new__(mcl, name, latexname=None): if not latexname: latexname = name return BasicMeta.__new__(mcl, name + "Gate", (OneQubitGate,), {'gate_name': name, 'gate_name_latex': latexname}) def CreateCGate(name, latexname=None): """Use a lexical closure to make a controlled gate. """ if not latexname: latexname = name onequbitgate = CreateOneQubitGate(name, latexname) def ControlledGate(ctrls,target): return CGate(tuple(ctrls),onequbitgate(target)) return ControlledGate
953794d0b9d6364cd3868d4ab9d0cde59036ed5c7f266ad03583d52bee5d413c
#TODO: # -Implement Clebsch-Gordan symmetries # -Improve simplification method # -Implement new simpifications """Clebsch-Gordon Coefficients.""" from sympy import (Add, expand, Eq, Expr, Mul, Piecewise, Pow, sqrt, Sum, symbols, sympify, Wild) from sympy.printing.pretty.stringpict import prettyForm, stringPict from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.physics.wigner import clebsch_gordan, wigner_3j, wigner_6j, wigner_9j __all__ = [ 'CG', 'Wigner3j', 'Wigner6j', 'Wigner9j', 'cg_simp' ] #----------------------------------------------------------------------------- # CG Coefficients #----------------------------------------------------------------------------- class Wigner3j(Expr): """Class for the Wigner-3j symbols Wigner 3j-symbols are coefficients determined by the coupling of two angular momenta. When created, they are expressed as symbolic quantities that, for numerical parameters, can be evaluated using the ``.doit()`` method [1]_. Parameters ========== j1, m1, j2, m2, j3, m3 : Number, Symbol Terms determining the angular momentum of coupled angular momentum systems. Examples ======== Declare a Wigner-3j coefficient and calculate its value >>> from sympy.physics.quantum.cg import Wigner3j >>> w3j = Wigner3j(6,0,4,0,2,0) >>> w3j Wigner3j(6, 0, 4, 0, 2, 0) >>> w3j.doit() sqrt(715)/143 See Also ======== CG: Clebsch-Gordan coefficients References ========== .. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988. """ is_commutative = True def __new__(cls, j1, m1, j2, m2, j3, m3): args = map(sympify, (j1, m1, j2, m2, j3, m3)) return Expr.__new__(cls, *args) @property def j1(self): return self.args[0] @property def m1(self): return self.args[1] @property def j2(self): return self.args[2] @property def m2(self): return self.args[3] @property def j3(self): return self.args[4] @property def m3(self): return self.args[5] @property def is_symbolic(self): return not all([arg.is_number for arg in self.args]) # This is modified from the _print_Matrix method def _pretty(self, printer, *args): m = ((printer._print(self.j1), printer._print(self.m1)), (printer._print(self.j2), printer._print(self.m2)), (printer._print(self.j3), printer._print(self.m3))) hsep = 2 vsep = 1 maxw = [-1]*3 for j in range(3): maxw[j] = max([ m[j][i].width() for i in range(2) ]) D = None for i in range(2): D_row = None for j in range(3): s = m[j][i] wdelta = maxw[j] - s.width() wleft = wdelta //2 wright = wdelta - wleft s = prettyForm(*s.right(' '*wright)) s = prettyForm(*s.left(' '*wleft)) if D_row is None: D_row = s continue D_row = prettyForm(*D_row.right(' '*hsep)) D_row = prettyForm(*D_row.right(s)) if D is None: D = D_row continue for _ in range(vsep): D = prettyForm(*D.below(' ')) D = prettyForm(*D.below(D_row)) D = prettyForm(*D.parens()) return D def _latex(self, printer, *args): label = map(printer._print, (self.j1, self.j2, self.j3, self.m1, self.m2, self.m3)) return r'\left(\begin{array}{ccc} %s & %s & %s \\ %s & %s & %s \end{array}\right)' % \ tuple(label) def doit(self, **hints): if self.is_symbolic: raise ValueError("Coefficients must be numerical") return wigner_3j(self.j1, self.j2, self.j3, self.m1, self.m2, self.m3) class CG(Wigner3j): r"""Class for Clebsch-Gordan coefficient Clebsch-Gordan coefficients describe the angular momentum coupling between two systems. The coefficients give the expansion of a coupled total angular momentum state and an uncoupled tensor product state. The Clebsch-Gordan coefficients are defined as [1]_: .. math :: C^{j_1,m_1}_{j_2,m_2,j_3,m_3} = \left\langle j_1,m_1;j_2,m_2 | j_3,m_3\right\rangle Parameters ========== j1, m1, j2, m2, j3, m3 : Number, Symbol Terms determining the angular momentum of coupled angular momentum systems. Examples ======== Define a Clebsch-Gordan coefficient and evaluate its value >>> from sympy.physics.quantum.cg import CG >>> from sympy import S >>> cg = CG(S(3)/2, S(3)/2, S(1)/2, -S(1)/2, 1, 1) >>> cg CG(3/2, 3/2, 1/2, -1/2, 1, 1) >>> cg.doit() sqrt(3)/2 See Also ======== Wigner3j: Wigner-3j symbols References ========== .. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988. """ def doit(self, **hints): if self.is_symbolic: raise ValueError("Coefficients must be numerical") return clebsch_gordan(self.j1, self.j2, self.j3, self.m1, self.m2, self.m3) def _pretty(self, printer, *args): bot = printer._print_seq( (self.j1, self.m1, self.j2, self.m2), delimiter=',') top = printer._print_seq((self.j3, self.m3), delimiter=',') pad = max(top.width(), bot.width()) bot = prettyForm(*bot.left(' ')) top = prettyForm(*top.left(' ')) if not pad == bot.width(): bot = prettyForm(*bot.right(' '*(pad - bot.width()))) if not pad == top.width(): top = prettyForm(*top.right(' '*(pad - top.width()))) s = stringPict('C' + ' '*pad) s = prettyForm(*s.below(bot)) s = prettyForm(*s.above(top)) return s def _latex(self, printer, *args): label = map(printer._print, (self.j3, self.m3, self.j1, self.m1, self.j2, self.m2)) return r'C^{%s,%s}_{%s,%s,%s,%s}' % tuple(label) class Wigner6j(Expr): """Class for the Wigner-6j symbols See Also ======== Wigner3j: Wigner-3j symbols """ def __new__(cls, j1, j2, j12, j3, j, j23): args = map(sympify, (j1, j2, j12, j3, j, j23)) return Expr.__new__(cls, *args) @property def j1(self): return self.args[0] @property def j2(self): return self.args[1] @property def j12(self): return self.args[2] @property def j3(self): return self.args[3] @property def j(self): return self.args[4] @property def j23(self): return self.args[5] @property def is_symbolic(self): return not all([arg.is_number for arg in self.args]) # This is modified from the _print_Matrix method def _pretty(self, printer, *args): m = ((printer._print(self.j1), printer._print(self.j3)), (printer._print(self.j2), printer._print(self.j)), (printer._print(self.j12), printer._print(self.j23))) hsep = 2 vsep = 1 maxw = [-1]*3 for j in range(3): maxw[j] = max([ m[j][i].width() for i in range(2) ]) D = None for i in range(2): D_row = None for j in range(3): s = m[j][i] wdelta = maxw[j] - s.width() wleft = wdelta //2 wright = wdelta - wleft s = prettyForm(*s.right(' '*wright)) s = prettyForm(*s.left(' '*wleft)) if D_row is None: D_row = s continue D_row = prettyForm(*D_row.right(' '*hsep)) D_row = prettyForm(*D_row.right(s)) if D is None: D = D_row continue for _ in range(vsep): D = prettyForm(*D.below(' ')) D = prettyForm(*D.below(D_row)) D = prettyForm(*D.parens(left='{', right='}')) return D def _latex(self, printer, *args): label = map(printer._print, (self.j1, self.j2, self.j12, self.j3, self.j, self.j23)) return r'\left\{\begin{array}{ccc} %s & %s & %s \\ %s & %s & %s \end{array}\right\}' % \ tuple(label) def doit(self, **hints): if self.is_symbolic: raise ValueError("Coefficients must be numerical") return wigner_6j(self.j1, self.j2, self.j12, self.j3, self.j, self.j23) class Wigner9j(Expr): """Class for the Wigner-9j symbols See Also ======== Wigner3j: Wigner-3j symbols """ def __new__(cls, j1, j2, j12, j3, j4, j34, j13, j24, j): args = map(sympify, (j1, j2, j12, j3, j4, j34, j13, j24, j)) return Expr.__new__(cls, *args) @property def j1(self): return self.args[0] @property def j2(self): return self.args[1] @property def j12(self): return self.args[2] @property def j3(self): return self.args[3] @property def j4(self): return self.args[4] @property def j34(self): return self.args[5] @property def j13(self): return self.args[6] @property def j24(self): return self.args[7] @property def j(self): return self.args[8] @property def is_symbolic(self): return not all([arg.is_number for arg in self.args]) # This is modified from the _print_Matrix method def _pretty(self, printer, *args): m = ( (printer._print( self.j1), printer._print(self.j3), printer._print(self.j13)), (printer._print( self.j2), printer._print(self.j4), printer._print(self.j24)), (printer._print(self.j12), printer._print(self.j34), printer._print(self.j))) hsep = 2 vsep = 1 maxw = [-1]*3 for j in range(3): maxw[j] = max([ m[j][i].width() for i in range(3) ]) D = None for i in range(3): D_row = None for j in range(3): s = m[j][i] wdelta = maxw[j] - s.width() wleft = wdelta //2 wright = wdelta - wleft s = prettyForm(*s.right(' '*wright)) s = prettyForm(*s.left(' '*wleft)) if D_row is None: D_row = s continue D_row = prettyForm(*D_row.right(' '*hsep)) D_row = prettyForm(*D_row.right(s)) if D is None: D = D_row continue for _ in range(vsep): D = prettyForm(*D.below(' ')) D = prettyForm(*D.below(D_row)) D = prettyForm(*D.parens(left='{', right='}')) return D def _latex(self, printer, *args): label = map(printer._print, (self.j1, self.j2, self.j12, self.j3, self.j4, self.j34, self.j13, self.j24, self.j)) return r'\left\{\begin{array}{ccc} %s & %s & %s \\ %s & %s & %s \\ %s & %s & %s \end{array}\right\}' % \ tuple(label) def doit(self, **hints): if self.is_symbolic: raise ValueError("Coefficients must be numerical") return wigner_9j(self.j1, self.j2, self.j12, self.j3, self.j4, self.j34, self.j13, self.j24, self.j) def cg_simp(e): """Simplify and combine CG coefficients This function uses various symmetry and properties of sums and products of Clebsch-Gordan coefficients to simplify statements involving these terms [1]_. Examples ======== Simplify the sum over CG(a,alpha,0,0,a,alpha) for all alpha to 2*a+1 >>> from sympy.physics.quantum.cg import CG, cg_simp >>> a = CG(1,1,0,0,1,1) >>> b = CG(1,0,0,0,1,0) >>> c = CG(1,-1,0,0,1,-1) >>> cg_simp(a+b+c) 3 See Also ======== CG: Clebsh-Gordan coefficients References ========== .. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988. """ if isinstance(e, Add): return _cg_simp_add(e) elif isinstance(e, Sum): return _cg_simp_sum(e) elif isinstance(e, Mul): return Mul(*[cg_simp(arg) for arg in e.args]) elif isinstance(e, Pow): return Pow(cg_simp(e.base), e.exp) else: return e def _cg_simp_add(e): #TODO: Improve simplification method """Takes a sum of terms involving Clebsch-Gordan coefficients and simplifies the terms. First, we create two lists, cg_part, which is all the terms involving CG coefficients, and other_part, which is all other terms. The cg_part list is then passed to the simplification methods, which return the new cg_part and any additional terms that are added to other_part """ cg_part = [] other_part = [] e = expand(e) for arg in e.args: if arg.has(CG): if isinstance(arg, Sum): other_part.append(_cg_simp_sum(arg)) elif isinstance(arg, Mul): terms = 1 for term in arg.args: if isinstance(term, Sum): terms *= _cg_simp_sum(term) else: terms *= term if terms.has(CG): cg_part.append(terms) else: other_part.append(terms) else: cg_part.append(arg) else: other_part.append(arg) cg_part, other = _check_varsh_871_1(cg_part) other_part.append(other) cg_part, other = _check_varsh_871_2(cg_part) other_part.append(other) cg_part, other = _check_varsh_872_9(cg_part) other_part.append(other) return Add(*cg_part) + Add(*other_part) def _check_varsh_871_1(term_list): # Sum( CG(a,alpha,b,0,a,alpha), (alpha, -a, a)) == KroneckerDelta(b,0) a, alpha, b, lt = map(Wild, ('a', 'alpha', 'b', 'lt')) expr = lt*CG(a, alpha, b, 0, a, alpha) simp = (2*a + 1)*KroneckerDelta(b, 0) sign = lt/abs(lt) build_expr = 2*a + 1 index_expr = a + alpha return _check_cg_simp(expr, simp, sign, lt, term_list, (a, alpha, b, lt), (a, b), build_expr, index_expr) def _check_varsh_871_2(term_list): # Sum((-1)**(a-alpha)*CG(a,alpha,a,-alpha,c,0),(alpha,-a,a)) a, alpha, c, lt = map(Wild, ('a', 'alpha', 'c', 'lt')) expr = lt*CG(a, alpha, a, -alpha, c, 0) simp = sqrt(2*a + 1)*KroneckerDelta(c, 0) sign = (-1)**(a - alpha)*lt/abs(lt) build_expr = 2*a + 1 index_expr = a + alpha return _check_cg_simp(expr, simp, sign, lt, term_list, (a, alpha, c, lt), (a, c), build_expr, index_expr) def _check_varsh_872_9(term_list): # Sum( CG(a,alpha,b,beta,c,gamma)*CG(a,alpha',b,beta',c,gamma), (gamma, -c, c), (c, abs(a-b), a+b)) a, alpha, alphap, b, beta, betap, c, gamma, lt = map(Wild, ( 'a', 'alpha', 'alphap', 'b', 'beta', 'betap', 'c', 'gamma', 'lt')) # Case alpha==alphap, beta==betap # For numerical alpha,beta expr = lt*CG(a, alpha, b, beta, c, gamma)**2 simp = 1 sign = lt/abs(lt) x = abs(a - b) y = abs(alpha + beta) build_expr = a + b + 1 - Piecewise((x, x > y), (0, Eq(x, y)), (y, y > x)) index_expr = a + b - c term_list, other1 = _check_cg_simp(expr, simp, sign, lt, term_list, (a, alpha, b, beta, c, gamma, lt), (a, alpha, b, beta), build_expr, index_expr) # For symbolic alpha,beta x = abs(a - b) y = a + b build_expr = (y + 1 - x)*(x + y + 1) index_expr = (c - x)*(x + c) + c + gamma term_list, other2 = _check_cg_simp(expr, simp, sign, lt, term_list, (a, alpha, b, beta, c, gamma, lt), (a, alpha, b, beta), build_expr, index_expr) # Case alpha!=alphap or beta!=betap # Note: this only works with leading term of 1, pattern matching is unable to match when there is a Wild leading term # For numerical alpha,alphap,beta,betap expr = CG(a, alpha, b, beta, c, gamma)*CG(a, alphap, b, betap, c, gamma) simp = KroneckerDelta(alpha, alphap)*KroneckerDelta(beta, betap) sign = sympify(1) x = abs(a - b) y = abs(alpha + beta) build_expr = a + b + 1 - Piecewise((x, x > y), (0, Eq(x, y)), (y, y > x)) index_expr = a + b - c term_list, other3 = _check_cg_simp(expr, simp, sign, sympify(1), term_list, (a, alpha, alphap, b, beta, betap, c, gamma), (a, alpha, alphap, b, beta, betap), build_expr, index_expr) # For symbolic alpha,alphap,beta,betap x = abs(a - b) y = a + b build_expr = (y + 1 - x)*(x + y + 1) index_expr = (c - x)*(x + c) + c + gamma term_list, other4 = _check_cg_simp(expr, simp, sign, sympify(1), term_list, (a, alpha, alphap, b, beta, betap, c, gamma), (a, alpha, alphap, b, beta, betap), build_expr, index_expr) return term_list, other1 + other2 + other4 def _check_cg_simp(expr, simp, sign, lt, term_list, variables, dep_variables, build_index_expr, index_expr): """ Checks for simplifications that can be made, returning a tuple of the simplified list of terms and any terms generated by simplification. Parameters ========== expr: expression The expression with Wild terms that will be matched to the terms in the sum simp: expression The expression with Wild terms that is substituted in place of the CG terms in the case of simplification sign: expression The expression with Wild terms denoting the sign that is on expr that must match lt: expression The expression with Wild terms that gives the leading term of the matched expr term_list: list A list of all of the terms is the sum to be simplified variables: list A list of all the variables that appears in expr dep_variables: list A list of the variables that must match for all the terms in the sum, i.e. the dependent variables build_index_expr: expression Expression with Wild terms giving the number of elements in cg_index index_expr: expression Expression with Wild terms giving the index terms have when storing them to cg_index """ other_part = 0 i = 0 while i < len(term_list): sub_1 = _check_cg(term_list[i], expr, len(variables)) if sub_1 is None: i += 1 continue if not sympify(build_index_expr.subs(sub_1)).is_number: i += 1 continue sub_dep = [(x, sub_1[x]) for x in dep_variables] cg_index = [None]*build_index_expr.subs(sub_1) for j in range(i, len(term_list)): sub_2 = _check_cg(term_list[j], expr.subs(sub_dep), len(variables) - len(dep_variables), sign=(sign.subs(sub_1), sign.subs(sub_dep))) if sub_2 is None: continue if not sympify(index_expr.subs(sub_dep).subs(sub_2)).is_number: continue cg_index[index_expr.subs(sub_dep).subs(sub_2)] = j, expr.subs(lt, 1).subs(sub_dep).subs(sub_2), lt.subs(sub_2), sign.subs(sub_dep).subs(sub_2) if all(i is not None for i in cg_index): min_lt = min(*[ abs(term[2]) for term in cg_index ]) indices = [ term[0] for term in cg_index] indices.sort() indices.reverse() [ term_list.pop(j) for j in indices ] for term in cg_index: if abs(term[2]) > min_lt: term_list.append( (term[2] - min_lt*term[3])*term[1] ) other_part += min_lt*(sign*simp).subs(sub_1) else: i += 1 return term_list, other_part def _check_cg(cg_term, expr, length, sign=None): """Checks whether a term matches the given expression""" # TODO: Check for symmetries matches = cg_term.match(expr) if matches is None: return if sign is not None: if not isinstance(sign, tuple): raise TypeError('sign must be a tuple') if not sign[0] == (sign[1]).subs(matches): return if len(matches) == length: return matches def _cg_simp_sum(e): e = _check_varsh_sum_871_1(e) e = _check_varsh_sum_871_2(e) e = _check_varsh_sum_872_4(e) return e def _check_varsh_sum_871_1(e): a = Wild('a') alpha = symbols('alpha') b = Wild('b') match = e.match(Sum(CG(a, alpha, b, 0, a, alpha), (alpha, -a, a))) if match is not None and len(match) == 2: return ((2*a + 1)*KroneckerDelta(b, 0)).subs(match) return e def _check_varsh_sum_871_2(e): a = Wild('a') alpha = symbols('alpha') c = Wild('c') match = e.match( Sum((-1)**(a - alpha)*CG(a, alpha, a, -alpha, c, 0), (alpha, -a, a))) if match is not None and len(match) == 2: return (sqrt(2*a + 1)*KroneckerDelta(c, 0)).subs(match) return e def _check_varsh_sum_872_4(e): alpha = symbols('alpha') beta = symbols('beta') a = Wild('a') b = Wild('b') c = Wild('c') cp = Wild('cp') gamma = Wild('gamma') gammap = Wild('gammap') cg1 = CG(a, alpha, b, beta, c, gamma) cg2 = CG(a, alpha, b, beta, cp, gammap) match1 = e.match(Sum(cg1*cg2, (alpha, -a, a), (beta, -b, b))) if match1 is not None and len(match1) == 6: return (KroneckerDelta(c, cp)*KroneckerDelta(gamma, gammap)).subs(match1) match2 = e.match(Sum(cg1**2, (alpha, -a, a), (beta, -b, b))) if match2 is not None and len(match2) == 4: return 1 return e def _cg_list(term): if isinstance(term, CG): return (term,), 1, 1 cg = [] coeff = 1 if not (isinstance(term, Mul) or isinstance(term, Pow)): raise NotImplementedError('term must be CG, Add, Mul or Pow') if isinstance(term, Pow) and sympify(term.exp).is_number: if sympify(term.exp).is_number: [ cg.append(term.base) for _ in range(term.exp) ] else: return (term,), 1, 1 if isinstance(term, Mul): for arg in term.args: if isinstance(arg, CG): cg.append(arg) else: coeff *= arg return cg, coeff, coeff/abs(coeff)
9a13af2bc999ab4594c0f6e7f7795e0e943f594ed42bc0a7f310edcaee6f93f8
"""Primitive circuit operations on quantum circuits.""" from sympy import Symbol, Tuple, Mul, sympify, default_sort_key from sympy.utilities import numbered_symbols from sympy.core.compatibility import reduce from sympy.physics.quantum.gate import Gate __all__ = [ 'kmp_table', 'find_subcircuit', 'replace_subcircuit', 'convert_to_symbolic_indices', 'convert_to_real_indices', 'random_reduce', 'random_insert' ] def kmp_table(word): """Build the 'partial match' table of the Knuth-Morris-Pratt algorithm. Note: This is applicable to strings or quantum circuits represented as tuples. """ # Current position in subcircuit pos = 2 # Beginning position of candidate substring that # may reappear later in word cnd = 0 # The 'partial match' table that helps one determine # the next location to start substring search table = list() table.append(-1) table.append(0) while pos < len(word): if word[pos - 1] == word[cnd]: cnd = cnd + 1 table.append(cnd) pos = pos + 1 elif cnd > 0: cnd = table[cnd] else: table.append(0) pos = pos + 1 return table def find_subcircuit(circuit, subcircuit, start=0, end=0): """Finds the subcircuit in circuit, if it exists. If the subcircuit exists, the index of the start of the subcircuit in circuit is returned; otherwise, -1 is returned. The algorithm that is implemented is the Knuth-Morris-Pratt algorithm. Parameters ========== circuit : tuple, Gate or Mul A tuple of Gates or Mul representing a quantum circuit subcircuit : tuple, Gate or Mul A tuple of Gates or Mul to find in circuit start : int The location to start looking for subcircuit. If start is the same or past end, -1 is returned. end : int The last place to look for a subcircuit. If end is less than 1 (one), then the length of circuit is taken to be end. Examples ======== Find the first instance of a subcircuit: >>> from sympy.physics.quantum.circuitutils import find_subcircuit >>> from sympy.physics.quantum.gate import X, Y, Z, H >>> circuit = X(0)*Z(0)*Y(0)*H(0) >>> subcircuit = Z(0)*Y(0) >>> find_subcircuit(circuit, subcircuit) 1 Find the first instance starting at a specific position: >>> find_subcircuit(circuit, subcircuit, start=1) 1 >>> find_subcircuit(circuit, subcircuit, start=2) -1 >>> circuit = circuit*subcircuit >>> find_subcircuit(circuit, subcircuit, start=2) 4 Find the subcircuit within some interval: >>> find_subcircuit(circuit, subcircuit, start=2, end=2) -1 """ if isinstance(circuit, Mul): circuit = circuit.args if isinstance(subcircuit, Mul): subcircuit = subcircuit.args if len(subcircuit) == 0 or len(subcircuit) > len(circuit): return -1 if end < 1: end = len(circuit) # Location in circuit pos = start # Location in the subcircuit index = 0 # 'Partial match' table table = kmp_table(subcircuit) while (pos + index) < end: if subcircuit[index] == circuit[pos + index]: index = index + 1 else: pos = pos + index - table[index] index = table[index] if table[index] > -1 else 0 if index == len(subcircuit): return pos return -1 def replace_subcircuit(circuit, subcircuit, replace=None, pos=0): """Replaces a subcircuit with another subcircuit in circuit, if it exists. If multiple instances of subcircuit exists, the first instance is replaced. The position to being searching from (if different from 0) may be optionally given. If subcircuit can't be found, circuit is returned. Parameters ========== circuit : tuple, Gate or Mul A quantum circuit subcircuit : tuple, Gate or Mul The circuit to be replaced replace : tuple, Gate or Mul The replacement circuit pos : int The location to start search and replace subcircuit, if it exists. This may be used if it is known beforehand that multiple instances exist, and it is desirable to replace a specific instance. If a negative number is given, pos will be defaulted to 0. Examples ======== Find and remove the subcircuit: >>> from sympy.physics.quantum.circuitutils import replace_subcircuit >>> from sympy.physics.quantum.gate import X, Y, Z, H >>> circuit = X(0)*Z(0)*Y(0)*H(0)*X(0)*H(0)*Y(0) >>> subcircuit = Z(0)*Y(0) >>> replace_subcircuit(circuit, subcircuit) (X(0), H(0), X(0), H(0), Y(0)) Remove the subcircuit given a starting search point: >>> replace_subcircuit(circuit, subcircuit, pos=1) (X(0), H(0), X(0), H(0), Y(0)) >>> replace_subcircuit(circuit, subcircuit, pos=2) (X(0), Z(0), Y(0), H(0), X(0), H(0), Y(0)) Replace the subcircuit: >>> replacement = H(0)*Z(0) >>> replace_subcircuit(circuit, subcircuit, replace=replacement) (X(0), H(0), Z(0), H(0), X(0), H(0), Y(0)) """ if pos < 0: pos = 0 if isinstance(circuit, Mul): circuit = circuit.args if isinstance(subcircuit, Mul): subcircuit = subcircuit.args if isinstance(replace, Mul): replace = replace.args elif replace is None: replace = () # Look for the subcircuit starting at pos loc = find_subcircuit(circuit, subcircuit, start=pos) # If subcircuit was found if loc > -1: # Get the gates to the left of subcircuit left = circuit[0:loc] # Get the gates to the right of subcircuit right = circuit[loc + len(subcircuit):len(circuit)] # Recombine the left and right side gates into a circuit circuit = left + replace + right return circuit def _sympify_qubit_map(mapping): new_map = {} for key in mapping: new_map[key] = sympify(mapping[key]) return new_map def convert_to_symbolic_indices(seq, start=None, gen=None, qubit_map=None): """Returns the circuit with symbolic indices and the dictionary mapping symbolic indices to real indices. The mapping is 1 to 1 and onto (bijective). Parameters ========== seq : tuple, Gate/Integer/tuple or Mul A tuple of Gate, Integer, or tuple objects, or a Mul start : Symbol An optional starting symbolic index gen : object An optional numbered symbol generator qubit_map : dict An existing mapping of symbolic indices to real indices All symbolic indices have the format 'i#', where # is some number >= 0. """ if isinstance(seq, Mul): seq = seq.args # A numbered symbol generator index_gen = numbered_symbols(prefix='i', start=-1) cur_ndx = next(index_gen) # keys are symbolic indices; values are real indices ndx_map = {} def create_inverse_map(symb_to_real_map): rev_items = lambda item: tuple([item[1], item[0]]) return dict(map(rev_items, symb_to_real_map.items())) if start is not None: if not isinstance(start, Symbol): msg = 'Expected Symbol for starting index, got %r.' % start raise TypeError(msg) cur_ndx = start if gen is not None: if not isinstance(gen, numbered_symbols().__class__): msg = 'Expected a generator, got %r.' % gen raise TypeError(msg) index_gen = gen if qubit_map is not None: if not isinstance(qubit_map, dict): msg = ('Expected dict for existing map, got ' + '%r.' % qubit_map) raise TypeError(msg) ndx_map = qubit_map ndx_map = _sympify_qubit_map(ndx_map) # keys are real indices; keys are symbolic indices inv_map = create_inverse_map(ndx_map) sym_seq = () for item in seq: # Nested items, so recurse if isinstance(item, Gate): result = convert_to_symbolic_indices(item.args, qubit_map=ndx_map, start=cur_ndx, gen=index_gen) sym_item, new_map, cur_ndx, index_gen = result ndx_map.update(new_map) inv_map = create_inverse_map(ndx_map) elif isinstance(item, tuple) or isinstance(item, Tuple): result = convert_to_symbolic_indices(item, qubit_map=ndx_map, start=cur_ndx, gen=index_gen) sym_item, new_map, cur_ndx, index_gen = result ndx_map.update(new_map) inv_map = create_inverse_map(ndx_map) elif item in inv_map: sym_item = inv_map[item] else: cur_ndx = next(gen) ndx_map[cur_ndx] = item inv_map[item] = cur_ndx sym_item = cur_ndx if isinstance(item, Gate): sym_item = item.__class__(*sym_item) sym_seq = sym_seq + (sym_item,) return sym_seq, ndx_map, cur_ndx, index_gen def convert_to_real_indices(seq, qubit_map): """Returns the circuit with real indices. Parameters ========== seq : tuple, Gate/Integer/tuple or Mul A tuple of Gate, Integer, or tuple objects or a Mul qubit_map : dict A dictionary mapping symbolic indices to real indices. Examples ======== Change the symbolic indices to real integers: >>> from sympy import symbols >>> from sympy.physics.quantum.circuitutils import convert_to_real_indices >>> from sympy.physics.quantum.gate import X, Y, H >>> i0, i1 = symbols('i:2') >>> index_map = {i0 : 0, i1 : 1} >>> convert_to_real_indices(X(i0)*Y(i1)*H(i0)*X(i1), index_map) (X(0), Y(1), H(0), X(1)) """ if isinstance(seq, Mul): seq = seq.args if not isinstance(qubit_map, dict): msg = 'Expected dict for qubit_map, got %r.' % qubit_map raise TypeError(msg) qubit_map = _sympify_qubit_map(qubit_map) real_seq = () for item in seq: # Nested items, so recurse if isinstance(item, Gate): real_item = convert_to_real_indices(item.args, qubit_map) elif isinstance(item, tuple) or isinstance(item, Tuple): real_item = convert_to_real_indices(item, qubit_map) else: real_item = qubit_map[item] if isinstance(item, Gate): real_item = item.__class__(*real_item) real_seq = real_seq + (real_item,) return real_seq def random_reduce(circuit, gate_ids, seed=None): """Shorten the length of a quantum circuit. random_reduce looks for circuit identities in circuit, randomly chooses one to remove, and returns a shorter yet equivalent circuit. If no identities are found, the same circuit is returned. Parameters ========== circuit : Gate tuple of Mul A tuple of Gates representing a quantum circuit gate_ids : list, GateIdentity List of gate identities to find in circuit seed : int or list seed used for _randrange; to override the random selection, provide a list of integers: the elements of gate_ids will be tested in the order given by the list """ from sympy.testing.randtest import _randrange if not gate_ids: return circuit if isinstance(circuit, Mul): circuit = circuit.args ids = flatten_ids(gate_ids) # Create the random integer generator with the seed randrange = _randrange(seed) # Look for an identity in the circuit while ids: i = randrange(len(ids)) id = ids.pop(i) if find_subcircuit(circuit, id) != -1: break else: # no identity was found return circuit # return circuit with the identity removed return replace_subcircuit(circuit, id) def random_insert(circuit, choices, seed=None): """Insert a circuit into another quantum circuit. random_insert randomly chooses a location in the circuit to insert a randomly selected circuit from amongst the given choices. Parameters ========== circuit : Gate tuple or Mul A tuple or Mul of Gates representing a quantum circuit choices : list Set of circuit choices seed : int or list seed used for _randrange; to override the random selections, give a list two integers, [i, j] where i is the circuit location where choice[j] will be inserted. Notes ===== Indices for insertion should be [0, n] if n is the length of the circuit. """ from sympy.testing.randtest import _randrange if not choices: return circuit if isinstance(circuit, Mul): circuit = circuit.args # get the location in the circuit and the element to insert from choices randrange = _randrange(seed) loc = randrange(len(circuit) + 1) choice = choices[randrange(len(choices))] circuit = list(circuit) circuit[loc: loc] = choice return tuple(circuit) # Flatten the GateIdentity objects (with gate rules) into one single list def flatten_ids(ids): collapse = lambda acc, an_id: acc + sorted(an_id.equivalent_ids, key=default_sort_key) ids = reduce(collapse, ids, []) ids.sort(key=default_sort_key) return ids
4b9353dfb211c9bf904b95f22145f9761d786207f26852ba903a18b507cd4d73
"""Hilbert spaces for quantum mechanics. Authors: * Brian Granger * Matt Curry """ from sympy import Basic, Interval, oo, sympify from sympy.printing.pretty.stringpict import prettyForm from sympy.physics.quantum.qexpr import QuantumError from sympy.core.compatibility import reduce __all__ = [ 'HilbertSpaceError', 'HilbertSpace', 'TensorProductHilbertSpace', 'TensorPowerHilbertSpace', 'DirectSumHilbertSpace', 'ComplexSpace', 'L2', 'FockSpace' ] #----------------------------------------------------------------------------- # Main objects #----------------------------------------------------------------------------- class HilbertSpaceError(QuantumError): pass #----------------------------------------------------------------------------- # Main objects #----------------------------------------------------------------------------- class HilbertSpace(Basic): """An abstract Hilbert space for quantum mechanics. In short, a Hilbert space is an abstract vector space that is complete with inner products defined [1]_. Examples ======== >>> from sympy.physics.quantum.hilbert import HilbertSpace >>> hs = HilbertSpace() >>> hs H References ========== .. [1] https://en.wikipedia.org/wiki/Hilbert_space """ def __new__(cls): obj = Basic.__new__(cls) return obj @property def dimension(self): """Return the Hilbert dimension of the space.""" raise NotImplementedError('This Hilbert space has no dimension.') def __add__(self, other): return DirectSumHilbertSpace(self, other) def __radd__(self, other): return DirectSumHilbertSpace(other, self) def __mul__(self, other): return TensorProductHilbertSpace(self, other) def __rmul__(self, other): return TensorProductHilbertSpace(other, self) def __pow__(self, other, mod=None): if mod is not None: raise ValueError('The third argument to __pow__ is not supported \ for Hilbert spaces.') return TensorPowerHilbertSpace(self, other) def __contains__(self, other): """Is the operator or state in this Hilbert space. This is checked by comparing the classes of the Hilbert spaces, not the instances. This is to allow Hilbert Spaces with symbolic dimensions. """ if other.hilbert_space.__class__ == self.__class__: return True else: return False def _sympystr(self, printer, *args): return 'H' def _pretty(self, printer, *args): ustr = '\N{LATIN CAPITAL LETTER H}' return prettyForm(ustr) def _latex(self, printer, *args): return r'\mathcal{H}' class ComplexSpace(HilbertSpace): """Finite dimensional Hilbert space of complex vectors. The elements of this Hilbert space are n-dimensional complex valued vectors with the usual inner product that takes the complex conjugate of the vector on the right. A classic example of this type of Hilbert space is spin-1/2, which is ``ComplexSpace(2)``. Generalizing to spin-s, the space is ``ComplexSpace(2*s+1)``. Quantum computing with N qubits is done with the direct product space ``ComplexSpace(2)**N``. Examples ======== >>> from sympy import symbols >>> from sympy.physics.quantum.hilbert import ComplexSpace >>> c1 = ComplexSpace(2) >>> c1 C(2) >>> c1.dimension 2 >>> n = symbols('n') >>> c2 = ComplexSpace(n) >>> c2 C(n) >>> c2.dimension n """ def __new__(cls, dimension): dimension = sympify(dimension) r = cls.eval(dimension) if isinstance(r, Basic): return r obj = Basic.__new__(cls, dimension) return obj @classmethod def eval(cls, dimension): if len(dimension.atoms()) == 1: if not (dimension.is_Integer and dimension > 0 or dimension is oo or dimension.is_Symbol): raise TypeError('The dimension of a ComplexSpace can only' 'be a positive integer, oo, or a Symbol: %r' % dimension) else: for dim in dimension.atoms(): if not (dim.is_Integer or dim is oo or dim.is_Symbol): raise TypeError('The dimension of a ComplexSpace can only' ' contain integers, oo, or a Symbol: %r' % dim) @property def dimension(self): return self.args[0] def _sympyrepr(self, printer, *args): return "%s(%s)" % (self.__class__.__name__, printer._print(self.dimension, *args)) def _sympystr(self, printer, *args): return "C(%s)" % printer._print(self.dimension, *args) def _pretty(self, printer, *args): ustr = '\N{LATIN CAPITAL LETTER C}' pform_exp = printer._print(self.dimension, *args) pform_base = prettyForm(ustr) return pform_base**pform_exp def _latex(self, printer, *args): return r'\mathcal{C}^{%s}' % printer._print(self.dimension, *args) class L2(HilbertSpace): """The Hilbert space of square integrable functions on an interval. An L2 object takes in a single sympy Interval argument which represents the interval its functions (vectors) are defined on. Examples ======== >>> from sympy import Interval, oo >>> from sympy.physics.quantum.hilbert import L2 >>> hs = L2(Interval(0,oo)) >>> hs L2(Interval(0, oo)) >>> hs.dimension oo >>> hs.interval Interval(0, oo) """ def __new__(cls, interval): if not isinstance(interval, Interval): raise TypeError('L2 interval must be an Interval instance: %r' % interval) obj = Basic.__new__(cls, interval) return obj @property def dimension(self): return oo @property def interval(self): return self.args[0] def _sympyrepr(self, printer, *args): return "L2(%s)" % printer._print(self.interval, *args) def _sympystr(self, printer, *args): return "L2(%s)" % printer._print(self.interval, *args) def _pretty(self, printer, *args): pform_exp = prettyForm('2') pform_base = prettyForm('L') return pform_base**pform_exp def _latex(self, printer, *args): interval = printer._print(self.interval, *args) return r'{\mathcal{L}^2}\left( %s \right)' % interval class FockSpace(HilbertSpace): """The Hilbert space for second quantization. Technically, this Hilbert space is a infinite direct sum of direct products of single particle Hilbert spaces [1]_. This is a mess, so we have a class to represent it directly. Examples ======== >>> from sympy.physics.quantum.hilbert import FockSpace >>> hs = FockSpace() >>> hs F >>> hs.dimension oo References ========== .. [1] https://en.wikipedia.org/wiki/Fock_space """ def __new__(cls): obj = Basic.__new__(cls) return obj @property def dimension(self): return oo def _sympyrepr(self, printer, *args): return "FockSpace()" def _sympystr(self, printer, *args): return "F" def _pretty(self, printer, *args): ustr = '\N{LATIN CAPITAL LETTER F}' return prettyForm(ustr) def _latex(self, printer, *args): return r'\mathcal{F}' class TensorProductHilbertSpace(HilbertSpace): """A tensor product of Hilbert spaces [1]_. The tensor product between Hilbert spaces is represented by the operator ``*`` Products of the same Hilbert space will be combined into tensor powers. A ``TensorProductHilbertSpace`` object takes in an arbitrary number of ``HilbertSpace`` objects as its arguments. In addition, multiplication of ``HilbertSpace`` objects will automatically return this tensor product object. Examples ======== >>> from sympy.physics.quantum.hilbert import ComplexSpace, FockSpace >>> from sympy import symbols >>> c = ComplexSpace(2) >>> f = FockSpace() >>> hs = c*f >>> hs C(2)*F >>> hs.dimension oo >>> hs.spaces (C(2), F) >>> c1 = ComplexSpace(2) >>> n = symbols('n') >>> c2 = ComplexSpace(n) >>> hs = c1*c2 >>> hs C(2)*C(n) >>> hs.dimension 2*n References ========== .. [1] https://en.wikipedia.org/wiki/Hilbert_space#Tensor_products """ def __new__(cls, *args): r = cls.eval(args) if isinstance(r, Basic): return r obj = Basic.__new__(cls, *args) return obj @classmethod def eval(cls, args): """Evaluates the direct product.""" new_args = [] recall = False #flatten arguments for arg in args: if isinstance(arg, TensorProductHilbertSpace): new_args.extend(arg.args) recall = True elif isinstance(arg, (HilbertSpace, TensorPowerHilbertSpace)): new_args.append(arg) else: raise TypeError('Hilbert spaces can only be multiplied by \ other Hilbert spaces: %r' % arg) #combine like arguments into direct powers comb_args = [] prev_arg = None for new_arg in new_args: if prev_arg is not None: if isinstance(new_arg, TensorPowerHilbertSpace) and \ isinstance(prev_arg, TensorPowerHilbertSpace) and \ new_arg.base == prev_arg.base: prev_arg = new_arg.base**(new_arg.exp + prev_arg.exp) elif isinstance(new_arg, TensorPowerHilbertSpace) and \ new_arg.base == prev_arg: prev_arg = prev_arg**(new_arg.exp + 1) elif isinstance(prev_arg, TensorPowerHilbertSpace) and \ new_arg == prev_arg.base: prev_arg = new_arg**(prev_arg.exp + 1) elif new_arg == prev_arg: prev_arg = new_arg**2 else: comb_args.append(prev_arg) prev_arg = new_arg elif prev_arg is None: prev_arg = new_arg comb_args.append(prev_arg) if recall: return TensorProductHilbertSpace(*comb_args) elif len(comb_args) == 1: return TensorPowerHilbertSpace(comb_args[0].base, comb_args[0].exp) else: return None @property def dimension(self): arg_list = [arg.dimension for arg in self.args] if oo in arg_list: return oo else: return reduce(lambda x, y: x*y, arg_list) @property def spaces(self): """A tuple of the Hilbert spaces in this tensor product.""" return self.args def _spaces_printer(self, printer, *args): spaces_strs = [] for arg in self.args: s = printer._print(arg, *args) if isinstance(arg, DirectSumHilbertSpace): s = '(%s)' % s spaces_strs.append(s) return spaces_strs def _sympyrepr(self, printer, *args): spaces_reprs = self._spaces_printer(printer, *args) return "TensorProductHilbertSpace(%s)" % ','.join(spaces_reprs) def _sympystr(self, printer, *args): spaces_strs = self._spaces_printer(printer, *args) return '*'.join(spaces_strs) def _pretty(self, printer, *args): length = len(self.args) pform = printer._print('', *args) for i in range(length): next_pform = printer._print(self.args[i], *args) if isinstance(self.args[i], (DirectSumHilbertSpace, TensorProductHilbertSpace)): next_pform = prettyForm( *next_pform.parens(left='(', right=')') ) pform = prettyForm(*pform.right(next_pform)) if i != length - 1: if printer._use_unicode: pform = prettyForm(*pform.right(' ' + '\N{N-ARY CIRCLED TIMES OPERATOR}' + ' ')) else: pform = prettyForm(*pform.right(' x ')) return pform def _latex(self, printer, *args): length = len(self.args) s = '' for i in range(length): arg_s = printer._print(self.args[i], *args) if isinstance(self.args[i], (DirectSumHilbertSpace, TensorProductHilbertSpace)): arg_s = r'\left(%s\right)' % arg_s s = s + arg_s if i != length - 1: s = s + r'\otimes ' return s class DirectSumHilbertSpace(HilbertSpace): """A direct sum of Hilbert spaces [1]_. This class uses the ``+`` operator to represent direct sums between different Hilbert spaces. A ``DirectSumHilbertSpace`` object takes in an arbitrary number of ``HilbertSpace`` objects as its arguments. Also, addition of ``HilbertSpace`` objects will automatically return a direct sum object. Examples ======== >>> from sympy.physics.quantum.hilbert import ComplexSpace, FockSpace >>> c = ComplexSpace(2) >>> f = FockSpace() >>> hs = c+f >>> hs C(2)+F >>> hs.dimension oo >>> list(hs.spaces) [C(2), F] References ========== .. [1] https://en.wikipedia.org/wiki/Hilbert_space#Direct_sums """ def __new__(cls, *args): r = cls.eval(args) if isinstance(r, Basic): return r obj = Basic.__new__(cls, *args) return obj @classmethod def eval(cls, args): """Evaluates the direct product.""" new_args = [] recall = False #flatten arguments for arg in args: if isinstance(arg, DirectSumHilbertSpace): new_args.extend(arg.args) recall = True elif isinstance(arg, HilbertSpace): new_args.append(arg) else: raise TypeError('Hilbert spaces can only be summed with other \ Hilbert spaces: %r' % arg) if recall: return DirectSumHilbertSpace(*new_args) else: return None @property def dimension(self): arg_list = [arg.dimension for arg in self.args] if oo in arg_list: return oo else: return reduce(lambda x, y: x + y, arg_list) @property def spaces(self): """A tuple of the Hilbert spaces in this direct sum.""" return self.args def _sympyrepr(self, printer, *args): spaces_reprs = [printer._print(arg, *args) for arg in self.args] return "DirectSumHilbertSpace(%s)" % ','.join(spaces_reprs) def _sympystr(self, printer, *args): spaces_strs = [printer._print(arg, *args) for arg in self.args] return '+'.join(spaces_strs) def _pretty(self, printer, *args): length = len(self.args) pform = printer._print('', *args) for i in range(length): next_pform = printer._print(self.args[i], *args) if isinstance(self.args[i], (DirectSumHilbertSpace, TensorProductHilbertSpace)): next_pform = prettyForm( *next_pform.parens(left='(', right=')') ) pform = prettyForm(*pform.right(next_pform)) if i != length - 1: if printer._use_unicode: pform = prettyForm(*pform.right(' \N{CIRCLED PLUS} ')) else: pform = prettyForm(*pform.right(' + ')) return pform def _latex(self, printer, *args): length = len(self.args) s = '' for i in range(length): arg_s = printer._print(self.args[i], *args) if isinstance(self.args[i], (DirectSumHilbertSpace, TensorProductHilbertSpace)): arg_s = r'\left(%s\right)' % arg_s s = s + arg_s if i != length - 1: s = s + r'\oplus ' return s class TensorPowerHilbertSpace(HilbertSpace): """An exponentiated Hilbert space [1]_. Tensor powers (repeated tensor products) are represented by the operator ``**`` Identical Hilbert spaces that are multiplied together will be automatically combined into a single tensor power object. Any Hilbert space, product, or sum may be raised to a tensor power. The ``TensorPowerHilbertSpace`` takes two arguments: the Hilbert space; and the tensor power (number). Examples ======== >>> from sympy.physics.quantum.hilbert import ComplexSpace, FockSpace >>> from sympy import symbols >>> n = symbols('n') >>> c = ComplexSpace(2) >>> hs = c**n >>> hs C(2)**n >>> hs.dimension 2**n >>> c = ComplexSpace(2) >>> c*c C(2)**2 >>> f = FockSpace() >>> c*f*f C(2)*F**2 References ========== .. [1] https://en.wikipedia.org/wiki/Hilbert_space#Tensor_products """ def __new__(cls, *args): r = cls.eval(args) if isinstance(r, Basic): return r return Basic.__new__(cls, *r) @classmethod def eval(cls, args): new_args = args[0], sympify(args[1]) exp = new_args[1] #simplify hs**1 -> hs if exp == 1: return args[0] #simplify hs**0 -> 1 if exp == 0: return sympify(1) #check (and allow) for hs**(x+42+y...) case if len(exp.atoms()) == 1: if not (exp.is_Integer and exp >= 0 or exp.is_Symbol): raise ValueError('Hilbert spaces can only be raised to \ positive integers or Symbols: %r' % exp) else: for power in exp.atoms(): if not (power.is_Integer or power.is_Symbol): raise ValueError('Tensor powers can only contain integers \ or Symbols: %r' % power) return new_args @property def base(self): return self.args[0] @property def exp(self): return self.args[1] @property def dimension(self): if self.base.dimension is oo: return oo else: return self.base.dimension**self.exp def _sympyrepr(self, printer, *args): return "TensorPowerHilbertSpace(%s,%s)" % (printer._print(self.base, *args), printer._print(self.exp, *args)) def _sympystr(self, printer, *args): return "%s**%s" % (printer._print(self.base, *args), printer._print(self.exp, *args)) def _pretty(self, printer, *args): pform_exp = printer._print(self.exp, *args) if printer._use_unicode: pform_exp = prettyForm(*pform_exp.left(prettyForm('\N{N-ARY CIRCLED TIMES OPERATOR}'))) else: pform_exp = prettyForm(*pform_exp.left(prettyForm('x'))) pform_base = printer._print(self.base, *args) return pform_base**pform_exp def _latex(self, printer, *args): base = printer._print(self.base, *args) exp = printer._print(self.exp, *args) return r'{%s}^{\otimes %s}' % (base, exp)
5d57d9465fc00c87d6e1c38dd5c7c9a37431cae918628cf1602880e0c1707037
"""Simple Harmonic Oscillator 1-Dimension""" from sympy import sqrt, I, Symbol, Integer, S from sympy.physics.quantum.constants import hbar from sympy.physics.quantum.operator import Operator from sympy.physics.quantum.state import Bra, Ket, State from sympy.physics.quantum.qexpr import QExpr from sympy.physics.quantum.cartesian import X, Px from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.physics.quantum.hilbert import ComplexSpace from sympy.physics.quantum.matrixutils import matrix_zeros #------------------------------------------------------------------------------ class SHOOp(Operator): """A base class for the SHO Operators. We are limiting the number of arguments to be 1. """ @classmethod def _eval_args(cls, args): args = QExpr._eval_args(args) if len(args) == 1: return args else: raise ValueError("Too many arguments") @classmethod def _eval_hilbert_space(cls, label): return ComplexSpace(S.Infinity) class RaisingOp(SHOOp): """The Raising Operator or a^dagger. When a^dagger acts on a state it raises the state up by one. Taking the adjoint of a^dagger returns 'a', the Lowering Operator. a^dagger can be rewritten in terms of position and momentum. We can represent a^dagger as a matrix, which will be its default basis. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the operator. Examples ======== Create a Raising Operator and rewrite it in terms of position and momentum, and show that taking its adjoint returns 'a': >>> from sympy.physics.quantum.sho1d import RaisingOp >>> from sympy.physics.quantum import Dagger >>> ad = RaisingOp('a') >>> ad.rewrite('xp').doit() sqrt(2)*(m*omega*X - I*Px)/(2*sqrt(hbar)*sqrt(m*omega)) >>> Dagger(ad) a Taking the commutator of a^dagger with other Operators: >>> from sympy.physics.quantum import Commutator >>> from sympy.physics.quantum.sho1d import RaisingOp, LoweringOp >>> from sympy.physics.quantum.sho1d import NumberOp >>> ad = RaisingOp('a') >>> a = LoweringOp('a') >>> N = NumberOp('N') >>> Commutator(ad, a).doit() -1 >>> Commutator(ad, N).doit() -RaisingOp(a) Apply a^dagger to a state: >>> from sympy.physics.quantum import qapply >>> from sympy.physics.quantum.sho1d import RaisingOp, SHOKet >>> ad = RaisingOp('a') >>> k = SHOKet('k') >>> qapply(ad*k) sqrt(k + 1)*|k + 1> Matrix Representation >>> from sympy.physics.quantum.sho1d import RaisingOp >>> from sympy.physics.quantum.represent import represent >>> ad = RaisingOp('a') >>> represent(ad, basis=N, ndim=4, format='sympy') Matrix([ [0, 0, 0, 0], [1, 0, 0, 0], [0, sqrt(2), 0, 0], [0, 0, sqrt(3), 0]]) """ def _eval_rewrite_as_xp(self, *args, **kwargs): return (Integer(1)/sqrt(Integer(2)*hbar*m*omega))*( Integer(-1)*I*Px + m*omega*X) def _eval_adjoint(self): return LoweringOp(*self.args) def _eval_commutator_LoweringOp(self, other): return Integer(-1) def _eval_commutator_NumberOp(self, other): return Integer(-1)*self def _apply_operator_SHOKet(self, ket): temp = ket.n + Integer(1) return sqrt(temp)*SHOKet(temp) def _represent_default_basis(self, **options): return self._represent_NumberOp(None, **options) def _represent_XOp(self, basis, **options): # This logic is good but the underlying position # representation logic is broken. # temp = self.rewrite('xp').doit() # result = represent(temp, basis=X) # return result raise NotImplementedError('Position representation is not implemented') def _represent_NumberOp(self, basis, **options): ndim_info = options.get('ndim', 4) format = options.get('format','sympy') matrix = matrix_zeros(ndim_info, ndim_info, **options) for i in range(ndim_info - 1): value = sqrt(i + 1) if format == 'scipy.sparse': value = float(value) matrix[i + 1, i] = value if format == 'scipy.sparse': matrix = matrix.tocsr() return matrix #-------------------------------------------------------------------------- # Printing Methods #-------------------------------------------------------------------------- def _print_contents(self, printer, *args): arg0 = printer._print(self.args[0], *args) return '%s(%s)' % (self.__class__.__name__, arg0) def _print_contents_pretty(self, printer, *args): from sympy.printing.pretty.stringpict import prettyForm pform = printer._print(self.args[0], *args) pform = pform**prettyForm('\N{DAGGER}') return pform def _print_contents_latex(self, printer, *args): arg = printer._print(self.args[0]) return '%s^{\\dagger}' % arg class LoweringOp(SHOOp): """The Lowering Operator or 'a'. When 'a' acts on a state it lowers the state up by one. Taking the adjoint of 'a' returns a^dagger, the Raising Operator. 'a' can be rewritten in terms of position and momentum. We can represent 'a' as a matrix, which will be its default basis. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the operator. Examples ======== Create a Lowering Operator and rewrite it in terms of position and momentum, and show that taking its adjoint returns a^dagger: >>> from sympy.physics.quantum.sho1d import LoweringOp >>> from sympy.physics.quantum import Dagger >>> a = LoweringOp('a') >>> a.rewrite('xp').doit() sqrt(2)*(m*omega*X + I*Px)/(2*sqrt(hbar)*sqrt(m*omega)) >>> Dagger(a) RaisingOp(a) Taking the commutator of 'a' with other Operators: >>> from sympy.physics.quantum import Commutator >>> from sympy.physics.quantum.sho1d import LoweringOp, RaisingOp >>> from sympy.physics.quantum.sho1d import NumberOp >>> a = LoweringOp('a') >>> ad = RaisingOp('a') >>> N = NumberOp('N') >>> Commutator(a, ad).doit() 1 >>> Commutator(a, N).doit() a Apply 'a' to a state: >>> from sympy.physics.quantum import qapply >>> from sympy.physics.quantum.sho1d import LoweringOp, SHOKet >>> a = LoweringOp('a') >>> k = SHOKet('k') >>> qapply(a*k) sqrt(k)*|k - 1> Taking 'a' of the lowest state will return 0: >>> from sympy.physics.quantum import qapply >>> from sympy.physics.quantum.sho1d import LoweringOp, SHOKet >>> a = LoweringOp('a') >>> k = SHOKet(0) >>> qapply(a*k) 0 Matrix Representation >>> from sympy.physics.quantum.sho1d import LoweringOp >>> from sympy.physics.quantum.represent import represent >>> a = LoweringOp('a') >>> represent(a, basis=N, ndim=4, format='sympy') Matrix([ [0, 1, 0, 0], [0, 0, sqrt(2), 0], [0, 0, 0, sqrt(3)], [0, 0, 0, 0]]) """ def _eval_rewrite_as_xp(self, *args, **kwargs): return (Integer(1)/sqrt(Integer(2)*hbar*m*omega))*( I*Px + m*omega*X) def _eval_adjoint(self): return RaisingOp(*self.args) def _eval_commutator_RaisingOp(self, other): return Integer(1) def _eval_commutator_NumberOp(self, other): return Integer(1)*self def _apply_operator_SHOKet(self, ket): temp = ket.n - Integer(1) if ket.n == Integer(0): return Integer(0) else: return sqrt(ket.n)*SHOKet(temp) def _represent_default_basis(self, **options): return self._represent_NumberOp(None, **options) def _represent_XOp(self, basis, **options): # This logic is good but the underlying position # representation logic is broken. # temp = self.rewrite('xp').doit() # result = represent(temp, basis=X) # return result raise NotImplementedError('Position representation is not implemented') def _represent_NumberOp(self, basis, **options): ndim_info = options.get('ndim', 4) format = options.get('format', 'sympy') matrix = matrix_zeros(ndim_info, ndim_info, **options) for i in range(ndim_info - 1): value = sqrt(i + 1) if format == 'scipy.sparse': value = float(value) matrix[i,i + 1] = value if format == 'scipy.sparse': matrix = matrix.tocsr() return matrix class NumberOp(SHOOp): """The Number Operator is simply a^dagger*a It is often useful to write a^dagger*a as simply the Number Operator because the Number Operator commutes with the Hamiltonian. And can be expressed using the Number Operator. Also the Number Operator can be applied to states. We can represent the Number Operator as a matrix, which will be its default basis. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the operator. Examples ======== Create a Number Operator and rewrite it in terms of the ladder operators, position and momentum operators, and Hamiltonian: >>> from sympy.physics.quantum.sho1d import NumberOp >>> N = NumberOp('N') >>> N.rewrite('a').doit() RaisingOp(a)*a >>> N.rewrite('xp').doit() -1/2 + (m**2*omega**2*X**2 + Px**2)/(2*hbar*m*omega) >>> N.rewrite('H').doit() -1/2 + H/(hbar*omega) Take the Commutator of the Number Operator with other Operators: >>> from sympy.physics.quantum import Commutator >>> from sympy.physics.quantum.sho1d import NumberOp, Hamiltonian >>> from sympy.physics.quantum.sho1d import RaisingOp, LoweringOp >>> N = NumberOp('N') >>> H = Hamiltonian('H') >>> ad = RaisingOp('a') >>> a = LoweringOp('a') >>> Commutator(N,H).doit() 0 >>> Commutator(N,ad).doit() RaisingOp(a) >>> Commutator(N,a).doit() -a Apply the Number Operator to a state: >>> from sympy.physics.quantum import qapply >>> from sympy.physics.quantum.sho1d import NumberOp, SHOKet >>> N = NumberOp('N') >>> k = SHOKet('k') >>> qapply(N*k) k*|k> Matrix Representation >>> from sympy.physics.quantum.sho1d import NumberOp >>> from sympy.physics.quantum.represent import represent >>> N = NumberOp('N') >>> represent(N, basis=N, ndim=4, format='sympy') Matrix([ [0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3]]) """ def _eval_rewrite_as_a(self, *args, **kwargs): return ad*a def _eval_rewrite_as_xp(self, *args, **kwargs): return (Integer(1)/(Integer(2)*m*hbar*omega))*(Px**2 + ( m*omega*X)**2) - Integer(1)/Integer(2) def _eval_rewrite_as_H(self, *args, **kwargs): return H/(hbar*omega) - Integer(1)/Integer(2) def _apply_operator_SHOKet(self, ket): return ket.n*ket def _eval_commutator_Hamiltonian(self, other): return Integer(0) def _eval_commutator_RaisingOp(self, other): return other def _eval_commutator_LoweringOp(self, other): return Integer(-1)*other def _represent_default_basis(self, **options): return self._represent_NumberOp(None, **options) def _represent_XOp(self, basis, **options): # This logic is good but the underlying position # representation logic is broken. # temp = self.rewrite('xp').doit() # result = represent(temp, basis=X) # return result raise NotImplementedError('Position representation is not implemented') def _represent_NumberOp(self, basis, **options): ndim_info = options.get('ndim', 4) format = options.get('format', 'sympy') matrix = matrix_zeros(ndim_info, ndim_info, **options) for i in range(ndim_info): value = i if format == 'scipy.sparse': value = float(value) matrix[i,i] = value if format == 'scipy.sparse': matrix = matrix.tocsr() return matrix class Hamiltonian(SHOOp): """The Hamiltonian Operator. The Hamiltonian is used to solve the time-independent Schrodinger equation. The Hamiltonian can be expressed using the ladder operators, as well as by position and momentum. We can represent the Hamiltonian Operator as a matrix, which will be its default basis. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the operator. Examples ======== Create a Hamiltonian Operator and rewrite it in terms of the ladder operators, position and momentum, and the Number Operator: >>> from sympy.physics.quantum.sho1d import Hamiltonian >>> H = Hamiltonian('H') >>> H.rewrite('a').doit() hbar*omega*(1/2 + RaisingOp(a)*a) >>> H.rewrite('xp').doit() (m**2*omega**2*X**2 + Px**2)/(2*m) >>> H.rewrite('N').doit() hbar*omega*(1/2 + N) Take the Commutator of the Hamiltonian and the Number Operator: >>> from sympy.physics.quantum import Commutator >>> from sympy.physics.quantum.sho1d import Hamiltonian, NumberOp >>> H = Hamiltonian('H') >>> N = NumberOp('N') >>> Commutator(H,N).doit() 0 Apply the Hamiltonian Operator to a state: >>> from sympy.physics.quantum import qapply >>> from sympy.physics.quantum.sho1d import Hamiltonian, SHOKet >>> H = Hamiltonian('H') >>> k = SHOKet('k') >>> qapply(H*k) hbar*k*omega*|k> + hbar*omega*|k>/2 Matrix Representation >>> from sympy.physics.quantum.sho1d import Hamiltonian >>> from sympy.physics.quantum.represent import represent >>> H = Hamiltonian('H') >>> represent(H, basis=N, ndim=4, format='sympy') Matrix([ [hbar*omega/2, 0, 0, 0], [ 0, 3*hbar*omega/2, 0, 0], [ 0, 0, 5*hbar*omega/2, 0], [ 0, 0, 0, 7*hbar*omega/2]]) """ def _eval_rewrite_as_a(self, *args, **kwargs): return hbar*omega*(ad*a + Integer(1)/Integer(2)) def _eval_rewrite_as_xp(self, *args, **kwargs): return (Integer(1)/(Integer(2)*m))*(Px**2 + (m*omega*X)**2) def _eval_rewrite_as_N(self, *args, **kwargs): return hbar*omega*(N + Integer(1)/Integer(2)) def _apply_operator_SHOKet(self, ket): return (hbar*omega*(ket.n + Integer(1)/Integer(2)))*ket def _eval_commutator_NumberOp(self, other): return Integer(0) def _represent_default_basis(self, **options): return self._represent_NumberOp(None, **options) def _represent_XOp(self, basis, **options): # This logic is good but the underlying position # representation logic is broken. # temp = self.rewrite('xp').doit() # result = represent(temp, basis=X) # return result raise NotImplementedError('Position representation is not implemented') def _represent_NumberOp(self, basis, **options): ndim_info = options.get('ndim', 4) format = options.get('format', 'sympy') matrix = matrix_zeros(ndim_info, ndim_info, **options) for i in range(ndim_info): value = i + Integer(1)/Integer(2) if format == 'scipy.sparse': value = float(value) matrix[i,i] = value if format == 'scipy.sparse': matrix = matrix.tocsr() return hbar*omega*matrix #------------------------------------------------------------------------------ class SHOState(State): """State class for SHO states""" @classmethod def _eval_hilbert_space(cls, label): return ComplexSpace(S.Infinity) @property def n(self): return self.args[0] class SHOKet(SHOState, Ket): """1D eigenket. Inherits from SHOState and Ket. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the ket This is usually its quantum numbers or its symbol. Examples ======== Ket's know about their associated bra: >>> from sympy.physics.quantum.sho1d import SHOKet >>> k = SHOKet('k') >>> k.dual <k| >>> k.dual_class() <class 'sympy.physics.quantum.sho1d.SHOBra'> Take the Inner Product with a bra: >>> from sympy.physics.quantum import InnerProduct >>> from sympy.physics.quantum.sho1d import SHOKet, SHOBra >>> k = SHOKet('k') >>> b = SHOBra('b') >>> InnerProduct(b,k).doit() KroneckerDelta(b, k) Vector representation of a numerical state ket: >>> from sympy.physics.quantum.sho1d import SHOKet, NumberOp >>> from sympy.physics.quantum.represent import represent >>> k = SHOKet(3) >>> N = NumberOp('N') >>> represent(k, basis=N, ndim=4) Matrix([ [0], [0], [0], [1]]) """ @classmethod def dual_class(self): return SHOBra def _eval_innerproduct_SHOBra(self, bra, **hints): result = KroneckerDelta(self.n, bra.n) return result def _represent_default_basis(self, **options): return self._represent_NumberOp(None, **options) def _represent_NumberOp(self, basis, **options): ndim_info = options.get('ndim', 4) format = options.get('format', 'sympy') options['spmatrix'] = 'lil' vector = matrix_zeros(ndim_info, 1, **options) if isinstance(self.n, Integer): if self.n >= ndim_info: return ValueError("N-Dimension too small") if format == 'scipy.sparse': vector[int(self.n), 0] = 1.0 vector = vector.tocsr() elif format == 'numpy': vector[int(self.n), 0] = 1.0 else: vector[self.n, 0] = Integer(1) return vector else: return ValueError("Not Numerical State") class SHOBra(SHOState, Bra): """A time-independent Bra in SHO. Inherits from SHOState and Bra. Parameters ========== args : tuple The list of numbers or parameters that uniquely specify the ket This is usually its quantum numbers or its symbol. Examples ======== Bra's know about their associated ket: >>> from sympy.physics.quantum.sho1d import SHOBra >>> b = SHOBra('b') >>> b.dual |b> >>> b.dual_class() <class 'sympy.physics.quantum.sho1d.SHOKet'> Vector representation of a numerical state bra: >>> from sympy.physics.quantum.sho1d import SHOBra, NumberOp >>> from sympy.physics.quantum.represent import represent >>> b = SHOBra(3) >>> N = NumberOp('N') >>> represent(b, basis=N, ndim=4) Matrix([[0, 0, 0, 1]]) """ @classmethod def dual_class(self): return SHOKet def _represent_default_basis(self, **options): return self._represent_NumberOp(None, **options) def _represent_NumberOp(self, basis, **options): ndim_info = options.get('ndim', 4) format = options.get('format', 'sympy') options['spmatrix'] = 'lil' vector = matrix_zeros(1, ndim_info, **options) if isinstance(self.n, Integer): if self.n >= ndim_info: return ValueError("N-Dimension too small") if format == 'scipy.sparse': vector[0, int(self.n)] = 1.0 vector = vector.tocsr() elif format == 'numpy': vector[0, int(self.n)] = 1.0 else: vector[0, self.n] = Integer(1) return vector else: return ValueError("Not Numerical State") ad = RaisingOp('a') a = LoweringOp('a') H = Hamiltonian('H') N = NumberOp('N') omega = Symbol('omega') m = Symbol('m')
2fe4191b4be82bd8456a2f4c03953dc63b14a6e12ba549c2f9fd5908159ccd0d
"""Logic for applying operators to states. Todo: * Sometimes the final result needs to be expanded, we should do this by hand. """ from sympy import Add, Mul, Pow, sympify, S from sympy.physics.quantum.anticommutator import AntiCommutator from sympy.physics.quantum.commutator import Commutator from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.innerproduct import InnerProduct from sympy.physics.quantum.operator import OuterProduct, Operator from sympy.physics.quantum.state import State, KetBase, BraBase, Wavefunction from sympy.physics.quantum.tensorproduct import TensorProduct __all__ = [ 'qapply' ] #----------------------------------------------------------------------------- # Main code #----------------------------------------------------------------------------- def qapply(e, **options): """Apply operators to states in a quantum expression. Parameters ========== e : Expr The expression containing operators and states. This expression tree will be walked to find operators acting on states symbolically. options : dict A dict of key/value pairs that determine how the operator actions are carried out. The following options are valid: * ``dagger``: try to apply Dagger operators to the left (default: False). * ``ip_doit``: call ``.doit()`` in inner products when they are encountered (default: True). Returns ======= e : Expr The original expression, but with the operators applied to states. Examples ======== >>> from sympy.physics.quantum import qapply, Ket, Bra >>> b = Bra('b') >>> k = Ket('k') >>> A = k * b >>> A |k><b| >>> qapply(A * b.dual / (b * b.dual)) |k> >>> qapply(k.dual * A / (k.dual * k), dagger=True) <b| >>> qapply(k.dual * A / (k.dual * k)) <k|*|k><b|/<k|k> """ from sympy.physics.quantum.density import Density dagger = options.get('dagger', False) if e == 0: return S.Zero # This may be a bit aggressive but ensures that everything gets expanded # to its simplest form before trying to apply operators. This includes # things like (A+B+C)*|a> and A*(|a>+|b>) and all Commutators and # TensorProducts. The only problem with this is that if we can't apply # all the Operators, we have just expanded everything. # TODO: don't expand the scalars in front of each Mul. e = e.expand(commutator=True, tensorproduct=True) # If we just have a raw ket, return it. if isinstance(e, KetBase): return e # We have an Add(a, b, c, ...) and compute # Add(qapply(a), qapply(b), ...) elif isinstance(e, Add): result = 0 for arg in e.args: result += qapply(arg, **options) return result.expand() # For a Density operator call qapply on its state elif isinstance(e, Density): new_args = [(qapply(state, **options), prob) for (state, prob) in e.args] return Density(*new_args) # For a raw TensorProduct, call qapply on its args. elif isinstance(e, TensorProduct): return TensorProduct(*[qapply(t, **options) for t in e.args]) # For a Pow, call qapply on its base. elif isinstance(e, Pow): return qapply(e.base, **options)**e.exp # We have a Mul where there might be actual operators to apply to kets. elif isinstance(e, Mul): c_part, nc_part = e.args_cnc() c_mul = Mul(*c_part) nc_mul = Mul(*nc_part) if isinstance(nc_mul, Mul): result = c_mul*qapply_Mul(nc_mul, **options) else: result = c_mul*qapply(nc_mul, **options) if result == e and dagger: return Dagger(qapply_Mul(Dagger(e), **options)) else: return result # In all other cases (State, Operator, Pow, Commutator, InnerProduct, # OuterProduct) we won't ever have operators to apply to kets. else: return e def qapply_Mul(e, **options): ip_doit = options.get('ip_doit', True) args = list(e.args) # If we only have 0 or 1 args, we have nothing to do and return. if len(args) <= 1 or not isinstance(e, Mul): return e rhs = args.pop() lhs = args.pop() # Make sure we have two non-commutative objects before proceeding. if (sympify(rhs).is_commutative and not isinstance(rhs, Wavefunction)) or \ (sympify(lhs).is_commutative and not isinstance(lhs, Wavefunction)): return e # For a Pow with an integer exponent, apply one of them and reduce the # exponent by one. if isinstance(lhs, Pow) and lhs.exp.is_Integer: args.append(lhs.base**(lhs.exp - 1)) lhs = lhs.base # Pull OuterProduct apart if isinstance(lhs, OuterProduct): args.append(lhs.ket) lhs = lhs.bra # Call .doit() on Commutator/AntiCommutator. if isinstance(lhs, (Commutator, AntiCommutator)): comm = lhs.doit() if isinstance(comm, Add): return qapply( e.func(*(args + [comm.args[0], rhs])) + e.func(*(args + [comm.args[1], rhs])), **options ) else: return qapply(e.func(*args)*comm*rhs, **options) # Apply tensor products of operators to states if isinstance(lhs, TensorProduct) and all([isinstance(arg, (Operator, State, Mul, Pow)) or arg == 1 for arg in lhs.args]) and \ isinstance(rhs, TensorProduct) and all([isinstance(arg, (Operator, State, Mul, Pow)) or arg == 1 for arg in rhs.args]) and \ len(lhs.args) == len(rhs.args): result = TensorProduct(*[qapply(lhs.args[n]*rhs.args[n], **options) for n in range(len(lhs.args))]).expand(tensorproduct=True) return qapply_Mul(e.func(*args), **options)*result # Now try to actually apply the operator and build an inner product. try: result = lhs._apply_operator(rhs, **options) except (NotImplementedError, AttributeError): try: result = rhs._apply_operator(lhs, **options) except (NotImplementedError, AttributeError): if isinstance(lhs, BraBase) and isinstance(rhs, KetBase): result = InnerProduct(lhs, rhs) if ip_doit: result = result.doit() else: result = None # TODO: I may need to expand before returning the final result. if result == 0: return S.Zero elif result is None: if len(args) == 0: # We had two args to begin with so args=[]. return e else: return qapply_Mul(e.func(*(args + [lhs])), **options)*rhs elif isinstance(result, InnerProduct): return result*qapply_Mul(e.func(*args), **options) else: # result is a scalar times a Mul, Add or TensorProduct return qapply(e.func(*args)*result, **options)
b2544e08699d88aea0f793e9506f165994523ca4c6fd6b066cc71b327347ecd0
from sympy.core.backend import Symbol from sympy.physics.vector import Point, Vector, ReferenceFrame from sympy.physics.mechanics import RigidBody, Particle, inertia __all__ = ['Body'] # XXX: We use type:ignore because the classes RigidBody and Particle have # inconsistent parallel axis methods that take different numbers of arguments. class Body(RigidBody, Particle): # type: ignore """ Body is a common representation of either a RigidBody or a Particle SymPy object depending on what is passed in during initialization. If a mass is passed in and central_inertia is left as None, the Particle object is created. Otherwise a RigidBody object will be created. Explanation =========== The attributes that Body possesses will be the same as a Particle instance or a Rigid Body instance depending on which was created. Additional attributes are listed below. Attributes ========== name : string The body's name masscenter : Point The point which represents the center of mass of the rigid body frame : ReferenceFrame The reference frame which the body is fixed in mass : Sympifyable The body's mass inertia : (Dyadic, Point) The body's inertia around its center of mass. This attribute is specific to the rigid body form of Body and is left undefined for the Particle form loads : iterable This list contains information on the different loads acting on the Body. Forces are listed as a (point, vector) tuple and torques are listed as (reference frame, vector) tuples. Parameters ========== name : String Defines the name of the body. It is used as the base for defining body specific properties. masscenter : Point, optional A point that represents the center of mass of the body or particle. If no point is given, a point is generated. mass : Sympifyable, optional A Sympifyable object which represents the mass of the body. If no mass is passed, one is generated. frame : ReferenceFrame, optional The ReferenceFrame that represents the reference frame of the body. If no frame is given, a frame is generated. central_inertia : Dyadic, optional Central inertia dyadic of the body. If none is passed while creating RigidBody, a default inertia is generated. Examples ======== Default behaviour. This results in the creation of a RigidBody object for which the mass, mass center, frame and inertia attributes are given default values. :: >>> from sympy.physics.mechanics import Body >>> body = Body('name_of_body') This next example demonstrates the code required to specify all of the values of the Body object. Note this will also create a RigidBody version of the Body object. :: >>> from sympy import Symbol >>> from sympy.physics.mechanics import ReferenceFrame, Point, inertia >>> from sympy.physics.mechanics import Body >>> mass = Symbol('mass') >>> masscenter = Point('masscenter') >>> frame = ReferenceFrame('frame') >>> ixx = Symbol('ixx') >>> body_inertia = inertia(frame, ixx, 0, 0) >>> body = Body('name_of_body', masscenter, mass, frame, body_inertia) The minimal code required to create a Particle version of the Body object involves simply passing in a name and a mass. :: >>> from sympy import Symbol >>> from sympy.physics.mechanics import Body >>> mass = Symbol('mass') >>> body = Body('name_of_body', mass=mass) The Particle version of the Body object can also receive a masscenter point and a reference frame, just not an inertia. """ def __init__(self, name, masscenter=None, mass=None, frame=None, central_inertia=None): self.name = name self.loads = [] if frame is None: frame = ReferenceFrame(name + '_frame') if masscenter is None: masscenter = Point(name + '_masscenter') if central_inertia is None and mass is None: ixx = Symbol(name + '_ixx') iyy = Symbol(name + '_iyy') izz = Symbol(name + '_izz') izx = Symbol(name + '_izx') ixy = Symbol(name + '_ixy') iyz = Symbol(name + '_iyz') _inertia = (inertia(frame, ixx, iyy, izz, ixy, iyz, izx), masscenter) else: _inertia = (central_inertia, masscenter) if mass is None: _mass = Symbol(name + '_mass') else: _mass = mass masscenter.set_vel(frame, 0) # If user passes masscenter and mass then a particle is created # otherwise a rigidbody. As a result a body may or may not have inertia. if central_inertia is None and mass is not None: self.frame = frame self.masscenter = masscenter Particle.__init__(self, name, masscenter, _mass) else: RigidBody.__init__(self, name, masscenter, frame, _mass, _inertia) def apply_force(self, vec, point=None): """ Adds a force to a point (center of mass by default) on the body. Parameters ========== vec: Vector Defines the force vector. Can be any vector w.r.t any frame or combinations of frames. point: Point, optional Defines the point on which the force is applied. Default is the Body's center of mass. Example ======= The first example applies a gravitational force in the x direction of Body's frame to the body's center of mass. :: >>> from sympy import Symbol >>> from sympy.physics.mechanics import Body >>> body = Body('body') >>> g = Symbol('g') >>> body.apply_force(body.mass * g * body.frame.x) To apply force to any other point than center of mass, pass that point as well. This example applies a gravitational force to a point a distance l from the body's center of mass in the y direction. The force is again applied in the x direction. :: >>> from sympy import Symbol >>> from sympy.physics.mechanics import Body >>> body = Body('body') >>> g = Symbol('g') >>> l = Symbol('l') >>> point = body.masscenter.locatenew('force_point', l * ... body.frame.y) >>> body.apply_force(body.mass * g * body.frame.x, point) """ if not isinstance(point, Point): if point is None: point = self.masscenter # masscenter else: raise TypeError("A Point must be supplied to apply force to.") if not isinstance(vec, Vector): raise TypeError("A Vector must be supplied to apply force.") self.loads.append((point, vec)) def apply_torque(self, vec): """ Adds a torque to the body. Parameters ========== vec: Vector Defines the torque vector. Can be any vector w.r.t any frame or combinations of frame. Example ======= This example adds a simple torque around the body's z axis. :: >>> from sympy import Symbol >>> from sympy.physics.mechanics import Body >>> body = Body('body') >>> T = Symbol('T') >>> body.apply_torque(T * body.frame.z) """ if not isinstance(vec, Vector): raise TypeError("A Vector must be supplied to add torque.") self.loads.append((self.frame, vec))
cae079341362056d83b9e4c335b22f4bdb63240a35d4ed58df801c8dcf7564d2
from sympy.core.backend import eye, Matrix, zeros from sympy.physics.mechanics import dynamicsymbols from sympy.physics.mechanics.functions import find_dynamicsymbols __all__ = ['SymbolicSystem'] class SymbolicSystem: """SymbolicSystem is a class that contains all the information about a system in a symbolic format such as the equations of motions and the bodies and loads in the system. There are three ways that the equations of motion can be described for Symbolic System: [1] Explicit form where the kinematics and dynamics are combined x' = F_1(x, t, r, p) [2] Implicit form where the kinematics and dynamics are combined M_2(x, p) x' = F_2(x, t, r, p) [3] Implicit form where the kinematics and dynamics are separate M_3(q, p) u' = F_3(q, u, t, r, p) q' = G(q, u, t, r, p) where x : states, e.g. [q, u] t : time r : specified (exogenous) inputs p : constants q : generalized coordinates u : generalized speeds F_1 : right hand side of the combined equations in explicit form F_2 : right hand side of the combined equations in implicit form F_3 : right hand side of the dynamical equations in implicit form M_2 : mass matrix of the combined equations in implicit form M_3 : mass matrix of the dynamical equations in implicit form G : right hand side of the kinematical differential equations Parameters ========== coord_states : ordered iterable of functions of time This input will either be a collection of the coordinates or states of the system depending on whether or not the speeds are also given. If speeds are specified this input will be assumed to be the coordinates otherwise this input will be assumed to be the states. right_hand_side : Matrix This variable is the right hand side of the equations of motion in any of the forms. The specific form will be assumed depending on whether a mass matrix or coordinate derivatives are given. speeds : ordered iterable of functions of time, optional This is a collection of the generalized speeds of the system. If given it will be assumed that the first argument (coord_states) will represent the generalized coordinates of the system. mass_matrix : Matrix, optional The matrix of the implicit forms of the equations of motion (forms [2] and [3]). The distinction between the forms is determined by whether or not the coordinate derivatives are passed in. If they are given form [3] will be assumed otherwise form [2] is assumed. coordinate_derivatives : Matrix, optional The right hand side of the kinematical equations in explicit form. If given it will be assumed that the equations of motion are being entered in form [3]. alg_con : Iterable, optional The indexes of the rows in the equations of motion that contain algebraic constraints instead of differential equations. If the equations are input in form [3], it will be assumed the indexes are referencing the mass_matrix/right_hand_side combination and not the coordinate_derivatives. output_eqns : Dictionary, optional Any output equations that are desired to be tracked are stored in a dictionary where the key corresponds to the name given for the specific equation and the value is the equation itself in symbolic form coord_idxs : Iterable, optional If coord_states corresponds to the states rather than the coordinates this variable will tell SymbolicSystem which indexes of the states correspond to generalized coordinates. speed_idxs : Iterable, optional If coord_states corresponds to the states rather than the coordinates this variable will tell SymbolicSystem which indexes of the states correspond to generalized speeds. bodies : iterable of Body/Rigidbody objects, optional Iterable containing the bodies of the system loads : iterable of load instances (described below), optional Iterable containing the loads of the system where forces are given by (point of application, force vector) and torques are given by (reference frame acting upon, torque vector). Ex [(point, force), (ref_frame, torque)] Attributes ========== coordinates : Matrix, shape(n, 1) This is a matrix containing the generalized coordinates of the system speeds : Matrix, shape(m, 1) This is a matrix containing the generalized speeds of the system states : Matrix, shape(o, 1) This is a matrix containing the state variables of the system alg_con : List This list contains the indices of the algebraic constraints in the combined equations of motion. The presence of these constraints requires that a DAE solver be used instead of an ODE solver. If the system is given in form [3] the alg_con variable will be adjusted such that it is a representation of the combined kinematics and dynamics thus make sure it always matches the mass matrix entered. dyn_implicit_mat : Matrix, shape(m, m) This is the M matrix in form [3] of the equations of motion (the mass matrix or generalized inertia matrix of the dynamical equations of motion in implicit form). dyn_implicit_rhs : Matrix, shape(m, 1) This is the F vector in form [3] of the equations of motion (the right hand side of the dynamical equations of motion in implicit form). comb_implicit_mat : Matrix, shape(o, o) This is the M matrix in form [2] of the equations of motion. This matrix contains a block diagonal structure where the top left block (the first rows) represent the matrix in the implicit form of the kinematical equations and the bottom right block (the last rows) represent the matrix in the implicit form of the dynamical equations. comb_implicit_rhs : Matrix, shape(o, 1) This is the F vector in form [2] of the equations of motion. The top part of the vector represents the right hand side of the implicit form of the kinemaical equations and the bottom of the vector represents the right hand side of the implicit form of the dynamical equations of motion. comb_explicit_rhs : Matrix, shape(o, 1) This vector represents the right hand side of the combined equations of motion in explicit form (form [1] from above). kin_explicit_rhs : Matrix, shape(m, 1) This is the right hand side of the explicit form of the kinematical equations of motion as can be seen in form [3] (the G matrix). output_eqns : Dictionary If output equations were given they are stored in a dictionary where the key corresponds to the name given for the specific equation and the value is the equation itself in symbolic form bodies : Tuple If the bodies in the system were given they are stored in a tuple for future access loads : Tuple If the loads in the system were given they are stored in a tuple for future access. This includes forces and torques where forces are given by (point of application, force vector) and torques are given by (reference frame acted upon, torque vector). Example ======= As a simple example, the dynamics of a simple pendulum will be input into a SymbolicSystem object manually. First some imports will be needed and then symbols will be set up for the length of the pendulum (l), mass at the end of the pendulum (m), and a constant for gravity (g). :: >>> from sympy import Matrix, sin, symbols >>> from sympy.physics.mechanics import dynamicsymbols, SymbolicSystem >>> l, m, g = symbols('l m g') The system will be defined by an angle of theta from the vertical and a generalized speed of omega will be used where omega = theta_dot. :: >>> theta, omega = dynamicsymbols('theta omega') Now the equations of motion are ready to be formed and passed to the SymbolicSystem object. :: >>> kin_explicit_rhs = Matrix([omega]) >>> dyn_implicit_mat = Matrix([l**2 * m]) >>> dyn_implicit_rhs = Matrix([-g * l * m * sin(theta)]) >>> symsystem = SymbolicSystem([theta], dyn_implicit_rhs, [omega], ... dyn_implicit_mat) Notes ===== m : number of generalized speeds n : number of generalized coordinates o : number of states """ def __init__(self, coord_states, right_hand_side, speeds=None, mass_matrix=None, coordinate_derivatives=None, alg_con=None, output_eqns={}, coord_idxs=None, speed_idxs=None, bodies=None, loads=None): """Initializes a SymbolicSystem object""" # Extract information on speeds, coordinates and states if speeds is None: self._states = Matrix(coord_states) if coord_idxs is None: self._coordinates = None else: coords = [coord_states[i] for i in coord_idxs] self._coordinates = Matrix(coords) if speed_idxs is None: self._speeds = None else: speeds_inter = [coord_states[i] for i in speed_idxs] self._speeds = Matrix(speeds_inter) else: self._coordinates = Matrix(coord_states) self._speeds = Matrix(speeds) self._states = self._coordinates.col_join(self._speeds) # Extract equations of motion form if coordinate_derivatives is not None: self._kin_explicit_rhs = coordinate_derivatives self._dyn_implicit_rhs = right_hand_side self._dyn_implicit_mat = mass_matrix self._comb_implicit_rhs = None self._comb_implicit_mat = None self._comb_explicit_rhs = None elif mass_matrix is not None: self._kin_explicit_rhs = None self._dyn_implicit_rhs = None self._dyn_implicit_mat = None self._comb_implicit_rhs = right_hand_side self._comb_implicit_mat = mass_matrix self._comb_explicit_rhs = None else: self._kin_explicit_rhs = None self._dyn_implicit_rhs = None self._dyn_implicit_mat = None self._comb_implicit_rhs = None self._comb_implicit_mat = None self._comb_explicit_rhs = right_hand_side # Set the remainder of the inputs as instance attributes if alg_con is not None and coordinate_derivatives is not None: alg_con = [i + len(coordinate_derivatives) for i in alg_con] self._alg_con = alg_con self.output_eqns = output_eqns # Change the body and loads iterables to tuples if they are not tuples # already if type(bodies) != tuple and bodies is not None: bodies = tuple(bodies) if type(loads) != tuple and loads is not None: loads = tuple(loads) self._bodies = bodies self._loads = loads @property def coordinates(self): """Returns the column matrix of the generalized coordinates""" if self._coordinates is None: raise AttributeError("The coordinates were not specified.") else: return self._coordinates @property def speeds(self): """Returns the column matrix of generalized speeds""" if self._speeds is None: raise AttributeError("The speeds were not specified.") else: return self._speeds @property def states(self): """Returns the column matrix of the state variables""" return self._states @property def alg_con(self): """Returns a list with the indices of the rows containing algebraic constraints in the combined form of the equations of motion""" return self._alg_con @property def dyn_implicit_mat(self): """Returns the matrix, M, corresponding to the dynamic equations in implicit form, M x' = F, where the kinematical equations are not included""" if self._dyn_implicit_mat is None: raise AttributeError("dyn_implicit_mat is not specified for " "equations of motion form [1] or [2].") else: return self._dyn_implicit_mat @property def dyn_implicit_rhs(self): """Returns the column matrix, F, corresponding to the dynamic equations in implicit form, M x' = F, where the kinematical equations are not included""" if self._dyn_implicit_rhs is None: raise AttributeError("dyn_implicit_rhs is not specified for " "equations of motion form [1] or [2].") else: return self._dyn_implicit_rhs @property def comb_implicit_mat(self): """Returns the matrix, M, corresponding to the equations of motion in implicit form (form [2]), M x' = F, where the kinematical equations are included""" if self._comb_implicit_mat is None: if self._dyn_implicit_mat is not None: num_kin_eqns = len(self._kin_explicit_rhs) num_dyn_eqns = len(self._dyn_implicit_rhs) zeros1 = zeros(num_kin_eqns, num_dyn_eqns) zeros2 = zeros(num_dyn_eqns, num_kin_eqns) inter1 = eye(num_kin_eqns).row_join(zeros1) inter2 = zeros2.row_join(self._dyn_implicit_mat) self._comb_implicit_mat = inter1.col_join(inter2) return self._comb_implicit_mat else: raise AttributeError("comb_implicit_mat is not specified for " "equations of motion form [1].") else: return self._comb_implicit_mat @property def comb_implicit_rhs(self): """Returns the column matrix, F, corresponding to the equations of motion in implicit form (form [2]), M x' = F, where the kinematical equations are included""" if self._comb_implicit_rhs is None: if self._dyn_implicit_rhs is not None: kin_inter = self._kin_explicit_rhs dyn_inter = self._dyn_implicit_rhs self._comb_implicit_rhs = kin_inter.col_join(dyn_inter) return self._comb_implicit_rhs else: raise AttributeError("comb_implicit_mat is not specified for " "equations of motion in form [1].") else: return self._comb_implicit_rhs def compute_explicit_form(self): """If the explicit right hand side of the combined equations of motion is to provided upon initialization, this method will calculate it. This calculation can potentially take awhile to compute.""" if self._comb_explicit_rhs is not None: raise AttributeError("comb_explicit_rhs is already formed.") inter1 = getattr(self, 'kin_explicit_rhs', None) if inter1 is not None: inter2 = self._dyn_implicit_mat.LUsolve(self._dyn_implicit_rhs) out = inter1.col_join(inter2) else: out = self._comb_implicit_mat.LUsolve(self._comb_implicit_rhs) self._comb_explicit_rhs = out @property def comb_explicit_rhs(self): """Returns the right hand side of the equations of motion in explicit form, x' = F, where the kinematical equations are included""" if self._comb_explicit_rhs is None: raise AttributeError("Please run .combute_explicit_form before " "attempting to access comb_explicit_rhs.") else: return self._comb_explicit_rhs @property def kin_explicit_rhs(self): """Returns the right hand side of the kinematical equations in explicit form, q' = G""" if self._kin_explicit_rhs is None: raise AttributeError("kin_explicit_rhs is not specified for " "equations of motion form [1] or [2].") else: return self._kin_explicit_rhs def dynamic_symbols(self): """Returns a column matrix containing all of the symbols in the system that depend on time""" # Create a list of all of the expressions in the equations of motion if self._comb_explicit_rhs is None: eom_expressions = (self.comb_implicit_mat[:] + self.comb_implicit_rhs[:]) else: eom_expressions = (self._comb_explicit_rhs[:]) functions_of_time = set() for expr in eom_expressions: functions_of_time = functions_of_time.union( find_dynamicsymbols(expr)) functions_of_time = functions_of_time.union(self._states) return tuple(functions_of_time) def constant_symbols(self): """Returns a column matrix containing all of the symbols in the system that do not depend on time""" # Create a list of all of the expressions in the equations of motion if self._comb_explicit_rhs is None: eom_expressions = (self.comb_implicit_mat[:] + self.comb_implicit_rhs[:]) else: eom_expressions = (self._comb_explicit_rhs[:]) constants = set() for expr in eom_expressions: constants = constants.union(expr.free_symbols) constants.remove(dynamicsymbols._t) return tuple(constants) @property def bodies(self): """Returns the bodies in the system""" if self._bodies is None: raise AttributeError("bodies were not specified for the system.") else: return self._bodies @property def loads(self): """Returns the loads in the system""" if self._loads is None: raise AttributeError("loads were not specified for the system.") else: return self._loads
f6ad60dc8db1629b93322faff607acc04ab12564cfdd18dc3aab917f33211f33
#!/usr/bin/env python """This module contains some sample symbolic models used for testing and examples.""" # Internal imports from sympy.core import backend as sm import sympy.physics.mechanics as me def multi_mass_spring_damper(n=1, apply_gravity=False, apply_external_forces=False): r"""Returns a system containing the symbolic equations of motion and associated variables for a simple multi-degree of freedom point mass, spring, damper system with optional gravitational and external specified forces. For example, a two mass system under the influence of gravity and external forces looks like: :: ---------------- | | | | g \ | | | V k0 / --- c0 | | | | x0, v0 --------- V | m0 | ----- --------- | | | | | \ v | | | k1 / f0 --- c1 | | | | x1, v1 --------- V | m1 | ----- --------- | f1 V Parameters ========== n : integer The number of masses in the serial chain. apply_gravity : boolean If true, gravity will be applied to each mass. apply_external_forces : boolean If true, a time varying external force will be applied to each mass. Returns ======= kane : sympy.physics.mechanics.kane.KanesMethod A KanesMethod object. """ mass = sm.symbols('m:{}'.format(n)) stiffness = sm.symbols('k:{}'.format(n)) damping = sm.symbols('c:{}'.format(n)) acceleration_due_to_gravity = sm.symbols('g') coordinates = me.dynamicsymbols('x:{}'.format(n)) speeds = me.dynamicsymbols('v:{}'.format(n)) specifieds = me.dynamicsymbols('f:{}'.format(n)) ceiling = me.ReferenceFrame('N') origin = me.Point('origin') origin.set_vel(ceiling, 0) points = [origin] kinematic_equations = [] particles = [] forces = [] for i in range(n): center = points[-1].locatenew('center{}'.format(i), coordinates[i] * ceiling.x) center.set_vel(ceiling, points[-1].vel(ceiling) + speeds[i] * ceiling.x) points.append(center) block = me.Particle('block{}'.format(i), center, mass[i]) kinematic_equations.append(speeds[i] - coordinates[i].diff()) total_force = (-stiffness[i] * coordinates[i] - damping[i] * speeds[i]) try: total_force += (stiffness[i + 1] * coordinates[i + 1] + damping[i + 1] * speeds[i + 1]) except IndexError: # no force from below on last mass pass if apply_gravity: total_force += mass[i] * acceleration_due_to_gravity if apply_external_forces: total_force += specifieds[i] forces.append((center, total_force * ceiling.x)) particles.append(block) kane = me.KanesMethod(ceiling, q_ind=coordinates, u_ind=speeds, kd_eqs=kinematic_equations) kane.kanes_equations(particles, forces) return kane def n_link_pendulum_on_cart(n=1, cart_force=True, joint_torques=False): r"""Returns the system containing the symbolic first order equations of motion for a 2D n-link pendulum on a sliding cart under the influence of gravity. :: | o y v \ 0 ^ g \ | --\-|---- | \| | F-> | o --|---> x | | --------- o o Parameters ========== n : integer The number of links in the pendulum. cart_force : boolean, default=True If true an external specified lateral force is applied to the cart. joint_torques : boolean, default=False If true joint torques will be added as specified inputs at each joint. Returns ======= kane : sympy.physics.mechanics.kane.KanesMethod A KanesMethod object. Notes ===== The degrees of freedom of the system are n + 1, i.e. one for each pendulum link and one for the lateral motion of the cart. M x' = F, where x = [u0, ..., un+1, q0, ..., qn+1] The joint angles are all defined relative to the ground where the x axis defines the ground line and the y axis points up. The joint torques are applied between each adjacent link and the between the cart and the lower link where a positive torque corresponds to positive angle. """ if n <= 0: raise ValueError('The number of links must be a positive integer.') q = me.dynamicsymbols('q:{}'.format(n + 1)) u = me.dynamicsymbols('u:{}'.format(n + 1)) if joint_torques is True: T = me.dynamicsymbols('T1:{}'.format(n + 1)) m = sm.symbols('m:{}'.format(n + 1)) l = sm.symbols('l:{}'.format(n)) g, t = sm.symbols('g t') I = me.ReferenceFrame('I') O = me.Point('O') O.set_vel(I, 0) P0 = me.Point('P0') P0.set_pos(O, q[0] * I.x) P0.set_vel(I, u[0] * I.x) Pa0 = me.Particle('Pa0', P0, m[0]) frames = [I] points = [P0] particles = [Pa0] forces = [(P0, -m[0] * g * I.y)] kindiffs = [q[0].diff(t) - u[0]] if cart_force is True or joint_torques is True: specified = [] else: specified = None for i in range(n): Bi = I.orientnew('B{}'.format(i), 'Axis', [q[i + 1], I.z]) Bi.set_ang_vel(I, u[i + 1] * I.z) frames.append(Bi) Pi = points[-1].locatenew('P{}'.format(i + 1), l[i] * Bi.y) Pi.v2pt_theory(points[-1], I, Bi) points.append(Pi) Pai = me.Particle('Pa' + str(i + 1), Pi, m[i + 1]) particles.append(Pai) forces.append((Pi, -m[i + 1] * g * I.y)) if joint_torques is True: specified.append(T[i]) if i == 0: forces.append((I, -T[i] * I.z)) if i == n - 1: forces.append((Bi, T[i] * I.z)) else: forces.append((Bi, T[i] * I.z - T[i + 1] * I.z)) kindiffs.append(q[i + 1].diff(t) - u[i + 1]) if cart_force is True: F = me.dynamicsymbols('F') forces.append((P0, F * I.x)) specified.append(F) kane = me.KanesMethod(I, q_ind=q, u_ind=u, kd_eqs=kindiffs) kane.kanes_equations(particles, forces) return kane
bec0a9456bed33eed4c0a623fd11e048d68490070ee1f63fd3d66e10ca0bd15d
from sympy.core.backend import zeros, Matrix, diff, eye from sympy import solve_linear_system_LU from sympy.utilities import default_sort_key from sympy.physics.vector import (ReferenceFrame, dynamicsymbols, partial_velocity) from sympy.physics.mechanics.particle import Particle from sympy.physics.mechanics.rigidbody import RigidBody from sympy.physics.mechanics.functions import (msubs, find_dynamicsymbols, _f_list_parser) from sympy.physics.mechanics.linearize import Linearizer from sympy.utilities.iterables import iterable __all__ = ['KanesMethod'] class KanesMethod: """Kane's method object. Explanation =========== This object is used to do the "book-keeping" as you go through and form equations of motion in the way Kane presents in: Kane, T., Levinson, D. Dynamics Theory and Applications. 1985 McGraw-Hill The attributes are for equations in the form [M] udot = forcing. Attributes ========== q, u : Matrix Matrices of the generalized coordinates and speeds bodylist : iterable Iterable of Point and RigidBody objects in the system. forcelist : iterable Iterable of (Point, vector) or (ReferenceFrame, vector) tuples describing the forces on the system. auxiliary : Matrix If applicable, the set of auxiliary Kane's equations used to solve for non-contributing forces. mass_matrix : Matrix The system's mass matrix forcing : Matrix The system's forcing vector mass_matrix_full : Matrix The "mass matrix" for the u's and q's forcing_full : Matrix The "forcing vector" for the u's and q's Examples ======== This is a simple example for a one degree of freedom translational spring-mass-damper. In this example, we first need to do the kinematics. This involves creating generalized speeds and coordinates and their derivatives. Then we create a point and set its velocity in a frame. >>> from sympy import symbols >>> from sympy.physics.mechanics import dynamicsymbols, ReferenceFrame >>> from sympy.physics.mechanics import Point, Particle, KanesMethod >>> q, u = dynamicsymbols('q u') >>> qd, ud = dynamicsymbols('q u', 1) >>> m, c, k = symbols('m c k') >>> N = ReferenceFrame('N') >>> P = Point('P') >>> P.set_vel(N, u * N.x) Next we need to arrange/store information in the way that KanesMethod requires. The kinematic differential equations need to be stored in a dict. A list of forces/torques must be constructed, where each entry in the list is a (Point, Vector) or (ReferenceFrame, Vector) tuple, where the Vectors represent the Force or Torque. Next a particle needs to be created, and it needs to have a point and mass assigned to it. Finally, a list of all bodies and particles needs to be created. >>> kd = [qd - u] >>> FL = [(P, (-k * q - c * u) * N.x)] >>> pa = Particle('pa', P, m) >>> BL = [pa] Finally we can generate the equations of motion. First we create the KanesMethod object and supply an inertial frame, coordinates, generalized speeds, and the kinematic differential equations. Additional quantities such as configuration and motion constraints, dependent coordinates and speeds, and auxiliary speeds are also supplied here (see the online documentation). Next we form FR* and FR to complete: Fr + Fr* = 0. We have the equations of motion at this point. It makes sense to rearrange them though, so we calculate the mass matrix and the forcing terms, for E.o.M. in the form: [MM] udot = forcing, where MM is the mass matrix, udot is a vector of the time derivatives of the generalized speeds, and forcing is a vector representing "forcing" terms. >>> KM = KanesMethod(N, q_ind=[q], u_ind=[u], kd_eqs=kd) >>> (fr, frstar) = KM.kanes_equations(BL, FL) >>> MM = KM.mass_matrix >>> forcing = KM.forcing >>> rhs = MM.inv() * forcing >>> rhs Matrix([[(-c*u(t) - k*q(t))/m]]) >>> KM.linearize(A_and_B=True)[0] Matrix([ [ 0, 1], [-k/m, -c/m]]) Please look at the documentation pages for more information on how to perform linearization and how to deal with dependent coordinates & speeds, and how do deal with bringing non-contributing forces into evidence. """ def __init__(self, frame, q_ind, u_ind, kd_eqs=None, q_dependent=None, configuration_constraints=None, u_dependent=None, velocity_constraints=None, acceleration_constraints=None, u_auxiliary=None): """Please read the online documentation. """ if not q_ind: q_ind = [dynamicsymbols('dummy_q')] kd_eqs = [dynamicsymbols('dummy_kd')] if not isinstance(frame, ReferenceFrame): raise TypeError('An inertial ReferenceFrame must be supplied') self._inertial = frame self._fr = None self._frstar = None self._forcelist = None self._bodylist = None self._initialize_vectors(q_ind, q_dependent, u_ind, u_dependent, u_auxiliary) self._initialize_kindiffeq_matrices(kd_eqs) self._initialize_constraint_matrices(configuration_constraints, velocity_constraints, acceleration_constraints) def _initialize_vectors(self, q_ind, q_dep, u_ind, u_dep, u_aux): """Initialize the coordinate and speed vectors.""" none_handler = lambda x: Matrix(x) if x else Matrix() # Initialize generalized coordinates q_dep = none_handler(q_dep) if not iterable(q_ind): raise TypeError('Generalized coordinates must be an iterable.') if not iterable(q_dep): raise TypeError('Dependent coordinates must be an iterable.') q_ind = Matrix(q_ind) self._qdep = q_dep self._q = Matrix([q_ind, q_dep]) self._qdot = self.q.diff(dynamicsymbols._t) # Initialize generalized speeds u_dep = none_handler(u_dep) if not iterable(u_ind): raise TypeError('Generalized speeds must be an iterable.') if not iterable(u_dep): raise TypeError('Dependent speeds must be an iterable.') u_ind = Matrix(u_ind) self._udep = u_dep self._u = Matrix([u_ind, u_dep]) self._udot = self.u.diff(dynamicsymbols._t) self._uaux = none_handler(u_aux) def _initialize_constraint_matrices(self, config, vel, acc): """Initializes constraint matrices.""" # Define vector dimensions o = len(self.u) m = len(self._udep) p = o - m none_handler = lambda x: Matrix(x) if x else Matrix() # Initialize configuration constraints config = none_handler(config) if len(self._qdep) != len(config): raise ValueError('There must be an equal number of dependent ' 'coordinates and configuration constraints.') self._f_h = none_handler(config) # Initialize velocity and acceleration constraints vel = none_handler(vel) acc = none_handler(acc) if len(vel) != m: raise ValueError('There must be an equal number of dependent ' 'speeds and velocity constraints.') if acc and (len(acc) != m): raise ValueError('There must be an equal number of dependent ' 'speeds and acceleration constraints.') if vel: u_zero = {i: 0 for i in self.u} udot_zero = {i: 0 for i in self._udot} # When calling kanes_equations, another class instance will be # created if auxiliary u's are present. In this case, the # computation of kinetic differential equation matrices will be # skipped as this was computed during the original KanesMethod # object, and the qd_u_map will not be available. if self._qdot_u_map is not None: vel = msubs(vel, self._qdot_u_map) self._f_nh = msubs(vel, u_zero) self._k_nh = (vel - self._f_nh).jacobian(self.u) # If no acceleration constraints given, calculate them. if not acc: _f_dnh = (self._k_nh.diff(dynamicsymbols._t) * self.u + self._f_nh.diff(dynamicsymbols._t)) if self._qdot_u_map is not None: _f_dnh = msubs(_f_dnh, self._qdot_u_map) self._f_dnh = _f_dnh self._k_dnh = self._k_nh else: if self._qdot_u_map is not None: acc = msubs(acc, self._qdot_u_map) self._f_dnh = msubs(acc, udot_zero) self._k_dnh = (acc - self._f_dnh).jacobian(self._udot) # Form of non-holonomic constraints is B*u + C = 0. # We partition B into independent and dependent columns: # Ars is then -B_dep.inv() * B_ind, and it relates dependent speeds # to independent speeds as: udep = Ars*uind, neglecting the C term. B_ind = self._k_nh[:, :p] B_dep = self._k_nh[:, p:o] self._Ars = -B_dep.LUsolve(B_ind) else: self._f_nh = Matrix() self._k_nh = Matrix() self._f_dnh = Matrix() self._k_dnh = Matrix() self._Ars = Matrix() def _initialize_kindiffeq_matrices(self, kdeqs): """Initialize the kinematic differential equation matrices.""" if kdeqs: if len(self.q) != len(kdeqs): raise ValueError('There must be an equal number of kinematic ' 'differential equations and coordinates.') kdeqs = Matrix(kdeqs) u = self.u qdot = self._qdot # Dictionaries setting things to zero u_zero = {i: 0 for i in u} uaux_zero = {i: 0 for i in self._uaux} qdot_zero = {i: 0 for i in qdot} f_k = msubs(kdeqs, u_zero, qdot_zero) k_ku = (msubs(kdeqs, qdot_zero) - f_k).jacobian(u) k_kqdot = (msubs(kdeqs, u_zero) - f_k).jacobian(qdot) f_k = k_kqdot.LUsolve(f_k) k_ku = k_kqdot.LUsolve(k_ku) k_kqdot = eye(len(qdot)) self._qdot_u_map = solve_linear_system_LU( Matrix([k_kqdot.T, -(k_ku * u + f_k).T]).T, qdot) self._f_k = msubs(f_k, uaux_zero) self._k_ku = msubs(k_ku, uaux_zero) self._k_kqdot = k_kqdot else: self._qdot_u_map = None self._f_k = Matrix() self._k_ku = Matrix() self._k_kqdot = Matrix() def _form_fr(self, fl): """Form the generalized active force.""" if fl is not None and (len(fl) == 0 or not iterable(fl)): raise ValueError('Force pairs must be supplied in an ' 'non-empty iterable or None.') N = self._inertial # pull out relevant velocities for constructing partial velocities vel_list, f_list = _f_list_parser(fl, N) vel_list = [msubs(i, self._qdot_u_map) for i in vel_list] f_list = [msubs(i, self._qdot_u_map) for i in f_list] # Fill Fr with dot product of partial velocities and forces o = len(self.u) b = len(f_list) FR = zeros(o, 1) partials = partial_velocity(vel_list, self.u, N) for i in range(o): FR[i] = sum(partials[j][i] & f_list[j] for j in range(b)) # In case there are dependent speeds if self._udep: p = o - len(self._udep) FRtilde = FR[:p, 0] FRold = FR[p:o, 0] FRtilde += self._Ars.T * FRold FR = FRtilde self._forcelist = fl self._fr = FR return FR def _form_frstar(self, bl): """Form the generalized inertia force.""" if not iterable(bl): raise TypeError('Bodies must be supplied in an iterable.') t = dynamicsymbols._t N = self._inertial # Dicts setting things to zero udot_zero = {i: 0 for i in self._udot} uaux_zero = {i: 0 for i in self._uaux} uauxdot = [diff(i, t) for i in self._uaux] uauxdot_zero = {i: 0 for i in uauxdot} # Dictionary of q' and q'' to u and u' q_ddot_u_map = {k.diff(t): v.diff(t) for (k, v) in self._qdot_u_map.items()} q_ddot_u_map.update(self._qdot_u_map) # Fill up the list of partials: format is a list with num elements # equal to number of entries in body list. Each of these elements is a # list - either of length 1 for the translational components of # particles or of length 2 for the translational and rotational # components of rigid bodies. The inner most list is the list of # partial velocities. def get_partial_velocity(body): if isinstance(body, RigidBody): vlist = [body.masscenter.vel(N), body.frame.ang_vel_in(N)] elif isinstance(body, Particle): vlist = [body.point.vel(N),] else: raise TypeError('The body list may only contain either ' 'RigidBody or Particle as list elements.') v = [msubs(vel, self._qdot_u_map) for vel in vlist] return partial_velocity(v, self.u, N) partials = [get_partial_velocity(body) for body in bl] # Compute fr_star in two components: # fr_star = -(MM*u' + nonMM) o = len(self.u) MM = zeros(o, o) nonMM = zeros(o, 1) zero_uaux = lambda expr: msubs(expr, uaux_zero) zero_udot_uaux = lambda expr: msubs(msubs(expr, udot_zero), uaux_zero) for i, body in enumerate(bl): if isinstance(body, RigidBody): M = zero_uaux(body.mass) I = zero_uaux(body.central_inertia) vel = zero_uaux(body.masscenter.vel(N)) omega = zero_uaux(body.frame.ang_vel_in(N)) acc = zero_udot_uaux(body.masscenter.acc(N)) inertial_force = (M.diff(t) * vel + M * acc) inertial_torque = zero_uaux((I.dt(body.frame) & omega) + msubs(I & body.frame.ang_acc_in(N), udot_zero) + (omega ^ (I & omega))) for j in range(o): tmp_vel = zero_uaux(partials[i][0][j]) tmp_ang = zero_uaux(I & partials[i][1][j]) for k in range(o): # translational MM[j, k] += M * (tmp_vel & partials[i][0][k]) # rotational MM[j, k] += (tmp_ang & partials[i][1][k]) nonMM[j] += inertial_force & partials[i][0][j] nonMM[j] += inertial_torque & partials[i][1][j] else: M = zero_uaux(body.mass) vel = zero_uaux(body.point.vel(N)) acc = zero_udot_uaux(body.point.acc(N)) inertial_force = (M.diff(t) * vel + M * acc) for j in range(o): temp = zero_uaux(partials[i][0][j]) for k in range(o): MM[j, k] += M * (temp & partials[i][0][k]) nonMM[j] += inertial_force & partials[i][0][j] # Compose fr_star out of MM and nonMM MM = zero_uaux(msubs(MM, q_ddot_u_map)) nonMM = msubs(msubs(nonMM, q_ddot_u_map), udot_zero, uauxdot_zero, uaux_zero) fr_star = -(MM * msubs(Matrix(self._udot), uauxdot_zero) + nonMM) # If there are dependent speeds, we need to find fr_star_tilde if self._udep: p = o - len(self._udep) fr_star_ind = fr_star[:p, 0] fr_star_dep = fr_star[p:o, 0] fr_star = fr_star_ind + (self._Ars.T * fr_star_dep) # Apply the same to MM MMi = MM[:p, :] MMd = MM[p:o, :] MM = MMi + (self._Ars.T * MMd) self._bodylist = bl self._frstar = fr_star self._k_d = MM self._f_d = -msubs(self._fr + self._frstar, udot_zero) return fr_star def to_linearizer(self): """Returns an instance of the Linearizer class, initiated from the data in the KanesMethod class. This may be more desirable than using the linearize class method, as the Linearizer object will allow more efficient recalculation (i.e. about varying operating points).""" if (self._fr is None) or (self._frstar is None): raise ValueError('Need to compute Fr, Fr* first.') # Get required equation components. The Kane's method class breaks # these into pieces. Need to reassemble f_c = self._f_h if self._f_nh and self._k_nh: f_v = self._f_nh + self._k_nh*Matrix(self.u) else: f_v = Matrix() if self._f_dnh and self._k_dnh: f_a = self._f_dnh + self._k_dnh*Matrix(self._udot) else: f_a = Matrix() # Dicts to sub to zero, for splitting up expressions u_zero = {i: 0 for i in self.u} ud_zero = {i: 0 for i in self._udot} qd_zero = {i: 0 for i in self._qdot} qd_u_zero = {i: 0 for i in Matrix([self._qdot, self.u])} # Break the kinematic differential eqs apart into f_0 and f_1 f_0 = msubs(self._f_k, u_zero) + self._k_kqdot*Matrix(self._qdot) f_1 = msubs(self._f_k, qd_zero) + self._k_ku*Matrix(self.u) # Break the dynamic differential eqs into f_2 and f_3 f_2 = msubs(self._frstar, qd_u_zero) f_3 = msubs(self._frstar, ud_zero) + self._fr f_4 = zeros(len(f_2), 1) # Get the required vector components q = self.q u = self.u if self._qdep: q_i = q[:-len(self._qdep)] else: q_i = q q_d = self._qdep if self._udep: u_i = u[:-len(self._udep)] else: u_i = u u_d = self._udep # Form dictionary to set auxiliary speeds & their derivatives to 0. uaux = self._uaux uauxdot = uaux.diff(dynamicsymbols._t) uaux_zero = {i: 0 for i in Matrix([uaux, uauxdot])} # Checking for dynamic symbols outside the dynamic differential # equations; throws error if there is. sym_list = set(Matrix([q, self._qdot, u, self._udot, uaux, uauxdot])) if any(find_dynamicsymbols(i, sym_list) for i in [self._k_kqdot, self._k_ku, self._f_k, self._k_dnh, self._f_dnh, self._k_d]): raise ValueError('Cannot have dynamicsymbols outside dynamic \ forcing vector.') # Find all other dynamic symbols, forming the forcing vector r. # Sort r to make it canonical. r = list(find_dynamicsymbols(msubs(self._f_d, uaux_zero), sym_list)) r.sort(key=default_sort_key) # Check for any derivatives of variables in r that are also found in r. for i in r: if diff(i, dynamicsymbols._t) in r: raise ValueError('Cannot have derivatives of specified \ quantities when linearizing forcing terms.') return Linearizer(f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a, q, u, q_i, q_d, u_i, u_d, r) # TODO : Remove `new_method` after 1.1 has been released. def linearize(self, *, new_method=None, **kwargs): """ Linearize the equations of motion about a symbolic operating point. Explanation =========== If kwarg A_and_B is False (default), returns M, A, B, r for the linearized form, M*[q', u']^T = A*[q_ind, u_ind]^T + B*r. If kwarg A_and_B is True, returns A, B, r for the linearized form dx = A*x + B*r, where x = [q_ind, u_ind]^T. Note that this is computationally intensive if there are many symbolic parameters. For this reason, it may be more desirable to use the default A_and_B=False, returning M, A, and B. Values may then be substituted in to these matrices, and the state space form found as A = P.T*M.inv()*A, B = P.T*M.inv()*B, where P = Linearizer.perm_mat. In both cases, r is found as all dynamicsymbols in the equations of motion that are not part of q, u, q', or u'. They are sorted in canonical form. The operating points may be also entered using the ``op_point`` kwarg. This takes a dictionary of {symbol: value}, or a an iterable of such dictionaries. The values may be numeric or symbolic. The more values you can specify beforehand, the faster this computation will run. For more documentation, please see the ``Linearizer`` class.""" linearizer = self.to_linearizer() result = linearizer.linearize(**kwargs) return result + (linearizer.r,) def kanes_equations(self, bodies, loads=None): """ Method to form Kane's equations, Fr + Fr* = 0. Explanation =========== Returns (Fr, Fr*). In the case where auxiliary generalized speeds are present (say, s auxiliary speeds, o generalized speeds, and m motion constraints) the length of the returned vectors will be o - m + s in length. The first o - m equations will be the constrained Kane's equations, then the s auxiliary Kane's equations. These auxiliary equations can be accessed with the auxiliary_eqs(). Parameters ========== bodies : iterable An iterable of all RigidBody's and Particle's in the system. A system must have at least one body. loads : iterable Takes in an iterable of (Particle, Vector) or (ReferenceFrame, Vector) tuples which represent the force at a point or torque on a frame. Must be either a non-empty iterable of tuples or None which corresponds to a system with no constraints. """ if not self._k_kqdot: raise AttributeError('Create an instance of KanesMethod with ' 'kinematic differential equations to use this method.') fr = self._form_fr(loads) frstar = self._form_frstar(bodies) if self._uaux: if not self._udep: km = KanesMethod(self._inertial, self.q, self._uaux, u_auxiliary=self._uaux) else: km = KanesMethod(self._inertial, self.q, self._uaux, u_auxiliary=self._uaux, u_dependent=self._udep, velocity_constraints=(self._k_nh * self.u + self._f_nh)) km._qdot_u_map = self._qdot_u_map self._km = km fraux = km._form_fr(loads) frstaraux = km._form_frstar(bodies) self._aux_eq = fraux + frstaraux self._fr = fr.col_join(fraux) self._frstar = frstar.col_join(frstaraux) return (self._fr, self._frstar) def rhs(self, inv_method=None): """Returns the system's equations of motion in first order form. The output is the right hand side of:: x' = |q'| =: f(q, u, r, p, t) |u'| The right hand side is what is needed by most numerical ODE integrators. Parameters ========== inv_method : str The specific sympy inverse matrix calculation method to use. For a list of valid methods, see :meth:`~sympy.matrices.matrices.MatrixBase.inv` """ rhs = zeros(len(self.q) + len(self.u), 1) kdes = self.kindiffdict() for i, q_i in enumerate(self.q): rhs[i] = kdes[q_i.diff()] if inv_method is None: rhs[len(self.q):, 0] = self.mass_matrix.LUsolve(self.forcing) else: rhs[len(self.q):, 0] = (self.mass_matrix.inv(inv_method, try_block_diag=True) * self.forcing) return rhs def kindiffdict(self): """Returns a dictionary mapping q' to u.""" if not self._qdot_u_map: raise AttributeError('Create an instance of KanesMethod with ' 'kinematic differential equations to use this method.') return self._qdot_u_map @property def auxiliary_eqs(self): """A matrix containing the auxiliary equations.""" if not self._fr or not self._frstar: raise ValueError('Need to compute Fr, Fr* first.') if not self._uaux: raise ValueError('No auxiliary speeds have been declared.') return self._aux_eq @property def mass_matrix(self): """The mass matrix of the system.""" if not self._fr or not self._frstar: raise ValueError('Need to compute Fr, Fr* first.') return Matrix([self._k_d, self._k_dnh]) @property def mass_matrix_full(self): """The mass matrix of the system, augmented by the kinematic differential equations.""" if not self._fr or not self._frstar: raise ValueError('Need to compute Fr, Fr* first.') o = len(self.u) n = len(self.q) return ((self._k_kqdot).row_join(zeros(n, o))).col_join((zeros(o, n)).row_join(self.mass_matrix)) @property def forcing(self): """The forcing vector of the system.""" if not self._fr or not self._frstar: raise ValueError('Need to compute Fr, Fr* first.') return -Matrix([self._f_d, self._f_dnh]) @property def forcing_full(self): """The forcing vector of the system, augmented by the kinematic differential equations.""" if not self._fr or not self._frstar: raise ValueError('Need to compute Fr, Fr* first.') f1 = self._k_ku * Matrix(self.u) + self._f_k return -Matrix([f1, self._f_d, self._f_dnh]) @property def q(self): return self._q @property def u(self): return self._u @property def bodylist(self): return self._bodylist @property def forcelist(self): return self._forcelist
f22b3a96f11a2e8c5c8a41642b3dce5516d56b92cdb5cc372972acb1638eaa8f
from sympy.core.backend import sympify from sympy.physics.vector import Point, ReferenceFrame, Dyadic from sympy.utilities.exceptions import SymPyDeprecationWarning __all__ = ['RigidBody'] class RigidBody: """An idealized rigid body. Explanation =========== This is essentially a container which holds the various components which describe a rigid body: a name, mass, center of mass, reference frame, and inertia. All of these need to be supplied on creation, but can be changed afterwards. Attributes ========== name : string The body's name. masscenter : Point The point which represents the center of mass of the rigid body. frame : ReferenceFrame The ReferenceFrame which the rigid body is fixed in. mass : Sympifyable The body's mass. inertia : (Dyadic, Point) The body's inertia about a point; stored in a tuple as shown above. Examples ======== >>> from sympy import Symbol >>> from sympy.physics.mechanics import ReferenceFrame, Point, RigidBody >>> from sympy.physics.mechanics import outer >>> m = Symbol('m') >>> A = ReferenceFrame('A') >>> P = Point('P') >>> I = outer (A.x, A.x) >>> inertia_tuple = (I, P) >>> B = RigidBody('B', P, A, m, inertia_tuple) >>> # Or you could change them afterwards >>> m2 = Symbol('m2') >>> B.mass = m2 """ def __init__(self, name, masscenter, frame, mass, inertia): if not isinstance(name, str): raise TypeError('Supply a valid name.') self._name = name self.masscenter = masscenter self.mass = mass self.frame = frame self.inertia = inertia self.potential_energy = 0 def __str__(self): return self._name def __repr__(self): return self.__str__() @property def frame(self): return self._frame @frame.setter def frame(self, F): if not isinstance(F, ReferenceFrame): raise TypeError("RigdBody frame must be a ReferenceFrame object.") self._frame = F @property def masscenter(self): return self._masscenter @masscenter.setter def masscenter(self, p): if not isinstance(p, Point): raise TypeError("RigidBody center of mass must be a Point object.") self._masscenter = p @property def mass(self): return self._mass @mass.setter def mass(self, m): self._mass = sympify(m) @property def inertia(self): return (self._inertia, self._inertia_point) @inertia.setter def inertia(self, I): if not isinstance(I[0], Dyadic): raise TypeError("RigidBody inertia must be a Dyadic object.") if not isinstance(I[1], Point): raise TypeError("RigidBody inertia must be about a Point.") self._inertia = I[0] self._inertia_point = I[1] # have I S/O, want I S/S* # I S/O = I S/S* + I S*/O; I S/S* = I S/O - I S*/O # I_S/S* = I_S/O - I_S*/O from sympy.physics.mechanics.functions import inertia_of_point_mass I_Ss_O = inertia_of_point_mass(self.mass, self.masscenter.pos_from(I[1]), self.frame) self._central_inertia = I[0] - I_Ss_O @property def central_inertia(self): """The body's central inertia dyadic.""" return self._central_inertia def linear_momentum(self, frame): """ Linear momentum of the rigid body. Explanation =========== The linear momentum L, of a rigid body B, with respect to frame N is given by L = M * v* where M is the mass of the rigid body and v* is the velocity of the mass center of B in the frame, N. Parameters ========== frame : ReferenceFrame The frame in which linear momentum is desired. Examples ======== >>> from sympy.physics.mechanics import Point, ReferenceFrame, outer >>> from sympy.physics.mechanics import RigidBody, dynamicsymbols >>> from sympy.physics.vector import init_vprinting >>> init_vprinting(pretty_print=False) >>> M, v = dynamicsymbols('M v') >>> N = ReferenceFrame('N') >>> P = Point('P') >>> P.set_vel(N, v * N.x) >>> I = outer (N.x, N.x) >>> Inertia_tuple = (I, P) >>> B = RigidBody('B', P, N, M, Inertia_tuple) >>> B.linear_momentum(N) M*v*N.x """ return self.mass * self.masscenter.vel(frame) def angular_momentum(self, point, frame): """Returns the angular momentum of the rigid body about a point in the given frame. Explanation =========== The angular momentum H of a rigid body B about some point O in a frame N is given by: H = I . w + r x Mv where I is the central inertia dyadic of B, w is the angular velocity of body B in the frame, N, r is the position vector from point O to the mass center of B, and v is the velocity of the mass center in the frame, N. Parameters ========== point : Point The point about which angular momentum is desired. frame : ReferenceFrame The frame in which angular momentum is desired. Examples ======== >>> from sympy.physics.mechanics import Point, ReferenceFrame, outer >>> from sympy.physics.mechanics import RigidBody, dynamicsymbols >>> from sympy.physics.vector import init_vprinting >>> init_vprinting(pretty_print=False) >>> M, v, r, omega = dynamicsymbols('M v r omega') >>> N = ReferenceFrame('N') >>> b = ReferenceFrame('b') >>> b.set_ang_vel(N, omega * b.x) >>> P = Point('P') >>> P.set_vel(N, 1 * N.x) >>> I = outer(b.x, b.x) >>> B = RigidBody('B', P, b, M, (I, P)) >>> B.angular_momentum(P, N) omega*b.x """ I = self.central_inertia w = self.frame.ang_vel_in(frame) m = self.mass r = self.masscenter.pos_from(point) v = self.masscenter.vel(frame) return I.dot(w) + r.cross(m * v) def kinetic_energy(self, frame): """Kinetic energy of the rigid body. Explanation =========== The kinetic energy, T, of a rigid body, B, is given by 'T = 1/2 (I omega^2 + m v^2)' where I and m are the central inertia dyadic and mass of rigid body B, respectively, omega is the body's angular velocity and v is the velocity of the body's mass center in the supplied ReferenceFrame. Parameters ========== frame : ReferenceFrame The RigidBody's angular velocity and the velocity of it's mass center are typically defined with respect to an inertial frame but any relevant frame in which the velocities are known can be supplied. Examples ======== >>> from sympy.physics.mechanics import Point, ReferenceFrame, outer >>> from sympy.physics.mechanics import RigidBody >>> from sympy import symbols >>> M, v, r, omega = symbols('M v r omega') >>> N = ReferenceFrame('N') >>> b = ReferenceFrame('b') >>> b.set_ang_vel(N, omega * b.x) >>> P = Point('P') >>> P.set_vel(N, v * N.x) >>> I = outer (b.x, b.x) >>> inertia_tuple = (I, P) >>> B = RigidBody('B', P, b, M, inertia_tuple) >>> B.kinetic_energy(N) M*v**2/2 + omega**2/2 """ rotational_KE = (self.frame.ang_vel_in(frame) & (self.central_inertia & self.frame.ang_vel_in(frame)) / sympify(2)) translational_KE = (self.mass * (self.masscenter.vel(frame) & self.masscenter.vel(frame)) / sympify(2)) return rotational_KE + translational_KE @property def potential_energy(self): """The potential energy of the RigidBody. Examples ======== >>> from sympy.physics.mechanics import RigidBody, Point, outer, ReferenceFrame >>> from sympy import symbols >>> M, g, h = symbols('M g h') >>> b = ReferenceFrame('b') >>> P = Point('P') >>> I = outer (b.x, b.x) >>> Inertia_tuple = (I, P) >>> B = RigidBody('B', P, b, M, Inertia_tuple) >>> B.potential_energy = M * g * h >>> B.potential_energy M*g*h """ return self._pe @potential_energy.setter def potential_energy(self, scalar): """Used to set the potential energy of this RigidBody. Parameters ========== scalar: Sympifyable The potential energy (a scalar) of the RigidBody. Examples ======== >>> from sympy.physics.mechanics import Point, outer >>> from sympy.physics.mechanics import RigidBody, ReferenceFrame >>> from sympy import symbols >>> b = ReferenceFrame('b') >>> M, g, h = symbols('M g h') >>> P = Point('P') >>> I = outer (b.x, b.x) >>> Inertia_tuple = (I, P) >>> B = RigidBody('B', P, b, M, Inertia_tuple) >>> B.potential_energy = M * g * h """ self._pe = sympify(scalar) def set_potential_energy(self, scalar): SymPyDeprecationWarning( feature="Method sympy.physics.mechanics." + "RigidBody.set_potential_energy(self, scalar)", useinstead="property sympy.physics.mechanics." + "RigidBody.potential_energy", deprecated_since_version="1.5", issue=9800).warn() self.potential_energy = scalar # XXX: To be consistent with the parallel_axis method in Particle this # should have a frame argument... def parallel_axis(self, point): """Returns the inertia dyadic of the body with respect to another point. Parameters ========== point : sympy.physics.vector.Point The point to express the inertia dyadic about. Returns ======= inertia : sympy.physics.vector.Dyadic The inertia dyadic of the rigid body expressed about the provided point. """ # circular import issue from sympy.physics.mechanics.functions import inertia a, b, c = self.masscenter.pos_from(point).to_matrix(self.frame) I = self.mass * inertia(self.frame, b**2 + c**2, c**2 + a**2, a**2 + b**2, -a * b, -b * c, -a * c) return self.central_inertia + I
4e392d5a0d9b76b4e98058caf92b0beaa46cf0c48e85f4eeb6a042c9945ff16b
from sympy.utilities import dict_merge from sympy.utilities.iterables import iterable from sympy.physics.vector import (Dyadic, Vector, ReferenceFrame, Point, dynamicsymbols) from sympy.physics.vector.printing import (vprint, vsprint, vpprint, vlatex, init_vprinting) from sympy.physics.mechanics.particle import Particle from sympy.physics.mechanics.rigidbody import RigidBody from sympy import simplify from sympy.core.backend import (Matrix, sympify, Mul, Derivative, sin, cos, tan, AppliedUndef, S) __all__ = ['inertia', 'inertia_of_point_mass', 'linear_momentum', 'angular_momentum', 'kinetic_energy', 'potential_energy', 'Lagrangian', 'mechanics_printing', 'mprint', 'msprint', 'mpprint', 'mlatex', 'msubs', 'find_dynamicsymbols'] # These are functions that we've moved and renamed during extracting the # basic vector calculus code from the mechanics packages. mprint = vprint msprint = vsprint mpprint = vpprint mlatex = vlatex def mechanics_printing(**kwargs): """ Initializes time derivative printing for all SymPy objects in mechanics module. """ init_vprinting(**kwargs) mechanics_printing.__doc__ = init_vprinting.__doc__ def inertia(frame, ixx, iyy, izz, ixy=0, iyz=0, izx=0): """Simple way to create inertia Dyadic object. Explanation =========== If you don't know what a Dyadic is, just treat this like the inertia tensor. Then, do the easy thing and define it in a body-fixed frame. Parameters ========== frame : ReferenceFrame The frame the inertia is defined in ixx : Sympifyable the xx element in the inertia dyadic iyy : Sympifyable the yy element in the inertia dyadic izz : Sympifyable the zz element in the inertia dyadic ixy : Sympifyable the xy element in the inertia dyadic iyz : Sympifyable the yz element in the inertia dyadic izx : Sympifyable the zx element in the inertia dyadic Examples ======== >>> from sympy.physics.mechanics import ReferenceFrame, inertia >>> N = ReferenceFrame('N') >>> inertia(N, 1, 2, 3) (N.x|N.x) + 2*(N.y|N.y) + 3*(N.z|N.z) """ if not isinstance(frame, ReferenceFrame): raise TypeError('Need to define the inertia in a frame') ol = sympify(ixx) * (frame.x | frame.x) ol += sympify(ixy) * (frame.x | frame.y) ol += sympify(izx) * (frame.x | frame.z) ol += sympify(ixy) * (frame.y | frame.x) ol += sympify(iyy) * (frame.y | frame.y) ol += sympify(iyz) * (frame.y | frame.z) ol += sympify(izx) * (frame.z | frame.x) ol += sympify(iyz) * (frame.z | frame.y) ol += sympify(izz) * (frame.z | frame.z) return ol def inertia_of_point_mass(mass, pos_vec, frame): """Inertia dyadic of a point mass relative to point O. Parameters ========== mass : Sympifyable Mass of the point mass pos_vec : Vector Position from point O to point mass frame : ReferenceFrame Reference frame to express the dyadic in Examples ======== >>> from sympy import symbols >>> from sympy.physics.mechanics import ReferenceFrame, inertia_of_point_mass >>> N = ReferenceFrame('N') >>> r, m = symbols('r m') >>> px = r * N.x >>> inertia_of_point_mass(m, px, N) m*r**2*(N.y|N.y) + m*r**2*(N.z|N.z) """ return mass * (((frame.x | frame.x) + (frame.y | frame.y) + (frame.z | frame.z)) * (pos_vec & pos_vec) - (pos_vec | pos_vec)) def linear_momentum(frame, *body): """Linear momentum of the system. Explanation =========== This function returns the linear momentum of a system of Particle's and/or RigidBody's. The linear momentum of a system is equal to the vector sum of the linear momentum of its constituents. Consider a system, S, comprised of a rigid body, A, and a particle, P. The linear momentum of the system, L, is equal to the vector sum of the linear momentum of the particle, L1, and the linear momentum of the rigid body, L2, i.e. L = L1 + L2 Parameters ========== frame : ReferenceFrame The frame in which linear momentum is desired. body1, body2, body3... : Particle and/or RigidBody The body (or bodies) whose linear momentum is required. Examples ======== >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame >>> from sympy.physics.mechanics import RigidBody, outer, linear_momentum >>> N = ReferenceFrame('N') >>> P = Point('P') >>> P.set_vel(N, 10 * N.x) >>> Pa = Particle('Pa', P, 1) >>> Ac = Point('Ac') >>> Ac.set_vel(N, 25 * N.y) >>> I = outer(N.x, N.x) >>> A = RigidBody('A', Ac, N, 20, (I, Ac)) >>> linear_momentum(N, A, Pa) 10*N.x + 500*N.y """ if not isinstance(frame, ReferenceFrame): raise TypeError('Please specify a valid ReferenceFrame') else: linear_momentum_sys = Vector(0) for e in body: if isinstance(e, (RigidBody, Particle)): linear_momentum_sys += e.linear_momentum(frame) else: raise TypeError('*body must have only Particle or RigidBody') return linear_momentum_sys def angular_momentum(point, frame, *body): """Angular momentum of a system. Explanation =========== This function returns the angular momentum of a system of Particle's and/or RigidBody's. The angular momentum of such a system is equal to the vector sum of the angular momentum of its constituents. Consider a system, S, comprised of a rigid body, A, and a particle, P. The angular momentum of the system, H, is equal to the vector sum of the angular momentum of the particle, H1, and the angular momentum of the rigid body, H2, i.e. H = H1 + H2 Parameters ========== point : Point The point about which angular momentum of the system is desired. frame : ReferenceFrame The frame in which angular momentum is desired. body1, body2, body3... : Particle and/or RigidBody The body (or bodies) whose angular momentum is required. Examples ======== >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame >>> from sympy.physics.mechanics import RigidBody, outer, angular_momentum >>> N = ReferenceFrame('N') >>> O = Point('O') >>> O.set_vel(N, 0 * N.x) >>> P = O.locatenew('P', 1 * N.x) >>> P.set_vel(N, 10 * N.x) >>> Pa = Particle('Pa', P, 1) >>> Ac = O.locatenew('Ac', 2 * N.y) >>> Ac.set_vel(N, 5 * N.y) >>> a = ReferenceFrame('a') >>> a.set_ang_vel(N, 10 * N.z) >>> I = outer(N.z, N.z) >>> A = RigidBody('A', Ac, a, 20, (I, Ac)) >>> angular_momentum(O, N, Pa, A) 10*N.z """ if not isinstance(frame, ReferenceFrame): raise TypeError('Please enter a valid ReferenceFrame') if not isinstance(point, Point): raise TypeError('Please specify a valid Point') else: angular_momentum_sys = Vector(0) for e in body: if isinstance(e, (RigidBody, Particle)): angular_momentum_sys += e.angular_momentum(point, frame) else: raise TypeError('*body must have only Particle or RigidBody') return angular_momentum_sys def kinetic_energy(frame, *body): """Kinetic energy of a multibody system. Explanation =========== This function returns the kinetic energy of a system of Particle's and/or RigidBody's. The kinetic energy of such a system is equal to the sum of the kinetic energies of its constituents. Consider a system, S, comprising a rigid body, A, and a particle, P. The kinetic energy of the system, T, is equal to the vector sum of the kinetic energy of the particle, T1, and the kinetic energy of the rigid body, T2, i.e. T = T1 + T2 Kinetic energy is a scalar. Parameters ========== frame : ReferenceFrame The frame in which the velocity or angular velocity of the body is defined. body1, body2, body3... : Particle and/or RigidBody The body (or bodies) whose kinetic energy is required. Examples ======== >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame >>> from sympy.physics.mechanics import RigidBody, outer, kinetic_energy >>> N = ReferenceFrame('N') >>> O = Point('O') >>> O.set_vel(N, 0 * N.x) >>> P = O.locatenew('P', 1 * N.x) >>> P.set_vel(N, 10 * N.x) >>> Pa = Particle('Pa', P, 1) >>> Ac = O.locatenew('Ac', 2 * N.y) >>> Ac.set_vel(N, 5 * N.y) >>> a = ReferenceFrame('a') >>> a.set_ang_vel(N, 10 * N.z) >>> I = outer(N.z, N.z) >>> A = RigidBody('A', Ac, a, 20, (I, Ac)) >>> kinetic_energy(N, Pa, A) 350 """ if not isinstance(frame, ReferenceFrame): raise TypeError('Please enter a valid ReferenceFrame') ke_sys = S.Zero for e in body: if isinstance(e, (RigidBody, Particle)): ke_sys += e.kinetic_energy(frame) else: raise TypeError('*body must have only Particle or RigidBody') return ke_sys def potential_energy(*body): """Potential energy of a multibody system. Explanation =========== This function returns the potential energy of a system of Particle's and/or RigidBody's. The potential energy of such a system is equal to the sum of the potential energy of its constituents. Consider a system, S, comprising a rigid body, A, and a particle, P. The potential energy of the system, V, is equal to the vector sum of the potential energy of the particle, V1, and the potential energy of the rigid body, V2, i.e. V = V1 + V2 Potential energy is a scalar. Parameters ========== body1, body2, body3... : Particle and/or RigidBody The body (or bodies) whose potential energy is required. Examples ======== >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame >>> from sympy.physics.mechanics import RigidBody, outer, potential_energy >>> from sympy import symbols >>> M, m, g, h = symbols('M m g h') >>> N = ReferenceFrame('N') >>> O = Point('O') >>> O.set_vel(N, 0 * N.x) >>> P = O.locatenew('P', 1 * N.x) >>> Pa = Particle('Pa', P, m) >>> Ac = O.locatenew('Ac', 2 * N.y) >>> a = ReferenceFrame('a') >>> I = outer(N.z, N.z) >>> A = RigidBody('A', Ac, a, M, (I, Ac)) >>> Pa.potential_energy = m * g * h >>> A.potential_energy = M * g * h >>> potential_energy(Pa, A) M*g*h + g*h*m """ pe_sys = S.Zero for e in body: if isinstance(e, (RigidBody, Particle)): pe_sys += e.potential_energy else: raise TypeError('*body must have only Particle or RigidBody') return pe_sys def gravity(acceleration, *bodies): """ Returns a list of gravity forces given the acceleration due to gravity and any number of particles or rigidbodies. Example ======= >>> from sympy.physics.mechanics import ReferenceFrame, Point, Particle, outer, RigidBody >>> from sympy.physics.mechanics.functions import gravity >>> from sympy import symbols >>> N = ReferenceFrame('N') >>> m, M, g = symbols('m M g') >>> F1, F2 = symbols('F1 F2') >>> po = Point('po') >>> pa = Particle('pa', po, m) >>> A = ReferenceFrame('A') >>> P = Point('P') >>> I = outer(A.x, A.x) >>> B = RigidBody('B', P, A, M, (I, P)) >>> forceList = [(po, F1), (P, F2)] >>> forceList.extend(gravity(g*N.y, pa, B)) >>> forceList [(po, F1), (P, F2), (po, g*m*N.y), (P, M*g*N.y)] """ gravity_force = [] if not bodies: raise TypeError("No bodies(instances of Particle or Rigidbody) were passed.") for e in bodies: point = getattr(e, 'masscenter', None) if point is None: point = e.point gravity_force.append((point, e.mass*acceleration)) return gravity_force def center_of_mass(point, *bodies): """ Returns the position vector from the given point to the center of mass of the given bodies(particles or rigidbodies). Example ======= >>> from sympy import symbols, S >>> from sympy.physics.vector import Point >>> from sympy.physics.mechanics import Particle, ReferenceFrame, RigidBody, outer >>> from sympy.physics.mechanics.functions import center_of_mass >>> a = ReferenceFrame('a') >>> m = symbols('m', real=True) >>> p1 = Particle('p1', Point('p1_pt'), S(1)) >>> p2 = Particle('p2', Point('p2_pt'), S(2)) >>> p3 = Particle('p3', Point('p3_pt'), S(3)) >>> p4 = Particle('p4', Point('p4_pt'), m) >>> b_f = ReferenceFrame('b_f') >>> b_cm = Point('b_cm') >>> mb = symbols('mb') >>> b = RigidBody('b', b_cm, b_f, mb, (outer(b_f.x, b_f.x), b_cm)) >>> p2.point.set_pos(p1.point, a.x) >>> p3.point.set_pos(p1.point, a.x + a.y) >>> p4.point.set_pos(p1.point, a.y) >>> b.masscenter.set_pos(p1.point, a.y + a.z) >>> point_o=Point('o') >>> point_o.set_pos(p1.point, center_of_mass(p1.point, p1, p2, p3, p4, b)) >>> expr = 5/(m + mb + 6)*a.x + (m + mb + 3)/(m + mb + 6)*a.y + mb/(m + mb + 6)*a.z >>> point_o.pos_from(p1.point) 5/(m + mb + 6)*a.x + (m + mb + 3)/(m + mb + 6)*a.y + mb/(m + mb + 6)*a.z """ if not bodies: raise TypeError("No bodies(instances of Particle or Rigidbody) were passed.") total_mass = 0 vec = Vector(0) for i in bodies: total_mass += i.mass masscenter = getattr(i, 'masscenter', None) if masscenter is None: masscenter = i.point vec += i.mass*masscenter.pos_from(point) return vec/total_mass def Lagrangian(frame, *body): """Lagrangian of a multibody system. Explanation =========== This function returns the Lagrangian of a system of Particle's and/or RigidBody's. The Lagrangian of such a system is equal to the difference between the kinetic energies and potential energies of its constituents. If T and V are the kinetic and potential energies of a system then it's Lagrangian, L, is defined as L = T - V The Lagrangian is a scalar. Parameters ========== frame : ReferenceFrame The frame in which the velocity or angular velocity of the body is defined to determine the kinetic energy. body1, body2, body3... : Particle and/or RigidBody The body (or bodies) whose Lagrangian is required. Examples ======== >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame >>> from sympy.physics.mechanics import RigidBody, outer, Lagrangian >>> from sympy import symbols >>> M, m, g, h = symbols('M m g h') >>> N = ReferenceFrame('N') >>> O = Point('O') >>> O.set_vel(N, 0 * N.x) >>> P = O.locatenew('P', 1 * N.x) >>> P.set_vel(N, 10 * N.x) >>> Pa = Particle('Pa', P, 1) >>> Ac = O.locatenew('Ac', 2 * N.y) >>> Ac.set_vel(N, 5 * N.y) >>> a = ReferenceFrame('a') >>> a.set_ang_vel(N, 10 * N.z) >>> I = outer(N.z, N.z) >>> A = RigidBody('A', Ac, a, 20, (I, Ac)) >>> Pa.potential_energy = m * g * h >>> A.potential_energy = M * g * h >>> Lagrangian(N, Pa, A) -M*g*h - g*h*m + 350 """ if not isinstance(frame, ReferenceFrame): raise TypeError('Please supply a valid ReferenceFrame') for e in body: if not isinstance(e, (RigidBody, Particle)): raise TypeError('*body must have only Particle or RigidBody') return kinetic_energy(frame, *body) - potential_energy(*body) def find_dynamicsymbols(expression, exclude=None, reference_frame=None): """Find all dynamicsymbols in expression. Explanation =========== If the optional ``exclude`` kwarg is used, only dynamicsymbols not in the iterable ``exclude`` are returned. If we intend to apply this function on a vector, the optional ``reference_frame`` is also used to inform about the corresponding frame with respect to which the dynamic symbols of the given vector is to be determined. Parameters ========== expression : sympy expression exclude : iterable of dynamicsymbols, optional reference_frame : ReferenceFrame, optional The frame with respect to which the dynamic symbols of the given vector is to be determined. Examples ======== >>> from sympy.physics.mechanics import dynamicsymbols, find_dynamicsymbols >>> from sympy.physics.mechanics import ReferenceFrame >>> x, y = dynamicsymbols('x, y') >>> expr = x + x.diff()*y >>> find_dynamicsymbols(expr) {x(t), y(t), Derivative(x(t), t)} >>> find_dynamicsymbols(expr, exclude=[x, y]) {Derivative(x(t), t)} >>> a, b, c = dynamicsymbols('a, b, c') >>> A = ReferenceFrame('A') >>> v = a * A.x + b * A.y + c * A.z >>> find_dynamicsymbols(v, reference_frame=A) {a(t), b(t), c(t)} """ t_set = {dynamicsymbols._t} if exclude: if iterable(exclude): exclude_set = set(exclude) else: raise TypeError("exclude kwarg must be iterable") else: exclude_set = set() if isinstance(expression, Vector): if reference_frame is None: raise ValueError("You must provide reference_frame when passing a " "vector expression, got %s." % reference_frame) else: expression = expression.to_matrix(reference_frame) return {i for i in expression.atoms(AppliedUndef, Derivative) if i.free_symbols == t_set} - exclude_set def msubs(expr, *sub_dicts, smart=False, **kwargs): """A custom subs for use on expressions derived in physics.mechanics. Traverses the expression tree once, performing the subs found in sub_dicts. Terms inside ``Derivative`` expressions are ignored: Examples ======== >>> from sympy.physics.mechanics import dynamicsymbols, msubs >>> x = dynamicsymbols('x') >>> msubs(x.diff() + x, {x: 1}) Derivative(x(t), t) + 1 Note that sub_dicts can be a single dictionary, or several dictionaries: >>> x, y, z = dynamicsymbols('x, y, z') >>> sub1 = {x: 1, y: 2} >>> sub2 = {z: 3, x.diff(): 4} >>> msubs(x.diff() + x + y + z, sub1, sub2) 10 If smart=True (default False), also checks for conditions that may result in ``nan``, but if simplified would yield a valid expression. For example: >>> from sympy import sin, tan >>> (sin(x)/tan(x)).subs(x, 0) nan >>> msubs(sin(x)/tan(x), {x: 0}, smart=True) 1 It does this by first replacing all ``tan`` with ``sin/cos``. Then each node is traversed. If the node is a fraction, subs is first evaluated on the denominator. If this results in 0, simplification of the entire fraction is attempted. Using this selective simplification, only subexpressions that result in 1/0 are targeted, resulting in faster performance. """ sub_dict = dict_merge(*sub_dicts) if smart: func = _smart_subs elif hasattr(expr, 'msubs'): return expr.msubs(sub_dict) else: func = lambda expr, sub_dict: _crawl(expr, _sub_func, sub_dict) if isinstance(expr, (Matrix, Vector, Dyadic)): return expr.applyfunc(lambda x: func(x, sub_dict)) else: return func(expr, sub_dict) def _crawl(expr, func, *args, **kwargs): """Crawl the expression tree, and apply func to every node.""" val = func(expr, *args, **kwargs) if val is not None: return val new_args = (_crawl(arg, func, *args, **kwargs) for arg in expr.args) return expr.func(*new_args) def _sub_func(expr, sub_dict): """Perform direct matching substitution, ignoring derivatives.""" if expr in sub_dict: return sub_dict[expr] elif not expr.args or expr.is_Derivative: return expr def _tan_repl_func(expr): """Replace tan with sin/cos.""" if isinstance(expr, tan): return sin(*expr.args) / cos(*expr.args) elif not expr.args or expr.is_Derivative: return expr def _smart_subs(expr, sub_dict): """Performs subs, checking for conditions that may result in `nan` or `oo`, and attempts to simplify them out. The expression tree is traversed twice, and the following steps are performed on each expression node: - First traverse: Replace all `tan` with `sin/cos`. - Second traverse: If node is a fraction, check if the denominator evaluates to 0. If so, attempt to simplify it out. Then if node is in sub_dict, sub in the corresponding value.""" expr = _crawl(expr, _tan_repl_func) def _recurser(expr, sub_dict): # Decompose the expression into num, den num, den = _fraction_decomp(expr) if den != 1: # If there is a non trivial denominator, we need to handle it denom_subbed = _recurser(den, sub_dict) if denom_subbed.evalf() == 0: # If denom is 0 after this, attempt to simplify the bad expr expr = simplify(expr) else: # Expression won't result in nan, find numerator num_subbed = _recurser(num, sub_dict) return num_subbed / denom_subbed # We have to crawl the tree manually, because `expr` may have been # modified in the simplify step. First, perform subs as normal: val = _sub_func(expr, sub_dict) if val is not None: return val new_args = (_recurser(arg, sub_dict) for arg in expr.args) return expr.func(*new_args) return _recurser(expr, sub_dict) def _fraction_decomp(expr): """Return num, den such that expr = num/den""" if not isinstance(expr, Mul): return expr, 1 num = [] den = [] for a in expr.args: if a.is_Pow and a.args[1] < 0: den.append(1 / a) else: num.append(a) if not den: return expr, 1 num = Mul(*num) den = Mul(*den) return num, den def _f_list_parser(fl, ref_frame): """Parses the provided forcelist composed of items of the form (obj, force). Returns a tuple containing: vel_list: The velocity (ang_vel for Frames, vel for Points) in the provided reference frame. f_list: The forces. Used internally in the KanesMethod and LagrangesMethod classes. """ def flist_iter(): for pair in fl: obj, force = pair if isinstance(obj, ReferenceFrame): yield obj.ang_vel_in(ref_frame), force elif isinstance(obj, Point): yield obj.vel(ref_frame), force else: raise TypeError('First entry in each forcelist pair must ' 'be a point or frame.') if not fl: vel_list, f_list = (), () else: unzip = lambda l: list(zip(*l)) if l[0] else [(), ()] vel_list, f_list = unzip(list(flist_iter())) return vel_list, f_list
08b5f8a8cbe7792fe326a9c87dc838c60d3af9d80fab7e192d7843947668165e
__all__ = ['Linearizer'] from sympy.core.backend import Matrix, eye, zeros from sympy.core.compatibility import Iterable from sympy import Dummy from sympy.utilities.iterables import flatten from sympy.physics.vector import dynamicsymbols from sympy.physics.mechanics.functions import msubs from collections import namedtuple class Linearizer: """This object holds the general model form for a dynamic system. This model is used for computing the linearized form of the system, while properly dealing with constraints leading to dependent coordinates and speeds. Attributes ========== f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a : Matrix Matrices holding the general system form. q, u, r : Matrix Matrices holding the generalized coordinates, speeds, and input vectors. q_i, u_i : Matrix Matrices of the independent generalized coordinates and speeds. q_d, u_d : Matrix Matrices of the dependent generalized coordinates and speeds. perm_mat : Matrix Permutation matrix such that [q_ind, u_ind]^T = perm_mat*[q, u]^T """ def __init__(self, f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a, q, u, q_i=None, q_d=None, u_i=None, u_d=None, r=None, lams=None): """ Parameters ========== f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a : array_like System of equations holding the general system form. Supply empty array or Matrix if the parameter doesn't exist. q : array_like The generalized coordinates. u : array_like The generalized speeds q_i, u_i : array_like, optional The independent generalized coordinates and speeds. q_d, u_d : array_like, optional The dependent generalized coordinates and speeds. r : array_like, optional The input variables. lams : array_like, optional The lagrange multipliers """ # Generalized equation form self.f_0 = Matrix(f_0) self.f_1 = Matrix(f_1) self.f_2 = Matrix(f_2) self.f_3 = Matrix(f_3) self.f_4 = Matrix(f_4) self.f_c = Matrix(f_c) self.f_v = Matrix(f_v) self.f_a = Matrix(f_a) # Generalized equation variables self.q = Matrix(q) self.u = Matrix(u) none_handler = lambda x: Matrix(x) if x else Matrix() self.q_i = none_handler(q_i) self.q_d = none_handler(q_d) self.u_i = none_handler(u_i) self.u_d = none_handler(u_d) self.r = none_handler(r) self.lams = none_handler(lams) # Derivatives of generalized equation variables self._qd = self.q.diff(dynamicsymbols._t) self._ud = self.u.diff(dynamicsymbols._t) # If the user doesn't actually use generalized variables, and the # qd and u vectors have any intersecting variables, this can cause # problems. We'll fix this with some hackery, and Dummy variables dup_vars = set(self._qd).intersection(self.u) self._qd_dup = Matrix([var if var not in dup_vars else Dummy() for var in self._qd]) # Derive dimesion terms l = len(self.f_c) m = len(self.f_v) n = len(self.q) o = len(self.u) s = len(self.r) k = len(self.lams) dims = namedtuple('dims', ['l', 'm', 'n', 'o', 's', 'k']) self._dims = dims(l, m, n, o, s, k) self._setup_done = False def _setup(self): # Calculations here only need to be run once. They are moved out of # the __init__ method to increase the speed of Linearizer creation. self._form_permutation_matrices() self._form_block_matrices() self._form_coefficient_matrices() self._setup_done = True def _form_permutation_matrices(self): """Form the permutation matrices Pq and Pu.""" # Extract dimension variables l, m, n, o, s, k = self._dims # Compute permutation matrices if n != 0: self._Pq = permutation_matrix(self.q, Matrix([self.q_i, self.q_d])) if l > 0: self._Pqi = self._Pq[:, :-l] self._Pqd = self._Pq[:, -l:] else: self._Pqi = self._Pq self._Pqd = Matrix() if o != 0: self._Pu = permutation_matrix(self.u, Matrix([self.u_i, self.u_d])) if m > 0: self._Pui = self._Pu[:, :-m] self._Pud = self._Pu[:, -m:] else: self._Pui = self._Pu self._Pud = Matrix() # Compute combination permutation matrix for computing A and B P_col1 = Matrix([self._Pqi, zeros(o + k, n - l)]) P_col2 = Matrix([zeros(n, o - m), self._Pui, zeros(k, o - m)]) if P_col1: if P_col2: self.perm_mat = P_col1.row_join(P_col2) else: self.perm_mat = P_col1 else: self.perm_mat = P_col2 def _form_coefficient_matrices(self): """Form the coefficient matrices C_0, C_1, and C_2.""" # Extract dimension variables l, m, n, o, s, k = self._dims # Build up the coefficient matrices C_0, C_1, and C_2 # If there are configuration constraints (l > 0), form C_0 as normal. # If not, C_0 is I_(nxn). Note that this works even if n=0 if l > 0: f_c_jac_q = self.f_c.jacobian(self.q) self._C_0 = (eye(n) - self._Pqd * (f_c_jac_q * self._Pqd).LUsolve(f_c_jac_q)) * self._Pqi else: self._C_0 = eye(n) # If there are motion constraints (m > 0), form C_1 and C_2 as normal. # If not, C_1 is 0, and C_2 is I_(oxo). Note that this works even if # o = 0. if m > 0: f_v_jac_u = self.f_v.jacobian(self.u) temp = f_v_jac_u * self._Pud if n != 0: f_v_jac_q = self.f_v.jacobian(self.q) self._C_1 = -self._Pud * temp.LUsolve(f_v_jac_q) else: self._C_1 = zeros(o, n) self._C_2 = (eye(o) - self._Pud * temp.LUsolve(f_v_jac_u)) * self._Pui else: self._C_1 = zeros(o, n) self._C_2 = eye(o) def _form_block_matrices(self): """Form the block matrices for composing M, A, and B.""" # Extract dimension variables l, m, n, o, s, k = self._dims # Block Matrix Definitions. These are only defined if under certain # conditions. If undefined, an empty matrix is used instead if n != 0: self._M_qq = self.f_0.jacobian(self._qd) self._A_qq = -(self.f_0 + self.f_1).jacobian(self.q) else: self._M_qq = Matrix() self._A_qq = Matrix() if n != 0 and m != 0: self._M_uqc = self.f_a.jacobian(self._qd_dup) self._A_uqc = -self.f_a.jacobian(self.q) else: self._M_uqc = Matrix() self._A_uqc = Matrix() if n != 0 and o - m + k != 0: self._M_uqd = self.f_3.jacobian(self._qd_dup) self._A_uqd = -(self.f_2 + self.f_3 + self.f_4).jacobian(self.q) else: self._M_uqd = Matrix() self._A_uqd = Matrix() if o != 0 and m != 0: self._M_uuc = self.f_a.jacobian(self._ud) self._A_uuc = -self.f_a.jacobian(self.u) else: self._M_uuc = Matrix() self._A_uuc = Matrix() if o != 0 and o - m + k != 0: self._M_uud = self.f_2.jacobian(self._ud) self._A_uud = -(self.f_2 + self.f_3).jacobian(self.u) else: self._M_uud = Matrix() self._A_uud = Matrix() if o != 0 and n != 0: self._A_qu = -self.f_1.jacobian(self.u) else: self._A_qu = Matrix() if k != 0 and o - m + k != 0: self._M_uld = self.f_4.jacobian(self.lams) else: self._M_uld = Matrix() if s != 0 and o - m + k != 0: self._B_u = -self.f_3.jacobian(self.r) else: self._B_u = Matrix() def linearize(self, op_point=None, A_and_B=False, simplify=False): """Linearize the system about the operating point. Note that q_op, u_op, qd_op, ud_op must satisfy the equations of motion. These may be either symbolic or numeric. Parameters ========== op_point : dict or iterable of dicts, optional Dictionary or iterable of dictionaries containing the operating point conditions. These will be substituted in to the linearized system before the linearization is complete. Leave blank if you want a completely symbolic form. Note that any reduction in symbols (whether substituted for numbers or expressions with a common parameter) will result in faster runtime. A_and_B : bool, optional If A_and_B=False (default), (M, A, B) is returned for forming [M]*[q, u]^T = [A]*[q_ind, u_ind]^T + [B]r. If A_and_B=True, (A, B) is returned for forming dx = [A]x + [B]r, where x = [q_ind, u_ind]^T. simplify : bool, optional Determines if returned values are simplified before return. For large expressions this may be time consuming. Default is False. Potential Issues ================ Note that the process of solving with A_and_B=True is computationally intensive if there are many symbolic parameters. For this reason, it may be more desirable to use the default A_and_B=False, returning M, A, and B. More values may then be substituted in to these matrices later on. The state space form can then be found as A = P.T*M.LUsolve(A), B = P.T*M.LUsolve(B), where P = Linearizer.perm_mat. """ # Run the setup if needed: if not self._setup_done: self._setup() # Compose dict of operating conditions if isinstance(op_point, dict): op_point_dict = op_point elif isinstance(op_point, Iterable): op_point_dict = {} for op in op_point: op_point_dict.update(op) else: op_point_dict = {} # Extract dimension variables l, m, n, o, s, k = self._dims # Rename terms to shorten expressions M_qq = self._M_qq M_uqc = self._M_uqc M_uqd = self._M_uqd M_uuc = self._M_uuc M_uud = self._M_uud M_uld = self._M_uld A_qq = self._A_qq A_uqc = self._A_uqc A_uqd = self._A_uqd A_qu = self._A_qu A_uuc = self._A_uuc A_uud = self._A_uud B_u = self._B_u C_0 = self._C_0 C_1 = self._C_1 C_2 = self._C_2 # Build up Mass Matrix # |M_qq 0_nxo 0_nxk| # M = |M_uqc M_uuc 0_mxk| # |M_uqd M_uud M_uld| if o != 0: col2 = Matrix([zeros(n, o), M_uuc, M_uud]) if k != 0: col3 = Matrix([zeros(n + m, k), M_uld]) if n != 0: col1 = Matrix([M_qq, M_uqc, M_uqd]) if o != 0 and k != 0: M = col1.row_join(col2).row_join(col3) elif o != 0: M = col1.row_join(col2) else: M = col1 elif k != 0: M = col2.row_join(col3) else: M = col2 M_eq = msubs(M, op_point_dict) # Build up state coefficient matrix A # |(A_qq + A_qu*C_1)*C_0 A_qu*C_2| # A = |(A_uqc + A_uuc*C_1)*C_0 A_uuc*C_2| # |(A_uqd + A_uud*C_1)*C_0 A_uud*C_2| # Col 1 is only defined if n != 0 if n != 0: r1c1 = A_qq if o != 0: r1c1 += (A_qu * C_1) r1c1 = r1c1 * C_0 if m != 0: r2c1 = A_uqc if o != 0: r2c1 += (A_uuc * C_1) r2c1 = r2c1 * C_0 else: r2c1 = Matrix() if o - m + k != 0: r3c1 = A_uqd if o != 0: r3c1 += (A_uud * C_1) r3c1 = r3c1 * C_0 else: r3c1 = Matrix() col1 = Matrix([r1c1, r2c1, r3c1]) else: col1 = Matrix() # Col 2 is only defined if o != 0 if o != 0: if n != 0: r1c2 = A_qu * C_2 else: r1c2 = Matrix() if m != 0: r2c2 = A_uuc * C_2 else: r2c2 = Matrix() if o - m + k != 0: r3c2 = A_uud * C_2 else: r3c2 = Matrix() col2 = Matrix([r1c2, r2c2, r3c2]) else: col2 = Matrix() if col1: if col2: Amat = col1.row_join(col2) else: Amat = col1 else: Amat = col2 Amat_eq = msubs(Amat, op_point_dict) # Build up the B matrix if there are forcing variables # |0_(n + m)xs| # B = |B_u | if s != 0 and o - m + k != 0: Bmat = zeros(n + m, s).col_join(B_u) Bmat_eq = msubs(Bmat, op_point_dict) else: Bmat_eq = Matrix() # kwarg A_and_B indicates to return A, B for forming the equation # dx = [A]x + [B]r, where x = [q_indnd, u_indnd]^T, if A_and_B: A_cont = self.perm_mat.T * M_eq.LUsolve(Amat_eq) if Bmat_eq: B_cont = self.perm_mat.T * M_eq.LUsolve(Bmat_eq) else: # Bmat = Matrix([]), so no need to sub B_cont = Bmat_eq if simplify: A_cont.simplify() B_cont.simplify() return A_cont, B_cont # Otherwise return M, A, B for forming the equation # [M]dx = [A]x + [B]r, where x = [q, u]^T else: if simplify: M_eq.simplify() Amat_eq.simplify() Bmat_eq.simplify() return M_eq, Amat_eq, Bmat_eq def permutation_matrix(orig_vec, per_vec): """Compute the permutation matrix to change order of orig_vec into order of per_vec. Parameters ========== orig_vec : array_like Symbols in original ordering. per_vec : array_like Symbols in new ordering. Returns ======= p_matrix : Matrix Permutation matrix such that orig_vec == (p_matrix * per_vec). """ if not isinstance(orig_vec, (list, tuple)): orig_vec = flatten(orig_vec) if not isinstance(per_vec, (list, tuple)): per_vec = flatten(per_vec) if set(orig_vec) != set(per_vec): raise ValueError("orig_vec and per_vec must be the same length, " + "and contain the same symbols.") ind_list = [orig_vec.index(i) for i in per_vec] p_matrix = zeros(len(orig_vec)) for i, j in enumerate(ind_list): p_matrix[i, j] = 1 return p_matrix
77ffc9629c2bd9a0709641ec25d2a098263dd73e1d2ee6abc482bdb1be4b81f5
from sympy.core.backend import diff, zeros, Matrix, eye, sympify from sympy.physics.vector import dynamicsymbols, ReferenceFrame from sympy.physics.mechanics.functions import (find_dynamicsymbols, msubs, _f_list_parser) from sympy.physics.mechanics.linearize import Linearizer from sympy.utilities import default_sort_key from sympy.utilities.iterables import iterable __all__ = ['LagrangesMethod'] class LagrangesMethod: """Lagrange's method object. Explanation =========== This object generates the equations of motion in a two step procedure. The first step involves the initialization of LagrangesMethod by supplying the Lagrangian and the generalized coordinates, at the bare minimum. If there are any constraint equations, they can be supplied as keyword arguments. The Lagrange multipliers are automatically generated and are equal in number to the constraint equations. Similarly any non-conservative forces can be supplied in an iterable (as described below and also shown in the example) along with a ReferenceFrame. This is also discussed further in the __init__ method. Attributes ========== q, u : Matrix Matrices of the generalized coordinates and speeds forcelist : iterable Iterable of (Point, vector) or (ReferenceFrame, vector) tuples describing the forces on the system. bodies : iterable Iterable containing the rigid bodies and particles of the system. mass_matrix : Matrix The system's mass matrix forcing : Matrix The system's forcing vector mass_matrix_full : Matrix The "mass matrix" for the qdot's, qdoubledot's, and the lagrange multipliers (lam) forcing_full : Matrix The forcing vector for the qdot's, qdoubledot's and lagrange multipliers (lam) Examples ======== This is a simple example for a one degree of freedom translational spring-mass-damper. In this example, we first need to do the kinematics. This involves creating generalized coordinates and their derivatives. Then we create a point and set its velocity in a frame. >>> from sympy.physics.mechanics import LagrangesMethod, Lagrangian >>> from sympy.physics.mechanics import ReferenceFrame, Particle, Point >>> from sympy.physics.mechanics import dynamicsymbols >>> from sympy import symbols >>> q = dynamicsymbols('q') >>> qd = dynamicsymbols('q', 1) >>> m, k, b = symbols('m k b') >>> N = ReferenceFrame('N') >>> P = Point('P') >>> P.set_vel(N, qd * N.x) We need to then prepare the information as required by LagrangesMethod to generate equations of motion. First we create the Particle, which has a point attached to it. Following this the lagrangian is created from the kinetic and potential energies. Then, an iterable of nonconservative forces/torques must be constructed, where each item is a (Point, Vector) or (ReferenceFrame, Vector) tuple, with the Vectors representing the nonconservative forces or torques. >>> Pa = Particle('Pa', P, m) >>> Pa.potential_energy = k * q**2 / 2.0 >>> L = Lagrangian(N, Pa) >>> fl = [(P, -b * qd * N.x)] Finally we can generate the equations of motion. First we create the LagrangesMethod object. To do this one must supply the Lagrangian, and the generalized coordinates. The constraint equations, the forcelist, and the inertial frame may also be provided, if relevant. Next we generate Lagrange's equations of motion, such that: Lagrange's equations of motion = 0. We have the equations of motion at this point. >>> l = LagrangesMethod(L, [q], forcelist = fl, frame = N) >>> print(l.form_lagranges_equations()) Matrix([[b*Derivative(q(t), t) + 1.0*k*q(t) + m*Derivative(q(t), (t, 2))]]) We can also solve for the states using the 'rhs' method. >>> print(l.rhs()) Matrix([[Derivative(q(t), t)], [(-b*Derivative(q(t), t) - 1.0*k*q(t))/m]]) Please refer to the docstrings on each method for more details. """ def __init__(self, Lagrangian, qs, forcelist=None, bodies=None, frame=None, hol_coneqs=None, nonhol_coneqs=None): """Supply the following for the initialization of LagrangesMethod. Lagrangian : Sympifyable qs : array_like The generalized coordinates hol_coneqs : array_like, optional The holonomic constraint equations nonhol_coneqs : array_like, optional The nonholonomic constraint equations forcelist : iterable, optional Takes an iterable of (Point, Vector) or (ReferenceFrame, Vector) tuples which represent the force at a point or torque on a frame. This feature is primarily to account for the nonconservative forces and/or moments. bodies : iterable, optional Takes an iterable containing the rigid bodies and particles of the system. frame : ReferenceFrame, optional Supply the inertial frame. This is used to determine the generalized forces due to non-conservative forces. """ self._L = Matrix([sympify(Lagrangian)]) self.eom = None self._m_cd = Matrix() # Mass Matrix of differentiated coneqs self._m_d = Matrix() # Mass Matrix of dynamic equations self._f_cd = Matrix() # Forcing part of the diff coneqs self._f_d = Matrix() # Forcing part of the dynamic equations self.lam_coeffs = Matrix() # The coeffecients of the multipliers forcelist = forcelist if forcelist else [] if not iterable(forcelist): raise TypeError('Force pairs must be supplied in an iterable.') self._forcelist = forcelist if frame and not isinstance(frame, ReferenceFrame): raise TypeError('frame must be a valid ReferenceFrame') self._bodies = bodies self.inertial = frame self.lam_vec = Matrix() self._term1 = Matrix() self._term2 = Matrix() self._term3 = Matrix() self._term4 = Matrix() # Creating the qs, qdots and qdoubledots if not iterable(qs): raise TypeError('Generalized coordinates must be an iterable') self._q = Matrix(qs) self._qdots = self.q.diff(dynamicsymbols._t) self._qdoubledots = self._qdots.diff(dynamicsymbols._t) mat_build = lambda x: Matrix(x) if x else Matrix() hol_coneqs = mat_build(hol_coneqs) nonhol_coneqs = mat_build(nonhol_coneqs) self.coneqs = Matrix([hol_coneqs.diff(dynamicsymbols._t), nonhol_coneqs]) self._hol_coneqs = hol_coneqs def form_lagranges_equations(self): """Method to form Lagrange's equations of motion. Returns a vector of equations of motion using Lagrange's equations of the second kind. """ qds = self._qdots qdd_zero = {i: 0 for i in self._qdoubledots} n = len(self.q) # Internally we represent the EOM as four terms: # EOM = term1 - term2 - term3 - term4 = 0 # First term self._term1 = self._L.jacobian(qds) self._term1 = self._term1.diff(dynamicsymbols._t).T # Second term self._term2 = self._L.jacobian(self.q).T # Third term if self.coneqs: coneqs = self.coneqs m = len(coneqs) # Creating the multipliers self.lam_vec = Matrix(dynamicsymbols('lam1:' + str(m + 1))) self.lam_coeffs = -coneqs.jacobian(qds) self._term3 = self.lam_coeffs.T * self.lam_vec # Extracting the coeffecients of the qdds from the diff coneqs diffconeqs = coneqs.diff(dynamicsymbols._t) self._m_cd = diffconeqs.jacobian(self._qdoubledots) # The remaining terms i.e. the 'forcing' terms in diff coneqs self._f_cd = -diffconeqs.subs(qdd_zero) else: self._term3 = zeros(n, 1) # Fourth term if self.forcelist: N = self.inertial self._term4 = zeros(n, 1) for i, qd in enumerate(qds): flist = zip(*_f_list_parser(self.forcelist, N)) self._term4[i] = sum(v.diff(qd, N) & f for (v, f) in flist) else: self._term4 = zeros(n, 1) # Form the dynamic mass and forcing matrices without_lam = self._term1 - self._term2 - self._term4 self._m_d = without_lam.jacobian(self._qdoubledots) self._f_d = -without_lam.subs(qdd_zero) # Form the EOM self.eom = without_lam - self._term3 return self.eom @property def mass_matrix(self): """Returns the mass matrix, which is augmented by the Lagrange multipliers, if necessary. Explanation =========== If the system is described by 'n' generalized coordinates and there are no constraint equations then an n X n matrix is returned. If there are 'n' generalized coordinates and 'm' constraint equations have been supplied during initialization then an n X (n+m) matrix is returned. The (n + m - 1)th and (n + m)th columns contain the coefficients of the Lagrange multipliers. """ if self.eom is None: raise ValueError('Need to compute the equations of motion first') if self.coneqs: return (self._m_d).row_join(self.lam_coeffs.T) else: return self._m_d @property def mass_matrix_full(self): """Augments the coefficients of qdots to the mass_matrix.""" if self.eom is None: raise ValueError('Need to compute the equations of motion first') n = len(self.q) m = len(self.coneqs) row1 = eye(n).row_join(zeros(n, n + m)) row2 = zeros(n, n).row_join(self.mass_matrix) if self.coneqs: row3 = zeros(m, n).row_join(self._m_cd).row_join(zeros(m, m)) return row1.col_join(row2).col_join(row3) else: return row1.col_join(row2) @property def forcing(self): """Returns the forcing vector from 'lagranges_equations' method.""" if self.eom is None: raise ValueError('Need to compute the equations of motion first') return self._f_d @property def forcing_full(self): """Augments qdots to the forcing vector above.""" if self.eom is None: raise ValueError('Need to compute the equations of motion first') if self.coneqs: return self._qdots.col_join(self.forcing).col_join(self._f_cd) else: return self._qdots.col_join(self.forcing) def to_linearizer(self, q_ind=None, qd_ind=None, q_dep=None, qd_dep=None): """Returns an instance of the Linearizer class, initiated from the data in the LagrangesMethod class. This may be more desirable than using the linearize class method, as the Linearizer object will allow more efficient recalculation (i.e. about varying operating points). Parameters ========== q_ind, qd_ind : array_like, optional The independent generalized coordinates and speeds. q_dep, qd_dep : array_like, optional The dependent generalized coordinates and speeds. """ # Compose vectors t = dynamicsymbols._t q = self.q u = self._qdots ud = u.diff(t) # Get vector of lagrange multipliers lams = self.lam_vec mat_build = lambda x: Matrix(x) if x else Matrix() q_i = mat_build(q_ind) q_d = mat_build(q_dep) u_i = mat_build(qd_ind) u_d = mat_build(qd_dep) # Compose general form equations f_c = self._hol_coneqs f_v = self.coneqs f_a = f_v.diff(t) f_0 = u f_1 = -u f_2 = self._term1 f_3 = -(self._term2 + self._term4) f_4 = -self._term3 # Check that there are an appropriate number of independent and # dependent coordinates if len(q_d) != len(f_c) or len(u_d) != len(f_v): raise ValueError(("Must supply {:} dependent coordinates, and " + "{:} dependent speeds").format(len(f_c), len(f_v))) if set(Matrix([q_i, q_d])) != set(q): raise ValueError("Must partition q into q_ind and q_dep, with " + "no extra or missing symbols.") if set(Matrix([u_i, u_d])) != set(u): raise ValueError("Must partition qd into qd_ind and qd_dep, " + "with no extra or missing symbols.") # Find all other dynamic symbols, forming the forcing vector r. # Sort r to make it canonical. insyms = set(Matrix([q, u, ud, lams])) r = list(find_dynamicsymbols(f_3, insyms)) r.sort(key=default_sort_key) # Check for any derivatives of variables in r that are also found in r. for i in r: if diff(i, dynamicsymbols._t) in r: raise ValueError('Cannot have derivatives of specified \ quantities when linearizing forcing terms.') return Linearizer(f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a, q, u, q_i, q_d, u_i, u_d, r, lams) def linearize(self, q_ind=None, qd_ind=None, q_dep=None, qd_dep=None, **kwargs): """Linearize the equations of motion about a symbolic operating point. Explanation =========== If kwarg A_and_B is False (default), returns M, A, B, r for the linearized form, M*[q', u']^T = A*[q_ind, u_ind]^T + B*r. If kwarg A_and_B is True, returns A, B, r for the linearized form dx = A*x + B*r, where x = [q_ind, u_ind]^T. Note that this is computationally intensive if there are many symbolic parameters. For this reason, it may be more desirable to use the default A_and_B=False, returning M, A, and B. Values may then be substituted in to these matrices, and the state space form found as A = P.T*M.inv()*A, B = P.T*M.inv()*B, where P = Linearizer.perm_mat. In both cases, r is found as all dynamicsymbols in the equations of motion that are not part of q, u, q', or u'. They are sorted in canonical form. The operating points may be also entered using the ``op_point`` kwarg. This takes a dictionary of {symbol: value}, or a an iterable of such dictionaries. The values may be numeric or symbolic. The more values you can specify beforehand, the faster this computation will run. For more documentation, please see the ``Linearizer`` class.""" linearizer = self.to_linearizer(q_ind, qd_ind, q_dep, qd_dep) result = linearizer.linearize(**kwargs) return result + (linearizer.r,) def solve_multipliers(self, op_point=None, sol_type='dict'): """Solves for the values of the lagrange multipliers symbolically at the specified operating point. Parameters ========== op_point : dict or iterable of dicts, optional Point at which to solve at. The operating point is specified as a dictionary or iterable of dictionaries of {symbol: value}. The value may be numeric or symbolic itself. sol_type : str, optional Solution return type. Valid options are: - 'dict': A dict of {symbol : value} (default) - 'Matrix': An ordered column matrix of the solution """ # Determine number of multipliers k = len(self.lam_vec) if k == 0: raise ValueError("System has no lagrange multipliers to solve for.") # Compose dict of operating conditions if isinstance(op_point, dict): op_point_dict = op_point elif iterable(op_point): op_point_dict = {} for op in op_point: op_point_dict.update(op) elif op_point is None: op_point_dict = {} else: raise TypeError("op_point must be either a dictionary or an " "iterable of dictionaries.") # Compose the system to be solved mass_matrix = self.mass_matrix.col_join(-self.lam_coeffs.row_join( zeros(k, k))) force_matrix = self.forcing.col_join(self._f_cd) # Sub in the operating point mass_matrix = msubs(mass_matrix, op_point_dict) force_matrix = msubs(force_matrix, op_point_dict) # Solve for the multipliers sol_list = mass_matrix.LUsolve(-force_matrix)[-k:] if sol_type == 'dict': return dict(zip(self.lam_vec, sol_list)) elif sol_type == 'Matrix': return Matrix(sol_list) else: raise ValueError("Unknown sol_type {:}.".format(sol_type)) def rhs(self, inv_method=None, **kwargs): """Returns equations that can be solved numerically. Parameters ========== inv_method : str The specific sympy inverse matrix calculation method to use. For a list of valid methods, see :meth:`~sympy.matrices.matrices.MatrixBase.inv` """ if inv_method is None: self._rhs = self.mass_matrix_full.LUsolve(self.forcing_full) else: self._rhs = (self.mass_matrix_full.inv(inv_method, try_block_diag=True) * self.forcing_full) return self._rhs @property def q(self): return self._q @property def u(self): return self._qdots @property def bodies(self): return self._bodies @property def forcelist(self): return self._forcelist
040ece4e773a70f5724c69a7b0cb09315ded0400f9d7a620e12c0b592cad741c
from sympy.core.backend import sympify from sympy.physics.vector import Point from sympy.utilities.exceptions import SymPyDeprecationWarning __all__ = ['Particle'] class Particle: """A particle. Explanation =========== Particles have a non-zero mass and lack spatial extension; they take up no space. Values need to be supplied on initialization, but can be changed later. Parameters ========== name : str Name of particle point : Point A physics/mechanics Point which represents the position, velocity, and acceleration of this Particle mass : sympifyable A SymPy expression representing the Particle's mass Examples ======== >>> from sympy.physics.mechanics import Particle, Point >>> from sympy import Symbol >>> po = Point('po') >>> m = Symbol('m') >>> pa = Particle('pa', po, m) >>> # Or you could change these later >>> pa.mass = m >>> pa.point = po """ def __init__(self, name, point, mass): if not isinstance(name, str): raise TypeError('Supply a valid name.') self._name = name self.mass = mass self.point = point self.potential_energy = 0 def __str__(self): return self._name def __repr__(self): return self.__str__() @property def mass(self): """Mass of the particle.""" return self._mass @mass.setter def mass(self, value): self._mass = sympify(value) @property def point(self): """Point of the particle.""" return self._point @point.setter def point(self, p): if not isinstance(p, Point): raise TypeError("Particle point attribute must be a Point object.") self._point = p def linear_momentum(self, frame): """Linear momentum of the particle. Explanation =========== The linear momentum L, of a particle P, with respect to frame N is given by L = m * v where m is the mass of the particle, and v is the velocity of the particle in the frame N. Parameters ========== frame : ReferenceFrame The frame in which linear momentum is desired. Examples ======== >>> from sympy.physics.mechanics import Particle, Point, ReferenceFrame >>> from sympy.physics.mechanics import dynamicsymbols >>> from sympy.physics.vector import init_vprinting >>> init_vprinting(pretty_print=False) >>> m, v = dynamicsymbols('m v') >>> N = ReferenceFrame('N') >>> P = Point('P') >>> A = Particle('A', P, m) >>> P.set_vel(N, v * N.x) >>> A.linear_momentum(N) m*v*N.x """ return self.mass * self.point.vel(frame) def angular_momentum(self, point, frame): """Angular momentum of the particle about the point. Explanation =========== The angular momentum H, about some point O of a particle, P, is given by: H = r x m * v where r is the position vector from point O to the particle P, m is the mass of the particle, and v is the velocity of the particle in the inertial frame, N. Parameters ========== point : Point The point about which angular momentum of the particle is desired. frame : ReferenceFrame The frame in which angular momentum is desired. Examples ======== >>> from sympy.physics.mechanics import Particle, Point, ReferenceFrame >>> from sympy.physics.mechanics import dynamicsymbols >>> from sympy.physics.vector import init_vprinting >>> init_vprinting(pretty_print=False) >>> m, v, r = dynamicsymbols('m v r') >>> N = ReferenceFrame('N') >>> O = Point('O') >>> A = O.locatenew('A', r * N.x) >>> P = Particle('P', A, m) >>> P.point.set_vel(N, v * N.y) >>> P.angular_momentum(O, N) m*r*v*N.z """ return self.point.pos_from(point) ^ (self.mass * self.point.vel(frame)) def kinetic_energy(self, frame): """Kinetic energy of the particle. Explanation =========== The kinetic energy, T, of a particle, P, is given by 'T = 1/2 m v^2' where m is the mass of particle P, and v is the velocity of the particle in the supplied ReferenceFrame. Parameters ========== frame : ReferenceFrame The Particle's velocity is typically defined with respect to an inertial frame but any relevant frame in which the velocity is known can be supplied. Examples ======== >>> from sympy.physics.mechanics import Particle, Point, ReferenceFrame >>> from sympy import symbols >>> m, v, r = symbols('m v r') >>> N = ReferenceFrame('N') >>> O = Point('O') >>> P = Particle('P', O, m) >>> P.point.set_vel(N, v * N.y) >>> P.kinetic_energy(N) m*v**2/2 """ return (self.mass / sympify(2) * self.point.vel(frame) & self.point.vel(frame)) @property def potential_energy(self): """The potential energy of the Particle. Examples ======== >>> from sympy.physics.mechanics import Particle, Point >>> from sympy import symbols >>> m, g, h = symbols('m g h') >>> O = Point('O') >>> P = Particle('P', O, m) >>> P.potential_energy = m * g * h >>> P.potential_energy g*h*m """ return self._pe @potential_energy.setter def potential_energy(self, scalar): """Used to set the potential energy of the Particle. Parameters ========== scalar : Sympifyable The potential energy (a scalar) of the Particle. Examples ======== >>> from sympy.physics.mechanics import Particle, Point >>> from sympy import symbols >>> m, g, h = symbols('m g h') >>> O = Point('O') >>> P = Particle('P', O, m) >>> P.potential_energy = m * g * h """ self._pe = sympify(scalar) def set_potential_energy(self, scalar): SymPyDeprecationWarning( feature="Method sympy.physics.mechanics." + "Particle.set_potential_energy(self, scalar)", useinstead="property sympy.physics.mechanics." + "Particle.potential_energy", deprecated_since_version="1.5", issue=9800).warn() self.potential_energy = scalar def parallel_axis(self, point, frame): """Returns an inertia dyadic of the particle with respect to another point and frame. Parameters ========== point : sympy.physics.vector.Point The point to express the inertia dyadic about. frame : sympy.physics.vector.ReferenceFrame The reference frame used to construct the dyadic. Returns ======= inertia : sympy.physics.vector.Dyadic The inertia dyadic of the particle expressed about the provided point and frame. """ # circular import issue from sympy.physics.mechanics import inertia_of_point_mass return inertia_of_point_mass(self.mass, self.point.pos_from(point), frame)
fc0498bdb44735cccb09a67a475261893390b8ed210cf15b6db0ed40d4308f2e
""" Unit system for physical quantities; include definition of constants. """ from typing import Dict from sympy import S, Mul, Pow, Add, Function, Derivative from sympy.physics.units.dimensions import _QuantityMapper from sympy.utilities.exceptions import SymPyDeprecationWarning from .dimensions import Dimension class UnitSystem(_QuantityMapper): """ UnitSystem represents a coherent set of units. A unit system is basically a dimension system with notions of scales. Many of the methods are defined in the same way. It is much better if all base units have a symbol. """ _unit_systems = {} # type: Dict[str, UnitSystem] def __init__(self, base_units, units=(), name="", descr="", dimension_system=None): UnitSystem._unit_systems[name] = self self.name = name self.descr = descr self._base_units = base_units self._dimension_system = dimension_system self._units = tuple(set(base_units) | set(units)) self._base_units = tuple(base_units) super().__init__() def __str__(self): """ Return the name of the system. If it does not exist, then it makes a list of symbols (or names) of the base dimensions. """ if self.name != "": return self.name else: return "UnitSystem((%s))" % ", ".join( str(d) for d in self._base_units) def __repr__(self): return '<UnitSystem: %s>' % repr(self._base_units) def extend(self, base, units=(), name="", description="", dimension_system=None): """Extend the current system into a new one. Take the base and normal units of the current system to merge them to the base and normal units given in argument. If not provided, name and description are overridden by empty strings. """ base = self._base_units + tuple(base) units = self._units + tuple(units) return UnitSystem(base, units, name, description, dimension_system) def print_unit_base(self, unit): """ Useless method. DO NOT USE, use instead ``convert_to``. Give the string expression of a unit in term of the basis. Units are displayed by decreasing power. """ SymPyDeprecationWarning( deprecated_since_version="1.2", issue=13336, feature="print_unit_base", useinstead="convert_to", ).warn() from sympy.physics.units import convert_to return convert_to(unit, self._base_units) def get_dimension_system(self): return self._dimension_system def get_quantity_dimension(self, unit): qdm = self.get_dimension_system()._quantity_dimension_map if unit in qdm: return qdm[unit] return super().get_quantity_dimension(unit) def get_quantity_scale_factor(self, unit): qsfm = self.get_dimension_system()._quantity_scale_factors if unit in qsfm: return qsfm[unit] return super().get_quantity_scale_factor(unit) @staticmethod def get_unit_system(unit_system): if isinstance(unit_system, UnitSystem): return unit_system if unit_system not in UnitSystem._unit_systems: raise ValueError( "Unit system is not supported. Currently" "supported unit systems are {}".format( ", ".join(sorted(UnitSystem._unit_systems)) ) ) return UnitSystem._unit_systems[unit_system] @staticmethod def get_default_unit_system(): return UnitSystem._unit_systems["SI"] @property def dim(self): """ Give the dimension of the system. That is return the number of units forming the basis. """ return len(self._base_units) @property def is_consistent(self): """ Check if the underlying dimension system is consistent. """ # test is performed in DimensionSystem return self.get_dimension_system().is_consistent def get_dimensional_expr(self, expr): from sympy import Mul, Add, Pow, Derivative from sympy import Function from sympy.physics.units import Quantity if isinstance(expr, Mul): return Mul(*[self.get_dimensional_expr(i) for i in expr.args]) elif isinstance(expr, Pow): return self.get_dimensional_expr(expr.base) ** expr.exp elif isinstance(expr, Add): return self.get_dimensional_expr(expr.args[0]) elif isinstance(expr, Derivative): dim = self.get_dimensional_expr(expr.expr) for independent, count in expr.variable_count: dim /= self.get_dimensional_expr(independent)**count return dim elif isinstance(expr, Function): args = [self.get_dimensional_expr(arg) for arg in expr.args] if all(i == 1 for i in args): return S.One return expr.func(*args) elif isinstance(expr, Quantity): return self.get_quantity_dimension(expr).name return S.One def _collect_factor_and_dimension(self, expr): """ Return tuple with scale factor expression and dimension expression. """ from sympy.physics.units import Quantity if isinstance(expr, Quantity): return expr.scale_factor, expr.dimension elif isinstance(expr, Mul): factor = 1 dimension = Dimension(1) for arg in expr.args: arg_factor, arg_dim = self._collect_factor_and_dimension(arg) factor *= arg_factor dimension *= arg_dim return factor, dimension elif isinstance(expr, Pow): factor, dim = self._collect_factor_and_dimension(expr.base) exp_factor, exp_dim = self._collect_factor_and_dimension(expr.exp) if exp_dim.is_dimensionless: exp_dim = 1 return factor ** exp_factor, dim ** (exp_factor * exp_dim) elif isinstance(expr, Add): factor, dim = self._collect_factor_and_dimension(expr.args[0]) for addend in expr.args[1:]: addend_factor, addend_dim = \ self._collect_factor_and_dimension(addend) if dim != addend_dim: raise ValueError( 'Dimension of "{}" is {}, ' 'but it should be {}'.format( addend, addend_dim, dim)) factor += addend_factor return factor, dim elif isinstance(expr, Derivative): factor, dim = self._collect_factor_and_dimension(expr.args[0]) for independent, count in expr.variable_count: ifactor, idim = self._collect_factor_and_dimension(independent) factor /= ifactor**count dim /= idim**count return factor, dim elif isinstance(expr, Function): fds = [self._collect_factor_and_dimension( arg) for arg in expr.args] return (expr.func(*(f[0] for f in fds)), expr.func(*(d[1] for d in fds))) elif isinstance(expr, Dimension): return 1, expr else: return expr, Dimension(1)
4d2be6d122780b3ccbed096b0ac610be84d5c57d040077a27a0e2d728ca7c20a
""" 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 sympy import (Integer, Matrix, S, Symbol, sympify, Basic, Tuple, Dict, default_sort_key) from sympy.core.compatibility import reduce 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() )) @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: 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 = get_for_name(name.base) return {k: v*name.exp for (k, v) in dim.items()} if name.is_Function: args = (Dimension._from_dimensional_dependencies( get_for_name(arg)) for arg in name.args) result = name.func(*args) if isinstance(result, Dimension): return self.get_dimensional_dependencies(result) elif result.func == name.func: return {} 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
287128e164e0a22cef8eb42e352843f284e859acd89a843ccc15201e3b550d4d
""" Module defining unit prefixe class and some constants. Constant dict for SI and binary prefixes are defined as PREFIXES and BIN_PREFIXES. """ from sympy import Expr, sympify class Prefix(Expr): """ This class represent prefixes, with their name, symbol and factor. Prefixes are used to create derived units from a given unit. They should always be encapsulated into units. The factor is constructed from a base (default is 10) to some power, and it gives the total multiple or fraction. For example the kilometer km is constructed from the meter (factor 1) and the kilo (10 to the power 3, i.e. 1000). The base can be changed to allow e.g. binary prefixes. A prefix multiplied by something will always return the product of this other object times the factor, except if the other object: - is a prefix and they can be combined into a new prefix; - defines multiplication with prefixes (which is the case for the Unit class). """ _op_priority = 13.0 is_commutative = True def __new__(cls, name, abbrev, exponent, base=sympify(10)): name = sympify(name) abbrev = sympify(abbrev) exponent = sympify(exponent) base = sympify(base) obj = Expr.__new__(cls, name, abbrev, exponent, base) obj._name = name obj._abbrev = abbrev obj._scale_factor = base**exponent obj._exponent = exponent obj._base = base return obj @property def name(self): return self._name @property def abbrev(self): return self._abbrev @property def scale_factor(self): return self._scale_factor @property def base(self): return self._base def __str__(self): # TODO: add proper printers and tests: if self.base == 10: return "Prefix(%r, %r, %r)" % ( str(self.name), str(self.abbrev), self._exponent) else: return "Prefix(%r, %r, %r, %r)" % ( str(self.name), str(self.abbrev), self._exponent, self.base) __repr__ = __str__ def __mul__(self, other): from sympy.physics.units import Quantity if not isinstance(other, (Quantity, Prefix)): return super().__mul__(other) fact = self.scale_factor * other.scale_factor if fact == 1: return 1 elif isinstance(other, Prefix): # simplify prefix for p in PREFIXES: if PREFIXES[p].scale_factor == fact: return PREFIXES[p] return fact return self.scale_factor * other def __truediv__(self, other): if not hasattr(other, "scale_factor"): return super().__truediv__(other) fact = self.scale_factor / other.scale_factor if fact == 1: return 1 elif isinstance(other, Prefix): for p in PREFIXES: if PREFIXES[p].scale_factor == fact: return PREFIXES[p] return fact return self.scale_factor / other def __rtruediv__(self, other): if other == 1: for p in PREFIXES: if PREFIXES[p].scale_factor == 1 / self.scale_factor: return PREFIXES[p] return other / self.scale_factor def prefix_unit(unit, prefixes): """ Return a list of all units formed by unit and the given prefixes. You can use the predefined PREFIXES or BIN_PREFIXES, but you can also pass as argument a subdict of them if you don't want all prefixed units. >>> from sympy.physics.units.prefixes import (PREFIXES, ... prefix_unit) >>> from sympy.physics.units import m >>> pref = {"m": PREFIXES["m"], "c": PREFIXES["c"], "d": PREFIXES["d"]} >>> prefix_unit(m, pref) # doctest: +SKIP [millimeter, centimeter, decimeter] """ from sympy.physics.units.quantities import Quantity from sympy.physics.units import UnitSystem prefixed_units = [] for prefix_abbr, prefix in prefixes.items(): quantity = Quantity( "%s%s" % (prefix.name, unit.name), abbrev=("%s%s" % (prefix.abbrev, unit.abbrev)) ) UnitSystem._quantity_dimensional_equivalence_map_global[quantity] = unit UnitSystem._quantity_scale_factors_global[quantity] = (prefix.scale_factor, unit) prefixed_units.append(quantity) return prefixed_units yotta = Prefix('yotta', 'Y', 24) zetta = Prefix('zetta', 'Z', 21) exa = Prefix('exa', 'E', 18) peta = Prefix('peta', 'P', 15) tera = Prefix('tera', 'T', 12) giga = Prefix('giga', 'G', 9) mega = Prefix('mega', 'M', 6) kilo = Prefix('kilo', 'k', 3) hecto = Prefix('hecto', 'h', 2) deca = Prefix('deca', 'da', 1) deci = Prefix('deci', 'd', -1) centi = Prefix('centi', 'c', -2) milli = Prefix('milli', 'm', -3) micro = Prefix('micro', 'mu', -6) nano = Prefix('nano', 'n', -9) pico = Prefix('pico', 'p', -12) femto = Prefix('femto', 'f', -15) atto = Prefix('atto', 'a', -18) zepto = Prefix('zepto', 'z', -21) yocto = Prefix('yocto', 'y', -24) # http://physics.nist.gov/cuu/Units/prefixes.html PREFIXES = { 'Y': yotta, 'Z': zetta, 'E': exa, 'P': peta, 'T': tera, 'G': giga, 'M': mega, 'k': kilo, 'h': hecto, 'da': deca, 'd': deci, 'c': centi, 'm': milli, 'mu': micro, 'n': nano, 'p': pico, 'f': femto, 'a': atto, 'z': zepto, 'y': yocto, } kibi = Prefix('kibi', 'Y', 10, 2) mebi = Prefix('mebi', 'Y', 20, 2) gibi = Prefix('gibi', 'Y', 30, 2) tebi = Prefix('tebi', 'Y', 40, 2) pebi = Prefix('pebi', 'Y', 50, 2) exbi = Prefix('exbi', 'Y', 60, 2) # http://physics.nist.gov/cuu/Units/binary.html BIN_PREFIXES = { 'Ki': kibi, 'Mi': mebi, 'Gi': gibi, 'Ti': tebi, 'Pi': pebi, 'Ei': exbi, }
f2a7beaf2dc2ee31fb966697a23df266623cdc518098bca429ca3e680e9238b5
""" Several methods to simplify expressions involving unit objects. """ from sympy import Add, Mul, Pow, Tuple, sympify from sympy.core.compatibility import reduce, Iterable, ordered from sympy.physics.units.dimensions import Dimension from sympy.physics.units.prefixes import Prefix from sympy.physics.units.quantities import Quantity from sympy.utilities.iterables import sift def _get_conversion_matrix_for_expr(expr, target_units, unit_system): from sympy import Matrix dimension_system = unit_system.get_dimension_system() expr_dim = Dimension(unit_system.get_dimensional_expr(expr)) dim_dependencies = dimension_system.get_dimensional_dependencies(expr_dim, mark_dimensionless=True) target_dims = [Dimension(unit_system.get_dimensional_expr(x)) for x in target_units] canon_dim_units = [i for x in target_dims for i in dimension_system.get_dimensional_dependencies(x, mark_dimensionless=True)] canon_expr_units = {i for i in dim_dependencies} if not canon_expr_units.issubset(set(canon_dim_units)): return None seen = set() canon_dim_units = [i for i in canon_dim_units if not (i in seen or seen.add(i))] camat = Matrix([[dimension_system.get_dimensional_dependencies(i, mark_dimensionless=True).get(j, 0) for i in target_dims] for j in canon_dim_units]) exprmat = Matrix([dim_dependencies.get(k, 0) for k in canon_dim_units]) res_exponents = camat.solve_least_squares(exprmat, method=None) return res_exponents def convert_to(expr, target_units, unit_system="SI"): """ Convert ``expr`` to the same expression with all of its units and quantities represented as factors of ``target_units``, whenever the dimension is compatible. ``target_units`` may be a single unit/quantity, or a collection of units/quantities. Examples ======== >>> from sympy.physics.units import speed_of_light, meter, gram, second, day >>> from sympy.physics.units import mile, newton, kilogram, atomic_mass_constant >>> from sympy.physics.units import kilometer, centimeter >>> from sympy.physics.units import gravitational_constant, hbar >>> from sympy.physics.units import convert_to >>> convert_to(mile, kilometer) 25146*kilometer/15625 >>> convert_to(mile, kilometer).n() 1.609344*kilometer >>> convert_to(speed_of_light, meter/second) 299792458*meter/second >>> convert_to(day, second) 86400*second >>> 3*newton 3*newton >>> convert_to(3*newton, kilogram*meter/second**2) 3*kilogram*meter/second**2 >>> convert_to(atomic_mass_constant, gram) 1.660539060e-24*gram Conversion to multiple units: >>> convert_to(speed_of_light, [meter, second]) 299792458*meter/second >>> convert_to(3*newton, [centimeter, gram, second]) 300000*centimeter*gram/second**2 Conversion to Planck units: >>> convert_to(atomic_mass_constant, [gravitational_constant, speed_of_light, hbar]).n() 7.62963085040767e-20*gravitational_constant**(-0.5)*hbar**0.5*speed_of_light**0.5 """ from sympy.physics.units import UnitSystem unit_system = UnitSystem.get_unit_system(unit_system) if not isinstance(target_units, (Iterable, Tuple)): target_units = [target_units] if isinstance(expr, Add): return Add.fromiter(convert_to(i, target_units, unit_system) for i in expr.args) expr = sympify(expr) if not isinstance(expr, Quantity) and expr.has(Quantity): expr = expr.replace(lambda x: isinstance(x, Quantity), lambda x: x.convert_to(target_units, unit_system)) def get_total_scale_factor(expr): if isinstance(expr, Mul): return reduce(lambda x, y: x * y, [get_total_scale_factor(i) for i in expr.args]) elif isinstance(expr, Pow): return get_total_scale_factor(expr.base) ** expr.exp elif isinstance(expr, Quantity): return unit_system.get_quantity_scale_factor(expr) return expr depmat = _get_conversion_matrix_for_expr(expr, target_units, unit_system) if depmat is None: return expr expr_scale_factor = get_total_scale_factor(expr) return expr_scale_factor * Mul.fromiter((1/get_total_scale_factor(u) * u) ** p for u, p in zip(target_units, depmat)) def quantity_simplify(expr): """Return an equivalent expression in which prefixes are replaced with numerical values and all units of a given dimension are the unified in a canonical manner. Examples ======== >>> from sympy.physics.units.util import quantity_simplify >>> from sympy.physics.units.prefixes import kilo >>> from sympy.physics.units import foot, inch >>> quantity_simplify(kilo*foot*inch) 250*foot**2/3 >>> quantity_simplify(foot - 6*inch) foot/2 """ if expr.is_Atom or not expr.has(Prefix, Quantity): return expr # replace all prefixes with numerical values p = expr.atoms(Prefix) expr = expr.xreplace({p: p.scale_factor for p in p}) # replace all quantities of given dimension with a canonical # quantity, chosen from those in the expression d = sift(expr.atoms(Quantity), lambda i: i.dimension) for k in d: if len(d[k]) == 1: continue v = list(ordered(d[k])) ref = v[0]/v[0].scale_factor expr = expr.xreplace({vi: ref*vi.scale_factor for vi in v[1:]}) return expr def check_dimensions(expr, unit_system="SI"): """Return expr if there are not unitless values added to dimensional quantities, else raise a ValueError.""" # the case of adding a number to a dimensional quantity # is ignored for the sake of SymPy core routines, so this # function will raise an error now if such an addend is # found. # Also, when doing substitutions, multiplicative constants # might be introduced, so remove those now from sympy.physics.units import UnitSystem unit_system = UnitSystem.get_unit_system(unit_system) adds = expr.atoms(Add) DIM_OF = unit_system.get_dimension_system().get_dimensional_dependencies for a in adds: deset = set() for ai in a.args: if ai.is_number: deset.add(()) continue dims = [] skip = False for i in Mul.make_args(ai): if i.has(Quantity): i = Dimension(unit_system.get_dimensional_expr(i)) if i.has(Dimension): dims.extend(DIM_OF(i).items()) elif i.free_symbols: skip = True break if not skip: deset.add(tuple(sorted(dims))) if len(deset) > 1: raise ValueError( "addends have incompatible dimensions") # clear multiplicative constants on Dimensions which may be # left after substitution reps = {} for m in expr.atoms(Mul): if any(isinstance(i, Dimension) for i in m.args): reps[m] = m.func(*[ i for i in m.args if not i.is_number]) return expr.xreplace(reps)
e9dbd92defd8c98e5e01dba04847330b5ccc43c5d393020c49f1cbc51db5cf65
""" Physical quantities. """ from sympy import AtomicExpr, Symbol, sympify from sympy.physics.units.dimensions import _QuantityMapper from sympy.physics.units.prefixes import Prefix from sympy.utilities.exceptions import SymPyDeprecationWarning class Quantity(AtomicExpr): """ Physical quantity: can be a unit of measure, a constant or a generic quantity. """ is_commutative = True is_real = True is_number = False is_nonzero = True _diff_wrt = True def __new__(cls, name, abbrev=None, dimension=None, scale_factor=None, latex_repr=None, pretty_unicode_repr=None, pretty_ascii_repr=None, mathml_presentation_repr=None, **assumptions): if not isinstance(name, Symbol): name = Symbol(name) # For Quantity(name, dim, scale, abbrev) to work like in the # old version of Sympy: if not isinstance(abbrev, str) and not \ isinstance(abbrev, Symbol): dimension, scale_factor, abbrev = abbrev, dimension, scale_factor if dimension is not None: SymPyDeprecationWarning( deprecated_since_version="1.3", issue=14319, feature="Quantity arguments", useinstead="unit_system.set_quantity_dimension_map", ).warn() if scale_factor is not None: SymPyDeprecationWarning( deprecated_since_version="1.3", issue=14319, feature="Quantity arguments", useinstead="SI_quantity_scale_factors", ).warn() if abbrev is None: abbrev = name elif isinstance(abbrev, str): abbrev = Symbol(abbrev) obj = AtomicExpr.__new__(cls, name, abbrev) obj._name = name obj._abbrev = abbrev obj._latex_repr = latex_repr obj._unicode_repr = pretty_unicode_repr obj._ascii_repr = pretty_ascii_repr obj._mathml_repr = mathml_presentation_repr if dimension is not None: # TODO: remove after deprecation: obj.set_dimension(dimension) if scale_factor is not None: # TODO: remove after deprecation: obj.set_scale_factor(scale_factor) return obj def set_dimension(self, dimension, unit_system="SI"): SymPyDeprecationWarning( deprecated_since_version="1.5", issue=17765, feature="Moving method to UnitSystem class", useinstead="unit_system.set_quantity_dimension or {}.set_global_relative_scale_factor".format(self), ).warn() from sympy.physics.units import UnitSystem unit_system = UnitSystem.get_unit_system(unit_system) unit_system.set_quantity_dimension(self, dimension) def set_scale_factor(self, scale_factor, unit_system="SI"): SymPyDeprecationWarning( deprecated_since_version="1.5", issue=17765, feature="Moving method to UnitSystem class", useinstead="unit_system.set_quantity_scale_factor or {}.set_global_relative_scale_factor".format(self), ).warn() from sympy.physics.units import UnitSystem unit_system = UnitSystem.get_unit_system(unit_system) unit_system.set_quantity_scale_factor(self, scale_factor) def set_global_dimension(self, dimension): _QuantityMapper._quantity_dimension_global[self] = dimension def set_global_relative_scale_factor(self, scale_factor, reference_quantity): """ Setting a scale factor that is valid across all unit system. """ from sympy.physics.units import UnitSystem 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 ) scale_factor = sympify(scale_factor) UnitSystem._quantity_scale_factors_global[self] = (scale_factor, reference_quantity) UnitSystem._quantity_dimensional_equivalence_map_global[self] = reference_quantity @property def name(self): return self._name @property def dimension(self): from sympy.physics.units import UnitSystem unit_system = UnitSystem.get_default_unit_system() return unit_system.get_quantity_dimension(self) @property def abbrev(self): """ Symbol representing the unit name. Prepend the abbreviation with the prefix symbol if it is defines. """ return self._abbrev @property def scale_factor(self): """ Overall magnitude of the quantity as compared to the canonical units. """ from sympy.physics.units import UnitSystem unit_system = UnitSystem.get_default_unit_system() return unit_system.get_quantity_scale_factor(self) def _eval_is_positive(self): return True def _eval_is_constant(self): return True def _eval_Abs(self): return self def _eval_subs(self, old, new): if isinstance(new, Quantity) and self != old: return self @staticmethod def get_dimensional_expr(expr, unit_system="SI"): SymPyDeprecationWarning( deprecated_since_version="1.5", issue=17765, feature="get_dimensional_expr() is now associated with UnitSystem objects. " \ "The dimensional relations depend on the unit system used.", useinstead="unit_system.get_dimensional_expr" ).warn() from sympy.physics.units import UnitSystem unit_system = UnitSystem.get_unit_system(unit_system) return unit_system.get_dimensional_expr(expr) @staticmethod def _collect_factor_and_dimension(expr, unit_system="SI"): """Return tuple with scale factor expression and dimension expression.""" SymPyDeprecationWarning( deprecated_since_version="1.5", issue=17765, feature="This method has been moved to the UnitSystem class.", useinstead="unit_system._collect_factor_and_dimension", ).warn() from sympy.physics.units import UnitSystem unit_system = UnitSystem.get_unit_system(unit_system) return unit_system._collect_factor_and_dimension(expr) def _latex(self, printer): if self._latex_repr: return self._latex_repr else: return r'\text{{{}}}'.format(self.args[1] \ if len(self.args) >= 2 else self.args[0]) def convert_to(self, other, unit_system="SI"): """ Convert the quantity to another quantity of same dimensions. Examples ======== >>> from sympy.physics.units import speed_of_light, meter, second >>> speed_of_light speed_of_light >>> speed_of_light.convert_to(meter/second) 299792458*meter/second >>> from sympy.physics.units import liter >>> liter.convert_to(meter**3) meter**3/1000 """ from .util import convert_to return convert_to(self, other, unit_system) @property def free_symbols(self): """Return free symbols from quantity.""" return set()