o
    §ƒðjQ9  ã                   @   s¶   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„ deƒZG dd„ deeƒZeZdS )é    )Ú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                       s  e Zd ZdZe‡ f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dd„ Zdd„ Zd*dd„Zd*dd„ZeedddƒZeedddƒZdd„ Zdd „ Zd+d"d#„Zd+d$d%„Zd&d'„ Zd(d)„ Zeje_eje_eje_eje_eje_eje_‡  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              
      s  t |ƒdkr"t|d tƒr"|d j}|d j}|d  ¡ ‰||ˆfS i ‰t |ƒdkr7|d d u r7d d |d g}t |ƒdk�ró|d d… \}}||  u rPd u rWn nd  }}nd ||fv ratdƒ‚t|d ƒt|d ƒ}}t|d tƒr¿|d }d ||fv r‡td 	||¡ƒ‚‡ fdd„t
|ƒD ƒ}‡ fd	d„t
|ƒD ƒ}	|D ]}
|	D ]}ˆ  ||
|ƒ¡}|ˆ jkr¸|ˆ|
|f< q£qŸ||ˆfS t|d ttfƒ�r3‡fd
d„}|d  ¡ D ]\\\}}}t|tƒrø| ¡  ¡ D ]\\}
}}|||
 || |ƒ qæqÕt|ttfƒ�r#ˆ j|fi |¤Ž\}}‰ˆD ]\}
}|||
 || ˆ|
|f ƒ �qqÕˆ  |¡}|||ˆ  |¡ƒ qÕnft|d ƒ�r™tdd„ |d D ƒƒ }|�sXˆ j|d fi |¤Ž\}}‰nA|d }t |ƒ|| k�rptd 	t |ƒ||¡ƒ‚t
|ƒD ]$}
t
|ƒD ]}||
| |  }ˆ  |¡}|ˆ jk�r•|ˆ|
|f< �qz�qt|d u �rÃˆ ¡ }|�r°tdd„ |D ƒƒd nd}|�rÀtdd„ |D ƒƒd nd}n+ˆ ¡ D ]&\}
}|
�rÓ|
|k�sÛ|�rì||k�rìtd 	|
|fd|d d|d ¡ƒ‚�qÇ||ˆfS t |ƒdk�rOt|d ttfƒ�rO|d }d}t|ƒD ]0\}
}t|ttfƒ�s|g}t|ƒD ]\}}|ˆ jk�r4ˆ  |¡ˆ|
|f< �q!t|t |ƒƒ}�q|�rFt |ƒnd}|}||ˆfS tƒ j|Ž \}}}t
|ƒD ]}
t
|ƒD ]}|||
 |  }|ˆ jk�rx|ˆ|
|f< �qb�q\||ˆfS )Nr   r   é   é   z*Pass rows=None and no cols for autosizing.z2{} and {} must be integers for this specification.c                    ó   g | ]}ˆ   |¡‘qS © ©Ú_sympify©Ú.0Úi©Úclsr   ú—/tmp/claude-1000/-var-www-html-academy/3f42efd1-c2b7-4d08-9b05-30d86bb35479/scratchpad/piper/venv/lib/python3.10/site-packages/sympy/matrices/sparse.pyÚ
<listcomp>Š   ó    z;SparseRepMatrix._handle_creation_inputs.<locals>.<listcomp>c                    r   r   r   )r   Újr   r   r   r    ‹   r!   c                    sR   |r'| |fˆ v r|ˆ | |f krt d | |f|ˆ | |f ¡ƒ‚|ˆ | |f< d S d S )Nz)There is a collision at {} for {} and {}.)Ú
ValueErrorÚformat)r   r"   Úv)Úsmatr   r   Úupdate–   s   þúz7SparseRepMatrix._handle_creation_inputs.<locals>.updatec                 s   s   � | ]}t |ƒV  qd S ©Nr   r   r   r   r   Ú	<genexpr>®   ó   € z:SparseRepMatrix._handle_creation_inputs.<locals>.<genexpr>zMThe length of the flat list ({}) does not match the specified size ({} * {}).c                 s   s   � | ]\}}|V  qd S r(   r   )r   ÚrÚ_r   r   r   r)   Ä   r*   c                 s   s   � | ]\}}|V  qd S r(   r   )r   r,   Úcr   r   r   r)   Å   r*   z?The location {} is out of the designated range[{}, {}]x[{}, {}])ÚlenÚ
isinstancer	   ÚrowsÚcolsÚtodokr#   r   r   r$   Úranger   ÚzeroÚdictr   ÚitemsÚlistÚtupleÚ_handle_creation_inputsr   ÚanyÚkeysÚmaxÚ	enumerateÚsuper)r   ÚargsÚkwargsr0   r1   r+   r-   ÚopÚrow_indicesÚcol_indicesr   r"   Úvaluer'   r%   Úvvr,   ÚflatÚ	flat_listr;   ÚrowÚmat©Ú	__class__)r   r&   r   r9   k   sÎ   



ÿþ
€ý

ÿ ÿ
ö
ÿý
€ü
 " ý€
