a
    RG5d                    @   s  d 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 ddlmZ ddlmZ dd	lmZ dd
lm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 ddlm Z m!Z!m"Z" ddl#m$Z$m%Z%m&Z& dd Z'G dd dZ(G dd de(Z)G dd de(eZ*dd Z+d.ddZ,G dd  d eZ-G d!d" d"e-Z.G d#d$ d$Z/G d%d& d&e/Z0G d'd( d(e0Z1G d)d* d*Z2d/d,d-Z3d+S )0aR  Modules in number fields.

The classes defined here allow us to work with finitely generated, free
modules, whose generators are algebraic numbers.

There is an abstract base class called :py:class:`~.Module`, which has two
concrete subclasses, :py:class:`~.PowerBasis` and :py:class:`~.Submodule`.

Every module is defined by its basis, or set of generators:

* For a :py:class:`~.PowerBasis`, the generators are the first $n$ powers
  (starting with the zeroth) of an algebraic integer $\theta$ of degree $n$.
  The :py:class:`~.PowerBasis` is constructed by passing either the minimal
  polynomial of $\theta$, or an :py:class:`~.AlgebraicField` having $\theta$
  as its primitive element.

* For a :py:class:`~.Submodule`, the generators are a set of
  $\mathbb{Q}$-linear combinations of the generators of another module. That
  other module is then the "parent" of the :py:class:`~.Submodule`. The
  coefficients of the $\mathbb{Q}$-linear combinations may be given by an
  integer matrix, and a positive integer denominator. Each column of the matrix
  defines a generator.

>>> from sympy.polys import Poly, cyclotomic_poly, ZZ
>>> from sympy.abc import x
>>> from sympy.polys.matrices import DomainMatrix, DM
>>> from sympy.polys.numberfields.modules import PowerBasis
>>> T = Poly(cyclotomic_poly(5, x))
>>> A = PowerBasis(T)
>>> print(A)
PowerBasis(x**4 + x**3 + x**2 + x + 1)
>>> B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ), denom=3)
>>> print(B)
Submodule[[2, 0, 0, 0], [0, 2, 0, 0], [0, 0, 2, 0], [0, 0, 0, 2]]/3
>>> print(B.parent)
PowerBasis(x**4 + x**3 + x**2 + x + 1)

Thus, every module is either a :py:class:`~.PowerBasis`,
or a :py:class:`~.Submodule`, some ancestor of which is a
:py:class:`~.PowerBasis`. (If ``S`` is a :py:class:`~.Submodule`, then its
ancestors are ``S.parent``, ``S.parent.parent``, and so on).

The :py:class:`~.ModuleElement` class represents a linear combination of the
generators of any module. Critically, the coefficients of this linear
combination are not restricted to be integers, but may be any rational
numbers. This is necessary so that any and all algebraic integers be
representable, starting from the power basis in a primitive element $\theta$
for the number field in question. For example, in a quadratic field
$\mathbb{Q}(\sqrt{d})$ where $d \equiv 1 \mod{4}$, a denominator of $2$ is
needed.

A :py:class:`~.ModuleElement` can be constructed from an integer column vector
and a denominator:

>>> U = Poly(x**2 - 5)
>>> M = PowerBasis(U)
>>> e = M(DM([[1], [1]], ZZ), denom=2)
>>> print(e)
[1, 1]/2
>>> print(e.module)
PowerBasis(x**2 - 5)

The :py:class:`~.PowerBasisElement` class is a subclass of
:py:class:`~.ModuleElement` that represents elements of a
:py:class:`~.PowerBasis`, and adds functionality pertinent to elements
represented directly over powers of the primitive element $\theta$.


Arithmetic with module elements
===============================

While a :py:class:`~.ModuleElement` represents a linear combination over the
generators of a particular module, recall that every module is either a
:py:class:`~.PowerBasis` or a descendant (along a chain of
:py:class:`~.Submodule` objects) thereof, so that in fact every
:py:class:`~.ModuleElement` represents an algebraic number in some field
$\mathbb{Q}(\theta)$, where $\theta$ is the defining element of some
:py:class:`~.PowerBasis`. It thus makes sense to talk about the number field
to which a given :py:class:`~.ModuleElement` belongs.

This means that any two :py:class:`~.ModuleElement` instances can be added,
subtracted, multiplied, or divided, provided they belong to the same number
field. Similarly, since $\mathbb{Q}$ is a subfield of every number field,
any :py:class:`~.ModuleElement` may be added, multiplied, etc. by any
rational number.

>>> from sympy import QQ
>>> from sympy.polys.numberfields.modules import to_col
>>> T = Poly(cyclotomic_poly(5))
>>> A = PowerBasis(T)
>>> C = A.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ))
>>> e = A(to_col([0, 2, 0, 0]), denom=3)
>>> f = A(to_col([0, 0, 0, 7]), denom=5)
>>> g = C(to_col([1, 1, 1, 1]))
>>> e + f
[0, 10, 0, 21]/15
>>> e - f
[0, 10, 0, -21]/15
>>> e - g
[-9, -7, -9, -9]/3
>>> e + QQ(7, 10)
[21, 20, 0, 0]/30
>>> e * f
[-14, -14, -14, -14]/15
>>> e ** 2
[0, 0, 4, 0]/9
>>> f // g
[7, 7, 7, 7]/15
>>> f * QQ(2, 3)
[0, 0, 0, 14]/15

However, care must be taken with arithmetic operations on
:py:class:`~.ModuleElement`, because the module $C$ to which the result will
belong will be the nearest common ancestor (NCA) of the modules $A$, $B$ to
which the two operands belong, and $C$ may be different from either or both
of $A$ and $B$.

>>> A = PowerBasis(T)
>>> B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
>>> C = A.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ))
>>> print((B(0) * C(0)).module == A)
True

Before the arithmetic operation is performed, copies of the two operands are
automatically converted into elements of the NCA (the operands themselves are
not modified). This upward conversion along an ancestor chain is easy: it just
requires the successive multiplication by the defining matrix of each
:py:class:`~.Submodule`.

Conversely, downward conversion, i.e. representing a given
:py:class:`~.ModuleElement` in a submodule, is also supported -- namely by
the :py:meth:`~sympy.polys.numberfields.modules.Submodule.represent` method
-- but is not guaranteed to succeed in general, since the given element may
not belong to the submodule. The main circumstance in which this issue tends
to arise is with multiplication, since modules, while closed under addition,
need not be closed under multiplication.


Multiplication
--------------

Generally speaking, a module need not be closed under multiplication, i.e. need
not form a ring. However, many of the modules we work with in the context of
number fields are in fact rings, and our classes do support multiplication.

Specifically, any :py:class:`~.Module` can attempt to compute its own
multiplication table, but this does not happen unless an attempt is made to
multiply two :py:class:`~.ModuleElement` instances belonging to it.

>>> A = PowerBasis(T)
>>> print(A._mult_tab is None)
True
>>> a = A(0)*A(1)
>>> print(A._mult_tab is None)
False

Every :py:class:`~.PowerBasis` is, by its nature, closed under multiplication,
so instances of :py:class:`~.PowerBasis` can always successfully compute their
multiplication table.

When a :py:class:`~.Submodule` attempts to compute its multiplication table,
it converts each of its own generators into elements of its parent module,
multiplies them there, in every possible pairing, and then tries to
represent the results in itself, i.e. as $\mathbb{Z}$-linear combinations
over its own generators. This will succeed if and only if the submodule is
in fact closed under multiplication.


Module Homomorphisms
====================

Many important number theoretic algorithms require the calculation of the
kernel of one or more module homomorphisms. Accordingly we have several
lightweight classes, :py:class:`~.ModuleHomomorphism`,
:py:class:`~.ModuleEndomorphism`, :py:class:`~.InnerEndomorphism`, and
:py:class:`~.EndomorphismRing`, which provide the minimal necessary machinery
to support this.

    )igcdilcm)Dummy)ANP)Poly)dup_clear_denoms)AlgebraicField)FF)QQZZ)DomainMatrix)DMBadInputError)hermite_normal_form)CoercionFailedUnificationFailed)IntegerPowerable   )ClosureFailureMissingUnityErrorStructureError)AlgIntPowersis_ratget_num_denomc                 C   s$   t dd | D gdt| ft S )z>Transform a list of integer coefficients into a column vector.c                 S   s   g | ]}t |qS  r   .0cr   r   \/var/www/html/django/DPS/env/lib/python3.9/site-packages/sympy/polys/numberfields/modules.py
