
    MZdS9                         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mZ ddlmZmZ  G d de      Z G d dee      ZeZy)    )Callable)Dict)sympy_deprecation_warningis_sequence)as_int   )
MatrixBase)MutableRepMatrix	RepMatrix)_iszero)_liupc _row_structure_symbolic_cholesky_cholesky_sparse_LDLdecomposition_sparse)_lower_triangular_solve_sparse_upper_triangular_solve_sparsec                       e Zd ZdZe fd       Zed        Zd Zd Z	d Z
d Zd Zd	 Zd
 Zd ZddZddZ eeddd      Z eeddd      Zd Zd ZddZddZd Zd Zej                  e_        ej                  e_        ej                  e_        ej                  e_        ej                  e_        ej                  e_         xZS )SparseRepMatrixa  
    A sparse matrix (a matrix with a large number of zero elements).

    Examples
    ========

    >>> from sympy import SparseMatrix, ones
    >>> SparseMatrix(2, 2, range(4))
    Matrix([
    [0, 1],
    [2, 3]])
    >>> SparseMatrix(2, 2, {(1, 1): 2})
    Matrix([
    [0, 0],
    [0, 2]])

    A SparseMatrix can be instantiated from a ragged list of lists:

    >>> SparseMatrix([[1, 2, 3], [1, 2], [1]])
    Matrix([
    [1, 2, 3],
    [1, 2, 0],
    [1, 0, 0]])

    For safety, one may include the expected size and then an error
    will be raised if the indices of any element are out of range or
    (for a flat list) if the total number of elements does not match
    the expected shape:

    >>> SparseMatrix(2, 2, [1, 2])
    Traceback (most recent call last):
    ...
    ValueError: List length (2) != rows*columns (4)

    Here, an error is not raised because the list is not flat and no
    element is out of range:

    >>> SparseMatrix(2, 2, [[1, 2]])
    Matrix([
    [1, 2],
    [0, 0]])

    But adding another element to the first (and only) row will cause
    an error to be raised:

    >>> SparseMatrix(2, 2, [[1, 2, 3]])
    Traceback (most recent call last):
    ...
    ValueError: The location (0, 2) is out of designated range: (1, 1)

    To autosize the matrix, pass None for rows:

    >>> SparseMatrix(None, [[1, 2, 3]])
    Matrix([[1, 2, 3]])
    >>> SparseMatrix(None, {(1, 1): 1, (3, 3): 3})
    Matrix([
    [0, 0, 0, 0],
    [0, 1, 0, 0],
    [0, 0, 0, 0],
    [0, 0, 0, 3]])

    Values that are themselves a Matrix are automatically expanded:

    >>> SparseMatrix(4, 4, {(1, 1): ones(2)})
    Matrix([
    [0, 0, 0, 0],
    [0, 1, 1, 0],
    [0, 1, 1, 0],
    [0, 0, 0, 0]])

    A ValueError is raised if the expanding matrix tries to overwrite
    a different element already present:

    >>> SparseMatrix(3, 3, {(0, 0): ones(2), (1, 1): 2})
    Traceback (most recent call last):
    ...
    ValueError: collision at (1, 1)

    See Also
    ========
    DenseMatrix
    MutableSparseMatrix
    ImmutableSparseMatrix
    c                 t
   t        |      dk(  rIt        |d   t              r6|d   j                  }|d   j                  }|d   j                         ||fS i t        |      dk(  r|d   d d |d   g}t        |      dk(  r|d d \  }}||cxu rn nd x}}n-d ||fv rt        d      t        |d         t        |d         }}t        |d   t              r|d   }d ||fv rt        dj                  ||            t        |      D cg c]  }| j                  |       }	}t        |      D 
cg c]  }
| j                  |
       }}
|	D ]8  }|D ]1  }
| j                   |||
            }|| j                  k7  s+|||
f<   3 : ||fS t        |d   t        t        f      rfd}|d   j                         D ]  \  \  }}}t        |t              r:|j                         j                         D ]  \  \  }}
} |||z   ||
z   |        St        |t         t"        f      r7 | j$                  |fi |\  }}D ]  \  }}
 |||z   ||
