o
    §ƒðjË€  ã                   @   sª   d dl mZ d dlmZ d dlmZ d dlmZmZ ddl	m
Z
mZmZmZmZmZmZ edkr3dgZedƒZd	gZedgd
�G dd	„ d	ƒƒZd dlmZ d dlmZ dS )é    )ÚGROUND_TYPES)Úimport_module)Údoctest_depends_on)ÚZZÚQQé   )ÚDMBadInputErrorÚDMDomainErrorÚDMNonSquareMatrixErrorÚDMNonInvertibleMatrixErrorÚDMRankErrorÚDMShapeErrorÚDMValueErrorÚflintÚ*ÚDFM©Úground_typesc                   @   sÌ  e Zd ZdZdZdZdZdd„ Zedd„ ƒZ	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edd„ ƒZdd„ Zdd„ Zdd „ Zd!d"„ Zd#d$„ Zd%d&„ Zed'd(„ ƒZed)d*„ ƒZd+d,„ Zd-d.„ Zed/d0„ ƒZd1d2„ Zed3d4„ ƒZ d5d6„ Z!ed7d8„ ƒZ"d9d:„ Z#d;d<„ Z$d=d>„ Z%d?d@„ Z&dAdB„ Z'dCdD„ Z(dEdF„ Z)dGdH„ Z*dIdJ„ Z+dKdL„ Z,dMdN„ Z-dOdP„ Z.dQdR„ Z/dSdT„ Z0dUdV„ Z1dWdX„ Z2edYdZ„ ƒZ3ed[d\„ ƒZ4ed]d^„ ƒZ5ed_d`„ ƒZ6dadb„ Z7dcdd„ Z8dedf„ Z9dgdh„ Z:didj„ Z;dkdl„ Z<dmdn„ Z=dodp„ Z>dqdr„ Z?dsdt„ Z@dudv„ ZAeBdwdx�dydz„ ƒZCeBdwdx�d{d|„ ƒZDeBdwdx�d}d~„ ƒZEdd€„ ZFd�d‚„ ZGeBdwdx�dƒd„„ ƒZHd…d†„ ZId‡dˆ„ ZJd™dŠd‹„ZKdŒd�„ ZLdšd’d“„ZMeBdwdx�d›d•d–„ƒZNeBdwdx�d›d—d˜„ƒZOd‰S )œr   a&  
    Dense FLINT matrix. This class is a wrapper for matrices from python-flint.

    >>> from sympy.polys.domains import ZZ
    >>> from sympy.polys.matrices.dfm import DFM
    >>> dfm = DFM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
    >>> dfm
    [[1, 2], [3, 4]]
    >>> dfm.rep
    [1, 2]
    [3, 4]
    >>> type(dfm.rep)  # doctest: +SKIP
    <class 'flint._flint.fmpz_mat'>

    Usually, the DFM class is not instantiated directly, but is created as the
    internal representation of :class:`~.DomainMatrix`. When
    `SYMPY_GROUND_TYPES` is set to `flint` and `python-flint` is installed, the
    :class:`DFM` class is used automatically as the internal representation of
    :class:`~.DomainMatrix` in dense format if the domain is supported by
    python-flint.

    >>> from sympy.polys.matrices.domainmatrix import DM
    >>> dM = DM([[1, 2], [3, 4]], ZZ)
    >>> dM.rep
    [[1, 2], [3, 4]]

    A :class:`~.DomainMatrix` can be converted to :class:`DFM` by calling the
    :meth:`to_dfm` method:

    >>> dM.to_dfm()
    [[1, 2], [3, 4]]

    ÚdenseTFc              	   C   sV   |   |¡}d|vr z||ƒ}W n ttfy   td|› �ƒ‚w ||Ž }|  |||¡S )úConstruct from a nested list.r   z"Input should be a list of list of )Ú_get_flint_funcÚ