<listcomp>       zto_col.<locals>.<listcomp>r   )r   lenr   	transpose)coeffsr   r   r   to_col   s    r$   c                   @   s   e Zd ZdZedd Zdd Zedd Zdd	 Zd,ddZ	dd Z
dd Zedd Zdd Zd-ddZdd Zdd Zdd Zdd Zd d! Zd.d$d%Zd/d&d'Zd(d) Zd*d+ Zd#S )0Moduleaf  
    Generic finitely-generated module.

    This is an abstract base class, and should not be instantiated directly.
    The two concrete subclasses are :py:class:`~.PowerBasis` and
    :py:class:`~.Submodule`.

    Every :py:class:`~.Submodule` is derived from another module, referenced
    by its ``parent`` attribute. If ``S`` is a submodule, then we refer to
    ``S.parent``, ``S.parent.parent``, and so on, as the "ancestors" of
    ``S``. Thus, every :py:class:`~.Module` is either a
    :py:class:`~.PowerBasis` or a :py:class:`~.Submodule`, some ancestor of
    which is a :py:class:`~.PowerBasis`.
    c                 C   s   t dS )z(The number of generators of this module.NNotImplementedErrorselfr   r   r   n   s    zModule.nc                 C   s   t dS )ad  
        Get the multiplication table for this module (if closed under mult).

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

        Computes a dictionary ``M`` of dictionaries of lists, representing the
        upper triangular half of the multiplication table.

        In other words, if ``0 <= i <= j < self.n``, then ``M[i][j]`` is the
        list ``c`` of coefficients such that
        ``g[i] * g[j] == sum(c[k]*g[k], k in range(self.n))``,
        where ``g`` is the list of generators of this module.

        If ``j < i`` then ``M[i][j]`` is undefined.

        Examples
        ========

        >>> from sympy.polys import Poly, cyclotomic_poly
        >>> from sympy.polys.numberfields.modules import PowerBasis
        >>> T = Poly(cyclotomic_poly(5))
        >>> A = PowerBasis(T)
        >>> print(A.mult_tab())  # doctest: +SKIP
        {0: {0: [1, 0, 0, 0], 1: [0, 1, 0, 0], 2: [0, 0, 1, 0],     3: [0, 0, 0, 1]},
                          1: {1: [0, 0, 1, 0], 2: [0, 0, 0, 1],     3: [-1, -1, -1, -1]},
                                           2: {2: [-1, -1, -1, -1], 3: [1, 0, 0, 0]},
                                                                3: {3: [0, 1, 0, 0]}}

        Returns
        =======

        dict of dict of lists

        Raises
        ======

        ClosureFailure
            If the module is not closed under multiplication.

        Nr&   r(   r   r   r   mult_tab   s    *zModule.mult_tabc                 C   s   dS )ae  
        The parent module, if any, for this module.

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

        For a :py:class:`~.Submodule` this is its ``parent`` attribute; for a
        :py:class:`~.PowerBasis` this is ``None``.

        Returns
        =======

        :py:class:`~.Module`, ``None``

        See Also
        ========

        Module

        Nr   r(   r   r   r   parent  s    zModule.parentc                 C   s   t dS )aa  
        Represent a module element as an integer-linear combination over the
        generators of this module.

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

        In our system, to "represent" always means to write a
        :py:class:`~.ModuleElement` as a :ref:`ZZ`-linear combination over the
        generators of the present :py:class:`~.Module`. Furthermore, the
        incoming :py:class:`~.ModuleElement` must belong to an ancestor of
        the present :py:class:`~.Module` (or to the present
        :py:class:`~.Module` itself).

        The most common application is to represent a
        :py:class:`~.ModuleElement` in a :py:class:`~.Submodule`. For example,
        this is involved in computing multiplication tables.

        On the other hand, representing in a :py:class:`~.PowerBasis` is an
        odd case, and one which tends not to arise in practice, except for
        example when using a :py:class:`~.ModuleEndomorphism` on a
        :py:class:`~.PowerBasis`.

        In such a case, (1) the incoming :py:class:`~.ModuleElement` must
        belong to the :py:class:`~.PowerBasis` itself (since the latter has no
        proper ancestors) and (2) it is "representable" iff it belongs to
        $\mathbb{Z}[\theta]$ (although generally a
        :py:class:`~.PowerBasisElement` may represent any element of
        $\mathbb{Q}(\theta)$, i.e. any algebraic number).

        Examples
        ========

        >>> from sympy import Poly, cyclotomic_poly
        >>> from sympy.polys.numberfields.modules import PowerBasis, to_col
        >>> from sympy.abc import zeta
        >>> T = Poly(cyclotomic_poly(5))
        >>> A = PowerBasis(T)
        >>> a = A(to_col([2, 4, 6, 8]))

        The :py:class:`~.ModuleElement` ``a`` has all even coefficients.
        If we represent ``a`` in the submodule ``B = 2*A``, the coefficients in
        the column vector will be halved:

        >>> B = A.submodule_from_gens([2*A(i) for i in range(4)])
        >>> b = B.represent(a)
        >>> print(b.transpose())  # doctest: +SKIP
        DomainMatrix([[1, 2, 3, 4]], (1, 4), ZZ)

        However, the element of ``B`` so defined still represents the same
        algebraic number:

        >>> print(a.poly(zeta).as_expr())
        8*zeta**3 + 6*zeta**2 + 4*zeta + 2
        >>> print(B(b).over_power_basis().poly(zeta).as_expr())
        8*zeta**3 + 6*zeta**2 + 4*zeta + 2

        Parameters
        ==========

        elt : :py:class:`~.ModuleElement`
            The module element to be represented. Must belong to some ancestor
            module of this module (including this module itself).

        Returns
        =======

        :py:class:`~.DomainMatrix` over :ref:`ZZ`
            This will be a column vector, representing the coefficients of a
            linear combination of this module's generators, which equals the
            given element.

        Raises
        ======

        ClosureFailure
            If the given element cannot be represented as a :ref:`ZZ`-linear
            combination over this module.

        See Also
        ========

        .Submodule.represent
        .PowerBasis.represent

        Nr&   r)   eltr   r   r   	represent%  s    WzModule.representFc                 C   s0   | j }|du rg n
|jdd}|r,||  |S )z
        Return the list of ancestor modules of this module, from the
        foundational :py:class:`~.PowerBasis` downward, optionally including
        ``self``.

        See Also
        ========

        Module

        NTinclude_self)r,   	ancestorsappend)r)   r1   r   ar   r   r   r2   ~  s
    
zModule.ancestorsc                 C   s(   t | tr| S | j}|dur$| S dS )z
        Return the :py:class:`~.PowerBasis` that is an ancestor of this module.

        See Also
        ========

        Module

        N)
isinstance
PowerBasisr,   power_basis_ancestor)r)   r   r   r   r   r7     s    