z   ||
f           | j                  |      } |||| j                  |              nt'        |d         rt)        d |d   D               }|s | j$                  |d   fi |\  }}n|d   }t        |      ||z  k7  r%t        d	j                  t        |      ||            t        |      D ]E  }t        |      D ]5  }
|||z  |
z      }| j                  |      }|| j                  k7  s/|||
f<   7 G |[j+                         }|r!t-        |D cg c]  \  }}|	 c}}      dz   nd}|r!t-        |D cg c]  \  }}|	 c}}      dz   nd}nMj+                         D ]:  \  }}
|r||k\  s	|
s|
|k\  st        d
j                  ||
fd|dz
  d|dz
               ||fS t        |      dk(  rt        |d   t         t"        f      r|d   }d}t/        |      D ]l  \  }}t        |t         t"        f      s|g}t/        |      D ]+  \  }
}|| j                  k7  s| j                  |      ||
f<   - t-        |t        |            }n |rt        |      nd}|}||fS t1        | H  | \  }}}t        |      D ]4  }t        |      D ]$  }
|||z  |
z      }|| j                  k7  s|||
f<   & 6 ||fS c c}w c c}
w c c}}w c c}}w )Nr	   r         z*Pass rows=None and no cols for autosizing.z2{} and {} must be integers for this specification.c           	          |r;| |fv r-|| |f   k7  r#t        dj                  | |f|| |f               || |f<   y y )Nz)There is a collision at {} for {} and {}.)
ValueErrorformat)ijvsmats      7/usr/lib/python3/dist-packages/sympy/matrices/sparse.pyupdatez7SparseRepMatrix._handle_creation_inputs.<locals>.update   s]    q6T>a41:o", K!'A41:!>#  &'QT
     c              3   2   K   | ]  }t        |        y wNr   ).0r   s     r    	<genexpr>z:SparseRepMatrix._handle_creation_inputs.<locals>.<genexpr>   s     ?!{1~?s   zMThe length of the flat list ({}) does not match the specified size ({} * {}).z?The location {} is out of the designated range[{}, {}]x[{}, {}])len
isinstancer
   rowscolstodokr   r   r   r   range_sympifyzerodictr   itemslisttuple_handle_creation_inputsr   anykeysmax	enumeratesuper)clsargskwargsr)   r*   rcopr   row_indicesr   col_indicesvaluer!   r   vv_flat	flat_listr5   rowmatr   	__class__s                         @r    r3   z'SparseRepMatrix._handle_creation_inputsk   s   t9>ja*=7<<D7<<D7==?Dt##t9>d1go$Q(Dt9>8DAqA~""t!Q @B B $DG_fT!Wod$q'8,!WD$<'$))/d);= = 9>dD1s||ADD8=dD1s||ADD$ /A( / #R1X 6 CHH,).DAJ// T4''DGdD\2' "&a 
