o
    §ƒðjÔ0  ã                   @   s¶   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 ddlmZ 	ddd	„Z		dd
d„Ze	fdd„Ze	ddfdd„Ze	dfdd„Zdd„ Zdd„ Ze	dddfdd„ZdS )é    )ÚFunctionType)ÚCoercionFailed)ÚZZÚQQé   )Ú_get_intermediate_simpÚ_iszeroÚ_dotprodsimpÚ	_simplify)Ú_find_reasonable_pivotTc	                    s8  ‡ ‡fdd„}	‡ ‡fdd„}
‡ ‡‡fdd„}t tƒ‰d\}}g }g }|ˆ k rÓ||k rÓt|	|ƒ|d… ||ƒ\}}}}|D ]\}}||7 }|ˆ|ˆ  | < q<|du rV|d	7 }q"| |¡ |d
kro|
||| ƒ | ||| f¡ |du rž||}}|ˆ|ˆ  | < t|ˆ  | d	 |d	 ˆ  ƒD ]}ˆˆ| | ƒˆ|< q�|}t|ƒD ]$}||kr©q¢|du r²||k r²q¢ˆ|ˆ  |  }||ƒr¿q¢|||||ƒ q¢|d	7 }|ˆ k rÓ||k s*|du �r|du �rt|ƒD ]1\}}ˆ|ˆ  |  }|ˆ|ˆ  | < t|ˆ  | d	 |d	 ˆ  ƒD ]}ˆˆ| | ƒˆ|< �qqáˆt|ƒt|ƒfS )aÛ  Row reduce a flat list representation of a matrix and return a tuple
    (rref_matrix, pivot_cols, swaps) where ``rref_matrix`` is a flat list,
    ``pivot_cols`` are the pivot columns and ``swaps`` are any row swaps that
    were used in the process of row reduction.

    Parameters
    ==========

    mat : list
        list of matrix elements, must be ``rows`` * ``cols`` in length

    rows, cols : integer
        number of rows and columns in flat list representation

    one : SymPy object
        represents the value one, from ``Matrix.one``

    iszerofunc : determines if an entry can be used as a pivot

    simpfunc : used to simplify elements and test if they are
        zero if ``iszerofunc`` returns `None`

    normalize_last : indicates where all row reduction should
        happen in a fraction-free manner and then the rows are
        normalized (so that the pivots are 1), or whether
        rows should be normalized along the way (like the naive
        row reduction algorithm)

    normalize : whether pivot rows should be normalized so that
        the pivot value is 1

    zero_above : whether entries above the pivot should be zeroed.
        If ``zero_above=False``, an echelon matrix will be returned.
    c                    s   ˆ| d ˆ … S ©N© ©Úi©ÚcolsÚmatr   ú›/tmp/claude-1000/-var-www-html-academy/3f42efd1-c2b7-4d08-9b05-30d86bb35479/scratchpad/piper/venv/lib/python3.10/site-packages/sympy/matrices/reductions.pyÚget_col/   s   z!_row_reduce_list.<locals>.get_colc                    s^   ˆ|ˆ  |d ˆ  … ˆ| ˆ  | d ˆ  … ˆ| ˆ  | d ˆ  …< ˆ|ˆ  |d ˆ  …< d S )Nr   r   )r   Újr   r   r   Úrow_swap2   s   .0ÿz"_row_reduce_list.<locals>.row_swapc                    sP   || ˆ  }t |ˆ  |d ˆ  ƒD ]}ˆ| ˆ|  |ˆ||    ƒˆ|< qdS )z,Does the row op row[i] = a*row[i] - b*row[j]r   N)Úrange)Úar   Úbr   ÚqÚp©r   Úisimpr   r   r   Úcross_cancel6   s   &ÿz&_row_reduce_list.<locals>.cross_cancel©r   r   Nr   r   FT)r   r	   r   Úappendr   Ú	enumerateÚtuple)r   Úrowsr   ÚoneÚ