zModule.power_basis_ancestorc                 C   sF   | j dd}|j dd}d}t||D ]\}}||kr<|}q& qBq&|S )z
        Locate the nearest common ancestor of this module and another.

        Returns
        =======

        :py:class:`~.Module`, ``None``

        See Also
        ========

        Module

        Tr0   N)r2   zip)r)   otherZsAZoAncasaoar   r   r   nearest_common_ancestor  s    zModule.nearest_common_ancestorc                 C   s
   |   jS )a#  
        Return the associated :py:class:`~.AlgebraicField`, if any.

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

        A :py:class:`~.PowerBasis` can be constructed on a :py:class:`~.Poly`
        $f$ or on an :py:class:`~.AlgebraicField` $K$. In the latter case, the
        :py:class:`~.PowerBasis` and all its descendant modules will return $K$
        as their ``.number_field`` property, while in the former case they will
        all return ``None``.

        Returns
        =======

        :py:class:`~.AlgebraicField`, ``None``

        )r7   number_fieldr(   r   r   r   r>     s    zModule.number_fieldc                 C   s"   t |to |j| jdfko |jjS )z>Say whether *col* is a suitable column vector for this module.r   )r5   r   shaper*   domainis_ZZ)r)   colr   r   r   is_compat_col  s    zModule.is_compat_colr   c                 C   sb   t |trBd|  kr | jk rBn nt| jtdd|f  }| |sTtdt	| ||dS )a  
        Generate a :py:class:`~.ModuleElement` belonging to this module.

        Examples
        ========

        >>> from sympy.polys import Poly, cyclotomic_poly
        >>> from sympy.polys.numberfields.modules import PowerBasis, to_col
        >>> T = Poly(cyclotomic_poly(5))
        >>> A = PowerBasis(T)
        >>> e = A(to_col([1, 2, 3, 4]), denom=3)
        >>> print(e)  # doctest: +SKIP
        [1, 2, 3, 4]/3
        >>> f = A(2)
        >>> print(f)  # doctest: +SKIP
        [0, 0, 1, 0]

        Parameters
        ==========

        spec : :py:class:`~.DomainMatrix`, int
            Specifies the numerators of the coefficients of the
            :py:class:`~.ModuleElement`. Can be either a column vector over
            :ref:`ZZ`, whose length must equal the number $n$ of generators of
            this module, or else an integer ``j``, $0 \leq j < n$, which is a
            shorthand for column $j$ of $I_n$, the $n \times n$ identity
            matrix.
        denom : int, optional (default=1)
            Denominator for the coefficients of the
            :py:class:`~.ModuleElement`.

        Returns
        =======

        :py:class:`~.ModuleElement`
            The coefficients are the entries of the *spec* vector, divided by
            *denom*.

        r   Nz"Compatible column vector required.denom)
r5   intr*   r   eyer   to_denserC   
ValueErrormake_mod_elt)r)   specrE   r   r   r   __call__  s
    ($
zModule.__call__c                 C   s   t dS )z6Say whether the module's first generator equals unity.Nr&   r(   r   r   r   starts_with_unity  s    zModule.starts_with_unityc                    s    fddt  jD S )zf
        Get list of :py:class:`~.ModuleElement` being the generators of this
        module.
        c                    s   g | ]} |qS r   r   r   jr(   r   r   r     r    z)Module.basis_elements.<locals>.<listcomp>)ranger*   r(   r   r(   r   basis_elements  s    zModule.basis_elementsc                 C   s   | dd S )z7Return a :py:class:`~.ModuleElement` representing zero.r   r   r(   r   r   r   zero  s    zModule.zeroc                 C   s
   |  dS )z
        Return a :py:class:`~.ModuleElement` representing unity,
        and belonging to the first ancestor of this module (including
        itself) that starts with unity.
        r   )element_from_rationalr(   r   r   r   one  s    z
Module.onec                 C   s   t dS )a*  
        Return a :py:class:`~.ModuleElement` representing a rational number.

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

        The returned :py:class:`~.ModuleElement` will belong to the first
        module on this module's ancestor chain (including this module
        itself) that starts with unity.

        Examples
        ========

        >>> from sympy.polys import Poly, cyclotomic_poly, QQ
        >>> from sympy.polys.numberfields.modules import PowerBasis
        >>> T = Poly(cyclotomic_poly(5))
        >>> A = PowerBasis(T)
        >>> a = A.element_from_rational(QQ(2, 3))
        >>> print(a)  # doctest: +SKIP
        [2, 0, 0, 0]/3

        Parameters
        ==========

        a : int, :ref:`ZZ`, :ref:`QQ`

        Returns
        =======

        :py:class:`~.ModuleElement`

        Nr&   r)   r4   r   r   r   rS     s    !zModule.element_from_rationalTNc                    s   t fdd|D stdt|}|dkr6td|d j}|dkrR|d jntdd |D   t|dftj	 fd	d|D  }|rt
||d
}j| dS )a  
        Form the submodule generated by a list of :py:class:`~.ModuleElement`
        belonging to this module.

        Examples
        ========

        >>> from sympy.polys import Poly, cyclotomic_poly
        >>> from sympy.polys.numberfields.modules import PowerBasis
        >>> T = Poly(cyclotomic_poly(5))
        >>> A = PowerBasis(T)
        >>> gens = [A(0), 2*A(1), 3*A(2), 4*A(3)//5]
        >>> B = A.submodule_from_gens(gens)
        >>> print(B)  # doctest: +SKIP
        Submodule[[5, 0, 0, 0], [0, 10, 0, 0], [0, 0, 15, 0], [0, 0, 0, 4]]/5

        Parameters
        ==========

        gens : list of :py:class:`~.ModuleElement` belonging to this module.
        hnf : boolean, optional (default=True)
            If True, we will reduce the matrix into Hermite Normal Form before
            forming the :py:class:`~.Submodule`.
        hnf_modulus : int, None, optional (default=None)
            Modulus for use in the HNF reduction algorithm. See
            :py:func:`~sympy.polys.matrices.normalforms.hermite_normal_form`.

        Returns
        =======

        :py:class:`~.Submodule`

        See Also
        ========

        submodule_from_matrix

        c                 3   s   | ]}|j  kV  qd S N)moduler   gr(   r   r   	<genexpr>c  r    z-Module.submodule_from_gens.<locals>.<genexpr>z&Generators must belong to this module.r   zNeed at least one generator.r   c                 S   s   g | ]
}|j qS r   rD   rX   r   r   r   r   i  r    z.Module.submodule_from_gens.<locals>.<listcomp>c                    s   g | ]} |j  |j qS r   )rE   rB   rX   )dr   r   r   j  r    DrD   )allrI   r!   r*   rE   r   r   zerosr   hstackr   submodule_from_matrix)r)   genshnfhnf_modulusr*   mBr   )r[   r)   r   submodule_from_gens<  s    '
$$zModule.submodule_from_gensc                 C   s:   |j \}}|jjstd|| jks,tdt| ||dS )a  
        Form the submodule generated by the elements of this module indicated
        by the columns of a matrix, with an optional denominator.

        Examples
        ========

        >>> from sympy.polys import Poly, cyclotomic_poly, ZZ
        >>> from sympy.polys.matrices import DM
        >>> from sympy.polys.numberfields.modules import PowerBasis
        >>> T = Poly(cyclotomic_poly(5))
        >>> A = PowerBasis(T)
        >>> B = A.submodule_from_matrix(DM([
        ...     [0, 10, 0, 0],
        ...     [0,  0, 7, 0],
        ... ], ZZ).transpose(), denom=15)
        >>> print(B)  # doctest: +SKIP
        Submodule[[0, 10, 0, 0], [0, 0, 7, 0]]/15

        Parameters
        ==========

        B : :py:class:`~.DomainMatrix` over :ref:`ZZ`
            Each column gives the numerators of the coefficients of one
            generator of the submodule. Thus, the number of rows of *B* must
            equal the number of generators of the present module.
        denom : int, optional (default=1)
            Common denominator for all generators of the submodule.

        Returns
        =======

        :py:class:`~.Submodule`

        Raises
        ======

        ValueError
            If the given matrix *B* is not over :ref:`ZZ` or its number of rows
            does not equal the number of generators of the present module.

        See Also
        ========

        submodule_from_gens

        zMatrix must be over ZZ.z(Matrix row count must match base module.rD   )r?   r@   rA   rI   r*   	Submodule)r)   rf   rE   re   r*   r   r   r   ra   o  s    0

zModule.submodule_from_matrixc                 C   s   t | jt}| |S )a"  
        Return a submodule equal to this entire module.

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

        This is useful when you have a :py:class:`~.PowerBasis` and want to
        turn it into a :py:class:`~.Submodule` (in order to use methods
        belonging to the latter).

        )r   rG   r*   r   ra   )r)   rf   r   r   r   whole_submodule  s    zModule.whole_submodulec                 C   s   t | S )z8Form the :py:class:`~.EndomorphismRing` for this module.)EndomorphismRingr(   r   r   r   endomorphism_ring  s    zModule.endomorphism_ring)F)r   )TN)r   )__name__
__module____qualname____doc__propertyr*   r+   r,   r/   r2   r7   r=   r>   rC   rL   rM   rQ   rR   rT   rS   rg   ra   ri   rk   r   r   r   r   r%      s.   
,
Y


.#
3
7r%   c                   @   s   e Zd ZdZdd Zedd Zdd Zdd	 Zed
d Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd Zdd ZdS )r6   z;The module generated by the powers of an algebraic integer.c                 C   sH   d}t |tr||j  }}|t}|| _|| _| | _	d| _
dS )a  
        Parameters
        ==========

        T : :py:class:`~.Poly`, :py:class:`~.AlgebraicField`
            Either (1) the monic, irreducible, univariate polynomial over
            :ref:`ZZ`, a root of which is the generator of the power basis,
            or (2) an :py:class:`~.AlgebraicField` whose primitive element
            is the generator of the power basis.

        N)r5   r   extminpoly_of_element
set_domainr   KTdegree_n	_mult_tab)r)   ru   rt   r   r   r   __init__  s    


