o
    Ö­jx<  ã                   @   s–   d Z ddlZddlmZ dgZd!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d„Zdd„ Zdd„ Zdd„ Zdd „ ZdS )#zSparse block 1-norm estimator.
é    N)ÚaslinearoperatorÚ
onenormesté   é   Fc                 C   s  t | ƒ} | jd | jd krtdƒ‚| jd }||krht t | ƒ t |¡¡¡}|j||fkr9tddt|jƒ ƒ‚t	|ƒj
dd�}|j|fkrQtddt|jƒ ƒ‚t |¡}t||ƒ}	|dd…|f }
|| }nt| | j||ƒ\}}	}
}}|sy|rŒ|f}|rƒ||	f7 }|rŠ||
f7 }|S |S )a¼	  
    Compute a lower bound of the 1-norm of a sparse array.

    Parameters
    ----------
    A : ndarray or other linear operator
        A linear operator that can be transposed and that can
        produce matrix products.
    t : int, optional
        A positive parameter controlling the tradeoff between
        accuracy versus time and memory usage.
        Larger values take longer and use more memory
        but give more accurate output.
    itmax : int, optional
        Use at most this many iterations.
    compute_v : bool, optional
        Request a norm-maximizing linear operator input vector if True.
    compute_w : bool, optional
        Request a norm-maximizing linear operator output vector if True.

    Returns
    -------
    est : float
        An underestimate of the 1-norm of the sparse array.
    v : ndarray, optional
        The vector such that ||Av||_1 == est*||v||_1.
        It can be thought of as an input to the linear operator
        that gives an output with particularly large norm.
    w : ndarray, optional
        The vector Av which has relatively large 1-norm.
        It can be thought of as an output of the linear operator
        that is relatively large in norm compared to the input.

    Notes
    -----
    This is algorithm 2.4 of [1].

    In [2] it is described as follows.
    "This algorithm typically requires the evaluation of
    about 4t matrix-vector products and almost invariably
    produces a norm estimate (which is, in fact, a lower
    bound on the norm) correct to within a factor 3."

    .. versionadded:: 0.13.0

    References
    ----------
    .. [1] Nicholas J. Higham and Francoise Tisseur (2000),
           "A Block Algorithm for Matrix 1-Norm Estimation,
           with an Application to 1-Norm Pseudospectra."
           SIAM J. Matrix Anal. Appl. Vol. 21, No. 4, pp. 1185-1201.

    .. [2] Awad H. Al-Mohy and Nicholas J. Higham (2009),
           "A new scaling and squaring algorithm for the matrix exponential."
           SIAM J. Matrix Anal. Appl. Vol. 31, No. 3, pp. 970-989.

    Examples
    --------
    >>> import numpy as np
    >>> from scipy.sparse import csc_array
    >>> from scipy.sparse.linalg import onenormest
    >>> A = csc_array([[1., 0., 0.], [5., 8., 2.], [0., -1., 0.]], dtype=float)
    >>> A.toarray()
    array([[ 1.,  0.,  0.],
           [ 5.,  8.,  2.],
           [ 0., -1.,  0.]])
    >>> onenormest(A)
    9.0
    >>> np.linalg.norm(A.toarray(), ord=1)
    9.0
    r   é   z1expected the operator to act like a square matrixzinternal error: zunexpected shape ©ÚaxisN)r   ÚshapeÚ
ValueErrorÚnpÚasarrayÚmatmatÚidentityÚ	ExceptionÚstrÚabsÚsumÚargmaxÚelementary_vectorÚ_onenormest_coreÚH)ÚAÚtÚitmaxÚ	compute_vÚ	compute_wÚnÚ
A_explicitÚcol_abs_sumsÚargmax_jÚvÚwÚestÚnmultsÚ
nresamplesÚresult© r&   ú\/var/www/html/CropPilot/venv/lib/python3.10/site-packages/scipy/sparse/linalg/_onenormest.pyr      s8   J
ÿÿ




c                    s   d‰ ‡ ‡fdd„}|S )z‘
    Decorator for an elementwise function, to apply it blockwise along
    first dimension, to avoid excessive memory usage in temporaries.
    é   c                    s–   | j d ˆ k rˆ| ƒS ˆ| d ˆ … ƒ}tj| j d f|j dd …  |jd�}||d ˆ …< ~tˆ | j d ˆ ƒD ]}ˆ| ||ˆ  … ƒ|||ˆ  …< q6|S )Nr   r   ©Údtype)r	   r   Úzerosr*   Úrange)ÚxÚy0ÚyÚj©Ú
