
    MZdv                        d Z ddlmZ ddlmZ ddlmZ ddlmZm	Z	 ddl
mZmZ ddlmZ ddlmZ dd	lmZ dd
lmZmZmZ ddlmZmZ ddlmZ ddlmZ e G d d             ZdgZy)z)Implementation of :class:`Domain` class.     )annotations)Any)AlgebraicNumber)Basicsympify)default_sort_keyordered)HAS_GMPY)DomainElement)lex)UnificationFailedCoercionFailedDomainError)_unify_gens_not_a_coeff)public)is_sequencec                     e Zd ZU dZdZded<   	 dZded<   	 dZded<   	 dZ	 dZ		 dZ
	 dZ	 dxZZdxZZdxZZdxZZdxZZdxZZdxZZdxZZdxZZdxZZdxZ Z!dxZ"Z#dZ$d	Z%dZ&dZ'dZ(dZ)	 dZ*dZ+d
ed<   dZ,d
ed<   d Z-d Z.d Z/d Z0d Z1e2d        Z3d Z4d Z5d Z6dcdZ7d Z8d Z9d Z:d Z;d Z<d Z=d Z>d Z?d Z@d  ZAd! ZBd" ZCd# ZDd$ ZEd% ZFd& ZGd' ZHd( ZId) ZJd* ZKd+ ZLd, ZMd- ZNdcd.ZOd/ ZPd0 ZQd1 ZRd2 ZSd3 ZTd4 ZUd5 ZVeWd6d7ZXeWd6d8ZYd9 ZZd: Z[dd;d<Z\ddd=Z]ded>Z^d? Z_d@ Z`dA ZadB ZbdC ZcdD ZddE ZedF ZfdG ZgdH ZhdI ZidJ ZjdK ZkdL ZldM ZmdN ZndO ZodP ZpdQ ZqdR ZrdS ZsdT ZtdU ZudV ZvdW ZwdX ZxdY ZydZ Zzd[ Z{d\ Z|d] Z}dcd^Z~e~Zd_ Zd` ZdcdaZdb Zy)fDomainay  Superclass for all domains in the polys domains system.

    See :ref:`polys-domainsintro` for an introductory explanation of the
    domains system.

    The :py:class:`~.Domain` class is an abstract base class for all of the
    concrete domain types. There are many different :py:class:`~.Domain`
    subclasses each of which has an associated ``dtype`` which is a class
    representing the elements of the domain. The coefficients of a
    :py:class:`~.Poly` are elements of a domain which must be a subclass of
    :py:class:`~.Domain`.

    Examples
    ========

    The most common example domains are the integers :ref:`ZZ` and the
    rationals :ref:`QQ`.

    >>> from sympy import Poly, symbols, Domain
    >>> x, y = symbols('x, y')
    >>> p = Poly(x**2 + y)
    >>> p
    Poly(x**2 + y, x, y, domain='ZZ')
    >>> p.domain
    ZZ
    >>> isinstance(p.domain, Domain)
    True
    >>> Poly(x**2 + y/2)
    Poly(x**2 + 1/2*y, x, y, domain='QQ')

    The domains can be used directly in which case the domain object e.g.
    (:ref:`ZZ` or :ref:`QQ`) can be used as a constructor for elements of
    ``dtype``.

    >>> from sympy import ZZ, QQ
    >>> ZZ(2)
    2
    >>> ZZ.dtype  # doctest: +SKIP
    <class 'int'>
    >>> type(ZZ(2))  # doctest: +SKIP
    <class 'int'>
    >>> QQ(1, 2)
    1/2
    >>> type(QQ(1, 2))  # doctest: +SKIP
    <class 'sympy.polys.domains.pythonrational.PythonRational'>

    The corresponding domain elements can be used with the arithmetic
    operations ``+,-,*,**`` and depending on the domain some combination of
    ``/,//,%`` might be usable. For example in :ref:`ZZ` both ``//`` (floor
    division) and ``%`` (modulo division) can be used but ``/`` (true
    division) cannot. Since :ref:`QQ` is a :py:class:`~.Field` its elements
    can be used with ``/`` but ``//`` and ``%`` should not be used. Some
    domains have a :py:meth:`~.Domain.gcd` method.

    >>> ZZ(2) + ZZ(3)
    5
    >>> ZZ(5) // ZZ(2)
    2
    >>> ZZ(5) % ZZ(2)
    1
    >>> QQ(1, 2) / QQ(2, 3)
    3/4
    >>> ZZ.gcd(ZZ(4), ZZ(2))
    2
    >>> QQ.gcd(QQ(2,7), QQ(5,3))
    1/21
    >>> ZZ.is_Field
    False
    >>> QQ.is_Field
    True

    There are also many other domains including:

        1. :ref:`GF(p)` for finite fields of prime order.
        2. :ref:`RR` for real (floating point) numbers.
        3. :ref:`CC` for complex (floating point) numbers.
        4. :ref:`QQ(a)` for algebraic number fields.
        5. :ref:`K[x]` for polynomial rings.
        6. :ref:`K(x)` for rational function fields.
        7. :ref:`EX` for arbitrary expressions.

    Each domain is represented by a domain object and also an implementation
    class (``dtype``) for the elements of the domain. For example the
    :ref:`K[x]` domains are represented by a domain object which is an
    instance of :py:class:`~.PolynomialRing` and the elements are always
    instances of :py:class:`~.PolyElement`. The implementation class
    represents particular types of mathematical expressions in a way that is
    more efficient than a normal SymPy expression which is of type
    :py:class:`~.Expr`. The domain methods :py:meth:`~.Domain.from_sympy` and
    :py:meth:`~.Domain.to_sympy` are used to convert from :py:class:`~.Expr`
    to a domain element and vice versa.

    >>> from sympy import Symbol, ZZ, Expr
    >>> x = Symbol('x')
    >>> K = ZZ[x]           # polynomial ring domain
    >>> K
    ZZ[x]
    >>> type(K)             # class of the domain
    <class 'sympy.polys.domains.polynomialring.PolynomialRing'>
    >>> K.dtype             # class of the elements
    <class 'sympy.polys.rings.PolyElement'>
    >>> p_expr = x**2 + 1   # Expr
    >>> p_expr
    x**2 + 1
    >>> type(p_expr)
    <class 'sympy.core.add.Add'>
    >>> isinstance(p_expr, Expr)
    True
    >>> p_domain = K.from_sympy(p_expr)
    >>> p_domain            # domain element
    x**2 + 1
    >>> type(p_domain)
    <class 'sympy.polys.rings.PolyElement'>
    >>> K.to_sympy(p_domain) == p_expr
    True

    The :py:meth:`~.Domain.convert_from` method is used to convert domain
    elements from one domain to another.

    >>> from sympy import ZZ, QQ
    >>> ez = ZZ(2)
    >>> eq = QQ.convert_from(ez, ZZ)
    >>> type(ez)  # doctest: +SKIP
    <class 'int'>
    >>> type(eq)  # doctest: +SKIP
    <class 'sympy.polys.domains.pythonrational.PythonRational'>

    Elements from different domains should not be mixed in arithmetic or other
    operations: they should be converted to a common domain first.  The domain
    method :py:meth:`~.Domain.unify` is used to find a domain that can
    represent all the elements of two given domains.

    >>> from sympy import ZZ, QQ, symbols
    >>> x, y = symbols('x, y')
    >>> ZZ.unify(QQ)
    QQ
    >>> ZZ[x].unify(QQ)
    QQ[x]
    >>> ZZ[x].unify(QQ[y])
    QQ[x,y]

    If a domain is a :py:class:`~.Ring` then is might have an associated
    :py:class:`~.Field` and vice versa. The :py:meth:`~.Domain.get_field` and
    :py:meth:`~.Domain.get_ring` methods will find or create the associated
    domain.

    >>> from sympy import ZZ, QQ, Symbol
    >>> x = Symbol('x')
    >>> ZZ.has_assoc_Field
    True
    >>> ZZ.get_field()
    QQ
    >>> QQ.has_assoc_Ring
    True
    >>> QQ.get_ring()
    ZZ
    >>> K = QQ[x]
    >>> K
    QQ[x]
    >>> K.get_field()
    QQ(x)

    See also
    ========

    DomainElement: abstract base class for domain elements
    construct_domain: construct a minimal domain for some expressions

    Nztype | Nonedtyper   zerooneFTz