zPowerBasis.__init__c                 C   s   | j S rV   )rt   r(   r   r   r   r>     s    zPowerBasis.number_fieldc                 C   s   d| j   dS )NzPowerBasis())ru   as_exprr(   r   r   r   __repr__  s    zPowerBasis.__repr__c                 C   s   t |tr| j|jkS tS rV   )r5   r6   ru   NotImplementedr)   r9   r   r   r   __eq__  s    
zPowerBasis.__eq__c                 C   s   | j S rV   rw   r(   r   r   r   r*     s    zPowerBasis.nc                 C   s   | j d u r|   | j S rV   rx   compute_mult_tabr(   r   r   r   r+     s    
zPowerBasis.mult_tabc                 C   sX   t | j}i }| j}t|D ]0}i ||< t||D ]}|||  || |< q2q|| _d S rV   )r   ru   r*   rP   rx   )r)   Z	theta_powMr*   uvr   r   r   r     s    
zPowerBasis.compute_mult_tabc                 C   s(   |j | kr|jdkr| S tddS )z
        Represent a module element as an integer-linear combination over the
        generators of this module.

        See Also
        ========

        .Module.represent
        .Submodule.represent

        r   z'Element not representable in ZZ[theta].N)rW   rE   columnr   r-   r   r   r   r/     s    zPowerBasis.representc                 C   s   dS )NTr   r(   r   r   r   rM     s    zPowerBasis.starts_with_unityc                 C   s   | d| S Nr   r   rU   r   r   r   rS     s    z PowerBasis.element_from_rationalc           	      C   s   | j |  }}||kr"|| j }|dkr2|  S t|jjtdd\}}tt|}t	|}t
dg||  }t|| }| ||dS )aE  
        Produce an element of this module, representing *f* after reduction mod
        our defining minimal polynomial.

        Parameters
        ==========

        f : :py:class:`~.Poly` over :ref:`ZZ` in same var as our defining poly.

        Returns
        =======

        :py:class:`~.PowerBasisElement`

        r   T)convertrD   )r*   rv   ru   rR   r   repr
   listreversedr!   r   r$   )	r)   fr*   kr[   r   ellzrB   r   r   r   element_from_poly
  s    
zPowerBasis.element_from_polyc                 C   s*   || j jjkrtd| t|| j jS )a  
        Produce a PowerBasisElement representing a given algebraic number.

        Parameters
        ==========

        rep : list of coeffs
            Represents the number as polynomial in the primitive element of the
            field.

        mod : list of coeffs
            Represents the minimal polynomial of the primitive element of the
            field.

        Returns
        =======

        :py:class:`~.PowerBasisElement`

        z0Element does not appear to be in the same field.)ru   r   r   r   r   gen)r)   r   modr   r   r   _element_from_rep_and_mod&  s    z$PowerBasis._element_from_rep_and_modc                 C   s   |  |j|jS )z)Convert an ANP into a PowerBasisElement. )r   r   r   rU   r   r   r   element_from_ANP?  s    zPowerBasis.element_from_ANPc                 C   s   |  |jj|jjjS )z5Convert an AlgebraicNumber into a PowerBasisElement. )r   r   minpolyrU   r   r   r   element_from_alg_numC  s    zPowerBasis.element_from_alg_numN)rl   rm   rn   ro   ry   rp   r>   r|   r   r*   r+   r   r/   rM   rS   r   r   r   r   r   r   r   r   r6     s"   


r6   c                   @   s  e Zd ZdZd9ddZdd Zdd	 Zd
d Zedd Z	dd Z
dd Zedd Zedd Zedd Zedd Zedd Zdd Zdd Zd d! Zd"d# Zd$d% Zd&d' Zd(d) Zd*d+ Zd:d-d.Zd/d0 ZeZd;d1d2Zd3d4 ZeZd5d6 Zd7d8 Z dS )<rh   zA submodule of another module.r   Nc                 C   s:   || _ || _|| _|| _|jd | _d| _d| _d| _dS )aN  
        Parameters
        ==========

        parent : :py:class:`~.Module`
            The module from which this one is derived.
        matrix : :py:class:`~.DomainMatrix` over :ref:`ZZ`
            The matrix whose columns define this submodule's generators as
            linear combinations over the parent's generators.
        denom : int, optional (default=1)
            Denominator for the coefficients given by the matrix.
        mult_tab : dict, ``None``, optional
            If already known, the multiplication table for this module may be
            supplied.

        r   N)	_parent_matrix_denomrx   r?   rw   
_QQ_matrix_starts_with_unity_is_sq_maxrank_HNF)r)   r,   matrixrE   r+   r   r   r   ry   K  s    zSubmodule.__init__c                 C   s8   dt | j    }| jdkr4|d| j 7 }|S )Nrh   r   /)reprr   r"   	to_MatrixtolistrE   r)   rr   r   r   r|   e  s    
zSubmodule.__repr__c                 C   sX   | j dkr| S t| j g| jR  }|dkr.| S t| | j| j| t| j | | jdS )af  
        Produce a reduced version of this submodule.

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

        In the reduced version, it is guaranteed that 1 is the only positive
        integer dividing both the submodule's denominator, and every entry in
        the submodule's matrix.

        Returns
        =======

        :py:class:`~.Submodule`

        r   rE   r+   )	rE   r   r#   typer,   r   
convert_tor   rx   r)   rY   r   r   r   reducedk  s    
zSubmodule.reducedc                 C   s   | j dd|df }| j| }d}| j}|duri }t|D ]@}i ||< t||D ](}|||  ||  |d || |< qTq>t| j|| j|dS )ze
        Produce a new module by discarding all generators before a given
        index *r*.
        Nr   )r   r*   rx   rP   rh   r,   rE   )r)   r   Wsr   mtr   r   r   r   r   discard_before  s    
(zSubmodule.discard_beforec                 C   s   | j S rV   r   r(   r   r   r   r*     s    zSubmodule.nc                 C   s   | j d u r|   | j S rV   r   r(   r   r   r   r+     s    
zSubmodule.mult_tabc                 C   sd   |   }i }| j}t|D ]>}i ||< t||D ]&}| || ||   || |< q0q|| _d S rV   )basis_element_pullbacksr*   rP   r/   flatrx   )r)   rb   r   r*   r   r   r   r   r   r     s    &zSubmodule.compute_mult_tabc                 C   s   | j S rV   )r   r(   r   r   r   r,     s    zSubmodule.parentc                 C   s   | j S rV   )r   r(   r   r   r   r     s    zSubmodule.matrixc                 C   s
   | j  S rV   )r   r   r(   r   r   r   r#     s    zSubmodule.coeffsc                 C   s   | j S rV   )r   r(   r   r   r   rE     s    zSubmodule.denomc                 C   s"   | j du r| j| j  | _ | j S )a1  
        :py:class:`~.DomainMatrix` over :ref:`QQ`, equal to
        ``self.matrix / self.denom``, and guaranteed to be dense.

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

        Depending on how it is formed, a :py:class:`~.DomainMatrix` may have
        an internal representation that is sparse or dense. We guarantee a
        dense representation here, so that tests for equivalence of submodules
        always come out as expected.

        Examples
        ========

        >>> from sympy.polys import Poly, cyclotomic_poly, ZZ
        >>> from sympy.abc import x
        >>> from sympy.polys.matrices import DomainMatrix
        >>> from sympy.polys.numberfields.modules import PowerBasis
        >>> T = Poly(cyclotomic_poly(5, x))
        >>> A = PowerBasis(T)
        >>> B = A.submodule_from_matrix(3*DomainMatrix.eye(4, ZZ), denom=6)
        >>> C = A.submodule_from_matrix(DomainMatrix.eye(4, ZZ), denom=2)
        >>> print(B.QQ_matrix == C.QQ_matrix)
        True

        Returns
        =======

        :py:class:`~.DomainMatrix` over :ref:`QQ`

        N)r   r   rE   rH   r(   r   r   r   	QQ_matrix  s    "
zSubmodule.QQ_matrixc                 C   s    | j d u r| dd| _ | j S )Nr   r   )r   equivr(   r   r   r   rM     s    
zSubmodule.starts_with_unityc                 C   s   | j d u rt| j| _ | j S rV   )r   is_sq_maxrank_HNFr   r(   r   r   r   r     s    
zSubmodule.is_sq_maxrank_HNFc                 C   s   t | jtS rV   )r5   r,   r6   r(   r   r   r   is_power_basis_submodule  s    z"Submodule.is_power_basis_submodulec                 C   s$   |   r| d| S | j|S d S r   )rM   r,   rS   rU   r   r   r   rS     s    zSubmodule.element_from_rationalc                 C   s   dd |   D S )zv
        Return list of this submodule's basis elements as elements of the
        submodule's parent module.
        c                 S   s   g | ]}|  qS r   )	to_parentr   er   r   r   r     r    z5Submodule.basis_element_pullbacks.<locals>.<listcomp>)rQ   r(   r   r   r   r     s    z!Submodule.basis_element_pullbacksc                 C   s   |j | kr| S |j | jkrz,| j}|j}||d  }|t}W n2 t	yd   t