block_sizeÚfuncr&   r'   Úwrapper€   s   &"z%_blocked_elementwise.<locals>.wrapperr&   )r3   r4   r&   r1   r'   Ú_blocked_elementwisey   s   r5   c                 C   s&   |   ¡ }d||dk< |t |¡ }|S )a9  
    This should do the right thing for both real and complex matrices.

    From Higham and Tisseur:
    "Everything in this section remains valid for complex matrices
    provided that sign(A) is redefined as the matrix (aij / |aij|)
    (and sign(0) = 1) transposes are replaced by conjugate transposes."

    r   r   )Úcopyr   r   ©ÚXÚYr&   r&   r'   Úsign_round_upŽ   s   r:   c                 C   s   t jt  | ¡dd�S )Nr   r   )r   Úmaxr   )r8   r&   r&   r'   Ú_max_abs_axis1Ÿ   s   r<   c                 C   sZ   d}d }t d| jd |ƒD ]}tjt | ||| … ¡dd�}|d u r&|}q||7 }q|S )Nr(   r   r   )r,   r	   r   r   r   )r8   r2   Úrr0   r/   r&   r&   r'   Ú_sum_abs_axis0¤   s    
r>   c                 C   s   t j| td�}d||< |S )Nr)   r   )r   r+   Úfloat)r   Úir    r&   r&   r'   r   °   s   r   c                 C   s8   | j dks| j|jkrtdƒ‚| jd }t | |¡|kS )Nr   z2expected conformant vectors with entries in {-1,1}r   )Úndimr	   r
   r   Údot)r    r!   r   r&   r&   r'   Úvectors_are_parallel¶   s   
rC   c                    s.   | j D ]‰ t‡ fdd„|j D ƒƒs dS qdS )Nc                 3   ó   � | ]}t ˆ |ƒV  qd S ©N©rC   ©Ú.0r!   ©r    r&   r'   Ú	<genexpr>Â   ó   € z;every_col_of_X_is_parallel_to_a_col_of_Y.<locals>.<genexpr>FT)ÚTÚanyr7   r&   rI   r'   Ú(every_col_of_X_is_parallel_to_a_col_of_YÀ   s
   
ÿrN   c                    sb   ˆ j \}}ˆ d d …| f ‰t‡ ‡fdd„t| ƒD ƒƒrdS |d ur/t‡fdd„|jD ƒƒr/dS dS )Nc                 3   s&   � | ]}t ˆˆ d d …|f ƒV  qd S rE   rF   )rH   r0   ©r8   r    r&   r'   rJ   Í   s   €$ z*column_needs_resampling.<locals>.<genexpr>Tc                 3   rD   rE   rF   rG   rI   r&   r'   rJ   Ð   rK   F)r	   rM   r,   rL   )r@   r8   r9   r   r   r&   rO   r'   Úcolumn_needs_resamplingÇ   s   
rP   c                 C   s0   t jjdd|jd d�d d |d d …| f< d S )Nr   r   ©Úsizer   )r   ÚrandomÚrandintr	   )r@   r8   r&   r&   r'   Úresample_columnÕ   s   0rU   c                 C   s   t  | |¡p	| |k S rE   )r   Úallclose)ÚaÚbr&   r&   r'   Úless_than_or_closeÙ   s   rY   c                 C   sæ  t | ƒ}t |ƒ}|jd }t ||f¡}|dkr1tjjdd||d fd�d d |dd…dd…f< |t|ƒ }d}d}d}	t|ƒ}
	 t | 	|¡¡}t
|ƒ}t |¡}| ¡  |ddd… }t|ƒ}t | 	|¡¡}t|ƒ}|	dkrŽtt|ƒt |dd…|f |dd…|f ¡ƒrŽ	 ||
fS t |¡ddd… d|… }
||
 }t|ƒD ]}t||
