a
    RG5d                     @   s   d Z ddlmZmZmZmZmZ ddlmZ ddl	m
Z
 ddlmZmZmZ ddlmZ G dd	 d	e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 )z

Module for the SDM class.

    )addnegpossubmul)defaultdict)_strongly_connected_components   )DMBadInputErrorDMDomainErrorDMShapeError)DDMc                       s  e Zd ZdZdZ f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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ed#d$ Zed%d& Zed'd( Zed)d* Zd+d, Zd-d. Zd/d0 Zd1d2 Zd3d4 Zd5d6 Z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 Z.dUdV Z/dWdX Z0dYdZ Z1d[d\ Z2d]d^ Z3d_d` Z4dadb Z5dcdd Z6  Z7S )eSDMa  Sparse matrix based on polys domain elements

    This is a dict subclass and is a wrapper for a dict of dicts that supports
    basic matrix arithmetic +, -, *, **.


    In order to create a new :py:class:`~.SDM`, a dict
    of dicts mapping non-zero elements to their
    corresponding row and column in the matrix is needed.

    We also need to specify the shape and :py:class:`~.Domain`
    of our :py:class:`~.SDM` object.

    We declare a 2x2 :py:class:`~.SDM` matrix belonging
    to QQ domain as shown below.
    The 2x2 Matrix in the example is

    .. math::
           A = \left[\begin{array}{ccc}
                0 & \frac{1}{2} \\
                0 & 0 \end{array} \right]


    >>> from sympy.polys.matrices.sdm import SDM
    >>> from sympy import QQ
    >>> elemsdict = {0:{1:QQ(1, 2)}}
    >>> A = SDM(elemsdict, (2, 2), QQ)
    >>> A
    {0: {1: 1/2}}

    We can manipulate :py:class:`~.SDM` the same way
    as a Matrix class

    >>> from sympy import ZZ
    >>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ)
    >>> B  = SDM({0:{0: ZZ(3)}, 1:{1:ZZ(4)}}, (2, 2), ZZ)
    >>> A + B
    {0: {0: 3, 1: 2}, 1: {0: 1, 1: 4}}

    Multiplication

    >>> A*B
    {0: {1: 8}, 1: {0: 3}}
    >>> A*ZZ(2)
    {0: {1: 4}, 1: {0: 2}}

    sparsec                    sp   t  | | | _ \| _| _\ || _t fdd| D sJtdtfdd|  D sltdd S )Nc                 3   s&   | ]}d |  ko k n  V  qdS r   N ).0r)mr   T/var/www/html/django/DPS/env/lib/python3.9/site-packages/sympy/polys/matrices/sdm.py	<genexpr>I       zSDM.__init__.<locals>.<genexpr>zRow out of rangec                 3   s0   | ](}|D ]}d |  ko  k n  V  q
qdS r   r   )r   rowcnr   r   r   K   r   zColumn out of range)	super__init__shaperowscolsdomainallr
   values)self	elemsdictr   r!   	__class__)r   r   r   r   D   s    zSDM.__init__c                 C   s   z| | | W S  t y   | j\}}| |  kr<|k rn nV| |  krV|k rn n<z| ||  ||  W  Y S  t y   | jj Y  Y S 0 ntdY n0 d S Nzindex out of range)KeyErrorr   r!   zero
IndexError)r$   ijr   r   r   r   r   getitemN   s    
4zSDM.getitemc                 C   s   | j \}}| |  kr |k r<n n| |  kr:|k sDn td|| ||  }}|rz|| | |< W q ty   ||i| |< Y q0 n<| |d }|d urz
||= W n ty   Y n0 |s| |= d S r(   )r   r+   r)   get)r$   r,   r-   valuer   r   rowir   r   r   setitem[   s"    
2
zSDM.setitemc           	         s   | j \}}t|| }t||  i }|  D ]8\}}||v r. fdd| D }|r.||||< q.| |t|t f| jS )Nc                    s$   i | ]\}}| v r  ||qS r   )indexr   r-   ecir   r   
<dictcomp>x   r   z%SDM.extract_slice.<locals>.<dictcomp>)r   rangeitemsr3   newlenr!   )	r$   slice1slice2r   r   risdmr,   r   r   r6   r   extract_slicep   s    
zSDM.extract_slicec                 C   s  | r|r|s&|  t|t|f| jS | j\}}| t|  krXt|  krX|k sbn td| t|  krt|  kr|k sn tdtt}tt}t	|D ]\}}|||  
| qt	|D ]\}	}
||
|  
|	 qt|}t|}| }i }|t|@ D ]h}|| }i }|t|@ D ]&}
||
 }||
 D ]}	|||	< q@q,|r|| D ]}| ||< qbq| |t|t|f| jS )NzRow index out of rangezColumn index out of range)zerosr<   r!   r   minmaxr+   r   list	enumerateappendsetcopyr;   )r$   r   r    r   r   ZrowmapZcolmapi2i1j2j1ZrowsetcolsetZsdm1Zsdm2row1row2Zrow1_j1r   r   r   extract~   s8    