dY n ty|   t
dY n0 |S t| jtr| j|}| |}| |S t
ddS )z
        Represent a module element as an integer-linear combination over the
        generators of this module.

        See Also
        ========

        .Module.represent
        .PowerBasis.represent

        r   z&Element outside QQ-span of this basis.z1Element in QQ-span but not ZZ-span of this basis.z.Element outside ancestor chain of this module.N)rW   r   r,   r   QQ_col_solver"   r   r   r   r   r   r5   rh   r/   )r)   r.   AbxZcoeffs_in_parentZparent_elementr   r   r   r/     s$    


zSubmodule.representc                 C   s   t |to|j| jkS rV   )r5   rh   r,   r~   r   r   r   is_compat_submodule  s    zSubmodule.is_compat_submodulec                 C   s   |  |r|j| jkS tS rV   )r   r   r}   r~   r   r   r   r     s    
zSubmodule.__eq__Tc           
      C   s`   | j |j  }}t||}|| ||  }}|| j ||j }	|rPt|	|d}	| jj|	|dS )a  
        Add this :py:class:`~.Submodule` to another.

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

        This represents the module generated by the union of the two modules'
        sets of generators.

        Parameters
        ==========

        other : :py:class:`~.Submodule`
        hnf : boolean, optional (default=True)
            If ``True``, reduce the matrix of the combined module to its
            Hermite Normal Form.
        hnf_modulus : :ref:`ZZ`, None, optional
            If a positive integer is provided, use this as modulus in the
            HNF reduction. See
            :py:func:`~sympy.polys.matrices.normalforms.hermite_normal_form`.

        Returns
        =======

        :py:class:`~.Submodule`

        r\   rD   )rE   r   r   r`   r   r,   ra   )
r)   r9   rc   rd   r[   r   re   r4   r   rf   r   r   r   add"  s    
zSubmodule.addc                 C   s   |  |r| |S tS rV   )r   r   r}   r~   r   r   r   __add__F  s    

zSubmodule.__add__c                    s   t rTt\}}||  kr(dkr0n n| S t| j| j| | j| dd S n~ttrj	| jkrfdd| 
 D }| jj|||dS | r| 
 
  }  fdd|D }| jj|||dS tS )a  
        Multiply this :py:class:`~.Submodule` by a rational number, a
        :py:class:`~.ModuleElement`, or another :py:class:`~.Submodule`.

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

        To multiply by a rational number or :py:class:`~.ModuleElement` means
        to form the submodule whose generators are the products of this
        quantity with all the generators of the present submodule.

        To multiply by another :py:class:`~.Submodule` means to form the
        submodule whose generators are all the products of one generator from
        the one submodule, and one generator from the other.

        Parameters
        ==========

        other : int, :ref:`ZZ`, :ref:`QQ`, :py:class:`~.ModuleElement`, :py:class:`~.Submodule`
        hnf : boolean, optional (default=True)
            If ``True``, reduce the matrix of the product module to its
            Hermite Normal Form.
        hnf_modulus : :ref:`ZZ`, None, optional
            If a positive integer is provided, use this as modulus in the
            HNF reduction. See
            :py:func:`~sympy.polys.matrices.normalforms.hermite_normal_form`.

        Returns
        =======

        :py:class:`~.Submodule`

        r   Nr   c                    s   g | ]} | qS r   r   r   )r9   r   r   r   z  r    z!Submodule.mul.<locals>.<listcomp>)rc   rd   c                    s   g | ]} D ]}|| qqS r   r   r   r4   r   )betasr   r   r     r    )r   r   rh   r,   r   rE   r   r5   ModuleElementrW   r   rg   r   r}   )r)   r9   rc   rd   r4   r   rb   alphasr   )r   r9   r   mulM  s     "
zSubmodule.mulc                 C   s
   |  |S rV   )r   r~   r   r   r   __mul__  s    zSubmodule.__mul__c                 C   s   | S rV   r   r(   r   r   r   _first_power  s    zSubmodule._first_powerc                 C   s   |j | jkst|  s$d}t||  }|}t| jd ddD ]8}|| }|j| |j	 |j| |j	  }||| 8 }qB|S )aD  
        If this submodule $B$ has defining matrix $W$ in square, maximal-rank
        Hermite normal form, then, given an element $x$ of the parent module
        $A$, we produce an element $y \in A$ such that $x - y \in B$, and the
        $i$th coordinate of $y$ satisfies $0 \leq y_i < w_{i,i}$. This
        representative $y$ is unique, in the sense that every element of
        the coset $x + B$ reduces to it under this procedure.

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

        In the special case where $A$ is a power basis for a number field $K$,
        and $B$ is a submodule representing an ideal $I$, this operation
        represents one of a few important ways of reducing an element of $K$
        modulo $I$ to obtain a "small" representative. See [Cohen00]_ Section
        1.4.3.

        Examples
        ========

        >>> from sympy import QQ, Poly, symbols
        >>> t = symbols('t')
        >>> k = QQ.alg_field_from_poly(Poly(t**3 + t**2 - 2*t + 8))
        >>> Zk = k.maximal_order()
        >>> A = Zk.parent
        >>> B = (A(2) - 3*A(0))*Zk
        >>> B.reduce_element(A(2))
        [3, 0, 0]

        Parameters
        ==========

        elt : :py:class:`~.ModuleElement`
            An element of this submodule's parent module.

        Returns
        =======

        elt : :py:class:`~.ModuleElement`
            An element of this submodule's parent module.

        Raises
        ======

        NotImplementedError
            If the given :py:class:`~.ModuleElement` does not belong to this
            submodule's parent module.
        StructureError
            If this submodule's defining matrix is not in square, maximal-rank
            Hermite normal form.

        References
        ==========

        .. [Cohen00] Cohen, H. *Advanced Topics in Computational Number
           Theory.*

        z;Reduction not implemented unless matrix square max-rank HNFr   )
rW   r,   r'   r   r   r   rP   r*   r#   rE   )r)   r.   msgrf   r4   ir   qr   r   r   reduce_element  s    ; zSubmodule.reduce_element)r   N)TN)TN)!rl   rm   rn   ro   ry   r|   r   r   rp   r*   r+   r   r,   r   r#   rE   r   rM   r   r   rS   r   r/   r   r   r   r   __radd__r   r   __rmul__r   r   r   r   r   r   rh   H  sF   







%#
$
7rh   c                 C   s   | j jr| jr| jr| jd }t|D ]\}| ||f j}|dkrF dS t|d |D ],}d| ||f j  krv|k sTn   dS qTq&dS dS )ar  
    Say whether a :py:class:`~.DomainMatrix` is in that special case of Hermite
    Normal Form, in which the matrix is also square and of maximal rank.

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

    We commonly work with :py:class:`~.Submodule` instances whose matrix is in
    this form, and it can be useful to be able to check that this condition is
    satisfied.

    For example this is the case with the :py:class:`~.Submodule` ``ZK``
    returned by :py:func:`~sympy.polys.numberfields.basis.round_two`, which
    represents the maximal order in a number field, and with ideals formed
    therefrom, such as ``2 * ZK``.

    r   Fr   T)r@   rA   	is_squareis_upperr?   rP   element)dmr*   r   r[   rO   r   r   r   r     s    
 r   c                 C   s*   t | trt| ||dS t| ||dS dS )z
    Factory function which builds a :py:class:`~.ModuleElement`, but ensures
    that it is a :py:class:`~.PowerBasisElement` if the module is a
    :py:class:`~.PowerBasis`.
    rD   N)r5   r6   PowerBasisElementr   )rW   rB   rE   r   r   r   rJ     s    
rJ   c                   @   s  e Zd ZdZd:ddZdd Zdd Zd	d
 Zed;ddZ	e
dd Zdd Zd<ddZe
dd Ze
dd Zdd Zdd Zdd Zdd Zd d! Zd"d# Zd$d% Zd&d' ZeZd(d) Zd*d+ Zd,d- Zd.d/ ZeZd0d1 Zd2d3 Zd4d5 Z d6d7 Z!d8d9 Z"dS )=r   z
    Represents an element of a :py:class:`~.Module`.

    NOTE: Should not be constructed directly. Use the
    :py:meth:`~.Module.__call__` method or the :py:func:`make_mod_elt()`
    factory function instead.
    r   c                 C   s   || _ || _|| _d| _dS )a  
        Parameters
        ==========

        module : :py:class:`~.Module`
            The module to which this element belongs.
        col : :py:class:`~.DomainMatrix` over :ref:`ZZ`
            Column vector giving the numerators of the coefficients of this
            element.
        denom : int, optional (default=1)
            Denominator for the coefficients of this element.

        N)rW   rB   rE   _QQ_col)r)   rW   rB   rE   r   r   r   ry   	  s    zModuleElement.__init__c                 C   s6   t dd | j D }| jdkr2|d| j 7 }|S )Nc                 S   s   g | ]}t |qS r   )rF   r   r   r   r   r     r    z*ModuleElement.__repr__.<locals>.<listcomp>r   r   )strrB   r   rE   r   r   r   r   r|     s    