str | Nonerepaliasc                    t         NNotImplementedErrorselfs    </usr/lib/python3/dist-packages/sympy/polys/domains/domain.py__init__zDomain.__init__g  s    !!    c                    | j                   S r   )r   r   s    r!   __str__zDomain.__str__j  s    xxr#   c                    t        |       S r   )strr   s    r!   __repr__zDomain.__repr__m      4yr#   c                X    t        | j                  j                  | j                  f      S r   )hash	__class____name__r   r   s    r!   __hash__zDomain.__hash__p  s     T^^,,djj9::r#   c                      | j                   | S r   r   r    argss     r!   newz
Domain.news      tzz4  r#   c                    | j                   S )z#Alias for :py:attr:`~.Domain.dtype`r0   r   s    r!   tpz	Domain.tpv  s     zzr#   c                      | j                   | S )z7Construct an element of ``self`` domain from ``args``. )r3   r1   s     r!   __call__zDomain.__call__{  s    txxr#   c                      | j                   | S r   r0   r1   s     r!   normalzDomain.normal  r4   r#   c           
         |j                   d|j                   z   }nd|j                  j                  z   }t        | |      }| |||      }||S t	        d|dt        |      d|d|       )z=Convert ``element`` to ``self.dtype`` given the base domain. from_Cannot convert 	 of type z from  to )r   r,   r-   getattrr   type)r    elementbasemethod_convertresults         r!   convert_fromzDomain.convert_from  st    ::!tzz)Ft~~666F4(gt,F!WVZ[bVceikopqqr#   c                   |+t        |      rt        d|z        | j                  ||      S | j                  |      r|S t        |      rt        d|z        ddlm}m}m}m} |j                  |      r| j                  ||      S t        |t              r| j                   ||      |      S t        rT|}t        ||j                        r| j                  ||      S |}t        ||j                        r| j                  ||      S t        |t              r! |d      }	| j                   |	|      |	      S t        |t              r! |d      }	| j                   |	|      |	      S t        |t              r | j                  ||j!                               S | j"                  r,t%        |dd      r| j'                  |j)                               S t        |t*              r	 | j-                  |      S t3        |      s0	 t5        |d      }t        |t*              r| j-                  |      S 	 t        d	|d
t7        |      d|       # t.        t0        f$ r Y .w xY w# t.        t0        f$ r Y Cw xY w)z'Convert ``element`` to ``self.dtype``. z%s is not in any domainr   )ZZQQ	RealFieldComplexFieldF)tol	is_groundT)strictr=   r>   r?   )r   r   rG   of_typesympy.polys.domainsrI   rJ   rK   rL   
isinstanceintr
   r6   floatcomplexr   parentis_Numericalr@   convertLCr   
from_sympy	TypeError
ValueErrorr   r   rA   )
r    rB   rC   rI   rJ   rK   rL   integers	rationalsrV   s
             r!   rX   zDomain.convert  s<    G$$%>%HII$$Wd33<< N  !:W!DEEGG::g$$Wb11gs#$$R["55H'8;;/(((;;I'9<<0(()<<gu%5)F$$VG_f==gw'!e,F$$VG_f==g}-$$Wgnn.>?? +u!E<<

--gu%w// w'%gd;G!'51#w77 2
 WdSZm]abcc z*  ":. s$   &I -I$ I! I!$I65I6c                .    t        || j                        S )z%Check if ``a`` is of type ``dtype``. )rR   r6   )r    rB   s     r!   rP   zDomain.of_type  s    '477++r#   c                h    	 t        |      rt        | j                  |       y# t        $ r Y yw xY w)z'Check if ``a`` belongs to this domain. FT)r   r   rX   r    as     r!   __contains__zDomain.__contains__  s8    	A$$LLO   		s   "% 	11c                    t         )a	  Convert domain element *a* to a SymPy expression (Expr).

        Explanation
        ===========

        Convert a :py:class:`~.Domain` element *a* to :py:class:`~.Expr`. Most
        public SymPy functions work with objects of type :py:class:`~.Expr`.
        The elements of a :py:class:`~.Domain` have a different internal
        representation. It is not possible to mix domain elements with
        :py:class:`~.Expr` so each domain has :py:meth:`~.Domain.to_sympy` and
        :py:meth:`~.Domain.from_sympy` methods to convert its domain elements
        to and from :py:class:`~.Expr`.

        Parameters
        ==========

        a: domain element
            An element of this :py:class:`~.Domain`.

        Returns
        =======

        expr: Expr
            A normal SymPy expression of type :py:class:`~.Expr`.

        Examples
        ========

        Construct an element of the :ref:`QQ` domain and then convert it to
        :py:class:`~.Expr`.

        >>> from sympy import QQ, Expr
        >>> q_domain = QQ(2)
        >>> q_domain
        2
        >>> q_expr = QQ.to_sympy(q_domain)
        >>> q_expr
        2

        Although the printed forms look similar these objects are not of the
        same type.

        >>> isinstance(q_domain, Expr)
        False
        >>> isinstance(q_expr, Expr)
        True

        Construct an element of :ref:`K[x]` and convert to
        :py:class:`~.Expr`.

        >>> from sympy import Symbol
        >>> x = Symbol('x')
        >>> K = QQ[x]
        >>> x_domain = K.gens[0]  # generator x as a domain element
        >>> p_domain = x_domain**2/3 + 1
        >>> p_domain
        1/3*x**2 + 1
        >>> p_expr = K.to_sympy(p_domain)
        >>> p_expr
        x**2/3 + 1

        The :py:meth:`~.Domain.from_sympy` method is used for the opposite
        conversion from a normal SymPy expression to a domain element.

        >>> p_domain == p_expr
        False
        >>> K.from_sympy(p_expr) == p_domain
        True
        >>> K.to_sympy(p_domain) == p_expr
        True
        >>> K.from_sympy(K.to_sympy(p_domain)) == p_domain
        True
        >>> K.to_sympy(K.from_sympy(p_expr)) == p_expr
        True

        The :py:meth:`~.Domain.from_sympy` method makes it easier to construct
        domain elements interactively.

        >>> from sympy import Symbol
        >>> x = Symbol('x')
        >>> K = QQ[x]
        >>> K.from_sympy(x**2/3 + 1)
        1/3*x**2 + 1

        See also
        ========

        from_sympy
        convert_from
        r   ra   s     r!   to_sympyzDomain.to_sympy  s    v "!r#   c                    t         )a  Convert a SymPy expression to an element of this domain.

        Explanation
        ===========

        See :py:meth:`~.Domain.to_sympy` for explanation and examples.

        Parameters
        ==========

        expr: Expr
            A normal SymPy expression of type :py:class:`~.Expr`.

        Returns
        =======

        a: domain element
            An element of this :py:class:`~.Domain`.

        See also
        ========

        to_sympy
        convert_from
        r   ra   s     r!   rZ   zDomain.from_sympy=  s
    4 "!r#   c                    t        |      S r   )sumr1   s     r!   rh   z