**zSDM.extractc                 C   sN   g }|   D ]2\}}ddd |  D }|d||f  qdd| S )Nz, c                 s   s   | ]\}}d ||f V  qdS )z%s: %sNr   )r   r-   elemr   r   r   r      r   zSDM.__str__.<locals>.<genexpr>z%s: {%s}z{%s})r:   joinrG   )r$   rowsstrr,   r   Zelemsstrr   r   r   __str__   s
    zSDM.__str__c                 C   s(   t | j}t| }d||| j| jf S )Nz%s(%s, %s, %s))type__name__dict__repr__r   r!   )r$   clsr   r   r   r   rY      s    

zSDM.__repr__c                 C   s   | |||S )a  

        Parameters
        ==========

        sdm: A dict of dicts for non-zero elements in SDM
        shape: tuple representing dimension of SDM
        domain: Represents :py:class:`~.Domain` of SDM

        Returns
        =======

        An :py:class:`~.SDM` object

        Examples
        ========

        >>> from sympy.polys.matrices.sdm import SDM
        >>> from sympy import QQ
        >>> elemsdict = {0:{1: QQ(2)}}
        >>> A = SDM.new(elemsdict, (2, 2), QQ)
        >>> A
        {0: {1: 2}}

        r   )rZ   r@   r   r!   r   r   r   r;      s    zSDM.newc                 C   s$   dd |   D }| || j| jS )aT  
        Returns the copy of a :py:class:`~.SDM` object

        Examples
        ========

        >>> from sympy.polys.matrices.sdm import SDM
        >>> from sympy import QQ
        >>> elemsdict = {0:{1:QQ(2)}, 1:{}}
        >>> A = SDM(elemsdict, (2, 2), QQ)
        >>> B = A.copy()
        >>> B
        {0: {1: 2}, 1: {}}

        c                 S   s   i | ]\}}||  qS r   rI   )r   r,   Air   r   r   r8      r   zSDM.copy.<locals>.<dictcomp>)r:   r;   r   r!   )AZAcr   r   r   rI      s    zSDM.copyc                    sp   |\}t  |kr*tfdd D s2td fddfddt|D }dd |D }| |||S )	ax  

        Parameters
        ==========

        ddm:
            list of lists containing domain elements
        shape:
            Dimensions of :py:class:`~.SDM` matrix
        domain:
            Represents :py:class:`~.Domain` of :py:class:`~.SDM` object

        Returns
        =======

        :py:class:`~.SDM` containing elements of ddm

        Examples
        ========

        >>> from sympy.polys.matrices.sdm import SDM
        >>> from sympy import QQ
        >>> ddm = [[QQ(1, 2), QQ(0)], [QQ(0), QQ(3, 4)]]
        >>> A = SDM.from_list(ddm, (2, 2), QQ)
        >>> A
        {0: {0: 1/2}, 1: {1: 3/4}}

        c                 3   s   | ]}t | kV  qd S N)r<   )r   r   r   r   r   r      r   z SDM.from_list.<locals>.<genexpr>zInconsistent row-list/shapec                    s    fddt D S )Nc                    s&   i | ]}  | r|  | qS r   r   )r   r-   )ddmr,   r   r   r8     r   z3SDM.from_list.<locals>.<lambda>.<locals>.<dictcomp>)r9   r,   )r_   r   r`   r   <lambda>  r   zSDM.from_list.<locals>.<lambda>c                 3   s   | ]}| |fV  qd S r^   r   r   r,   )getrowr   r   r     r   c                 S   s   i | ]\}}|r||qS r   r   r   r,   r   r   r   r   r8     r   z!SDM.from_list.<locals>.<dictcomp>)r<   r"   r
   r9   )rZ   r_   r   r!   r   Zirowsr@   r   )r_   rc   r   r   	from_list   s    "zSDM.from_listc                 C   s   |  ||j|jS )a  
        converts object of :py:class:`~.DDM` to
        :py:class:`~.SDM`

        Examples
        ========

        >>> from sympy.polys.matrices.ddm import DDM
        >>> from sympy.polys.matrices.sdm import SDM
        >>> from sympy import QQ
        >>> ddm = DDM( [[QQ(1, 2), 0], [0, QQ(3, 4)]], (2, 2), QQ)
        >>> A = SDM.from_ddm(ddm)
        >>> A
        {0: {0: 1/2}, 1: {1: 3/4}}

        )re   r   r!   )rZ   r_   r   r   r   from_ddm  s    zSDM.from_ddmc                    s^   | j \} | jj fddt|D }|  D ]&\}}| D ]\}}||| |< qBq2|S )aC  

        Converts a :py:class:`~.SDM` object to a list

        Examples
        ========

        >>> from sympy.polys.matrices.sdm import SDM
        >>> from sympy import QQ
        >>> elemsdict = {0:{1:QQ(2)}, 1:{}}
        >>> A = SDM(elemsdict, (2, 2), QQ)
        >>> A.to_list()
        [[0, 2], [0, 0]]

        c                    s   g | ]}g  qS r   r   )r   _r   r*   r   r   
<listcomp>-  r   zSDM.to_list.<locals>.<listcomp>)r   r!   r*   r9   r:   )Mr   r_   r,   r   r-   r5   r   rh   r   to_list  s    
zSDM.to_listc           	      C   sX   | j \}}| jj}|g||  }|  D ]*\}}| D ]\}}|||| | < q8q(|S r^   )r   r!   r*   r:   )	rj   r   r   r*   flatr,   r   r-   r5   r   r   r   to_list_flat3  s    
zSDM.to_list_flatc                 C   s   dd |   D S )Nc                 S   s,   i | ]$\}}|  D ]\}}||f|qqS r   r:   )r   r,   r   r-   r5   r   r   r   r8   =  r   zSDM.to_dok.<locals>.<dictcomp>rn   rj   r   r   r   to_dok<  s    z
SDM.to_dokc                 C   s   t |  | j| jS )a2  
        Convert a :py:class:`~.SDM` object to a :py:class:`~.DDM` object

        Examples
        ========

        >>> from sympy.polys.matrices.sdm import SDM
        >>> from sympy import QQ
        >>> A = SDM({0:{1:QQ(2)}, 1:{}}, (2, 2), QQ)
        >>> A.to_ddm()
        [[0, 2], [0, 0]]

        )r   rk   r   r!   ro   r   r   r   to_ddm?  s    z
SDM.to_ddmc                 C   s   | S r^   r   ro   r   r   r   to_sdmO  s    z
SDM.to_sdmc                 C   s   | i ||S )a  

        Returns a :py:class:`~.SDM` of size shape,
        belonging to the specified domain

        In the example below we declare a matrix A where,

        .. math::
            A := \left[\begin{array}{ccc}
            0 & 0 & 0 \\
            0 & 0 & 0 \end{array} \right]

        >>> from sympy.polys.matrices.sdm import SDM
        >>> from sympy import QQ
        >>> A = SDM.zeros((2, 3), QQ)
        >>> A
        {}

        r   )rZ   r   r!   r   r   r   rB   R  s    z	SDM.zerosc                    sH   |j }|\}}ttt||g|   fddt|D }| |||S )Nc                    s   i | ]}|   qS r   r[   rb   r   r   r   r8   n  r   zSDM.ones.<locals>.<dictcomp>)onerX   zipr9   )rZ   r   r!   rt   r   r   r@   r   rs   r   onesi  s
    zSDM.onesc                    s6   |\}}|j   fddtt||D }| |||S )aO  

        Returns a identity :py:class:`~.SDM` matrix of dimensions
        size x size, belonging to the specified domain

        Examples
        ========

        >>> from sympy.polys.matrices.sdm import SDM
        >>> from sympy import QQ
        >>> I = SDM.eye((2, 2), QQ)
        >>> I
        {0: {0: 1}, 1: {1: 1}}

        c                    s   i | ]}|| iqS r   r   rb   rt   r   r   r8     r   zSDM.eye.<locals>.<dictcomp>)rt   r9   rC   )rZ   r   r!   r   r    r@   r   rw   r   eyeq  s    zSDM.eyec                 C   s   dd t |D }| |||S )Nc                 S   s   i | ]\}}|r|||iqS r   r   )r   r,   vr   r   r   r8     r   zSDM.diag.<locals>.<dictcomp>)rF   )rZ   diagonalr!   r   r@   r   r   r   diag  s    zSDM.diagc                 C   s$   t | }| || jddd | jS )a$  

        Returns the transpose of a :py:class:`~.SDM` matrix

        Examples
        ========

        >>> from sympy.polys.matrices.sdm import SDM
        >>> from sympy import QQ
        >>> A = SDM({0:{1:QQ(2)}, 1:{}}, (2, 2), QQ)
        >>> A.transpose()
        {1: {0: 2}}

        N)sdm_transposer;   r   r!   )rj   MTr   r   r   	transpose  s    zSDM.transposec                 C   s   t |tstS | |S r^   )
isinstancer   NotImplementedr   r]   Br   r   r   __add__  s    
zSDM.__add__c                 C   s   t |tstS | |S r^   )r   r   r   r   r   r   r   r   __sub__  s    
zSDM.__sub__c                 C   s   |   S r^   )r   r]   r   r   r   __neg__  s    zSDM.__neg__c                 C   s0   t |tr| |S || jv r(| |S tS dS )zA * BN)r   r   matmulr!   r   r   r   r   r   r   __mul__  s
    



zSDM.__mul__c                 C   s   || j v r| |S tS d S r^   )r!   rmulr   )abr   r   r   __rmul__  s    

zSDM.__rmul__c                 C   sV   | j |j krt| j\}}|j\}}||kr0tt| || j ||}| |||f| j S )a  
        Performs matrix multiplication of two SDM matrices

        Parameters
        ==========

        A, B: SDM to multiply

        Returns
        =======

        SDM
            SDM after multiplication

        Raises
        ======

        DomainError
            If domain of A does not match
            with that of B

        Examples
        ========

        >>> from sympy import ZZ
        >>> from sympy.polys.matrices.sdm import SDM
        >>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ)
        >>> B = SDM({0:{0:ZZ(2), 1:ZZ(3)}, 1:{0:ZZ(4)}}, (2, 2), ZZ)
        >>> A.matmul(B)
        {0: {0: 8}, 1: {0: 2, 1: 3}}

        )r!   r   r   r   
sdm_matmulr;   )r]   r   r   r   n2oCr   r   r   r     s    !

z
SDM.matmulc                    s$   t |  fdd}| || j| jS )a.  
        Multiplies each element of A with a scalar b

        Examples
        ========

        >>> from sympy import ZZ
        >>> from sympy.polys.matrices.sdm import SDM
        >>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ)
        >>> A.mul(ZZ(3))
        {0: {1: 6}, 1: {0: 3}}

        c                    s   |   S r^   r   aijr   r   r   ra     r   zSDM.mul.<locals>.<lambda>	unop_dictr;   r   r!   r]   r   Csdmr   r   r   r     s    zSDM.mulc                    s$   t |  fdd}| || j| jS )Nc                    s    |  S r^   r   r   r   r   r   ra     r   zSDM.rmul.<locals>.<lambda>r   r   r   r   r   r     s    zSDM.rmulc                    sV   | j |j krt| j|jkr t| j j  fdd}t| |t||}| || j| j S )Nc                    s    S r^   r   r5   r*   r   r   ra     r   z%SDM.mul_elementwise.<locals>.<lambda>)r!   r   r   r   r*   
binop_dictr   r;   )r]   r   fzeror   r   r   r   mul_elementwise  s    zSDM.mul_elementwisec                 C   s"   t | |ttt}| || j| jS )ak  

        Adds two :py:class:`~.SDM` matrices

        Examples
        ========

        >>> from sympy import ZZ
        >>> from sympy.polys.matrices.sdm import SDM
        >>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ)
        >>> B = SDM({0:{0: ZZ(3)}, 1:{1:ZZ(4)}}, (2, 2), ZZ)
        >>> A.add(B)
        {0: {0: 3, 1: 2}, 1: {0: 1, 1: 4}}

        )r   r   r   r;   r   r!   r]   r   r   r   r   r   r     s    zSDM.addc                 C   s"   t | |ttt}| || j| jS )as  

        Subtracts two :py:class:`~.SDM` matrices

        Examples
        ========

        >>> from sympy import ZZ
        >>> from sympy.polys.matrices.sdm import SDM
        >>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ)
        >>> B  = SDM({0:{0: ZZ(3)}, 1:{1:ZZ(4)}}, (2, 2), ZZ)
        >>> A.sub(B)
        {0: {0: -3, 1: 2}, 1: {0: 1, 1: -4}}

        )r   r   r   r   r;   r   r!   r   r   r   r   r     s    zSDM.subc                 C   s   t | t}| || j| jS )a2  

        Returns the negative of a :py:class:`~.SDM` matrix

        Examples
        ========

        >>> from sympy import ZZ
        >>> from sympy.polys.matrices.sdm import SDM
        >>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ)
        >>> A.neg()
        {0: {1: -2}, 1: {0: -1}}

        )r   r   r;   r   r!   )r]   r   r   r   r   r   *  s    
zSDM.negc                    s:   | j  kr|  S t|  fdd}| || j S )aO  

        Converts the :py:class:`~.Domain` of a :py:class:`~.SDM` matrix to K

        Examples
        ========

        >>> from sympy import ZZ, QQ
        >>> from sympy.polys.matrices.sdm import SDM
        >>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ)
        >>> A.convert_to(QQ)
        {0: {1: 2}, 1: {0: 1}}

        c                    s     | S r^   )convert_fromr   KKoldr   r   ra   N  r   z SDM.convert_to.<locals>.<lambda>)r!   rI   r   r;   r   )r]   r   Akr   r   r   
convert_to<  s
    zSDM.convert_toc                    s:    j \}}||ksJ t|} fdd|D }t||S )a{  Strongly connected components of a square matrix *A*.

        Examples
        ========

        >>> from sympy import ZZ
        >>> from sympy.polys.matrices.sdm import SDM
        >>> A = SDM({0:{0: ZZ(2)}, 1:{1:ZZ(1)}}, (2, 2), ZZ)
        >>> A.scc()
        [[0], [1]]

        See also
        ========

        sympy.polys.matrices.domainmatrix.DomainMatrix.scc
        c                    s   i | ]}|t  |g qS r   )rE   r/   )r   ry   r   r   r   r8   e  r   zSDM.scc.<locals>.<dictcomp>)r   r9   r   )r]   r   r    VZEmapr   r   r   sccQ  s
    
zSDM.sccc                 C   s$   t | \}}}| || j| j|fS )a_  

        Returns reduced-row echelon form and list of pivots for the :py:class:`~.SDM`

        Examples
        ========

        >>> from sympy import QQ
        >>> from sympy.polys.matrices.sdm import SDM
        >>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(2), 1:QQ(4)}}, (2, 2), QQ)
        >>> A.rref()
        ({0: {0: 1, 1: 2}}, [0])

        )	sdm_irrefr;   r   r!   )r]   r   pivotsrg   r   r   r   rrefh  s    zSDM.rrefc                 C   s   |  |   S )a>  

        Returns inverse of a matrix A

        Examples
        ========

        >>> from sympy import QQ
        >>> from sympy.polys.matrices.sdm import SDM
        >>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ)
        >>> A.inv()
        {0: {0: -2, 1: 1}, 1: {0: 3/2, 1: -1/2}}

        )rf   rq   invr   r   r   r   r   z  s    zSDM.invc                 C   s   |    S )a  
        Returns determinant of A

        Examples
        ========

        >>> from sympy import QQ
        >>> from sympy.polys.matrices.sdm import SDM
        >>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ)
        >>> A.det()
        -2

        )rq   detr   r   r   r   r     s    zSDM.detc                 C   s(   |    \}}}| || ||fS )a`  

        Returns LU decomposition for a matrix A

        Examples
        ========

        >>> from sympy import QQ
        >>> from sympy.polys.matrices.sdm import SDM
        >>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ)
        >>> A.lu()
        ({0: {0: 1}, 1: {0: 3, 1: 1}}, {0: {0: 1, 1: 2}, 1: {1: -2}}, [])

        )rq   lurf   )r]   LUswapsr   r   r   r     s    zSDM.luc                 C   s   |  |  | S )an  

        Uses LU decomposition to solve Ax = b,

        Examples
        ========

        >>> from sympy import QQ
        >>> from sympy.polys.matrices.sdm import SDM
        >>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ)
        >>> b = SDM({0:{0:QQ(1)}, 1:{0:QQ(2)}}, (2, 1), QQ)
        >>> A.lu_solve(b)
        {1: {0: 1/2}}

        )rf   rq   lu_solve)r]   r   r   r   r   r     s    zSDM.lu_solvec           	      C   s`   | j d }| jj}t| \}}}t|||||\}}tt|}t||f}| ||| j|fS )aL  

        Returns nullspace for a :py:class:`~.SDM` matrix A

        Examples
        ========

        >>> from sympy import QQ
        >>> from sympy.polys.matrices.sdm import SDM
        >>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0: QQ(2), 1: QQ(4)}}, (2, 2), QQ)
        >>> A.nullspace()
        ({0: {0: -2, 1: 1}}, [1])

        r	   )	r   r!   rt   r   sdm_nullspace_from_rrefrX   rF   r<   r;   )	r]   ncolsrt   r   r   nzcolsr   	nonpivotsr   r   r   r   	nullspace  s    
zSDM.nullspacec                 C   sL   | j d }t| \}}}t|||}|r0d|ini }| |d|d f| jS )Nr	   r   )r   r   sdm_particular_from_rrefr;   r!   )r]   r   r   r   r   Prepr   r   r   
particular  s
    
zSDM.particularc                 G   s   t |  }| j\}}| j}|D ]}|j\}}||ks:J |j|ksHJ | D ]F\}	}
||	d}|du rxi  ||	< }|
 D ]\}}|||| < qqP||7 }q | |||f| jS )a  Horizontally stacks :py:class:`~.SDM` matrices.

        Examples
        ========

        >>> from sympy import ZZ
        >>> from sympy.polys.matrices.sdm import SDM

        >>> A = SDM({0: {0: ZZ(1), 1: ZZ(2)}, 1: {0: ZZ(3), 1: ZZ(4)}}, (2, 2), ZZ)
        >>> B = SDM({0: {0: ZZ(5), 1: ZZ(6)}, 1: {0: ZZ(7), 1: ZZ(8)}}, (2, 2), ZZ)
        >>> A.hstack(B)
        {0: {0: 1, 1: 2, 2: 5, 3: 6}, 1: {0: 3, 1: 4, 2: 7, 3: 8}}

        >>> C = SDM({0: {0: ZZ(9), 1: ZZ(10)}, 1: {0: ZZ(11), 1: ZZ(12)}}, (2, 2), ZZ)
        >>> A.hstack(B, C)
        {0: {0: 1, 1: 2, 2: 5, 3: 6, 4: 9, 5: 10}, 1: {0: 3, 1: 4, 2: 7, 3: 8, 4: 11, 5: 12}}
        N)rX   rI   r   r!   r:   r/   r;   )r]   r   Anewr   r    r!   BkBkrowsBkcolsr,   Bkir\   r-   ZBkijr   r   r   hstack  s    


z
SDM.hstackc                 G   s   t |  }| j\}}| j}|D ]N}|j\}}||ks:J |j|ksHJ | D ]\}	}
|
||	| < qP||7 }q | |||f| jS )a  Vertically stacks :py:class:`~.SDM` matrices.

        Examples
        ========

        >>> from sympy import ZZ
        >>> from sympy.polys.matrices.sdm import SDM

        >>> A = SDM({0: {0: ZZ(1), 1: ZZ(2)}, 1: {0: ZZ(3), 1: ZZ(4)}}, (2, 2), ZZ)
        >>> B = SDM({0: {0: ZZ(5), 1: ZZ(6)}, 1: {0: ZZ(7), 1: ZZ(8)}}, (2, 2), ZZ)
        >>> A.vstack(B)
        {0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}, 2: {0: 5, 1: 6}, 3: {0: 7, 1: 8}}

        >>> C = SDM({0: {0: ZZ(9), 1: ZZ(10)}, 1: {0: ZZ(11), 1: ZZ(12)}}, (2, 2), ZZ)
        >>> A.vstack(B, C)
        {0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}, 2: {0: 5, 1: 6}, 3: {0: 7, 1: 8}, 4: {0: 9, 1: 10}, 5: {0: 11, 1: 12}}
        )rX   rI   r   r!   r:   r;   )r]   r   r   r   r    r!   r   r   r   r,   r   r   r   r   vstack  s    


z
SDM.vstackc                    s&    fdd|   D }| || j|S )Nc                    s(   i | ] \}}| fd d|  D qS )c                    s   i | ]\}}| |qS r   r   r4   funcr   r   r8   $  r   z,SDM.applyfunc.<locals>.<dictcomp>.<dictcomp>rn   rd   r   r   r   r8   $  r   z!SDM.applyfunc.<locals>.<dictcomp>)r:   r;   r   )r$   r   r!   r@   r   r   r   	applyfunc#  s    zSDM.applyfuncc                 C   s   |    S )a  
        Returns the coefficients of the characteristic polynomial
        of the :py:class:`~.SDM` matrix. These elements will be domain elements.
        The domain of the elements will be same as domain of the :py:class:`~.SDM`.

        Examples
        ========

        >>> from sympy import QQ, Symbol
        >>> from sympy.polys.matrices.sdm import SDM
        >>> from sympy.polys import Poly
        >>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ)
        >>> A.charpoly()
        [1, -5, -2]

        We can create a polynomial using the
        coefficients using :py:class:`~.Poly`

        >>> x = Symbol('x')
        >>> p = Poly(A.charpoly(), x, domain=A.domain)
        >>> p
        Poly(x**2 - 5*x - 2, x, domain='QQ')

        )rq   charpolyr   r   r   r   r   '  s    zSDM.charpolyc                 C   s   |  S )z@
        Says whether this matrix has all zero entries.
        r   r$   r   r   r   is_zero_matrixB  s    zSDM.is_zero_matrixc                 C   s   t dd |  D S )z~
        Says whether this matrix is upper-triangular. True can be returned
        even if the matrix is not square.
        c                 s   s$   | ]\}}|D ]}||kV  qqd S r^   r   r   r,   r   r-   r   r   r   r   M  r   zSDM.is_upper.<locals>.<genexpr>r"   r:   r   r   r   r   is_upperH  s    zSDM.is_upperc                 C   s   t dd |  D S )z~
        Says whether this matrix is lower-triangular. True can be returned
        even if the matrix is not square.
        c                 s   s$   | ]\}}|D ]}||kV  qqd S r^   r   r   r   r   r   r   T  r   zSDM.is_lower.<locals>.<genexpr>r   r   r   r   r   is_lowerO  s    zSDM.is_lower)8rW   
__module____qualname____doc__fmtr   r.   r2   rA   rQ   rU   rY   classmethodr;   rI   re   rf   rk   rm   rp   rq   rr   rB   rv   rx   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   __classcell__r   r   r&   r   r      st   0
&

&
	



	*
%!r   c                 C   st  t | t | }}i }||@ D ]}| | ||  }	}
i }t |	t |
 }}||@ D ]"}||	| |
| }|rR|||< qR|| D ]}||	| }|r~|||< q~|| D ]}||
| }|r|||< q|r|||< q|| D ]B}| | }	i }|	 D ]\}}||}|r|||< q|r|||< q|| D ]J}|| }
i }|
 D ] \}}||}|r<|||< q<|r$|||< q$|S r^   )rH   r:   )r]   r   ZfabfafbZAnzZBnzr   r,   r\   BiCiZAnziZBnzir-   CijAijBijr   r   r   r   W  sN    





r   c           	      C   sP   i }|   D ]>\}}i }|  D ]\}}||}|r |||< q |r|||< q|S r^   rn   )	r]   fr   r,   r\   r   r-   r   r   r   r   r   r     s    

r   c              
   C   s\   i }|   D ]J\}}|  D ]8\}}z||| |< W q tyR   ||i||< Y q0 qq|S r^   )r:   r)   )rj   r~   r,   Mir-   Mijr   r   r   r}     s    r}   c                 C   s   |j rt| ||||S i }t|}|  D ]\}}i }	t|}
|
|@ D ]p}|| }||  D ]V\}}|	|d }|d ur|||  }|r||	|< q|	| q^|| }|r^||	|< q^qF|	r*|	||< q*|S r^   )is_EXRAWsdm_matmul_exrawrH   r:   r/   pop)r]   r   r   r   r   r   B_knzr,   r\   r   Ai_knzkAikr-   Bkjr   r   r   r   r     s,    

r   c              
   C   s  |j }i }t|}|  D ]\}}	tt}
t|	}||@ D ]n}|	| }|| |kr~||  D ]\}}|
| ||  q`q<t|D ]"}|
| ||| ||  qq<|| D ]4}||	|  }||krt|D ]}|
| | qqi }|
 D ]\}}||}|r|||< q|r|||< q| D ]\}}| D ]\}}|| |kr<t|D ]d}| |i ||}||krZ||i }|||||  }||kr|||< nt	|||< qZq<q,|S r^   )