zModuleElement.__repr__c                 C   sT   | j dkr| S t| j g| jR  }|dkr.| S t| | j| j| t| j | dS )z
        Produce a reduced version of this ModuleElement, i.e. one in which the
        gcd of the denominator together with all numerator coefficients is 1.
        r   rD   )rE   r   r#   r   rW   rB   r   r   r   r   r   r   r   "  s    

zModuleElement.reducedc                 C   s$   t | j| jt|t| jdS )z
        Produce a version of this :py:class:`~.ModuleElement` in which all
        numerator coefficients have been reduced mod *p*.
        rD   )rJ   rW   rB   r   r	   r   rE   )r)   pr   r   r   reduced_mod_p0  s    zModuleElement.reduced_mod_pc                 C   s   t |}| |||dS )zn
        Make a :py:class:`~.ModuleElement` from a list of ints (instead of a
        column vector).
        rD   )r$   )clsrW   r#   rE   rB   r   r   r   from_int_list9  s    zModuleElement.from_int_listc                 C   s   | j jS )z$The length of this element's column.)rW   r*   r(   r   r   r   r*   B  s    zModuleElement.nc                 C   s   | j S rV   )r*   r(   r   r   r   __len__G  s    zModuleElement.__len__Nc                 C   s   | j |S )zY
        Get a copy of this element's column, optionally converting to a domain.
        )rB   r   r)   r@   r   r   r   r   J  s    zModuleElement.columnc                 C   s
   | j  S rV   )rB   r   r(   r   r   r   r#   P  s    zModuleElement.coeffsc                 C   s"   | j du r| j| j  | _ | j S )z
        :py:class:`~.DomainMatrix` over :ref:`QQ`, equal to
        ``self.col / self.denom``, and guaranteed to be dense.

        See Also
        ========

        .Submodule.QQ_matrix

        N)r   rB   rE   rH   r(   r   r   r   r   T  s    
zModuleElement.QQ_colc                 C   s:   t | jtstdt| jj| jj| j | jj| j dS )zx
        Transform into a :py:class:`~.ModuleElement` belonging to the parent of
        this element's module.
        zNot an element of a Submodule.rD   )	r5   rW   rh   rI   rJ   r,   r   rB   rE   r(   r   r   r   r   d  s    zModuleElement.to_parentc                 C   s    || j kr| S |  |S dS )z
        Transform into a :py:class:`~.ModuleElement` belonging to a given
        ancestor of this element's module.

        Parameters
        ==========

        anc : :py:class:`~.Module`

        N)rW   r   to_ancestor)r)   Zancr   r   r   r   o  s    
zModuleElement.to_ancestorc                 C   s   | }t |jts| }q|S )zv
        Transform into a :py:class:`~.PowerBasisElement` over our
        :py:class:`~.PowerBasis` ancestor.
        )r5   rW   r6   r   )r)   r   r   r   r   over_power_basis  s    
zModuleElement.over_power_basisc                 C   s   t |to|j| jkS )ze
        Test whether other is another :py:class:`~.ModuleElement` with same
        module.
        )r5   r   rW   r~   r   r   r   	is_compat  s    zModuleElement.is_compatc                 C   sV   | j |j kr| |fS | j |j }|dur>| |||fS td|  d| dS )a  
        Try to make a compatible pair of :py:class:`~.ModuleElement`, one
        equivalent to this one, and one equivalent to the other.

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

        We search for the nearest common ancestor module for the pair of
        elements, and represent each one there.

        Returns
        =======

        Pair ``(e1, e2)``
            Each ``ei`` is a :py:class:`~.ModuleElement`, they belong to the
            same :py:class:`~.Module`, ``e1`` is equivalent to ``self``, and
            ``e2`` is equivalent to ``other``.

        Raises
        ======

        UnificationFailed
            If ``self`` and ``other`` have no common ancestor module.

        NzCannot unify z with )rW   r=   r   r   )r)   r9   r:   r   r   r   unify  s    zModuleElement.unifyc                 C   s   |  |r| j|jkS tS rV   )r   r   r}   r~   r   r   r   r     s    
zModuleElement.__eq__c                 C   sb   | |krdS t |tr,| |\}}||kS t|r^t | trP| | d| kS |  |S dS )a  
        A :py:class:`~.ModuleElement` may test as equivalent to a rational
        number or another :py:class:`~.ModuleElement`, if they represent the
        same algebraic number.

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

        This method is intended to check equivalence only in those cases in
        which it is easy to test; namely, when *other* is either a
        :py:class:`~.ModuleElement` that can be unified with this one (i.e. one
        which shares a common :py:class:`~.PowerBasis` ancestor), or else a
        rational number (which is easy because every :py:class:`~.PowerBasis`
        represents every rational number).

        Parameters
        ==========

        other : int, :ref:`ZZ`, :ref:`QQ`, :py:class:`~.ModuleElement`

        Returns
        =======

        bool

        Raises
        ======

        UnificationFailed
            If ``self`` and ``other`` do not share a common
            :py:class:`~.PowerBasis` ancestor.

        Tr   F)r5   r   r   r   r   rW   r   r   )r)   r9   r4   r   r   r   r   r     s    "

zModuleElement.equivc                    s   |  |rn| j|j }}t||}|| ||   t fddt| j|jD }t| | j||d S t	|t
rz| |\}}W n ty   t Y S 0 || S t|r| | j| S tS )a.  
        A :py:class:`~.ModuleElement` can be added to a rational number, or to
        another :py:class:`~.ModuleElement`.

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

        When the other summand is a rational number, it will be converted into
        a :py:class:`~.ModuleElement` (belonging to the first ancestor of this
        module that starts with unity).

        In all cases, the sum belongs to the nearest common ancestor (NCA) of
        the modules of the two summands. If the NCA does not exist, we return
        ``NotImplemented``.
        c                    s    g | ]\}} | |  qS r   r   r   r   r   r   r   r     r    z)ModuleElement.__add__.<locals>.<listcomp>rD   )r   rE   r   r$   r8   r#   r   rW   r   r5   r   r   r   r}   r   rS   )r)   r9   r[   r   re   rB   r4   r   r   r   r   r     s    

"

zModuleElement.__add__c                 C   s   | d S )Nr   r   r(   r   r   r   __neg__  s    zModuleElement.__neg__c                 C   s
   | |  S rV   r   r~   r   r   r   __sub__	  s    zModuleElement.__sub__c                 C   s
   |  | S rV   r   r~   r   r   r   __rsub__  s    zModuleElement.__rsub__c              	   C   sv  |  |r| j }| j |j  }}| j}dg| }t|D ]z}t||D ]j}|| ||  }	||kr|	|| ||  7 }	|	dkrP|| | }
t|D ]}||  |	|
|  7  < qqPqB| j|j }| j| j||dS t	|t
rz| |\}}W n ty   t Y S 0 || S t|rrt|\}}||  krJdkrRn n| S t| j| j| | j| d S tS )a  
        A :py:class:`~.ModuleElement` can be multiplied by a rational number,
        or by another :py:class:`~.ModuleElement`.

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

        When the multiplier is a rational number, the product is computed by
        operating directly on the coefficients of this
        :py:class:`~.ModuleElement`.

        When the multiplier is another :py:class:`~.ModuleElement`, the product
        will belong to the nearest common ancestor (NCA) of the modules of the
        two operands, and that NCA must have a multiplication table. If the NCA
        does not exist, we return ``NotImplemented``. If the NCA does not have
        a mult. table, ``ClosureFailure`` will be raised.
        r   rD   r   )r   rW   r+   rB   r   r*   rP   rE   r   r5   r   r   r   r}   r   r   rJ   r   )r)   r9   r   r   rf   r*   Cr   r   r   Rr   r[   r4   r   r   r   r   r     s<    





zModuleElement.__mul__c                 C   s
   | j  S rV   )rW   rT   r(   r   r   r   _zeroth_powerB  s    zModuleElement._zeroth_powerc                 C   s   | S rV   r   r(   r   r   r   r   E  s    zModuleElement._first_powerc                 C   s6   t |rt|}| d|  S t|tr2| d|  S tS )Nr   )r   r
   r5   r   r}   rU   r   r   r   __floordiv__H  s    