ValueErrorÚ	TypeErrorr   Ú_new)ÚclsÚrowslistÚshapeÚdomainÚ	flint_matÚrep© r    ú›/tmp/claude-1000/-var-www-html-academy/3f42efd1-c2b7-4d08-9b05-30d86bb35479/scratchpad/piper/venv/lib/python3.10/site-packages/sympy/polys/matrices/_dfm.pyÚ__new__m   s   
ÿzDFM.__new__c                 C   s:   |   |||¡ t | ¡}||_| |_\|_|_||_|S )z)Internal constructor from a flint matrix.)Ú_checkÚobjectr"   r   r   ÚrowsÚcolsr   )r   r   r   r   Úobjr    r    r!   r   {   s   
zDFM._newc                 C   s   |   || j| j¡S )z>Create a new DFM with the same shape and domain but a new rep.)r   r   r   )Úselfr   r    r    r!   Ú_new_rep…   ó   zDFM._new_repc                 C   sš   |  ¡ | ¡ f}||krtdƒ‚|tkrt|tjƒstdƒ‚|tkr,t|tj	ƒs,tdƒ‚|j
r<t|tjtjfƒs<tdƒ‚|ttfvrI|j
sKtdƒ‚d S d S )Nz(Shape of rep does not match shape of DFMzRep is not a flint.fmpz_matzRep is not a flint.fmpq_matz1Rep is not a flint.fmpz_mod_mat or flint.nmod_matú#Only ZZ and QQ are supported by DFM)ÚnrowsÚncolsr   r   Ú
isinstancer   Úfmpz_matÚRuntimeErrorr   Úfmpq_matÚis_FFÚfmpz_mod_matÚnmod_matÚNotImplementedError)r   r   r   r   Úrepshaper    r    r!   r#   ‰   s   ÿz
DFM._checkc                 C   s   |t tfv p|jo|jS )z4Return True if the given domain is supported by DFM.)r   r   r2   Ú	_is_flint)r   r   r    r    r!   Ú_supports_domain—   s   zDFM._supports_domainc                    sr   |t krtjS |tkrtjS |jr5| ¡ ‰t|jtj	ƒr(tj
‰ ‡ ‡fdd„}|S t ˆ¡‰‡fdd„}|S tdƒ‚)z3Return the flint matrix class for the given domain.c                     s:   t | ƒdkrt| d tjƒrˆ | d ƒS ˆ g | ¢ˆ‘R Ž S )Nr   r   )Úlenr.   r   r4   ©Úe)Ú_clsÚcr    r!   Ú_func§   s   z"DFM._get_flint_func.<locals>._funcc                     s   t jg | ¢ˆ ‘R Ž S ©N)r   r3   r:   )Úmr    r!   Ú<lambda>®   ó    z%DFM._get_flint_func.<locals>.<lambda>r+   )r   r   r/   r   r1   r2   Úcharacteristicr.   ÚoneÚnmodr4   Úfmpz_mod_ctxr5   )r   r   r>   r    )r<   r=   r@   r!   r   œ   s   
þzDFM._get_flint_funcc                 C   s   |   | j¡S )z5Callable to create a flint matrix of the same domain.)r   r   ©r(   r    r    r!   r>   ³   ó   z	DFM._funcc                 C   s   t |  ¡ ƒS )zReturn ``str(self)``.)ÚstrÚto_ddmrG   r    r    r!   Ú__str__¸   ó   zDFM.__str__c                 C   s   dt |  ¡ ƒdd… › �S )zReturn ``repr(self)``.r   é   N)ÚreprrJ   rG   r    r    r!   Ú__repr__¼   s   zDFM.__repr__c                 C   s&   t |tƒstS | j|jko| j|jkS )zReturn ``self == other``.)r.   r   ÚNotImplementedr   r   ©r(   Úotherr    r    r!   Ú__eq__À   s   
z
DFM.__eq__c                 C   s   | |||ƒS )r   r    )r   r   r   r   r    r    r!   Ú	from_listÉ   rH   zDFM.from_listc                 C   ó
   | j  ¡ S )zConvert to a nested list.)r   ÚtolistrG   r    r    r!   Úto_listÎ   ó   
