o
    g\3                     @   s   d 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 dd	 Zd
d Zdd Zdd Zdd Zdd ZdddddZdS )z,Functions returning normal forms of matrices    )defaultdict   )DomainMatrix)DMDomainErrorDMShapeError)symmetric_residue)QQZZc                 C   s   t | }t|| j| j}|S )aJ  
    Return the Smith Normal Form of a matrix `m` over the ring `domain`.
    This will only work if the ring is a principal ideal domain.

    Examples
    ========

    >>> from sympy import ZZ
    >>> from sympy.polys.matrices import DomainMatrix
    >>> from sympy.polys.matrices.normalforms import smith_normal_form
    >>> m = DomainMatrix([[ZZ(12), ZZ(6), ZZ(4)],
    ...                   [ZZ(3), ZZ(9), ZZ(6)],
    ...                   [ZZ(2), ZZ(16), ZZ(14)]], (3, 3), ZZ)
    >>> print(smith_normal_form(m).to_Matrix())
    Matrix([[1, 0, 0], [0, 10, 0], [0, 0, -30]])

    )invariant_factorsr   diagdomainshape)minvssmf r   W/var/www/visachat/venv/lib/python3.10/site-packages/sympy/polys/matrices/normalforms.pysmith_normal_form   s   r   c           	      C   sb   t t| D ](}| | | }|| || | |   | | |< || || | |   | | |< qd S N)rangelen	r   ijabcdker   r   r   add_columns(   s
    "r    c                    s  j jsd}t|djv rdS j \}t j fdd  fdd}fdd	}fd
dtD }|r]|d dkr]|d  d d< |d < n)fddtD }|r|d dkrD ]}||d  |d |d< ||d < qrt	fddtdD st	fddtdD r||t	fddtdD st	fddtdD sd|v rd}nt
dd dd D d d f}t|}d d rHd d g}	|	| tt|	d D ]B}
|	|
 r?|	|
d  |	|
 d dkr?|	|
d  |	|
 }|	|
 |d |	|
d   |	|
d < ||	|
< q t|	S t|	S |d d f }	t|	S )a3  
    Return the tuple of abelian invariants for a matrix `m`
    (as in the Smith-Normal form)

    References
    ==========

    [1] https://en.wikipedia.org/wiki/Smith_normal_form#Algorithm
    [2] https://web.archive.org/web/20200331143852/https://sierra.nmsu.edu/morandi/notes/SmithNormalForm.pdf

    z8The matrix entries must be over a principal ideal domainr   r   c           	         s^   t  D ](}| | | }|| || | |   | | |< || || | |   | | |< qd S r   )r   r   )colsr   r   add_rowsH   s
    "z#invariant_factors.<locals>.add_rowsc           
   	      s   | d d dkr
| S | d d }t dD ]U}| | d dkr q| | d |\}}|dkr< | d|dd| d q|| | d \}}}| | d |d }||d }	 | d|||||	  |}q| S Nr   r   )r   divgcdex
r   pivotr   r   rr   r   gd_0d_j)r"   r   rowsr   r   clear_columnP      z'invariant_factors.<locals>.clear_columnc           
   	      s   | d d dkr
| S | d d }t d D ]U}| d | dkr q| d | |\}}|dkr<t| d|dd| d q|| d | \}}}| d | |d }||d }	t| d|||||	  |}q| S r#   )r   r$   r    r%   r&   )r!   r   r   r   	clear_rowc   r.   z$invariant_factors.<locals>.clear_rowc                    s    g | ]} | d  d kr|qS r   r   .0r   r   r   r   
<listcomp>w        z%invariant_factors.<locals>.<listcomp>c                    s    g | ]} d  | d kr|qS r0   r   )r2   r   r3   r   r   r4   {   r5   c                 3   s     | ]} d  | d kV  qdS r   Nr   r1   r3   r   r   	<genexpr>       z$invariant_factors.<locals>.<genexpr>r   c                 3   s     | ]} | d  d kV  qdS r6   r   r1   r3   r   r   r7      r8   c                 S   s   g | ]}|d d qS )r   Nr   )r2   r(   r   r   r   r4      s    N)r   is_PID
ValueErrorr   listto_denserepto_ddmr   anyr   r
   extendr   r$   gcdtuple)r   msgr   r-   r/   indrowr   lower_rightresultr   r)   r   )r"   r!   r   r   r,   r   r
   1   sT   
$$*
,(r
   c                 C   sD   t | |\}}}| dkr||  dkrd}| dk rdnd}|||fS )a  
    This supports the functions that compute Hermite Normal Form.

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

    Let x, y be the coefficients returned by the extended Euclidean
    Algorithm, so that x*a + y*b = g. In the algorithms for computing HNF,
    it is critical that x, y not only satisfy the condition of being small
    in magnitude -- namely that |x| <= |b|/g, |y| <- |a|/g -- but also that
    y == 0 when a | b.

    r   r   )r	   r%   )r   r   xyr)   r   r   r   _gcdex   s
   
rK   c              
   C   sp  | j jstd| j\}}|  j  } |}t|d ddD ]}|dkr( n|d8 }t|d ddD ]6}| | | dkrjt	| | | | | | \}}}| | | | | | | | }	}
t
| |||||
 |	 q4| | | }|dk rt