zModuleElement.__floordiv__c                 C   s   ||    S rV   )r   rU   r   r   r   __rfloordiv__P  s    zModuleElement.__rfloordiv__c                 C   s:   t |r|| j  }t|tr6|j| jkr6|| S tS )a  
        Reduce this :py:class:`~.ModuleElement` mod a :py:class:`~.Submodule`.

        Parameters
        ==========

        m : int, :ref:`ZZ`, :ref:`QQ`, :py:class:`~.Submodule`
            If a :py:class:`~.Submodule`, reduce ``self`` relative to this.
            If an integer or rational, reduce relative to the
            :py:class:`~.Submodule` that is our own module times this constant.

        See Also
        ========

        .Submodule.reduce_element

        )r   rW   ri   r5   rh   r,   r   r}   )r)   re   r   r   r   __mod__S  s
    
zModuleElement.__mod__)r   )r   )N)#rl   rm   rn   ro   ry   r|   r   r   classmethodr   rp   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      sD   
	




!. 1r   c                   @   s   e Zd ZdZedd ZdddZdddZed	d
 Zedd Z	dddZ
dddZdd Zdd ZdddZdd Zdd ZdS ) r   zl
    Subclass for :py:class:`~.ModuleElement` instances whose module is a
    :py:class:`~.PowerBasis`.
    c                 C   s   | j jS )z?Access the defining polynomial of the :py:class:`~.PowerBasis`.)rW   ru   r(   r   r   r   ru   r  s    zPowerBasisElement.TNc                 C   s    |p
| j j}tt| j|tdS )z4Obtain the numerator as a polynomial over :ref:`ZZ`.r@   )ru   r   r   r   r#   r   r)   r   r   r   r   	numeratorw  s    zPowerBasisElement.numeratorc                 C   s   | j |d| j S )z1Obtain the number as a polynomial over :ref:`QQ`.r   )r   rE   r   r   r   r   poly|  s    zPowerBasisElement.polyc                 C   s   | j ddddf jS )z6Say whether this element represents a rational number.r   N)rB   is_zero_matrixr(   r   r   r   is_rational  s    zPowerBasisElement.is_rationalc                 C   s$   | j j}|r|jjr|jjS | jjS )a^  
        Return a :py:class:`~.Symbol` to be used when expressing this element
        as a polynomial.

        If we have an associated :py:class:`~.AlgebraicField` whose primitive
        element has an alias symbol, we use that. Otherwise we use the variable
        of the minimal polynomial defining the power basis to which we belong.
        )rW   r>   rq   
is_aliasedaliasru   r   r)   rt   r   r   r   	generator  s    
zPowerBasisElement.generatorc                 C   s   |  |p| j S )z)Create a Basic expression from ``self``. )r   r   r{   r   r   r   r   r{     s    zPowerBasisElement.as_exprc                 C   s2   |p| j }|j}| j|d}||| j| j  S )z Compute the norm of this number.r   )ru   r   r   	resultantrE   r*   )r)   ru   r   r   r   r   r   norm  s    
zPowerBasisElement.normc                 C   s    |   }|| j}| j|S rV   )r   invertru   rW   r   )r)   r   Zf_invr   r   r   inverse  s    zPowerBasisElement.inversec                 C   s   |   | S rV   )r   rU   r   r   r   r     s    zPowerBasisElement.__rfloordiv__c                 C   s   |   t| S rV   )r   abs)r)   r   modulor   r   r   _negative_power  s    z!PowerBasisElement._negative_powerc                 C   s&   t tt| j t| jjjtS )z,Convert to an equivalent :py:class:`~.ANP`. )	r   r   r   r   r   r
   mapru   r   r(   r   r   r   to_ANP  s    zPowerBasisElement.to_ANPc                 C   s&   | j j}|r||  S tddS )a  
        Try to convert to an equivalent :py:class:`~.AlgebraicNumber`.

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

        In general, the conversion from an :py:class:`~.AlgebraicNumber` to a
        :py:class:`~.PowerBasisElement` throws away information, because an
        :py:class:`~.AlgebraicNumber` specifies a complex embedding, while a
        :py:class:`~.PowerBasisElement` does not. However, in some cases it is
        possible to convert a :py:class:`~.PowerBasisElement` back into an
        :py:class:`~.AlgebraicNumber`, namely when the associated
        :py:class:`~.PowerBasis` has a reference to an
        :py:class:`~.AlgebraicField`.

        Returns
        =======

        :py:class:`~.AlgebraicNumber`

        Raises
        ======

        StructureError
            If the :py:class:`~.PowerBasis` to which this element belongs does
            not have an associated :py:class:`~.AlgebraicField`.

        zNo associated AlgebraicFieldN)rW   r>   
to_alg_numr   r   r   r   r   r   r     s    zPowerBasisElement.to_alg_num)N)N)N)N)N)rl   rm   rn   ro   rp   ru   r   r   r   r   r{   r   r   r   r   r   r   r   r   r   r   r   l  s    







r   c                   @   s,   e Zd ZdZdd Zd	ddZd
ddZdS )ModuleHomomorphismz*A homomorphism from one module to another.c                 C   s   || _ || _|| _dS )a  
        Parameters
        ==========

        domain : :py:class:`~.Module`
            The domain of the mapping.

        codomain : :py:class:`~.Module`
            The codomain of the mapping.

        mapping : callable
            An arbitrary callable is accepted, but should be chosen so as
            to represent an actual module homomorphism. In particular, should
            accept elements of *domain* and return elements of *codomain*.

        Examples
        ========

        >>> from sympy import Poly, cyclotomic_poly
        >>> from sympy.polys.numberfields.modules import PowerBasis, ModuleHomomorphism
        >>> T = Poly(cyclotomic_poly(5))
        >>> A = PowerBasis(T)
        >>> B = A.submodule_from_gens([2*A(j) for j in range(4)])
        >>> phi = ModuleHomomorphism(A, B, lambda x: 6*x)
        >>> print(phi.matrix())  # doctest: +SKIP
        DomainMatrix([[3, 0, 0, 0], [0, 3, 0, 0], [0, 0, 3, 0], [0, 0, 0, 3]], (4, 4), ZZ)

        N)r@   codomainmapping)r)   r@   r   r   r   r   r   ry     s    zModuleHomomorphism.__init__Nc                    sd    j  } fdd|D }|s8t jjdft S |d j|dd  }|r`|	t
|}|S )a  
        Compute the matrix of this homomorphism.

        Parameters
        ==========

        modulus : int, optional
            A positive prime number $p$ if the matrix should be reduced mod
            $p$.

        Returns
        =======

        :py:class:`~.DomainMatrix`
            The matrix is over :ref:`ZZ`, or else over :ref:`GF(p)` if a
            modulus was given.

        c                    s   g | ]} j  |qS r   )r   r/   r   )r   r.   r(   r   r   r     r    z-ModuleHomomorphism.matrix.<locals>.<listcomp>r   r   N)r@   rQ   r   r_   r   r*   r   rH   r`   r   r	   )r)   modulusbasiscolsr   r   r(   r   r     s    
zModuleHomomorphism.matrixc                 C   s<   | j |d}|du r|t}| t }| j|S )a  
        Compute a Submodule representing the kernel of this homomorphism.

        Parameters
        ==========

        modulus : int, optional
            A positive prime number $p$ if the kernel should be computed mod
            $p$.

        Returns
        =======

        :py:class:`~.Submodule`
            This submodule's generators span the kernel of this
            homomorphism over :ref:`ZZ`, or else over :ref:`GF(p)` if a
            modulus was given.

        r   N)r   r   r
   	nullspacer   r"   r@   ra   )r)   r   r   rt   r   r   r   kernel  s
    
zModuleHomomorphism.kernel)N)N)rl   rm   rn   ro   ry   r   r  r   r   r   r   r     s   !
r   c                       s    e Zd ZdZ fddZ  ZS )ModuleEndomorphismz)A homomorphism from one module to itself.c                    s   t  ||| dS )az  
        Parameters
        ==========

        domain : :py:class:`~.Module`
            The common domain and codomain of the mapping.

        mapping : callable
            An arbitrary callable is accepted, but should be chosen so as
            to represent an actual module endomorphism. In particular, should
            accept and return elements of *domain*.

        N)superry   )r)   r@   r   	__class__r   r   ry   7  s    zModuleEndomorphism.__init__rl   rm   rn   ro   ry   __classcell__r   r   r  r   r  4  s   r  c                       s    e Zd ZdZ fddZ  ZS )InnerEndomorphismzz
    An inner endomorphism on a module, i.e. the endomorphism corresponding to
    multiplication by a fixed element.
    c                    s    t  | fdd  | _dS )a  
        Parameters
        ==========

        domain : :py:class:`~.Module`
            The domain and codomain of the endomorphism.

        multiplier : :py:class:`~.ModuleElement`
            The element $a$ defining the mapping as $x \mapsto a x$.

        c                    s    |  S rV   r   r   