zDFM.to_listc                 C   s   |   |  | j¡¡S )zReturn a copy of self.)r)   r>   r   rG   r    r    r!   ÚcopyÒ   r*   zDFM.copyc                 C   ó   t  |  ¡ | j| j¡S )zConvert to a DDM.)ÚDDMrT   rW   r   r   rG   r    r    r!   rJ   Ö   ó   z
DFM.to_ddmc                 C   rZ   )zConvert to a SDM.)ÚSDMrT   rW   r   r   rG   r    r    r!   Úto_sdmÚ   r\   z
DFM.to_sdmc                 C   ó   | S )zReturn self.r    rG   r    r    r!   Úto_dfmÞ   s   z
DFM.to_dfmc                 C   r_   )aL  
        Convert to a :class:`DFM`.

        This :class:`DFM` method exists to parallel the :class:`~.DDM` and
        :class:`~.SDM` methods. For :class:`DFM` it will always return self.

        See Also
        ========

        to_ddm
        to_sdm
        sympy.polys.matrices.domainmatrix.DomainMatrix.to_dfm_or_ddm
        r    rG   r    r    r!   Úto_dfm_or_ddmâ   s   zDFM.to_dfm_or_ddmc                 C   s   |   | ¡ |j|j¡S )zConvert from a DDM.)rT   rW   r   r   )r   Úddmr    r    r!   Úfrom_ddmò   ó   zDFM.from_ddmc                 C   sd   |   |¡}z|g |¢|‘R Ž }W n ty   td|› �ƒ‚ ty+   td|› �ƒ‚w | |||ƒS )z Inverse of :meth:`to_list_flat`.z'Incorrect number of elements for shape zInput should be a list of )r   r   r   r   )r   Úelementsr   r   Úfuncr   r    r    r!   Úfrom_list_flat÷   s   
ÿzDFM.from_list_flatc                 C   rU   )zConvert to a flat list.)r   ÚentriesrG   r    r    r!   Úto_list_flat  rX   zDFM.to_list_flatc                 C   ó   |   ¡  ¡ S )z$Convert to a flat list of non-zeros.)rJ   Ú
to_flat_nzrG   r    r    r!   rk     rL   zDFM.to_flat_nzc                 C   ó   t  |||¡ ¡ S )zInverse of :meth:`to_flat_nz`.)r[   Úfrom_flat_nzr`   )r   re   Údatar   r    r    r!   rm     ó   zDFM.from_flat_nzc                 C   rj   )zConvert to a DOD.)rJ   Úto_dodrG   r    r    r!   rp     rL   z
DFM.to_dodc                 C   rl   )zInverse of :meth:`to_dod`.)r[   Úfrom_dodr`   )r   Údodr   r   r    r    r!   rq     ro   zDFM.from_dodc                 C   rj   )zConvert to a DOK.)rJ   Úto_dokrG   r    r    r!   rs     rL   z
DFM.to_dokc                 C   rl   )zInverse of :math:`to_dod`.)r[   Úfrom_dokr`   )r   Údokr   r   r    r    r!   rt     ro   zDFM.from_dokc                 c   sP   � | j \}}| j}t|ƒD ]}t|ƒD ]}|||f }|r$|||f V  qqdS )z/Iterate over the non-zero values of the matrix.N©r   r   Úrange©r(   r@   Únr   ÚiÚjÚrepijr    r    r!   Úiter_values"  ó   €
€ýÿzDFM.iter_valuesc                 c   sP   � | j \}}| j}t|ƒD ]}t|ƒD ]}|||f }|r$||f|fV  qqdS )zBIterate over indices and values of nonzero elements of the matrix.Nrv   rx   r    r    r!   Ú
iter_items,  r~   zDFM.iter_itemsc                 C   s`   || j kr	|  ¡ S |tkr| j tkr|  t | j¡| j|¡S |  	|¡r,|  
¡  |¡ ¡ S tdƒ‚)zConvert to a new domain.r+   )r   rY   r   r   r   r   r1   r   r   r8   rJ   Ú
convert_tor`   r5   )r(   r   r    r    r!   r€   6  s   

zDFM.convert_toc              
   C   sf   | j \}}|dk r||7 }|dk r||7 }z| j||f W S  ty2   td|› d|› d| j › �ƒ‚w )zGet the ``(i, j)``-th entry.r   úInvalid indices (ú, ú) for Matrix of shape ©r   r   r   Ú
IndexError)r(   rz   r{   r@   ry   r    r    r!   ÚgetitemD  s   
ÿzDFM.getitemc              
   C   sj   | j \}}|dk r||7 }|dk r||7 }z
|| j||f< W dS  ty4   td|› d|› d| j › �ƒ‚w )zSet the ``(i, j)``-th entry.r   r�   r‚   rƒ   Nr„   )r(   rz   r{   Úvaluer@   ry   r    r    r!   ÚsetitemR  s   
ÿzDFM.setitemc                    s:   | j ‰ ‡ ‡fdd„|D ƒ}t|ƒtˆƒf}|  ||| j¡S )z%Extract a submatrix with no checking.c                    s    g | ]‰ ‡‡ fd d„ˆD ƒ‘qS )c                    s   g | ]}ˆ ˆ|f ‘qS r    r    )Ú.0r{   )ÚMrz   r    r!   Ú
<listcomp>d  ó    z+DFM._extract.<locals>.<listcomp>.<listcomp>r    )r‰   ©rŠ   Ú	j_indices)rz   r!   r‹   d  s     z DFM._extract.<locals>.<listcomp>)r   r9   rT   r   )r(   Ú	i_indicesrŽ   Úlolr   r    r�   r!   Ú_extract`  s   zDFM._extractc                 C   sÊ   | j \}}g }g }|D ](}|dk r|| }n|}d|  kr"|k s.n td|› d| j › �ƒ‚| |¡ q|D ](}	|	dk rA|	| }
n|	}
d|
  krM|k sYn td|	› d| j › �ƒ‚| |