Domain.sumY  r)   r#   c                     yz.Convert ``ModularInteger(int)`` to ``dtype``. N K1rb   K0s      r!   from_FFzDomain.from_FF\      r#   c                     yrj   rk   rl   s      r!   from_FF_pythonzDomain.from_FF_python`  rp   r#   c                     y)z.Convert a Python ``int`` object to ``dtype``. Nrk   rl   s      r!   from_ZZ_pythonzDomain.from_ZZ_pythond  rp   r#   c                     y)z3Convert a Python ``Fraction`` object to ``dtype``. Nrk   rl   s      r!   from_QQ_pythonzDomain.from_QQ_pythonh  rp   r#   c                     y)z.Convert ``ModularInteger(mpz)`` to ``dtype``. Nrk   rl   s      r!   from_FF_gmpyzDomain.from_FF_gmpyl  rp   r#   c                     y)z,Convert a GMPY ``mpz`` object to ``dtype``. Nrk   rl   s      r!   from_ZZ_gmpyzDomain.from_ZZ_gmpyp  rp   r#   c                     y)z,Convert a GMPY ``mpq`` object to ``dtype``. Nrk   rl   s      r!   from_QQ_gmpyzDomain.from_QQ_gmpyt  rp   r#   c                     y)z,Convert a real element object to ``dtype``. Nrk   rl   s      r!   from_RealFieldzDomain.from_RealFieldx  rp   r#   c                     y)z(Convert a complex element to ``dtype``. Nrk   rl   s      r!   from_ComplexFieldzDomain.from_ComplexField|  rp   r#   c                     y)z*Convert an algebraic number to ``dtype``. Nrk   rl   s      r!   from_AlgebraicFieldzDomain.from_AlgebraicField  rp   r#   c                h    |j                   r&| j                  |j                  |j                        S y)#Convert a polynomial to ``dtype``. N)rN   rX   rY   domrl   s      r!   from_PolynomialRingzDomain.from_PolynomialRing  s'    ;;::addBFF++ r#   c                     y)z*Convert a rational function to ``dtype``. Nrk   rl   s      r!   from_FractionFieldzDomain.from_FractionField  rp   r#   c                N    | j                  |j                  |j                        S )z.Convert an ``ExtensionElement`` to ``dtype``. )rG   r   ringrl   s      r!   from_MonogenicFiniteExtensionz$Domain.from_MonogenicFiniteExtension  s    quubgg..r#   c                8    | j                  |j                        S z&Convert a ``EX`` object to ``dtype``. )rZ   exrl   s      r!   from_ExpressionDomainzDomain.from_ExpressionDomain  s    }}QTT""r#   c                $    | j                  |      S r   )rZ   rl   s      r!   from_ExpressionRawDomainzDomain.from_ExpressionRawDomain  s    }}Qr#   c                ~    |j                         dk  r*| j                  |j                         |j                        S y)r   r   N)degreerX   rY   r   rl   s      r!   from_GlobalPolynomialRingz Domain.from_GlobalPolynomialRing  s/    88:?::addfbff-- r#   c                &    | j                  ||      S r   )r   rl   s      r!   from_GeneralizedPolynomialRingz%Domain.from_GeneralizedPolynomialRing  s    $$Q++r#   c           
        | j                   r!t        | j                        t        |      z  s-|j                   r?t        |j                        t        |      z  rt        d| d|dt	        |      d      | j                  |      S )NzCannot unify z with z, given z generators)is_Compositesetsymbolsr   tupleunify)rn   rm   r   s      r!   unify_with_symbolszDomain.unify_with_symbols  sf    OORZZ3w<!?boo[^_a_i_i[jmpqxmy[y#VXZ\^cdk^l$mnnxx|r#   c                b
   || j                  ||      S | |k(  r| S | j                  r| S |j                  r|S | j                  r| S |j                  r|S | j                  s|j                  r|j                  r|| }} |j                  rOt	        t        | j                  |j                  g            d   | j                  k(  r|| }} |j                  |       S |j                  | j                        }| j                  j                  |      }| j                  |      S | j                  s|j                  r| j                  r| j                  n| }|j                  r|j                  n|}| j                  r| j                  nd}|j                  r|j                  nd}|j                  |      }t        ||      }| j                  r| j                   n|j                   }| j"                  r|j$                  s|j"                  rL| j$                  r@|j&                  r|j&                  s(|j&                  r|j(                  r|j+                         }| j                  r1|j                  r| j"                  s|j$                  r| j,                  }	n|j,                  }	ddlm}
 |	|
k(  r	 |	||      S  |	|||      S d }|j2                  r|| }} | j2                  r.|j2                  s|j4                  r || j,                  | |      S | S |j4                  r|| }} | j4                  r^|j4                  r || j,                  | |      S |j6                  s|j8                  r$ddlm}  || j>                  | j@                        S | S |jB                  r|| }} | jB                  r|j6                  r|jE                         }|j8                  r|jG                         }|jB                  rT | j,                  | j                  j                  |j                        gt        | jH                  |jH                         S | S | j8                  r| S |j8                  r|S | j6                  r|jJ                  r| jE                         } | S |j6                  r| jJ                  r|jE                         }|S | jJ                  r| S |jJ                  r|S | jL                  r| S |jL                  r|S | jN                  rA|jN                  r5| j-                  tQ        | jR                  |jR                  tT                    S dd	l+m,} |S )
aZ  
        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``

           rk   r   )GlobalPolynomialRingc                    t        |j                  |j                        }t        |j                  |j                        } | ||      S )NprecrM   )max	precision	tolerance)clsrn   rm   r   rM   s        r!   	mkinexactzDomain.unify.<locals>.mkinexact  s7    r||R\\2DbllBLL1CDc**r#   )rL   r   )key)EX)-r   is_EXRAWis_EXis_FiniteExtensionlistr	   modulus
