
    sg\3                     ~    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 Zd	 Zd
 Zd Zd Zd ZddddZy)z,Functions returning normal forms of matrices    )defaultdict   )DomainMatrix)DMDomainErrorDMShapeError)symmetric_residue)QQZZc                 r    t        |       }t        j                  || 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smfs      S/var/www/html/venv/lib/python3.12/site-packages/sympy/polys/matrices/normalforms.pysmith_normal_formr      s/    $ QD


D!((AGG
4CJ    c                     t        t        |             D ]8  }| |   |   }||z  || |   |   z  z   | |   |<   ||z  || |   |   z  z   | |   |<   : y N)rangelen)	r   ijabcdkes	            r   add_columnsr"   (   sj     3q6] "aDGA#!A$q'	/!QA#!A$q'	/!Q"r   c                      j                   j                  sd}t        |      d j                  v ry j                  x\  }t	         j                         j                  j                                fdfd}fd}t              D cg c]  } |   d   dk7  s| }}|r |d   dk7  r |d       d   c d<    |d   <   nLt              D cg c]  } d   |   dk7  s| }}|r&|d   dk7  r D ]  }||d      |d   c|d<   ||d   <    t         fdt        d      D              st         fd	t        d      D              rN |         |        t         fdt        d      D              r/t         fd	t        d      D              rNd|v rd}	n4t         dd
 D 
cg c]  }
|
dd
 	 c}
dz
  dz
  f      }t        |      }	 d   d   r d   d   g}|j                  |	       t        t        |      dz
        D ]{  }||   rij                  ||dz      ||         d   dk7  rHj                  ||dz      ||         }j                  ||   |      d   ||dz      z  ||dz   <   |||<   q t!        |      S  t!        |      S |	 d   d   fz   }t!        |      S c c}w c c}w c c}
w )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    c                     t        	      D ]8  }| |   |   }||z  || |   |   z  z   | |   |<   ||z  || |   |   z  z   | |   |<   : y r   )r   )
r   r   r   r   r   r   r   r    r!   colss
            r   add_rowsz#invariant_factors.<locals>.add_rowsH   sg     t 	&A!QAcAad1gIoAaDGcAad1gIoAaDG	&r   c           
         | d   d   dk(  r| S | d   d   }t        d      D ]  }| |   d   dk(  rj                  | |   d   |      \  }}|dk(  r 
| d|dd| d       ?j                  || |   d         \  }}}j                  | |   d   |      d   }j                  ||      d   }	 
| d|||||	        |} | S Nr   r   )r   divgcdex)r   pivotr   r   rr   r   gd_0d_jr'   r   rowss             r   clear_columnz'invariant_factors.<locals>.clear_columnP   s    Q47a<H!Qq$ 	AtAw!|::ad1gu-DAqAvAq!QA. ,,uad1g61ajj1a!,Q/jj*1-Aq!QcT2	 r   c           
         | d   d   dk(  r| S | d   d   }t        d
      D ]  }| d   |   dk(  rj                  | d   |   |      \  }}|dk(  rt        | d|dd| d       Bj                  || d   |         \  }}}j                  | d   |   |      d   }j                  ||      d   }	t        | d|||||	        |} | S r)   )r   r*   r"   r+   )r   r,   r   r   r-   r   r   r.   r/   r0   r&   r   s             r   	clear_rowz$invariant_factors.<locals>.clear_rowc   s    Q47a<H!Qq$ 	AtAw!|::ad1gu-DAqAvAq!QA2q1 ,,uad1g61ajj1a!,Q/jj*1-Aq!Q35	 r   c              3   4   K   | ]  }d    |   d k7    ywr   Nr$   .0r   r   s     r   	<genexpr>z$invariant_factors.<locals>.<genexpr>        3qtAw!|3   r   c              3   4   K   | ]  }|   d    d k7    ywr6   r$   r7   s     r   r9   z$invariant_factors.<locals>.<genexpr>   r:   r;   N)r   is_PID