¡ q6|  ||¡S )zExtract a submatrix.r   zInvalid row index z for Matrix of shape zInvalid column index )r   r…   Úappendr‘   )r(   r   Úcolslistr@   ry   Únew_rowsÚnew_colsrz   Úi_posr{   Új_posr    r    r!   Úextracth  s$   


zDFM.extractc                 C   s.   | j \}}t|ƒ| }t|ƒ| }|  ||¡S )zSlice a DFM.)r   rw   r‘   )r(   ÚrowsliceÚcolslicer@   ry   r�   rŽ   r    r    r!   Úextract_slice†  s   
zDFM.extract_slicec                 C   s   |   | j ¡S ©zNegate a DFM matrix.©r)   r   rG   r    r    r!   ÚnegŽ  s   zDFM.negc                 C   s   |   | j|j ¡S )zAdd two DFM matrices.r�   rQ   r    r    r!   Úadd’  r*   zDFM.addc                 C   s   |   | j|j ¡S )zSubtract two DFM matrices.r�   rQ   r    r    r!   Úsub–  r*   zDFM.subc                 C   s   |   | j| ¡S )z1Multiply a DFM matrix from the right by a scalar.r�   rQ   r    r    r!   Úmulš  ó   zDFM.mulc                 C   s   |   || j ¡S )z0Multiply a DFM matrix from the left by a scalar.r�   rQ   r    r    r!   Úrmulž  r¢   zDFM.rmulc                 C   s   |   ¡  |  ¡ ¡ ¡ S )z/Elementwise multiplication of two DFM matrices.)rJ   Úmul_elementwiser`   rQ   r    r    r!   r¤   ¢  rd   zDFM.mul_elementwisec                 C   s$   | j |jf}|  | j|j || j¡S )zMultiply two DFM matrices.)r%   r&   r   r   r   )r(   rR   r   r    r    r!   Úmatmul§  s   z
DFM.matmulc                 C   s   |   ¡ S rœ   )rž   rG   r    r    r!   Ú__neg__°  s   zDFM.__neg__c                 C   s   |   |¡}|  ||Ž ||¡S )zReturn a zero DFM matrix.)r   r   )r   r   r   rf   r    r    r!   Úzeros´  s   
z	DFM.zerosc                 C   ó   t  ||¡ ¡ S )zReturn a one DFM matrix.)r[   Úonesr`   )r   r   r   r    r    r!   r©   ¾  ó   zDFM.onesc                 C   r¨   )z%Return the identity matrix of size n.)r[   Úeyer`   )r   ry   r   r    r    r!   r«   Ä  rª   zDFM.eyec                 C   r¨   )zReturn a diagonal matrix.)r[   Údiagr`   )r   re   r   r    r    r!   r¬   Ê  s   zDFM.diagc                 C   s   |   ¡  ||¡ ¡ S )z/Apply a function to each entry of a DFM matrix.)rJ   Ú	applyfuncr`   )r(   rf   r   r    r    r!   r­   Ï  s   zDFM.applyfuncc                 C   s   |   | j ¡ | j| jf| j¡S )zTranspose a DFM matrix.)r   r   Ú	transposer&   r%   r   rG   r    r    r!   r®   Ó  s   zDFM.transposec                 G   ó   |   ¡ jdd„ |D ƒŽ  ¡ S )zHorizontally stack matrices.c                 S   ó   g | ]}|  ¡ ‘qS r    ©rJ   ©r‰   Úor    r    r!   r‹   Ù  rB   zDFM.hstack.<locals>.<listcomp>)rJ   Úhstackr`   ©r(   Úothersr    r    r!   r´   ×  ó   z
DFM.hstackc                 G   r¯   )zVertically stack matrices.c                 S   r°   r    r±   r²   r    r    r!   r‹   Ý  rB   zDFM.vstack.<locals>.<listcomp>)rJ   Úvstackr`   rµ   r    r    r!   r¸   Û  r·   z
DFM.vstackc                    s,   | j ‰ | j\}}‡ fdd„tt||ƒƒD ƒS )z$Return the diagonal of a DFM matrix.c                    s   g | ]}ˆ ||f ‘qS r    r    )r‰   rz   ©rŠ   r    r!   r‹   ã  rŒ   z DFM.diagonal.<locals>.<listcomp>)r   r   rw   Úmin)r(   r@   ry   r    r¹   r!   Údiagonalß  s   
zDFM.diagonalc                 C   sD   | j }t| jƒD ]}tt|| jƒƒD ]}|||f r  dS qqdS )z2Return ``True`` if the matrix is upper triangular.FT)r   rw   r%   rº   r&   ©r(   rŠ   rz   r{   r    r    r!   Úis_upperå  ó   ÿÿzDFM.is_upperc                 C   sD   | j }t| jƒD ]}t|d | jƒD ]}|||f r  dS qqdS )z2Return ``True`` if the matrix is lower triangular.r   FT©r   rw   r%   r&   r¼   r    r    r!   Úis_lowerî  r¾   zDFM.is_lowerc                 C   s   |   ¡ o|  ¡ S )z*Return ``True`` if the matrix is diagonal.)r½   rÀ   rG   r    r    r!   Úis_diagonal÷  r¢   zDFM.is_diagonalc                 C   s>   | j }t| jƒD ]}t| jƒD ]}|||f r  dS qqdS )z1Return ``True`` if the matrix is the zero matrix.FTr¿   r¼   r    r    r!   Úis_zero_matrixû  s   ÿÿzDFM.is_zero_matrixc                 C   rj   )z5Return the number of non-zero elements in the matrix.)rJ   ÚnnzrG   r    r    r!   rÃ     rL   zDFM.nnzc                 C   rj   )z7Return the strongly connected components of the matrix.)rJ   ÚsccrG   r    r    r!   rÄ     rL   zDFM.sccr   r   c                 C   rU   )a£  
        Compute the determinant of the matrix using FLINT.

        Examples
        ========

        >>> from sympy import Matrix
        >>> M = Matrix([[1, 2], [3, 4]])
        >>> dfm = M.to_DM().to_dfm()
        >>> dfm
        [[1, 2], [3, 4]]
        >>> dfm.det()
        -2

        Notes
        =====

        Calls the ``.det()`` method of the underlying FLINT matrix.

        For :ref:`ZZ` or :ref:`QQ` this calls ``fmpz_mat_det`` or
        ``fmpq_mat_det`` respectively.

        At the time of writing the implementation of ``fmpz_mat_det`` uses one
        of several algorithms depending on the size of the matrix and bit size
        of the entries. The algorithms used are:

        - Cofactor for very small (up to 4x4) matrices.
        - Bareiss for small (up to 25x25) matrices.
        - Modular algorithms for larger matrices (up to 60x60) or for larger
          matrices with large bit sizes.
        - Modular "accelerated" for larger matrices (60x60 upwards) if the bit
          size is smaller than the dimensions of the matrix.

        The implementation of ``fmpq_mat_det`` clears denominators from each
        row (not the whole matrix) and then calls ``fmpz_mat_det`` and divides
        by the product of the denominators.

        See Also
        ========

        sympy.polys.matrices.domainmatrix.DomainMatrix.det
            Higher level interface to compute the determinant of a matrix.
        )r   ÚdetrG   r    r    r!   rÅ     s   
1zDFM.detc                 C   s   | j  ¡  ¡ ddd… S )a#  
        Compute the characteristic polynomial of the matrix using FLINT.

        Examples
        ========

        >>> from sympy import Matrix
        >>> M = Matrix([[1, 2], [3, 4]])
        >>> dfm = M.to_DM().to_dfm()  # need ground types = 'flint'
        >>> dfm
        [[1, 2], [3, 4]]
        >>> dfm.charpoly()
        [1, -5, -2]

        Notes
        =====

        Calls the ``.charpoly()`` method of the underlying FLINT matrix.

        For :ref:`ZZ` or :ref:`QQ` this calls ``fmpz_mat_charpoly`` or
        ``fmpq_mat_charpoly`` respectively.

        At the time of writing the implementation of ``fmpq_mat_charpoly``
        clears a denominator from the whole matrix and then calls
        ``fmpz_mat_charpoly``. The coefficients of the characteristic
        polynomial are then multiplied by powers of the denominator.

        The ``fmpz_mat_charpoly`` method uses a modular algorithm with CRT
        reconstruction. The modular algorithm uses ``nmod_mat_charpoly`` which
        uses Berkowitz for small matrices and non-prime moduli or otherwise
        the Danilevsky method.

        See Also
        ========

        sympy.polys.matrices.domainmatrix.DomainMatrix.charpoly
            Higher level interface to compute the characteristic polynomial of
            a matrix.
        Néÿÿÿÿ)r   ÚcharpolyÚcoeffsrG   r    r    r!   rÇ   ?  s   *zDFM.charpolyc                 C   sx   | j }| j\}}||krtdƒ‚|tkrtd| ƒ‚|tks!|jr6z	|  | j 	¡ ¡W S  t
y5   tdƒ‚w td| ƒ‚)aä  
        Compute the inverse of a matrix using FLINT.

        Examples
        ========

        >>> from sympy import Matrix, QQ
        >>> M = Matrix([[1, 2], [3, 4]])
        >>> dfm = M.to_DM().to_dfm().convert_to(QQ)
        >>> dfm
        [[1, 2], [3, 4]]
        >>> dfm.inv()
        [[-2, 1], [3/2, -1/2]]
        >>> dfm.matmul(dfm.inv())
        [[1, 0], [0, 1]]

        Notes
        =====

        Calls the ``.inv()`` method of the underlying FLINT matrix.

        For now this will raise an error if the domain is :ref:`ZZ` but will
        use the FLINT method for :ref:`QQ`.

        The FLINT methods for :ref:`ZZ` and :ref:`QQ` are ``fmpz_mat_inv`` and
        ``fmpq_mat_inv`` respectively. The ``fmpz_mat_inv`` method computes an
        inverse with denominator. This is implemented by calling
        ``fmpz_mat_solve`` (see notes in :meth:`lu_solve` about the algorithm).

        The ``fmpq_mat_inv`` method clears denominators from each row and then
        multiplies those into the rhs identity matrix before calling
        ``fmpz_mat_solve``.

        See Also
        ========

        sympy.polys.matrices.domainmatrix.DomainMatrix.inv
            Higher level method for computing the inverse of a matrix.
        z!cannot invert a non-square matrixzfield expected, got %szmatrix is not invertiblez#DFM.inv() is not implemented for %s)r   r   r
   r   r	   r   r2   r)   r   ÚinvÚZeroDivisionErrorr   r5   )r(   ÚKr@   ry   r    r    r!   rÉ   k  s   7
ÿzDFM.invc                 C   s$   |   ¡  ¡ \}}}| ¡ | ¡ |fS )z*Return the LU decomposition of the matrix.)rJ   Úlur`   )r(   ÚLÚUÚswapsr    r    r!   rÌ   ´  s   zDFM.luc                 C   s    |   ¡  ¡ \}}| ¡ | ¡ fS )z*Return the QR decomposition of the matrix.)rJ   Úqrr`   )r(   ÚQÚRr    r    r!   rÐ   ¹  s   zDFM.qrc                 C   sÆ   | j |j kstd| j |j f ƒ‚| j jstd| j  ƒ‚| j\}}|j\}}||kr3td||||f ƒ‚||f}||krF|  ¡  | ¡ ¡ ¡ S z	| j 	|j¡}W n t
yZ   tdƒ‚w |  ||| j ¡S )aè  
        Solve a matrix equation using FLINT.

        Examples
        ========

        >>> from sympy import Matrix, QQ
        >>> M = Matrix([[1, 2], [3, 4]])
        >>> dfm = M.to_DM().to_dfm().convert_to(QQ)
        >>> dfm
        [[1, 2], [3, 4]]
        >>> rhs = Matrix([1, 2]).to_DM().to_dfm().convert_to(QQ)
        >>> dfm.lu_solve(rhs)
        [[0], [1/2]]

        Notes
        =====

        Calls the ``.solve()`` method of the underlying FLINT matrix.

        For now this will raise an error if the domain is :ref:`ZZ` but will
        use the FLINT method for :ref:`QQ`.

        The FLINT methods for :ref:`ZZ` and :ref:`QQ` are ``fmpz_mat_solve``
        and ``fmpq_mat_solve`` respectively. The ``fmpq_mat_solve`` method
        uses one of two algorithms:

        - For small matrices (<25 rows) it clears denominators between the
          matrix and rhs and uses ``fmpz_mat_solve``.
        - For larger matrices it uses ``fmpq_mat_solve_dixon`` which is a
          modular approach with CRT reconstruction over :ref:`QQ`.

        The ``fmpz_mat_solve`` method uses one of four algorithms:

        - For very small (<= 3x3) matrices it uses a Cramer's rule.
        - For small (<= 15x15) matrices it uses a fraction-free LU solve.
        - Otherwise it uses either Dixon or another multimodular approach.

        See Also
        ========

        sympy.polys.matrices.domainmatrix.DomainMatrix.lu_solve
            Higher level interface to solve a matrix equation.
        zDomains must match: %s != %szField expected, got %sz(Matrix size mismatch: %s * %s vs %s * %sz Matrix det == 0; not invertible.)r   r	   Úis_Fieldr   r   rJ   Úlu_solver`   r   ÚsolverÊ   r   r   )r(   Úrhsr@   ry   r{   ÚkÚ	sol_shapeÚsolr    r    r!   rÔ   É  s"   .

ÿzDFM.lu_solvec                 C   sÆ   | j tkrCt| jddƒ}|durC| j ¡ \}}}}| j\}}|  |||f| j ¡|  |||f| j ¡|  |||f| j ¡|  || j| j ¡fS |  ¡  ¡ \}}	}
}| ¡ }|	 ¡ }|
 ¡ }| ¡ }||||fS )a  
        Fraction-free LU decomposition of DFM.

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

        Uses `python-flint` if possible for a matrix of
        integers otherwise uses the DDM method.

        See Also
        ========

        sympy.polys.matrices.ddm.DDM.fflu
        ÚffluN)	r   r   Úgetattrr   rÚ   r   r   rJ   r`   )r(   rÚ   ÚPrÍ   ÚDrÎ   r@   ry   Úddm_pÚddm_lÚddm_dÚddm_ur    r    r!   rÚ     s    

üzDFM.ffluc                 C   s   |   ¡  ¡ \}}| ¡ |fS )ú/Return a basis for the nullspace of the matrix.)rJ   Ú	nullspacer`   )r(   rb   Ú	nonpivotsr    r    r!   rã   5  s   zDFM.nullspaceNc                 C   s    |   ¡ j|d�\}}| ¡ |fS )râ   )Úpivots)r^   Únullspace_from_rrefr`   )r(   rå   Úsdmrä   r    r    r!   ræ   K  s   zDFM.nullspace_from_rrefc                 C   s   |   ¡  ¡  ¡ S )z+Return a particular solution to the system.)rJ   Ú
particularr`   rG   r    r    r!   rè   Q  r¢   zDFM.particularç®Gáz®ï?çR¸…ëQà?ÚzbasisÚapproxc           	      C   sr   dd„ }||ƒ}||ƒ}d|  k rdk st dƒ‚ t dƒ‚| j\}}| j ¡ |kr.tdƒ‚| jj|||||d�S )zACall the fmpz_mat.lll() method but check rank to avoid segfaults.c                 S   s&   t  | ¡rt| jƒt| jƒ S t| ƒS r?   )r   Úof_typeÚfloatÚ	numeratorÚdenominator)Úxr    r    r!   Úto_float_  s   
zDFM._lll.<locals>.to_floatg      Ð?r   z delta must be between 0.25 and 1z-Matrix must have full row rank for Flint LLL.)Ú	transformÚdeltaÚetar   Úgram)r   r   r   Úrankr   Úlll)	r(   ró   rô   rõ   r   rö   rò   r@   ry   r    r    r!   Ú_lllU  s   
ÿ
zDFM._lllç      è?c                 C   sB   | j tkrtd| j  ƒ‚| j| jkrtdƒ‚| j|d�}|  |¡S )a  Compute LLL-reduced basis using FLINT.

        See :meth:`lll_transform` for more information.

        Examples
        ========

        >>> from sympy import Matrix
        >>> M = Matrix([[1, 2, 3], [4, 5, 6]])
        >>> M.to_DM().to_dfm().lll()
        [[2, 1, 0], [-1, 1, 3]]

        See Also
        ========

        sympy.polys.matrices.domainmatrix.DomainMatrix.lll
            Higher level interface to compute LLL-reduced basis.
        lll_transform
            Compute LLL-reduced basis and transform matrix.
        úZZ expected, got %sú,Matrix must not have more rows than columns.)rô   )r   r   r	   r%   r&   r   rù   r)   )r(   rô   r   r    r    r!   rø   s  s   

zDFM.lllc                 C   sh   | j tkrtd| j  ƒ‚| j| jkrtdƒ‚| jd|d�\}}|  |¡}|  || j| jf| j ¡}||fS )ad  Compute LLL-reduced basis and transform using FLINT.

        Examples
        ========

        >>> from sympy import Matrix
        >>> M = Matrix([[1, 2, 3], [4, 5, 6]]).to_DM().to_dfm()
        >>> M_lll, T = M.lll_transform()
        >>> M_lll
        [[2, 1, 0], [-1, 1, 3]]
        >>> T
        [[-2, 1], [3, -1]]
        >>> T.matmul(M) == M_lll
        True

        See Also
        ========

        sympy.polys.matrices.domainmatrix.DomainMatrix.lll
            Higher level interface to compute LLL-reduced basis.
        lll
            Compute LLL-reduced basis without transform matrix.
        rû   rü   T)ró   rô   )	r   r   r	   r%   r&   r   rù   r)   r   )r(   rô   r   ÚTÚbasisÚT_dfmr    r    r!   Úlll_transform‘  s   

zDFM.lll_transformr?   )Fré   rê   rë   rì   )rú   )PÚ__name__Ú
__module__Ú__qualname__Ú__doc__ÚfmtÚis_DFMÚis_DDMr"   Úclassmethodr   r)   r#   r8   r   Úpropertyr>   rK   rO   rS   rT   rW   rY   rJ   r^   r`   ra   rc   rg   ri   rk   rm   rp   rq   rs   rt   r}   r   r€   r†   rˆ   r‘   r˜   r›   rž   rŸ   r    r¡   r£   r¤   r¥   r¦   r§   r©   r«   r¬   r­   r®   r´   r¸   r»   r½   rÀ   rÁ   rÂ   rÃ   rÄ   r   rÅ   rÇ   rÉ   rÌ   rÐ   rÔ   rÚ   rã   ræ   rè   rù   rø   r   r    r    r    r!   r   E   sÀ    "
	



	







	
	


			
2
+
H
J!

)r[   )r]   N)Úsympy.external.gmpyr   Úsympy.external.importtoolsr   Úsympy.utilities.decoratorr   Úsympy.polys.domainsr   r   Ú
exceptionsr   r	   r
   r   r   r   r   Ú__doctest_skip__r   Ú__all__r   Úsympy.polys.matrices.ddmr[   r]   r    r    r    r!   Ú<module>   s&   )$
      v