6IFQA!!Z0*+'')//*; 5JFQB"1q5!a%45#Ae}5%@S%@%@%Mf%M
1d$( =DAq"1q5!a%ad<=  LLOq!S\\!_5
6 T!W%?tAw???333DGFvF Aq$ !%QI9~4(B#VC	ND$?  #4[ 3!&t 3A$-afqj$9E$'LL$7E$0-2QT
	33 |yy{8<s$/$!QA/014!8<s$/$!QA/014! !IIK DAqQ$Y!T	(0#VQFAtaxD1HE  t##Y!^
47T5M BQAA#A, %3!#e}5%C&s^ 6EArSXX~%(\\"%5QT
6 3s8$% 3q6ADDt## $g=tDOD$4[ +t +AQ
OE(%*QT
++ t##A EDr 0/s   T$7T)>T.
#T4
c                 >    t        ddd       | j                         S )Nz
            The private _smat attribute of SparseMatrix is deprecated. Use the
            .todok() method instead.
            z1.9z$deprecated-private-matrix-attributes)deprecated_since_versionactive_deprecations_target)r   r+   selfs    r    _smatzSparseRepMatrix._smat   s'     	" &+'M	
 zz|r"   c                     | j                  |j                  dd      |j                  dt              |j                  dd            S )NmethodLDL
iszerofunctry_block_diagF)rP   rR   rS   )invgetr   )rM   r;   s     r    _eval_inversezSparseRepMatrix._eval_inverse   sD    xxvzz(E:#)::lG#D'-zz2BE'J  L 	Lr"   c                     t        |      st        d      i }| j                         j                         D ]  \  }} ||      }|dk7  s|||<    | j	                  | j
                  | j                  |      S )aX  Apply a function to each element of the matrix.

        Examples
        ========

        >>> from sympy import SparseMatrix
        >>> m = SparseMatrix(2, 2, lambda i, j: i*2+j)
        >>> m
        Matrix([
        [0, 1],
        [2, 3]])
        >>> m.applyfunc(lambda i: 2*i)
        Matrix([
        [0, 2],
        [4, 6]])

        z`f` must be callable.r   )callable	TypeErrorr+   r0   _newr)   r*   )rM   fdokkr   fvs         r    	applyfunczSparseRepMatrix.applyfunc   sv    $ {344
 JJL&&( 	DAq1BQwA	
 yyDIIs33r"   c                     ddl m}  ||       S )z,Returns an Immutable version of this Matrix.r	   )ImmutableSparseMatrix)	immutablera   )rM   ra   s     r    as_immutablezSparseRepMatrix.as_immutable  s    4$T**r"   c                     t        |       S )aC  Returns a mutable version of this matrix.

        Examples
        ========

        >>> from sympy import ImmutableMatrix
        >>> X = ImmutableMatrix([[1, 2], [3, 4]])
        >>> Y = X.as_mutable()
        >>> Y[1, 1] = 5 # Can set values in Y
        >>> Y
        Matrix([
        [1, 2],
        [3, 5]])
        )MutableSparseMatrixrL   s    r    