set_domaindropsymboldomainr   r   r   r   r   orderis_FractionFieldis_PolynomialRingis_Fieldhas_assoc_Ringget_ringr,   &sympy.polys.domains.old_polynomialringr   is_ComplexFieldis_RealFieldis_GaussianRingis_GaussianField sympy.polys.domains.complexfieldrL   r   r   is_AlgebraicField	get_fieldas_AlgebraicFieldorig_extis_RationalFieldis_IntegerRingis_FiniteFieldr   modr   rQ   r   )rn   rm   r   	K0_ground	K1_ground
K0_symbols
K1_symbolsr   r   r   r   r   rL   r   s                 r!   r   zDomain.unify  s)   " ((W558I;;I;;I88I88I  B$9$9$$RB$$ RZZ 89:1=KB}}R(( WWRYY'YY__R(}}R((??boo"$//rI"$//rI')BJ')BJ__Y/F!*j9G "BHHRXXE$$)=)=$$)=)=((	0B0B***2;N;NRTRfRfllllS**67++vw..	+
 B!!R__ r266	??B?? r266##r':':I#2<<HH	B!!\\^""))+###r||BFFLL$8a;r{{TVT_T_;`aa	II""\\^I""\\^IIIII!2!2<<BFFBFF8H IJJ*	r#   c                X    t        |t              xr | j                  |j                  k(  S )z0Returns ``True`` if two domains are equivalent. )rR   r   r   r    others     r!   __eq__zDomain.__eq__5  s!    %(FTZZ5;;-FFr#   c                    | |k(   S )z1Returns ``False`` if two domains are equivalent. rk   r   s     r!   __ne__zDomain.__ne__9  s    5=  r#   c                    g }|D ]J  }t        |t              r!|j                  | j                  |             4|j                   | |             L |S )z5Rersively apply ``self`` to all elements of ``seq``. )rR   r   appendmap)r    seqrF   elts       r!   r   z
