
    EdY9                         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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                   x    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          |          dk    rTt          |d         t                    r9|d         j        }|d         j        }|d                                         ||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	                    ||                     fdt          |          D             } fdt          |          D             }	|D ]8}
|	D ]3}                      ||
|                    }| j        k    r||
|f<   49||fS t          |d         t          t          f          rfd	}|d                                         D ]\  \  }}}t          |t                    rC|                                                                D ]\  \  }
}} |||
z   ||z   |           `t          |t           t"          f          r6  j        |fi |\  }}D ] \  }
} |||
z   ||z   |
|f                    !                     |          } |||                     |                     nt'          |d                   rt)          d
 |d         D                        }|s  j        |d         fi |\  }}n|d         }t          |          ||z  k    r1t          d	                    t          |          ||                    t          |          D ]I}
t          |          D ]7}||
|z  |z            }                     |          }| j        k    r||
|f<   8J|U                                }|rt-          d |D                       dz   nd}|rt-          d |D                       dz   nd}nX                                D ]C\  }
}|
r|
|k    s|r4||k    r.t          d	                    |
|fd|dz
  d|dz
                      D||fS t          |          dk    rt          |d         t           t"          f          r|d         }d}t/          |          D ]{\  }
}t          |t           t"          f          s|g}t/          |          D ]*\  }}| j        k    r                     |          |
|f<   +t-          |t          |                    }||rt          |          nd}|}||fS  t1                      j        | \  }}}t          |          D ]4}
t          |          D ]"}|||
z  |z            }| j        k    r||
|f<   #5||fS )Nr	   r         z*Pass rows=None and no cols for autosizing.z2{} and {} must be integers for this specification.c                 :    g | ]}                     |          S  _sympify).0iclss     5lib/python3.11/site-packages/sympy/matrices/sparse.py
<listcomp>z;SparseRepMatrix._handle_creation_inputs.<locals>.<listcomp>   #    DDD1s||ADDD    c                 :    g | ]}                     |          S r   r   )r   jr   s     r    r!   z;SparseRepMatrix._handle_creation_inputs.<locals>.<listcomp>   r"   r#   c           	          |rK| |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smats      r    updatez7SparseRepMatrix._handle_creation_inputs.<locals>.update   s}     'q6T> a41:o ", K!'A41:!>!># #  &'QT


' 'r#   c              3   4   K   | ]}t          |          V  d S Nr   )r   r   s     r    	<genexpr>z:SparseRepMatrix._handle_creation_inputs.<locals>.<genexpr>   s(      ??!{1~~??????r#   zMThe length of the flat list ({}) does not match the specified size ({} * {}).c                     g | ]\  }}|S r   r   )r   r_s      r    r!   z;SparseRepMatrix._handle_creation_inputs.<locals>.<listcomp>       ///$!QA///r#   c                     g | ]\  }}|S r   r   )r   r1   cs      r    r!   z;SparseRepMatrix._handle_creation_inputs.<locals>.<listcomp>   r2   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kwargsr7   r8   r0   r4   oprow_indicescol_indicesr   r%   valuer+   r)   vvr1   flat	flat_listrB   rowmatr*   	__class__s   `                     @r    r@   z'SparseRepMatrix._handle_creation_inputsk   s3   t99> 	$ja*== 	$7<D7<D7==??Dt##t99> 	)d1g 	)$Q(Dt99> r	$8DAqA > > > > > > > >""tt!Q > @B B B $DG__fT!Wood$q'8,, >3!WD$<' =$))/d););= = = EDDDdDDDDDDDdDDD$ / /A( / / #RR1XX 6 6 CH, /).DAJ/
 T4''DGdD\22 +3' ' ' ' ' "&a 