ValueErrorr   listto_denserepto_ddmr   anyr   r   extendr   r*   gcdtuple)r   msgr   r2   r4   r   indr   rowr   r-   lower_rightresultr.   r'   r&   r   r1   s   `             @@@@r   r   r   1   s    XXF==HoAGG| JD$QZZ\$$&'A&&( Dk
2QqT!W\1
2C
2
s1v{CF)QqT!aAi+6Q1aAq663q6Q; :&)#a&k3q6#ACF: 3U1T]333U1T]33OaL 3U1T]333U1T]33 	Ez"1QR5#9aAabE#9DFDF;KVT -tAwA$q'ds6{1}% 	AayVZZqsVAY?BaGJJvac{F1I6$jjA6q9&1+Eqsq	 =	 = 1a
"=E 3 7 $:s   J>,J>!K2K=Kc                 p    t        j                  | |      \  }}}| dk7  r|| z  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.   s        r   _gcdexrP      sG     hhq!nGAq!Av!a%1*a%BQa7Nr   c                    | j                   j                  st        d      | j                  \  }}| j	                         j
                  j                         j                         } |}t        |dz
  dd      D ]  }|dk(  r n|dz  }t        |dz
  dd      D ]R  }| |   |   dk7  st        | |   |   | |   |         \  }}}| |   |   |z  | |   |   |z  }
}	t        | |||||
 |	       T | |   |   }|dk  rt        | ||dddd       | }|dk(  r|dz  }t        |dz   |      D ]  }| |   |   |z  }t        | ||d| dd       !  t        j                  | j                               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   rM   r   N)r   is_ZZr   r   r@   rA   rB   copyr   rP   r"   r   from_repto_dfm_or_ddm)Ar   nr    r   r   uvr   r-   sr   qs                r   _hermite_normal_formr]      s   8 88>><== 77DAq	

!&&(A 	
A1q5"b! !26 	Q q1ub"% 	2AtAw!| !1a!A$q'21atAw!|QqT!W\1Aq!QA2q1	2 aDGq51aQA.A 6FA
 1q5!_ 2aDGqLAq!QAq12?!2H   !23AqrE::r   c                    | j                   j                  st        d      t        j                  |      r|dk  rt        d      d }t        t              }| j                  \  }}||k  rt        d      | j                         j                  j                         j                         } |}|}t        |dz
  dd      D ]  }|dz  }t        |dz
  dd      D ]P  }	| |   |	   dk7  st        | |   |   | |   |	         \  }
}}| |   |   |z  | |   |	   |z  }} || |||	|
|| |       R | |   |   }|dk(  r
|x| |   |<   }t        ||      \  }
}}t        |      D ]  }|
| |   |   z  |z  ||   |<    ||   |   dk(  r|||   |<   t        |dz   |      D ]%  }	||   |	   ||   |   z  }t        ||	|d| dd       ' ||z  } t!        |||ft              j                         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.)

    rR   r   z0Modulus D must be positive element of domain ZZ.c                     t        t        |             D ]R  }| |   |   }	t        ||	z  || |   |   z  z   |z  |      | |   |<   t        ||	z  || |   |   z  z   |z  |      | |   |<   T y r   )r   r   r   )
r   Rr   r   r   r   r   r   r    r!   s
             r   add_columns_mod_Rz8_hermite_normal_form_modulo_D.<locals>.add_columns_mod_R0  s     s1v 	FA!QA'QQqT!W)<(A1EAaDG'QQqT!W)<(A1EAaDG	Fr   z2Matrix must have at least as many columns as rows.rM   r   )r   rS   r   r
   of_typer   dictr   r   r@   rA   rB   rT   r   rP   r"   r   )rW   Dra   Wr   rX   r    r`   r   r   rY   rZ   r   r-   r[   r   iir\   s                     r   _hermite_normal_form_modulo_Drg      s9   Z 88>><==::a=AENOOF 	DA77DAq1uOPP	

!&&(A	A	A1q5"b! 	Qq1ub"% 	;AtAw!| 1a!A$q'21atAw!|QqT!W\1!!Q1aQB:		;
 aDG6OAaDGaA,1a( 	&B2qzA~AbE!H	&Q47a<AaDGq1ua 	.A!Q1Q47"A1aQB1-	. 	
a%& Aq62&//11r   NF)rd   
check_rankc                    | j                   j                  st        d      |A|r3| j                  t              j                         | 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.)

    rR   r   )	r   rS   r   
convert_tor	   rankr   rg   r]   )rW   rd   rh   s      r   hermite_normal_formrl   V  s\    v 88>><==}jALL,<,A,A,Cqwwqz,Q,Q22#A&&r   )__doc__collectionsr   domainmatrixr   
exceptionsr   r   sympy.ntheory.modularr   sympy.polys.domainsr	   r
   r   r"   r   rP   r]   rg   rl   r$   r   r   <module>rs      sH    2 # & 3 3 &."hV*J;ZU2p !% @'r   