iszerofuncÚsimpfuncÚnormalize_lastÚ	normalizeÚ
zero_abover   r   r   Úpiv_rowÚpiv_colÚ
pivot_colsÚswapsÚpivot_offsetÚ	pivot_valÚassumed_nonzeroÚnewly_determinedÚoffsetÚvalr   r   r   ÚrowÚpiv_iÚpiv_jr   r   r   Ú_row_reduce_list
   s`   %ÿÿ

"Ô/"ÿr7   c           	      C   sB   t t| ƒ| j| j| j|||||d�	\}}}|  | j| j|¡||fS )N©r'   r(   r)   )r7   Úlistr#   r   r$   Ú_new)	ÚMr%   r&   r'   r(   r)   r   r,   r-   r   r   r   Ú_row_reduce|   s
   þr<   c                    s‚   | j dks
| jdkrdS t‡ fdd„| dd…df D ƒƒ}ˆ | d ƒr2|o1t| dd…dd…f ˆ ƒS |o@t| dd…dd…f ˆ ƒS )z¦Returns `True` if the matrix is in echelon form. That is, all rows of
    zeros are at the bottom, and below each leading non-zero in a row are
    exclusively zeros.r   Tc                 3   s   � | ]}ˆ |ƒV  qd S r   r   )Ú.0Út©r%   r   r   Ú	<genexpr>Ž   s   € z_is_echelon.<locals>.<genexpr>r   Nr   )r#   r   ÚallÚ_is_echelon)r;   r%   Úzeros_belowr   r?   r   rB   †   s   "rB   Fc                 C   s<   t |tƒr|nt}t| ||dddd�\}}}|r||fS |S )an  Returns a matrix row-equivalent to ``M`` that is in echelon form. Note
    that echelon form of a matrix is *not* unique, however, properties like the
    row space and the null space are preserved.

    Examples
    ========

    >>> from sympy import Matrix
    >>> M = Matrix([[1, 2], [3, 4]])
    >>> M.echelon_form()
    Matrix([
    [1,  2],
    [0, -2]])
    TFr8   )Ú
isinstancer   r
   r<   )r;   r%   ÚsimplifyÚwith_pivotsr&   r   ÚpivotsÚ_r   r   r   Ú_echelon_form–   s   ÿrI   c           
         sü   dd„ }t |tƒr|nt}| jdks| jdkrdS | jdks#| jdkr2‡ fdd„| D ƒ}d|v r2dS | jdkre| jdkre‡ fd	d„| D ƒ}d|vrOd
|vrOdS |  ¡ }ˆ |ƒr]d|v r]dS ˆ |ƒdu redS || ˆ d�\}}t|ˆ |dddd�\}}	}t|	ƒS )zÿReturns the rank of a matrix.

    Examples
    ========

    >>> from sympy import Matrix
    >>> from sympy.abc import x
    >>> m = Matrix([[1, 2], [x, 1 - 1/x]])
    >>> m.rank()
    2
    >>> n = Matrix(3, 3, range(1, 10))
    >>> n.rank()
    2
    c                    sJ   ‡ ‡fdd„‰‡fdd„t ˆ jƒD ƒ}dd„ t|ƒD ƒ}ˆ j|dd�|fS )a€  Permute columns with complicated elements as
        far right as they can go.  Since the ``sympy`` row reduction
        algorithms start on the left, having complexity right-shifted
        speeds things up.

        Returns a tuple (mat, perm) where perm is a permutation
        of the columns to perform to shift the complex columns right, and mat
        is the permuted matrix.c                    s"   t ‡fdd„ˆ d d …| f D ƒƒS )Nc                 3   s$   � | ]}ˆ |ƒd u rdndV  qd S )Nr   r   r   ©r=   Úer?   r   r   r@   Ï   s   €" zO_rank.<locals>._permute_complexity_right.<locals>.complexity.<locals>.<genexpr>)Úsumr   )r;   r%   r   r   Ú
complexityÌ   s   "z<_rank.<locals>._permute_complexity_right.<locals>.complexityc                    s   g | ]}ˆ |ƒ|f‘qS r   r   )r=   r   )rM   r   r   Ú
<listcomp>Ñ   s    z<_rank.<locals>._permute_complexity_right.<locals>.<listcomp>c                 S   s   g | ]\}}|‘qS r   r   )r=   r   r   r   r   r   rN   Ò   ó    r   )Úorientation)r   r   ÚsortedÚpermute)r;   r%   ÚcomplexÚpermr   )r;   rM   r%   r   Ú_permute_complexity_rightÂ   s   
z(_rank.<locals>._permute_complexity_rightr   r   c                    ó   g | ]}ˆ |ƒ‘qS r   r   ©r=   Úxr?   r   r   rN   ß   rO   z_rank.<locals>.<listcomp>Fé   c                    rV   r   r   rW   r?   r   r   rN   å   rO   Nr?   Tr8   )rD   r   r
   r#   r   Údetr<   Úlen)
r;   r%   rE   rU   r&   ÚzerosÚdr   rH   rG   r   r?   r   Ú_rank²   s,   
ÿr^   c                 C   sŽ   t | dƒsd S | j}|j}|jr|S |jr'z| t¡W S  ty&   | Y S w tdd„ | D ƒƒs2d S z| t¡W S  tyF   | t	¡ Y S w )NÚ_repc                 s   s   � | ]}|j V  qd S r   )Úis_RationalrJ   r   r   r   r@     s   € z_to_DM_ZZ_QQ.<locals>.<genexpr>)
Úhasattrr_   ÚdomainÚis_ZZÚis_QQÚ
convert_tor   r   rA   r   )r;   ÚrepÚKr   r   r   Ú_to_DM_ZZ_QQø   s&   
ÿÿrh   c                 C   sT   | j }|jr| jdd�\}}}| ¡ | }n|jr |  ¡ \}}nJ ‚| ¡ }||fS )z7Compute the reduced row echelon form of a DomainMatrix.F)Úkeep_domain)rb   rc   Úrref_denÚto_fieldrd   ÚrrefÚ	to_Matrix)ÚdMrg   ÚdM_rrefÚdenrG   ÚM_rrefr   r   r   Ú_rref_dm  s   rr   c           
      C   s\   t | ƒ}|durt|ƒ\}}nt|tƒr|}nt}t| |||ddd�\}}}	|r,||fS |S )a-	  Return reduced row-echelon form of matrix and indices
    of pivot vars.

    Parameters
    ==========

    iszerofunc : Function
        A function used for detecting whether an element can
        act as a pivot.  ``lambda x: x.is_zero`` is used by default.

    simplify : Function
        A function used to simplify elements when looking for a pivot.
        By default SymPy's ``simplify`` is used.

    pivots : True or False
        If ``True``, a tuple containing the row-reduced matrix and a tuple
        of pivot columns is returned.  If ``False`` just the row-reduced
        matrix is returned.

    normalize_last : True or False
        If ``True``, no pivots are normalized to `1` until after all
        entries above and below each pivot are zeroed.  This means the row
        reduction algorithm is fraction free until the very last step.
        If ``False``, the naive row reduction procedure is used where
        each pivot is normalized to be `1` before row operations are
        used to zero above and below the pivot.

    Examples
    ========

    >>> from sympy import Matrix
    >>> from sympy.abc import x
    >>> m = Matrix([[1, 2], [x, 1 - 1/x]])
    >>> m.rref()
    (Matrix([
    [1, 0],
    [0, 1]]), (0, 1))
    >>> rref_matrix, rref_pivots = m.rref()
    >>> rref_matrix
    Matrix([
    [1, 0],
    [0, 1]])
    >>> rref_pivots
    (0, 1)

    ``iszerofunc`` can correct rounding errors in matrices with float
    values. In the following example, calling ``rref()`` leads to
    floating point errors, incorrectly row reducing the matrix.
    ``iszerofunc= lambda x: abs(x) < 1e-9`` sets sufficiently small numbers
    to zero, avoiding this error.

    >>> m = Matrix([[0.9, -0.1, -0.2, 0], [-0.8, 0.9, -0.4, 0], [-0.1, -0.8, 0.6, 0]])
    >>> m.rref()
    (Matrix([
    [1, 0, 0, 0],
    [0, 1, 0, 0],
    [0, 0, 1, 0]]), (0, 1, 2))
    >>> m.rref(iszerofunc=lambda x:abs(x)<1e-9)
    (Matrix([
    [1, 0, -0.301369863013699, 0],
    [0, 1, -0.712328767123288, 0],
    [0, 0,         0,          0]]), (0, 1))

    Notes
    =====

    The default value of ``normalize_last=True`` can provide significant
    speedup to row reduction, especially on matrices with symbols.  However,
    if you depend on the form row reduction algorithm leaves entries
    of the matrix, set ``normalize_last=False``
    NT)r(   r)   )rh   rr   rD   r   r
   r<   )
r;   r%   rE   rG   r'   rn   r   r,   r&   rH   r   r   r   Ú_rref'  s   J
ÿrs   N)TTT)Útypesr   Úsympy.polys.polyerrorsr   Úsympy.polys.domainsr   r   Ú	utilitiesr   r   r	   r
   Údeterminantr   r7   r<   rB   rI   r^   rh   rr   rs   r   r   r   r   Ú<module>   s$    
ÿr
ÿ
Fÿ