Domain.map=  sK     	)C#t$dhhsm,d3i(		) r#   c                    t        d| z        )z)Returns a ring associated with ``self``. z#there is no ring associated with %sr   r   s    r!   r   zDomain.get_ringI  s    ?$FGGr#   c                    t        d| z        )z*Returns a field associated with ``self``. z$there is no field associated with %sr   r   s    r!   r   zDomain.get_fieldM  s    @4GHHr#   c                    | S )z2Returns an exact domain associated with ``self``. rk   r   s    r!   	get_exactzDomain.get_exactQ  s    r#   c                Z    t        |d      r | j                  | S | j                  |      S )z0The mathematical way to make a polynomial ring. __iter__)hasattr	poly_ringr    r   s     r!   __getitem__zDomain.__getitem__U  s,    7J'!4>>7++>>'**r#   )r   c               "    ddl m}  || ||      S z(Returns a polynomial ring, i.e. `K[X]`. r   )PolynomialRing)"sympy.polys.domains.polynomialringr   )r    r   r   r   s       r!   r   zDomain.poly_ring\  s    EdGU33r#   c               "    ddl m}  || ||      S z'Returns a fraction field, i.e. `K(X)`. r   )FractionField)!sympy.polys.domains.fractionfieldr   )r    r   r   r   s       r!   
frac_fieldzDomain.frac_fielda  s    CT7E22r#   c                &    ddl m}  || g|i |S r   )r   r   )r    r   kwargsr   s       r!   old_poly_ringzDomain.old_poly_ringf  s    Id7W777r#   c                &    ddl m}  || g|i |S r   )%sympy.polys.domains.old_fractionfieldr   )r    r   r   r   s       r!   old_frac_fieldzDomain.old_frac_fieldk  s    GT6G6v66r#   r   c                   t        d| z        )z6Returns an algebraic field, i.e. `K(\alpha, \ldots)`. z%Cannot create algebraic field over %sr   )r    r   	extensions      r!   algebraic_fieldzDomain.algebraic_fieldp  s    ADHIIr#   c                `    ddl m}  |||      }t        ||      }| j                  ||      S )a  
        Convenience method to construct an algebraic extension on a root of a
        polynomial, chosen by root index.

        Parameters
        ==========

        poly : :py:class:`~.Poly`
            The polynomial whose root generates the extension.
        alias : str, optional (default=None)
            Symbol name for the generator of the extension.
            E.g. "alpha" or "theta".
        root_index : int, optional (default=-1)
            Specifies which root of the polynomial is desired. The ordering is
            as defined by the :py:class:`~.ComplexRootOf` class. The default of
            ``-1`` selects the most natural choice in the common cases of
            quadratic and cyclotomic fields (the square root on the positive
            real or imaginary axis, resp. $\mathrm{e}^{2\pi i/n}$).

        Examples
        ========

        >>> from sympy import QQ, Poly
        >>> from sympy.abc import x
        >>> f = Poly(x**2 - 2)
        >>> K = QQ.alg_field_from_poly(f)
        >>> K.ext.minpoly == f
        True
        >>> g = Poly(8*x**3 - 6*x - 1)
        >>> L = QQ.alg_field_from_poly(g, "alpha")
        >>> L.ext.minpoly == g
        True
        >>> L.to_sympy(L([1, 1, 1]))
        alpha**2 + alpha + 1

        r   )CRootOfr   )sympy.polys.rootoftoolsr   r   r   )r    polyr   