| ||dddd | }|dkr|d7 }q t|d |D ]}| | | | }t
| ||d| dd qq t|  dd|df S )a  
    Compute the Hermite Normal Form of DomainMatrix *A* over :ref:`ZZ`.

    Parameters
    ==========

    A : :py:class:`~.DomainMatrix` over domain :ref:`ZZ`.

    Returns
    =======

    :py:class:`~.DomainMatrix`
        The HNF of matrix *A*.

    Raises
    ======

    DMDomainError
        If the domain of the matrix is not :ref:`ZZ`.

    References
    ==========

    .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.*
       (See Algorithm 2.4.5.)

    Matrix must be over domain ZZ.r   rH   r   N)r   is_ZZr   r   r<   r=   r>   copyr   rK   r    r   from_repto_dfm_or_ddm)Ar   nr   r   r   uvr   r(   sr   qr   r   r   _hermite_normal_form   s4   
 "
rW   c                 C   s  | j jstdt|r|dk rtddd }tt}| j\}}||k r*td| 	 j
  } |}|}t|d ddD ]}|d8 }t|d ddD ]7}	| | |	 dkrt| | | | | |	 \}
}}| | | | | | |	 | }}|| |||	|
|| | qM| | | }|dkr| | | |< }t||\}
}}t|D ]}|
| | |  | || |< q|| | dkr||| |< t|d |D ]}	|| |	 || |  }t||	|d| dd q|| }q?t|||ft	 S )	a[  
    Perform the mod *D* Hermite Normal Form reduction algorithm on
    :py:class:`~.DomainMatrix` *A*.

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

    If *A* is an $m \times n$ matrix of rank $m$, having Hermite Normal Form
    $W$, and if *D* is any positive integer known in advance to be a multiple
    of $\det(W)$, then the HNF of *A* can be computed by an algorithm that
    works mod *D* in order to prevent coefficient explosion.

    Parameters
    ==========

    A : :py:class:`~.DomainMatrix` over :ref:`ZZ`
        $m \times n$ matrix, having rank $m$.
    D : :ref:`ZZ`
        Positive integer, known to be a multiple of the determinant of the
        HNF of *A*.

    Returns
    =======

    :py:class:`~.DomainMatrix`
        The HNF of matrix *A*.

    Raises
    ======

    DMDomainError
        If the domain of the matrix is not :ref:`ZZ`, or
        if *D* is given but is not in :ref:`ZZ`.

    DMShapeError
        If the matrix has more rows than columns.

    References
    ==========

    .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.*
       (See Algorithm 2.4.8.)

    rL   r   z0Modulus D must be positive element of domain ZZ.c           
      S   sv   t t| D ]2}| | | }	t||	 || | |   | || | |< t||	 || | |   | || | |< qd S r   )r   r   r   )
r   Rr   r   r   r   r   r   r   r   r   r   r   add_columns_mod_R0  s
   *,z8_hermite_normal_form_modulo_D.<locals>.add_columns_mod_Rz2Matrix must have at least as many columns as rows.rH   r   )r   rM   r   r	   of_typer   dictr   r   r<   r=   r>   rN   r   rK   r    r   )rQ   DrY   Wr   rR   r   rX   r   r   rS   rT   r   r(   rU   r   iirV   r   r   r   _hermite_normal_form_modulo_D   sB   -
 "
r_   NF)r\   
check_rankc                C   sF   | j jstd|dur|r| t | jd krt| |S t| S )a)  
    Compute the Hermite Normal Form of :py:class:`~.DomainMatrix` *A* over
    :ref:`ZZ`.

    Examples
    ========

    >>> from sympy import ZZ
    >>> from sympy.polys.matrices import DomainMatrix
    >>> from sympy.polys.matrices.normalforms import hermite_normal_form
    >>> m = DomainMatrix([[ZZ(12), ZZ(6), ZZ(4)],
    ...                   [ZZ(3), ZZ(9), ZZ(6)],
    ...                   [ZZ(2), ZZ(16), ZZ(14)]], (3, 3), ZZ)
    >>> print(hermite_normal_form(m).to_Matrix())
    Matrix([[10, 0, 2], [0, 15, 3], [0, 0, 2]])

    Parameters
    ==========

    A : $m \times n$ ``DomainMatrix`` over :ref:`ZZ`.

    D : :ref:`ZZ`, optional
        Let $W$ be the HNF of *A*. If known in advance, a positive integer *D*
        being any multiple of $\det(W)$ may be provided. In this case, if *A*
        also has rank $m$, then we may use an alternative algorithm that works
        mod *D* in order to prevent coefficient explosion.

    check_rank : boolean, optional (default=False)
        The basic assumption is that, if you pass a value for *D*, then
        you already believe that *A* has rank $m$, so we do not waste time
        checking it for you. If you do want this to be checked (and the
        ordinary, non-modulo *D* algorithm to be used if the check fails), then
        set *check_rank* to ``True``.

    Returns
    =======

    :py:class:`~.DomainMatrix`
        The HNF of matrix *A*.

    Raises
    ======

    DMDomainError
        If the domain of the matrix is not :ref:`ZZ`, or
        if *D* is given but is not in :ref:`ZZ`.

    DMShapeError
        If the mod *D* algorithm is used but the matrix has more rows than
        columns.

    References
    ==========

    .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.*
       (See Algorithms 2.4.5 and 2.4.8.)

    rL   Nr   )	r   rM   r   
convert_tor   rankr   r_   rW   )rQ   r\   r`   r   r   r   hermite_normal_formV  s
   ;$
rc   )__doc__collectionsr   domainmatrixr   
exceptionsr   r   sympy.ntheory.modularr   sympy.polys.domainsr   r	   r   r    r
   rK   rW   r_   rc   r   r   r   r   <module>   s    		kMX