6 
6IFQA!!Z00 	6*+''))//*;*; 5 5JFQB"F1q5!a%44445#Ae}55 6%@S%@%M%Mf%M%M
1d$( = =DAq"F1q5!a%ad<<<<=  LLOOq!S\\!__5555
6 T!W%% 3??tAw?????? 333DGFFvFF Aq$$ !%QI9~~4 (B#VC	NND$??   #4[[ 3 3!&t 3 3A$-afqj$9E$'LL$7$7E$0 3-2QT
	3  yy{{8<Cs//$///00144!8<Cs//$///00144! !IIKK  DAq Q$Y ! T	 (0#VQFAtaxD1HEE   t##YY!^ 	$
47T5M B B 	$QAA#A,, % %3!#e}55  %C&s^^ 6 6EArSX~ 6%(\\"%5%5QT
3s88$$%3q666ADDt## >egg=tDOD$4[[ + +t + +AQ
OE( +%*QT
+
 t##r#   c                 N    t          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   r9   selfs    r    _smatzSparseRepMatrix._smat   s8     	" &+'M	
 	
 	
 	
 zz||r#   c                     |                      |                    dd          |                    dt                    |                    dd                    S )NmethodLDL
iszerofunctry_block_diagF)rY   r[   r\   )invgetr   )rV   rG   s     r    _eval_inversezSparseRepMatrix._eval_inverse   sS    xxvzz(E::#)::lG#D#D'-zz2BE'J'J  L L 	Lr#   c                    t          |          st          d          i }|                                                                 D ]\  }} ||          }|dk    r|||<   |                     | 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	TypeErrorr9   r=   _newr7   r8   )rV   fdokkr)   fvs         r    	applyfunczSparseRepMatrix.applyfunc   s    $ {{ 	53444
 JJLL&&(( 	 	DAq1BQw AyyDIs333r#   c                 $    ddl m}  ||           S )z,Returns an Immutable version of this Matrix.r	   )ImmutableSparseMatrix)	immutablerj   )rV   rj   s     r    as_immutablezSparseRepMatrix.as_immutable  s%    44444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]])
        )MutableSparseMatrixrU   s    r    
as_mutablezSparseRepMatrix.as_mutable$  s     #4(((r#   c                       fdt          t                                                                                     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                 B    g | ]}t          ||         fz             S r   r?   r   rf   rV   s     r    r!   z,SparseRepMatrix.col_list.<locals>.<listcomp>I  s+    rrr!a47*n%%rrrr#   c                 :    t          t          |                     S r-   )r>   reversed)rf   s    r    <lambda>z*SparseRepMatrix.col_list.<locals>.<lambda>I  s    _cdlmndodo_p_p r#   key)sortedr>   r9   rB   rU   s   `r    col_listzSparseRepMatrix.col_list5  sM    ( srrrvd4::<<;L;L;N;N6O6OUpUp/q/q/qrrrrr#   c                 D    t          |                                           S )z2Returns the number of non-zero elements in Matrix.)r5   r9   rU   s    r    nnzzSparseRepMatrix.nnzK  s    4::<<   r#   c                       fdt                                                                           t                    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                 B    g | ]}t          ||         fz             S r   rr   rs   s     r    r!   z,SparseRepMatrix.row_list.<locals>.<listcomp>c  s7     3 3 3!a47*n%% 3 3 3r#   rw   )ry   r9   rB   r>   rU   s   `r    row_listzSparseRepMatrix.row_listO  sO    (3 3 3 34::<<$$&&D1113 3 3 	3r#   c                     || z  S )z"Scalar element-wise multiplicationr   )rV   scalars     r    scalar_multiplyzSparseRepMatrix.scalar_multiplyf  s    }r#   rZ   c                 N    | j         }|| z                      |          |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

        rY   )Tr]   )rV   rhsrY   ts       r    solve_least_squaresz#SparseRepMatrix.solve_least_squaresj  s.    l F$||6|**1,S00r#   c                     | j         s@| j        | j        k     rt          d          | j        | j        k    rt          d          dS |                     |                              |          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).r   N)	is_squarer7   r8   r'   r]   multiply)rV   r   rY   s      r    solvezSparseRepMatrix.solve  s    
 ~ 	9y49$ O !;<<<TY& O  "N O O OO O 8868**33C888r#   NzAlternate faster representationc                      t          |           S r-   )r   rU   s    r    liupczSparseRepMatrix.liupc  s    d||r#   c                      t          |           S r-   )r   rU   s    r    row_structure_symbolic_choleskyz/SparseRepMatrix.row_structure_symbolic_cholesky  s    /555r#   Tc                 $    t          | |          S N)	hermitian)r   rV   r   s     r    choleskyzSparseRepMatrix.cholesky  s    	::::r#   c                 $    t          | |          S r   )r   r   s     r    LDLdecompositionz SparseRepMatrix.LDLdecomposition  s    '	BBBBr#   c                 "    t          | |          S r-   )r   rV   r   s     r    lower_triangular_solvez&SparseRepMatrix.lower_triangular_solve      -dC888r#   c                 "    t          | |          S r-   )r   r   s     r    upper_triangular_solvez&SparseRepMatrix.upper_triangular_solve  r   r#   )rZ   )T)__name__
__module____qualname____doc__classmethodr@   propertyrW   r_   rh   rl   ro   rz   r|   r   r   r   r   RLCLr   r   r   r   r   r   r   r   r   r   __classcell__)rQ   s   @r    r   r      s       S Sj ~$ ~$ ~$ ~$ [~$@   XL L L
4 4 4@+ + +
) ) )"s s s,! ! !3 3 3.  71 71 71 71r9 9 9 9 
(D$(I	J	JB	(D$(I	J	JB  6 6 6; ; ; ;C C C C9 9 99 9 9 /5nEM.N.V#+.>.FH.F.N.D.L".D.L"""""r#   r   c                   $    e Zd Zed             ZdS )rn   c                 |     | j         |i |\  }}}|                     |||          }|                     |          S r-   )r@   _smat_to_DomainMatrix_fromrep)r   rF   rG   r7   r8   r*   reps          r    rc   zMutableSparseMatrix._new  sI    636GGGdD''dD99||C   r#   N)r   r   r   r   rc   r   r#   r    rn   rn     s-        ! ! [! ! !r#   rn   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   rn   SparseMatrixr   r#   r    <module>r      sz   $ $ $ $ $ $ & & & & & & @ @ @ @ @ @ 1 1 1 1 1 1 ' ' ' ' ' '             2 2 2 2 2 2 2 2                 D D D D D D D DvM vM vM vM vMi vM vM vMr! ! ! ! !/+; ! ! ! #r#   