root_indexr   rootalphas          r!   alg_field_from_polyzDomain.alg_field_from_polyt  s6    J 	4tZ(E2##E#77r#   c                d    ddl m} |r|t        |      z  }| j                   |||      ||      S )a  
        Convenience method to construct a cyclotomic field.

        Parameters
        ==========

        n : int
            Construct the nth cyclotomic field.
        ss : boolean, optional (default=False)
            If True, append *n* as a subscript on the alias string.
        alias : str, optional (default="zeta")
            Symbol name for the generator.
        gen : :py:class:`~.Symbol`, optional (default=None)
            Desired variable for the cyclotomic polynomial that defines the
            field. If ``None``, a dummy variable will be used.
        root_index : int, optional (default=-1)
            Specifies which root of the polynomial is desired. The ordering is
            as defined by the :py:class:`~.ComplexRootOf` class. The default of
            ``-1`` selects the root $\mathrm{e}^{2\pi i/n}$.

        Examples
        ========

        >>> from sympy import QQ, latex
        >>> K = QQ.cyclotomic_field(5)
        >>> K.to_sympy(K([-1, 1]))
        1 - zeta
        >>> L = QQ.cyclotomic_field(7, True)
        >>> a = L.to_sympy(L([-1, 1]))
        >>> print(a)
        1 - zeta7
        >>> print(latex(a))
        1 - \zeta_{7}

        r   )cyclotomic_poly)r   r   )sympy.polys.specialpolysr   r'   r   )r    nssr   genr   r   s          r!   cyclotomic_fieldzDomain.cyclotomic_field  s>    H 	=SVOE''3(?u3= ( ? 	?r#   c                    t         )z$Inject generators into this domain. r   r   s     r!   injectzDomain.inject      !!r#   c                *    | j                   r| S t        )z"Drop generators from this domain. )	is_Simpler   r   s     r!   r   zDomain.drop  s    >>K!!r#   c                    | S )zReturns True if ``a`` is zero. rk   ra   s     r!   is_zerozDomain.is_zero  s	    ur#   c                     || j                   k(  S )zReturns True if ``a`` is one. )r   ra   s     r!   is_onezDomain.is_one  s    DHH}r#   c                    |dkD  S )z#Returns True if ``a`` is positive. r   rk   ra   s     r!   is_positivezDomain.is_positive      1ur#   c                    |dk  S )z#Returns True if ``a`` is negative. r   rk   ra   s     r!   is_negativezDomain.is_negative  r  r#   c                    |dk  S )z'Returns True if ``a`` is non-positive. r   rk   ra   s     r!   is_nonpositivezDomain.is_nonpositive      Avr#   c                    |dk\  S )z'Returns True if ``a`` is non-negative. r   rk   ra   s     r!   is_nonnegativezDomain.is_nonnegative  r  r#   c                V    | j                  |      r| j                   S | j                  S r   )r  r   ra   s     r!   canonical_unitzDomain.canonical_unit  s%    AHH988Or#   c                    t        |      S )z.Absolute value of ``a``, implies ``__abs__``. )absra   s     r!   r  z
Domain.abs  s    1vr#   c                    | S )z,Returns ``a`` negated, implies ``__neg__``. rk   ra   s     r!   negz
Domain.neg  	    r	r#   c                    |S )z-Returns ``a`` positive, implies ``__pos__``. rk   ra   s     r!   posz
Domain.pos  r  r#   c                    ||z   S )z.Sum of ``a`` and ``b``, implies ``__add__``.  rk   r    rb   bs      r!   addz
Domain.add  r  r#   c                    ||z
  S )z5Difference of ``a`` and ``b``, implies ``__sub__``.  rk   r!  s      r!   subz