| ƒ|dd…|f< q¤|	dkrÒt|d |d ƒsÅtdƒ‚t|d |d ƒsÒtdƒ‚|	d	krêt|ƒD ]}t|| || ƒsétd
ƒ‚qÚ|}|}|	d7 }	qB)a"  
    This is Algorithm 2.2.

    Parameters
    ----------
    A : ndarray or other linear operator
        A linear operator that can produce matrix products.
    AT : ndarray or other linear operator
        The transpose of A.
    t : int, optional
        A positive parameter controlling the tradeoff between
        accuracy versus time and memory usage.

    Returns
    -------
    g : sequence
        A non-negative decreasing vector
        such that g[j] is a lower bound for the 1-norm
        of the column of A of jth largest 1-norm.
        The first entry of this vector is therefore a lower bound
        on the 1-norm of the linear operator A.
        This sequence has length t.
    ind : sequence
        The ith entry of ind is the index of the column A whose 1-norm
        is given by g[i].
        This sequence of indices has length t, and its entries are
        chosen from range(n), possibly with repetition,
        where n is the order of the operator A.

    Notes
    -----
    This algorithm is mainly for testing.
    It uses the 'ind' array in a way that is similar to
    its usage in algorithm 2.4. This algorithm 2.2 may be easier to test,
    so it gives a chance of uncovering bugs related to indexing
    which could have propagated less noticeably to algorithm 2.4.

    r   r   r   rQ   NTéÿÿÿÿzinvariant (2.2) is violatedé   zinvariant (2.3) is violated)r   r	   r   ÚonesrS   rT   r?   r,   r   r   r>   r   Úsortr:   r<   rY   r;   rB   Úargsortr   r   )r   ÚATr   ÚA_linear_operatorÚAT_linear_operatorr   r8   Úg_prevÚh_prevÚkÚindr9   ÚgÚbest_jÚSÚZÚhr0   r&   r&   r'   Ú_algorithm_2_2Ý   sT   '
2

.èÿÖrk   c                 C   s
  t | ƒ}t |ƒ}|dk rtdƒ‚|dk rtdƒ‚| jd }||kr%tdƒ‚d}d}tj||ftd�}	|dkr]td|ƒD ]}
t|
|	ƒ q;t|ƒD ]}
t|
|	ƒr\t|
|	ƒ |d7 }t|
|	ƒsNqG|	t|ƒ }	tj	dtj
d�}d}tj	||ftd�}d}d}	 t | |	¡¡}|d7 }t|ƒ}t |¡}t |¡}||ks�|dkr­|dkr¥|| }|dd…|f }|dkr¸||kr¸|}nÁ|}|}||krÁn¸t|ƒ}~t||ƒrÌn­|dkrìt|ƒD ]}
t|
||ƒrët|
|ƒ |d7 }t|
||ƒsÜqÔ~t | |¡¡}|d7 }t|ƒ}~|dk�rt|ƒ|| k�rnlt |¡ddd
… d|t|ƒ …  ¡ }~|dk�rGt |d|… |¡ ¡ �r5nDt ||¡}t ||  || f¡}t|ƒD ]}t||| ƒ|	dd…|f< �qK|d|… t |d|… |¡  }t ||f¡}|d7 }q{t||ƒ}|||||fS )aî  
    Compute a lower bound of the 1-norm of a sparse array.

    Parameters
    ----------
    A : ndarray or other linear operator
        A linear operator that can produce matrix products.
    AT : ndarray or other linear operator
        The transpose of A.
    t : int, optional
        A positive parameter controlling the tradeoff between
        accuracy versus time and memory usage.
    itmax : int, optional
        Use at most this many iterations.

    Returns
    -------
    est : float
        An underestimate of the 1-norm of the sparse array.
    v : ndarray, optional
        The vector such that ||Av||_1 == est*||v||_1.
        It can be thought of as an input to the linear operator
        that gives an output with particularly large norm.
    w : ndarray, optional
        The vector Av which has relatively large 1-norm.
        It can be thought of as an output of the linear operator
        that is relatively large in norm compared to the input.
    nmults : int, optional
        The number of matrix products that were computed.
    nresamples : int, optional
        The number of times a parallel column was observed,
        necessitating a re-randomization of the column.

    Notes
    -----
    This is algorithm 2.4.

    r   z$at least two iterations are requiredr   zat least one column is requiredr   z't should be smaller than the order of Ar)   NTrZ   )r   r
   r	   r   r\   r?   r,   rU   rP   r+   Úintpr   r   r>   r;   r   r:   rN   r<   r^   Úlenr6   ÚisinÚallÚconcatenater   )r   r_   r   r   r`   ra   r   r#   r$   r8   r@   Úind_histÚest_oldrh   rd   re   r9   Úmagsr"   rg   Úind_bestr!   ÚS_oldri   rj   Úseenr0   Únew_indr    r&   r&   r'   r   D  sš   )



þ€



þ€(
"Ã
>r   )r   r   FFrE   )Ú__doc__Únumpyr   Úscipy.sparse.linalgr   Ú__all__r   r5   r:   r<   r>   r   rC   rN   rP   rU   rY   rk   r   r&   r&   r&   r'   Ú<module>   s&    
n



g