multiplierr   r   <lambda>Z  r    z,InnerEndomorphism.__init__.<locals>.<lambda>N)r  ry   r  )r)   r@   r  r  r  r   ry   N  s    zInnerEndomorphism.__init__r
  r   r   r  r   r  H  s   r  c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	rj   z&The ring of endomorphisms on a module.c                 C   s
   || _ dS )z
        Parameters
        ==========

        domain : :py:class:`~.Module`
            The domain and codomain of the endomorphisms.

        Nr   r   r   r   r   ry   a  s    	zEndomorphismRing.__init__c                 C   s   t | j|S )a>  
        Form an inner endomorphism belonging to this endomorphism ring.

        Parameters
        ==========

        multiplier : :py:class:`~.ModuleElement`
            Element $a$ defining the inner endomorphism $x \mapsto a x$.

        Returns
        =======

        :py:class:`~.InnerEndomorphism`

        )r  r@   )r)   r  r   r   r   inner_endomorphisml  s    z#EndomorphismRing.inner_endomorphismc                    sf   t |tr^|j| jkr^|   j\}}|dkr4 S  dddf j fddtd|D  S tdS )a  
        Represent an element of this endomorphism ring, as a single column
        vector.

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

        Let $M$ be a module, and $E$ its ring of endomorphisms. Let $N$ be
        another module, and consider a homomorphism $\varphi: N \rightarrow E$.
        In the event that $\varphi$ is to be represented by a matrix $A$, each
        column of $A$ must represent an element of $E$. This is possible when
        the elements of $E$ are themselves representable as matrices, by
        stacking the columns of such a matrix into a single column.

        This method supports calculating such matrices $A$, by representing
        an element of this endomorphism ring first as a matrix, and then
        stacking that matrix's columns into a single column.

        Examples
        ========

        Note that in these examples we print matrix transposes, to make their
        columns easier to inspect.

        >>> from sympy import Poly, cyclotomic_poly
        >>> from sympy.polys.numberfields.modules import PowerBasis
        >>> from sympy.polys.numberfields.modules import ModuleHomomorphism
        >>> T = Poly(cyclotomic_poly(5))
        >>> M = PowerBasis(T)
        >>> E = M.endomorphism_ring()

        Let $\zeta$ be a primitive 5th root of unity, a generator of our field,
        and consider the inner endomorphism $\tau$ on the ring of integers,
        induced by $\zeta$:

        >>> zeta = M(1)
        >>> tau = E.inner_endomorphism(zeta)
        >>> tau.matrix().transpose()  # doctest: +SKIP
        DomainMatrix(
            [[0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], [-1, -1, -1, -1]],
            (4, 4), ZZ)

        The matrix representation of $\tau$ is as expected. The first column
        shows that multiplying by $\zeta$ carries $1$ to $\zeta$, the second
        column that it carries $\zeta$ to $\zeta^2$, and so forth.

        The ``represent`` method of the endomorphism ring ``E`` stacks these
        into a single column:

        >>> E.represent(tau).transpose()  # doctest: +SKIP
        DomainMatrix(
            [[0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, -1, -1, -1, -1]],
            (1, 16), ZZ)

        This is useful when we want to consider a homomorphism $\varphi$ having
        ``E`` as codomain:

        >>> phi = ModuleHomomorphism(M, E, lambda x: E.inner_endomorphism(x))

        and we want to compute the matrix of such a homomorphism:

        >>> phi.matrix().transpose()  # doctest: +SKIP
        DomainMatrix(
            [[1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
            [0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, -1, -1, -1, -1],
            [0, 0, 1, 0, 0, 0, 0, 1, -1, -1, -1, -1, 1, 0, 0, 0],
            [0, 0, 0, 1, -1, -1, -1, -1, 1, 0, 0, 0, 0, 1, 0, 0]],
            (4, 16), ZZ)

        Note that the stacked matrix of $\tau$ occurs as the second column in
        this example. This is because $\zeta$ is the second basis element of
        ``M``, and $\varphi(\zeta) = \tau$.

        Parameters
        ==========

        element : :py:class:`~.ModuleEndomorphism` belonging to this ring.

        Returns
        =======

        :py:class:`~.DomainMatrix`
            Column vector equalling the vertical stacking of all the columns
            of the matrix that represents the given *element* as a mapping.

        r   Nc                    s   g | ]} d d |f qS rV   r   rN   r   r   r   r     r    z.EndomorphismRing.represent.<locals>.<listcomp>r   )r5   r  r@   r   r?   vstackrP   r'   )r)   r   re   r*   r   r  r   r/   ~  s    W
*zEndomorphismRing.representN)rl   rm   rn   ro   ry   r  r/   r   r   r   r   rj   ^  s   rj   Nc              	   C   s  | j }| std|du r"g }|d}|| |j|d}| }d}td|jd D ]}	|| |j|d}
z||
d }W n$ ty   |	|
}|| 9 }Y qX0 dgdd t
| D  }|ptd}|jrt|||jd	}nt|||d} qqX|S )
a|  
    Find a polynomial of least degree (not necessarily irreducible) satisfied
    by an element of a finitely-generated ring with unity.

    Examples
    ========

    For the $n$th cyclotomic field, $n$ an odd prime, consider the quadratic
    equation whose roots are the two periods of length $(n-1)/2$. Article 356
    of Gauss tells us that we should get $x^2 + x - (n-1)/4$ or
    $x^2 + x + (n+1)/4$ according to whether $n$ is 1 or 3 mod 4, respectively.

    >>> from sympy import Poly, cyclotomic_poly, primitive_root, QQ
    >>> from sympy.abc import x
    >>> from sympy.polys.numberfields.modules import PowerBasis, find_min_poly
    >>> n = 13
    >>> g = primitive_root(n)
    >>> C = PowerBasis(Poly(cyclotomic_poly(n, x)))
    >>> ee = [g**(2*k+1) % n for k in range((n-1)//2)]
    >>> eta = sum(C(e) for e in ee)
    >>> print(find_min_poly(eta, QQ, x=x).as_expr())
    x**2 + x - 3
    >>> n = 19
    >>> g = primitive_root(n)
    >>> C = PowerBasis(Poly(cyclotomic_poly(n, x)))
    >>> ee = [g**(2*k+2) % n for k in range((n-1)//2)]
    >>> eta = sum(C(e) for e in ee)
    >>> print(find_min_poly(eta, QQ, x=x).as_expr())
    x**2 + x + 5

    Parameters
    ==========

    alpha : :py:class:`~.ModuleElement`
        The element whose min poly is to be found, and whose module has
        multiplication and starts with unity.

    domain : :py:class:`~.Domain`
        The desired domain of the polynomial.

    x : :py:class:`~.Symbol`, optional
        The desired variable for the polynomial.

    powers : list, optional
        If desired, pass an empty list. The powers of *alpha* (as
        :py:class:`~.ModuleElement` instances) from the zeroth up to the degree
        of the min poly will be recorded here, as we compute them.

    Returns
    =======

    :py:class:`~.Poly`, ``None``
        The minimal polynomial for alpha, or ``None`` if no polynomial could be
        found over the desired domain.

    Raises
    ======

    MissingUnityError
        If the module to which alpha belongs does not start with unity.
    ClosureFailure
        If the module to which alpha belongs is not closed under
        multiplication.

    z8alpha must belong to finitely generated ring with unity.Nr   r   r   c                 S   s   g | ]
}| qS r   r   r   r   r   r   r   8  r    z!find_min_poly.<locals>.<listcomp>r   r  )rW   rM   r   r3   r   rP   r*   r   r   r`   r   to_list_flatr   is_FFr   r   )alphar@   r   powersr   rT   Zpowers_matrixakre   r   Zak_colXr#   r   r   r   find_min_poly  s2    B


r  )r   )NN)4ro   sympy.core.numbersr   r   sympy.core.symbolr   sympy.polys.polyclassesr   sympy.polys.polytoolsr   sympy.polys.densetoolsr   "sympy.polys.domains.algebraicfieldr   Zsympy.polys.domains.finitefieldr	   !sympy.polys.domains.rationalfieldr
   sympy.polys.domains.integerringr   Z!sympy.polys.matrices.domainmatrixr   Zsympy.polys.matrices.exceptionsr   Z sympy.polys.matrices.normalformsr   sympy.polys.polyerrorsr   r   sympy.polys.polyutilsr   
exceptionsr   r   r   	utilitiesr   r   r   r$   r%   r6   rh   r   rJ   r   r   r   r  r  rj   r  r   r   r   r   <module>   sP    5   q    
  nce 