Domain.sub   r  r#   c                    ||z  S )z2Product of ``a`` and ``b``, implies ``__mul__``.  rk   r!  s      r!   mulz
Domain.mul  r  r#   c                    ||z  S )z2Raise ``a`` to power ``b``, implies ``__pow__``.  rk   r!  s      r!   powz
Domain.pow  r  r#   c                    t         )a  Exact quotient of *a* and *b*. Analogue of ``a / b``.

        Explanation
        ===========

        This is essentially the same as ``a / b`` except that an error will be
        raised if the division is inexact (if there is any remainder) and the
        result will always be a domain element. When working in a
        :py:class:`~.Domain` that is not a :py:class:`~.Field` (e.g. :ref:`ZZ`
        or :ref:`K[x]`) ``exquo`` should be used instead of ``/``.

        The key invariant is that if ``q = K.exquo(a, b)`` (and ``exquo`` does
        not raise an exception) then ``a == b*q``.

        Examples
        ========

        We can use ``K.exquo`` instead of ``/`` for exact division.

        >>> from sympy import ZZ
        >>> ZZ.exquo(ZZ(4), ZZ(2))
        2
        >>> ZZ.exquo(ZZ(5), ZZ(2))
        Traceback (most recent call last):
            ...
        ExactQuotientFailed: 2 does not divide 5 in ZZ

        Over a :py:class:`~.Field` such as :ref:`QQ`, division (with nonzero
        divisor) is always exact so in that case ``/`` can be used instead of
        :py:meth:`~.Domain.exquo`.

        >>> from sympy import QQ
        >>> QQ.exquo(QQ(5), QQ(2))
        5/2
        >>> QQ(5) / QQ(2)
        5/2

        Parameters
        ==========

        a: domain element
            The dividend
        b: domain element
            The divisor

        Returns
        =======

        q: domain element
            The exact quotient

        Raises
        ======

        ExactQuotientFailed: if exact division is not possible.
        ZeroDivisionError: when the divisor is zero.

        See also
        ========

        quo: Analogue of ``a // b``
        rem: Analogue of ``a % b``
        div: Analogue of ``divmod(a, b)``

        Notes
        =====

        Since the default :py:attr:`~.Domain.dtype` for :ref:`ZZ` is ``int``
        (or ``mpz``) division as ``a / b`` should not be used as it would give
        a ``float``.

        >>> ZZ(4) / ZZ(2)
        2.0
        >>> ZZ(5) / ZZ(2)
        2.5

        Using ``/`` with :ref:`ZZ` will lead to incorrect results so
        :py:meth:`~.Domain.exquo` should be used instead.

        r   r!  s      r!   exquozDomain.exquo  s    b "!r#   c                    t         )aG  Quotient of *a* and *b*. Analogue of ``a // b``.

        ``K.quo(a, b)`` is equivalent to ``K.div(a, b)[0]``. See
        :py:meth:`~.Domain.div` for more explanation.

        See also
        ========

        rem: Analogue of ``a % b``
        div: Analogue of ``divmod(a, b)``
        exquo: Analogue of ``a / b``
        r   r!  s      r!   quoz
Domain.quo_  
     "!r#   c                    t         )aN  Modulo division of *a* and *b*. Analogue of ``a % b``.

        ``K.rem(a, b)`` is equivalent to ``K.div(a, b)[1]``. See
        :py:meth:`~.Domain.div` for more explanation.

        See also
        ========

        quo: Analogue of ``a // b``
        div: Analogue of ``divmod(a, b)``
        exquo: Analogue of ``a / b``
        r   r!  s      r!   remz
Domain.remn  r.  r#   c                    t         )a[	  Quotient and remainder for *a* and *b*. Analogue of ``divmod(a, b)``

        Explanation
        ===========

        This is essentially the same as ``divmod(a, b)`` except that is more
        consistent when working over some :py:class:`~.Field` domains such as
        :ref:`QQ`. When working over an arbitrary :py:class:`~.Domain` the
        :py:meth:`~.Domain.div` method should be used instead of ``divmod``.

        The key invariant is that if ``q, r = K.div(a, b)`` then
        ``a == b*q + r``.

        The result of ``K.div(a, b)`` is the same as the tuple
        ``(K.quo(a, b), K.rem(a, b))`` except that if both quotient and
        remainder are needed then it is more efficient to use
        :py:meth:`~.Domain.div`.

        Examples
        ========

        We can use ``K.div`` instead of ``divmod`` for floor division and
        remainder.

        >>> from sympy import ZZ, QQ
        >>> ZZ.div(ZZ(5), ZZ(2))
        (2, 1)

        If ``K`` is a :py:class:`~.Field` then the division is always exact
        with a remainder of :py:attr:`~.Domain.zero`.

        >>> QQ.div(QQ(5), QQ(2))
        (5/2, 0)

        Parameters
        ==========

        a: domain element
            The dividend
        b: domain element
            The divisor

        Returns
        =======

        (q, r): tuple of domain elements
            The quotient and remainder

        Raises
        ======

        ZeroDivisionError: when the divisor is zero.

        See also
        ========

        quo: Analogue of ``a // b``
        rem: Analogue of ``a % b``
        exquo: Analogue of ``a / b``

        Notes
        =====

        If ``gmpy`` is installed then the ``gmpy.mpq`` type will be used as
        the :py:attr:`~.Domain.dtype` for :ref:`QQ`. The ``gmpy.mpq`` type
        defines ``divmod`` in a way that is undesirable so
        :py:meth:`~.Domain.div` should be used instead of ``divmod``.

        >>> a = QQ(1)
        >>> b = QQ(3, 2)
        >>> a               # doctest: +SKIP
        mpq(1,1)
        >>> b               # doctest: +SKIP
        mpq(3,2)
        >>> divmod(a, b)    # doctest: +SKIP
        (mpz(0), mpq(1,1))
        >>> QQ.div(a, b)    # doctest: +SKIP
        (mpq(2,3), mpq(0,1))

        Using ``//`` or ``%`` with :ref:`QQ` will lead to incorrect results so
        :py:meth:`~.Domain.div` should be used instead.

        r   r!  s      r!   divz