as_mutablezSparseRepMatrix.as_mutable$  s     #4((r"   c                     t        | j                         j                         d       D cg c]  }t        || |   fz          c}S c c}w )a  Returns a column-sorted list of non-zero elements of the matrix.

        Examples
        ========

        >>> from sympy import SparseMatrix
        >>> a=SparseMatrix(((1, 2), (3, 4)))
        >>> a
        Matrix([
        [1, 2],
        [3, 4]])
        >>> a.CL
        [(0, 0, 1), (1, 0, 3), (0, 1, 2), (1, 1, 4)]

        See Also
        ========

        sympy.matrices.sparse.SparseMatrix.row_list
        c                 *    t        t        |             S r$   )r1   reversed)r]   s    r    <lambda>z*SparseRepMatrix.col_list.<locals>.<lambda>I  s    Y]^fgh^iYj r"   key)sortedr+   r5   r2   rM   r]   s     r    col_listzSparseRepMatrix.col_list5  s>    ( 06djjl6G6G6IOj/kl!a47*n%llls   A	c                 4    t        | j                               S )z2Returns the number of non-zero elements in Matrix.)r'   r+   rL   s    r    nnzzSparseRepMatrix.nnzK  s    4::<  r"   c                     t        | j                         j                         t              D cg c]  }t	        || |   fz          c}S c c}w )a  Returns a row-sorted list of non-zero elements of the matrix.

        Examples
        ========

        >>> from sympy import SparseMatrix
        >>> a = SparseMatrix(((1, 2), (3, 4)))
        >>> a
        Matrix([
        [1, 2],
        [3, 4]])
        >>> a.RL
        [(0, 0, 1), (0, 1, 2), (1, 0, 3), (1, 1, 4)]

        See Also
        ========

        sympy.matrices.sparse.SparseMatrix.col_list
        rk   )rm   r+   r5   r1   r2   rn   s     r    row_listzSparseRepMatrix.row_listO  sE    * 4::<$$&D13!a47*n% 3 	3 3s   Ac                     || z  S )z"Scalar element-wise multiplication )rM   scalars     r    scalar_multiplyzSparseRepMatrix.scalar_multiplyf  s    }r"   c                 P    | j                   }|| z  j                  |      |z  |z  S )a  Return the least-square fit to the data.

        By default the cholesky_solve routine is used (method='CH'); other
        methods of matrix inversion can be used. To find out which are
        available, see the docstring of the .inv() method.

        Examples
        ========

        >>> from sympy import SparseMatrix, Matrix, ones
        >>> A = Matrix([1, 2, 3])
        >>> B = Matrix([2, 3, 4])
        >>> S = SparseMatrix(A.row_join(B))
        >>> S
        Matrix([
        [1, 2],
        [2, 3],
        [3, 4]])

        If each line of S represent coefficients of Ax + By
        and x and y are [2, 3] then S*xy is:

        >>> r = S*Matrix([2, 3]); r
        Matrix([
        [ 8],
        [13],
        [18]])

        But let's add 1 to the middle value and then solve for the
        least-squares value of xy:

        >>> xy = S.solve_least_squares(Matrix([8, 14, 18])); xy
        Matrix([
        [ 5/3],
        [10/3]])

        The error is given by S*xy - r:

        >>> S*xy - r
        Matrix([
        [1/3],
        [1/3],
        [1/3]])
        >>> _.norm().n(2)
        0.58

        If a different xy is used, the norm will be higher:

        >>> xy += ones(2, 1)/10
        >>> (S*xy - r).norm().n(2)
        1.5

        rP   )TrT   )rM   rhsrP   ts       r    solve_least_squaresz#SparseRepMatrix.solve_least_squaresj  s-    l FF$||6|*1,S00r"   c                     | j                   sI| j                  | j                  k  rt        d      | j                  | j                  kD  rt        d      y| j	                  |      j                  |      S )zReturn solution to self*soln = rhs using given inversion method.

        For a list of possible inversion methods, see the .inv() docstring.
        zUnder-determined system.z]For over-determined system, M, having more rows than columns, try M.solve_least_squares(rhs).ry   N)	is_squarer)   r*   r   rT   multiply)rM   r{   rP   s      r    solvezSparseRepMatrix.solve  so    
 ~~yy499$ !;<<TYY&  "N O O ' 8868*33C88r"   NzAlternate faster representationc                     t        |       S r$   )r   rL   s    r    liupczSparseRepMatrix.liupc  s    d|r"   c                     t        |       S r$   )r   rL   s    r    row_structure_symbolic_choleskyz/SparseRepMatrix.row_structure_symbolic_cholesky  s    /55r"   c                     t        | |      S N)	hermitian)r   rM   r   s     r    choleskyzSparseRepMatrix.cholesky  s    	::r"   c                     t        | |      S r   )r   r   s     r    LDLdecompositionz SparseRepMatrix.LDLdecomposition  s    '	BBr"   c                     t        | |      S r$   )r   rM   r{   s     r    lower_triangular_solvez&SparseRepMatrix.lower_triangular_solve      -dC88r"   c                     t        | |      S r$   )r   r   s     r    upper_triangular_solvez&SparseRepMatrix.upper_triangular_solve  r   r"   )rQ   )T)__name__
__module____qualname____doc__classmethodr3   propertyrN   rV   r_   rc   rf   ro   rq   rs   rw   r}   r   RLCLr   r   r   r   r   r   r   r   r   r   __classcell__)rH   s   @r    r   r      s   Sj ~$ ~$@  L
4@+
)"m,!3.71r9 
(D$(I	JB	(D$(I	JB6;C99 /5nnEM.N.V.V#+.>.F.FH.F.N.N.D.L.L".D.L.L""r"   r   c                       e Zd Zed        Zy)re   c                 v     | j                   |i |\  }}}| j                  |||      }| j                  |      S r$   )r3   _smat_to_DomainMatrix_fromrep)r9   r:   r;   r)   r*   r   reps          r    rZ   zMutableSparseMatrix._new  sC    6366GGdD''dD9||C  r"   N)r   r   r   r   rZ   ru   r"   r    re   re     s    ! !r"   re   N)collections.abcr   sympy.core.containersr   sympy.utilities.exceptionsr   sympy.utilities.iterablesr   sympy.utilities.miscr   matricesr
   	repmatrixr   r   	utilitiesr   decompositionsr   r   r   r   solversr   r   r   re   SparseMatrixru   r"   r    <module>r      sT    $ & @ 1 '   2  DvMi vMr!/+; ! #r"   