r*   rH   r:   r   rE   rG   r9   r/   sumRuntimeError)r]   r   r   r   r   r*   r   r   r,   r\   ZCi_listr   r   r   r-   r   ZzAikr   ZCij_listr   r   r   r   r   r     sL    "





r   c                    s  t dd |  D td}i t t }tt}|rr| }fdd| D }|t|@ D ]}| }|| }t|}t|}	|	| D ]}
| ||
  ||
< q|| || |	|@ D ]0}
||
 |||
   }|r|||
< q||
 qqb|sq2t|}|| }||< t|}|d }|D ]}||  |9  < q(||dD ]}
|
 }|| }t|}|| D ]&}| ||  ||< || |
 qp|| || ||@ D ]L}|| |||   }|r|||< n"|| ||kr|| |
 qt	|dkrL|
 ||
 qLt	|dkrB| q2|| |D ]}||krP|| | qPq2t |B }d	d t
|D   fd
d| D }fdd|D }tt
|}|||fS )ao  RREF and pivots of a sparse matrix *A*.

    Compute the reduced row echelon form (RREF) of the matrix *A* and return a
    list of the pivot columns. This routine does not work in place and leaves
    the original matrix *A* unmodified.

    Examples
    ========

    This routine works with a dict of dicts sparse representation of a matrix:

    >>> from sympy import QQ
    >>> from sympy.polys.matrices.sdm import sdm_irref
    >>> A = {0: {0: QQ(1), 1: QQ(2)}, 1: {0: QQ(3), 1: QQ(4)}}
    >>> Arref, pivots, _ = sdm_irref(A)
    >>> Arref
    {0: {0: 1}, 1: {1: 1}}
    >>> pivots
    [0, 1]

   The analogous calculation with :py:class:`~.Matrix` would be

    >>> from sympy import Matrix
    >>> M = Matrix([[1, 2], [3, 4]])
    >>> Mrref, pivots = M.rref()
    >>> Mrref
    Matrix([
    [1, 0],
    [0, 1]])
    >>> pivots
    (0, 1)

    Notes
    =====

    The cost of this algorithm is determined purely by the nonzero elements of
    the matrix. No part of the cost of any step in this algorithm depends on
    the number of rows or columns in the matrix. No step depends even on the
    number of nonzero rows apart from the primary loop over those rows. The
    implementation is much faster than ddm_rref for sparse matrices. In fact
    at the time of writing it is also (slightly) faster than the dense
    implementation even if the input is a fully dense matrix so it seems to be
    faster in all cases.

    The elements of the matrix should support exact division with ``/``. For
    example elements of any domain that is a field (e.g. ``QQ``) should be
    fine. No attempt is made to handle inexact arithmetic.

    c                 s   s   | ]}|  V  qd S r^   r[   )r   r\   r   r   r   r   V  r   zsdm_irref.<locals>.<genexpr>)keyc                    s   i | ]\}}| vr||qS r   r   )r   r-   r   )reduced_pivotsr   r   r8   m  r   zsdm_irref.<locals>.<dictcomp>r|   r   r	   c                 S   s   i | ]\}}||qS r   r   )r   r   pr   r   r   r8     r   c                    s(   i | ] \}}|t  fd d|D qS )c                 3   s   | ]} | V  qd S r^   r   )r   r   	pivot2rowr   r   r     r   z'sdm_irref.<locals>.<dictcomp>.<genexpr>)rH   )r   r   sr   r   r   r8     r   c                    s   g | ]} | qS r   r   rb   )pivot_row_mapr   r   ri     r   zsdm_irref.<locals>.<listcomp>)sortedr#   rC   rH   r   r   r:   remover   r<   rF   rX   )r]   ZArowsZnonreduced_pivotsZnonzero_columnsr\   r-   ZAjr   ZAinzZAjnzr   r   ZAijinvlr   ZAkjZAknzZAklr   r   r   r   )r   r   r   r   r     s|    O










r   c           
      C   sh   t tt|t| }g }|D ]>}||i}||dD ]}	| |	 |  |||	 < q8|| q ||fS )z%Get nullspace from A which is in RREFr   )r   rH   r9   r/   rG   )
r]   rt   r   r   Znonzero_colsr   r   r-   ZKjr,   r   r   r   r     s    r   c                 C   sJ   i }t |D ]8\}}| | |d d}|dur|| | |  ||< q|S )z1Get a particular solution from A which is in RREFr	   N)rF   r/   )r]   r   r   r   r,   r-   ZAinr   r   r   r     s    r   N)r   operatorr   r   r   r   r   collectionsr   sympy.utilities.iterablesr   
exceptionsr
   r   r   r_   r   rX   r   r   r   r}   r   r   r   r   r   r   r   r   r   <module>   s*         L.,> 5