Domain.div}  s    h "!r#   c                    t         )z5Returns inversion of ``a mod b``, implies something. r   r!  s      r!   invertzDomain.invert  r  r#   c                    t         )z!Returns ``a**(-1)`` if possible. r   ra   s     r!   revertzDomain.revert  r  r#   c                    t         )zReturns numerator of ``a``. r   ra   s     r!   numerzDomain.numer  r  r#   c                    t         )zReturns denominator of ``a``. r   ra   s     r!   denomzDomain.denom  r  r#   c                6    | j                  ||      \  }}}||fS )z&Half extended GCD of ``a`` and ``b``. )gcdex)r    rb   r"  sths         r!   
half_gcdexzDomain.half_gcdex  s!    **Q"1a!tr#   c                    t         )z!Extended GCD of ``a`` and ``b``. r   r!  s      r!   r<  zDomain.gcdex  r  r#   c                x    | j                  ||      }| j                  ||      }| j                  ||      }|||fS )z.Returns GCD and cofactors of ``a`` and ``b``. )gcdr-  )r    rb   r"  rC  cfacfbs         r!   	cofactorszDomain.cofactors  s=    hhq!nhhq#hhq#C}r#   c                    t         )z Returns GCD of ``a`` and ``b``. r   r!  s      r!   rC  z
Domain.gcd  r  r#   c                    t         )z Returns LCM of ``a`` and ``b``. r   r!  s      r!   lcmz
Domain.lcm  r  r#   c                    t         )z#Returns b-base logarithm of ``a``. r   r!  s      r!   logz
Domain.log  r  r#   c                    t         )zReturns square root of ``a``. r   ra   s     r!   sqrtzDomain.sqrt  r  r#   c                F     | j                  |      j                  |fi |S )z*Returns numerical approximation of ``a``. )re   evalf)r    rb   r   optionss       r!   rO  zDomain.evalf  s#    %t}}Q%%d6g66r#   c                    |S r   rk   ra   s     r!   realzDomain.real	  s    r#   c                    | j                   S r   )r   ra   s     r!   imagzDomain.imag  s    yyr#   c                    ||k(  S )z+Check if ``a`` and ``b`` are almost equal. rk   )r    rb   r"  r   s       r!   almosteqzDomain.almosteq  r  r#   c                    t        d      )z*Return the characteristic of this domain. zcharacteristic()r   r   s    r!   characteristiczDomain.characteristic  s    !"455r#   r   )N)FzetaNrY  )r-   
__module____qualname____doc__r   __annotations__r   r   is_Ringr   r   has_assoc_Fieldr   is_FFr   is_ZZr   is_QQr   is_ZZ_Ir   is_QQ_Ir   is_RRr   is_CCr   is_Algebraicr   is_Polyr   is_Fracis_SymbolicDomainr   is_SymbolicRawDomainr   r   is_ExactrW   r  r   is_PIDhas_CharacteristicZeror   r   r"   r%   r(   r.   r3   propertyr6   r8   r:   rG   rX   rP   rc   re   rZ   rh   ro   rr   rt   rv   rx   rz   r|   r~   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r   r
  r  r  r  r  r  r  r  r  r  r#  r%  r'  r)  r+  r-  r0  r2  r4  r6  r8  r:  r@  r<  rF  rC  rI  rK  rM  rO  r   rR  rT  rV  rX  rk   r#   r!   r   r      s   hT E;, D# CO G$ H" N  O  #"NU""NU$$u %%Og!&&w  L5##Oe',,"''!&&w %%&++8HLILF" #CE:";!  !r"<d|,	["z"8,
/# .
,L\G!
HI+ ), 4
 *- 3
8
7
 15 J(8T(?T""Q"f""T"l""""
"""""7 	A6r#   r   N) r]  
__future__r   typingr   sympy.core.numbersr   
sympy.corer   r   sympy.core.sortingr   r	   sympy.external.gmpyr
   !sympy.polys.domains.domainelementr   sympy.polys.orderingsr   sympy.polys.polyerrorsr   r   r   sympy.polys.polyutilsr   r   sympy.utilitiesr   sympy.utilities.iterablesr   r   __all__rk   r#   r!   <module>r~     sU    / "  . % 8 ( ; % Q Q ; " 1 B6 B6 B6J( *r#   