"€
€ý
z'SparseRepMatrix._handle_creation_inputsc                 C   s   t dddd� |  ¡ 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   r2   ©Úselfr   r   r   Ú_smatì   s   ú	zSparseRepMatrix._smatc                 K   s(   | j | dd¡| dt¡| dd¡d�S )NÚmethodÚLDLÚ
iszerofuncÚtry_block_diagF)rQ   rS   rT   )ÚinvÚgetr   )rO   r@   r   r   r   Ú_eval_inverseú   s   

þzSparseRepMatrix._eval_inversec                 C   sT   t |ƒstdƒ‚i }|  ¡  ¡ D ]\}}||ƒ}|dkr |||< q|  | 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Ú	TypeErrorr2   r6   Ú_newr0   r1   )rO   ÚfÚdokÚkr%   Úfvr   r   r   Ú	applyfuncÿ   s   €zSparseRepMatrix.applyfuncc                 C   s   ddl m} || ƒS )z,Returns an Immutable version of this Matrix.r   )ÚImmutableSparseMatrix)Ú	immutabler`   )rO   r`   r   r   r   Úas_immutable  s   zSparseRepMatrix.as_immutablec                 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]])
        )ÚMutableSparseMatrixrN   r   r   r   Ú
as_mutable$  s   zSparseRepMatrix.as_mutablec                    s&   ‡ fdd„t ˆ  ¡  ¡ dd„ d�D ƒS )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                    ó   g | ]}t |ˆ | f ƒ‘qS r   ©r8   ©r   r]   rN   r   r   r    I  ó    z,SparseRepMatrix.col_list.<locals>.<listcomp>c                 S   s   t t| ƒƒS r(   )r7   Úreversed)r]   r   r   r   Ú<lambda>I  s    z*SparseRepMatrix.col_list.<locals>.<lambda>©Úkey)Úsortedr2   r;   rN   r   rN   r   Úcol_list5  s   &zSparseRepMatrix.col_listc                 C   s   t |  ¡ ƒS )z2Returns the number of non-zero elements in Matrix.)r.   r2   rN   r   r   r   ÚnnzK  s   zSparseRepMatrix.nnzc                    s"   ‡ fdd„t ˆ  ¡  ¡ td�D ƒS )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
        c                    rf   r   rg   rh   rN   r   r   r    c  ri   z,SparseRepMatrix.row_list.<locals>.<listcomp>rl   )rn   r2   r;   r7   rN   r   rN   r   Úrow_listO  s   
ÿzSparseRepMatrix.row_listc                 C   s   ||  S )z"Scalar element-wise multiplicationr   )rO   Úscalarr   r   r   Úscalar_multiplyf  s   zSparseRepMatrix.scalar_multiplyrR   c                 C   s   | j }||  j|d�| | 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

        ©rQ   )ÚTrU   )rO   ÚrhsrQ   Útr   r   r   Úsolve_least_squaresj  s   6z#SparseRepMatrix.solve_least_squaresc                 C   sD   | j s| j| jk rtdƒ‚| j| jkrtdƒ‚dS | j|d� |¡S )z–Return 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).rt   N)Ú	is_squarer0   r1   r#   rU   Úmultiply)rO   rv   rQ   r   r   r   Úsolve£  s   ÿzSparseRepMatrix.solveNzAlternate faster representationc                 C   rc   r(   )r   rN   r   r   r   Úliupc´  ó   zSparseRepMatrix.liupcc                 C   rc   r(   )r   rN   r   r   r   Úrow_structure_symbolic_cholesky·  r}   z/SparseRepMatrix.row_structure_symbolic_choleskyTc                 C   ó   t | |d�S ©N)Ú	hermitian)r   ©rO   r�   r   r   r   Úcholeskyº  ó   zSparseRepMatrix.choleskyc                 C   r   r€   )r   r‚   r   r   r   ÚLDLdecomposition½  r„   z SparseRepMatrix.LDLdecompositionc                 C   ó
   t | |ƒS r(   )r   ©rO   rv   r   r   r   Úlower_triangular_solveÀ  ó   
z&SparseRepMatrix.lower_triangular_solvec                 C   r†   r(   )r   r‡   r   r   r   Úupper_triangular_solveÃ  r‰   z&SparseRepMatrix.upper_triangular_solve)rR   )T)Ú__name__Ú
__module__Ú__qualname__Ú__doc__Úclassmethodr9   ÚpropertyrP   rW   r_   rb   re   ro   rp   rq   rs   rx   r{   ÚRLÚCLr|   r~   rƒ   r…   rˆ   rŠ   r   r   r   r   Ú__classcell__r   r   rJ   r   r      s>    U 
 

9

r   c                   @   s   e Zd Zedd„ ƒZdS )rd   c                 O   s.   | j |i |¤Ž\}}}|  |||¡}|  |¡S r(   )r9   Ú_smat_to_DomainMatrixÚ_fromrep)r   r?   r@   r0   r1   r&   Úrepr   r   r   rZ   Ð  s   
zMutableSparseMatrix._newN)r‹   rŒ   r�   r�   rZ   r   r   r   r   rd   Î  s    rd   N)Úcollections.abcr   Úsympy.core.containersr   Úsympy.utilities.exceptionsr   Úsympy.utilities.iterablesr   Úsympy.utilities.miscr   Ú
matrixbaser	   Ú	repmatrixr
   r   Ú	utilitiesr   Údecompositionsr   r   r   r   Úsolversr   r   r   rd   ÚSparseMatrixr   r   r   r   Ú<module>   s        <