U
    »mœd~<  ã                   @   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rÐt t | ƒ t |¡¡¡}|j||fkrrtddt|jƒ ƒ‚t	|ƒj
dd�}|j|fkr¢tddt|jƒ ƒ‚t |¡}t||ƒ}	|dd…|f }
|| }nt| | j||ƒ\}}	}
}}|sô|�r|f}|�r
||	f7 }|�r||
f7 }|S |S dS )aÀ	  
    Compute a lower bound of the 1-norm of a sparse matrix.

    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 matrix.
    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_matrix
    >>> from scipy.sparse.linalg import onenormest
    >>> A = csc_matrix([[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 ©ZaxisN)r   ÚshapeÚ
ValueErrorÚnpÚasarrayÚmatmatÚidentityÚ	ExceptionÚstrÚabsÚsumÚargmaxÚelementary_vectorÚ_onenormest_coreÚH)ÚAÚtÚitmaxZ	compute_vZ	compute_wÚnZ
A_explicitZcol_abs_sumsZargmax_jÚvÚwÚestÚnmultsÚ
nresamplesÚresult© r    úX/home/sam/Atlas/atlas_env/lib/python3.8/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 ]$}ˆ| ||ˆ  … ƒ|||ˆ  …< ql|S d S )Nr   r   ©Údtype)r   r
   Úzerosr$   Úrange)ÚxZy0ÚyÚj©Ú
block_sizeÚfuncr    r!   Úwrapper€   s    &"z%_blocked_elementwise.<locals>.wrapperr    )r,   r-   r    r*   r!   Ú_blocked_elementwisey   s    r.   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    r3   c                 C   s   t jt  | ¡dd�S )Nr   r   )r
   Úmaxr   )r1   r    r    r!   Ú_max_abs_axis1Ÿ   s    r5   c                 C   sZ   d}d }t d| jd |ƒD ]:}tjt | ||| … ¡dd�}|d krL|}q||7 }q|S )Nr"   r   r   )r&   r   r
   r   r   )r1   r+   Úrr)   r(   r    r    r!   Ú_sum_abs_axis0¤   s     
r7   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    
r<   c                    s.   | j D ]"‰ t‡ fdd„|j D ƒƒs dS qdS )Nc                 3   s   | ]}t ˆ |ƒV  qd S ©N©r<   ©Ú.0r   ©r   r    r!   Ú	<genexpr>Â   s     z;every_col_of_X_is_parallel_to_a_col_of_Y.<locals>.<genexpr>FT)ÚTÚanyr0   r    rA   r!   Ú(every_col_of_X_is_parallel_to_a_col_of_YÀ   s    
rE   c                    sb   ˆ j \}}ˆ d d …| f ‰t‡ ‡fdd„t| ƒD ƒƒr:dS |d k	r^t‡fdd„|jD ƒƒr^dS dS )Nc                 3   s$   | ]}t ˆˆ d d …|f ƒV  qd S r=   r>   )r@   r)   ©r1   r   r    r!   rB   Í   s     z*column_needs_resampling.<locals>.<genexpr>Tc                 3   s   | ]}t ˆ |ƒV  qd S r=   r>   r?   rA   r    r!   rB   Ð   s     F)r   rD   r&   rC   )r9   r1   r2   r   r   r    rF   r!   Úcolumn_needs_resamplingÇ   s    
rG   c                 C   s0   t jjdd|jd d�d d |d d …| f< d S )Nr   r   ©Úsizer   )r
   ÚrandomÚrandintr   )r9   r1   r    r    r!   Úresample_columnÕ   s    rL   c                 C   s   t  | |¡p| |k S r=   )r
   Zallclose)ÚaÚbr    r    r!   Úless_than_or_closeÙ   s    rO   c                 C   sø  t | ƒ}t |ƒ}|jd }t ||f¡}|dkrbt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�qðt |¡ddd… d|… }
||
 }t|ƒD ] }t||
| ƒ|dd…|f< �qD|	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 }	q‚||
fS )
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   rH   Néÿÿÿÿzinvariant (2.2) is violatedé   zinvariant (2.3) is violated)r   r   r
   ÚonesrJ   rK   r8   r&   r   r   r7   r   Úsortr3   r5   rO   r4   r;   Úargsortr   r   )r   ÚATr   ÚA_linear_operatorÚAT_linear_operatorr   r1   Zg_prevZh_prevÚkÚindr2   ÚgÚbest_jÚSÚZÚhr)   r    r    r!   Ú_algorithm_2_2Ý   sN    '
2


0


r_   c                 C   s  t | ƒ}t |ƒ}|dk r tdƒ‚|dk r0tdƒ‚| jd }||krJtdƒ‚d}d}tj||ftd�}	|dkr²td|ƒD ]}
t|
|	ƒ qvt|ƒD ]"}
t|
|	ƒrŽt|
|	ƒ |d7 }q’qŽ|	t|ƒ }	tj	dtj
d�}d}tj	||ftd�}d}d}t | |	¡¡}|d7 }t|ƒ}t |¡}t |¡}||k�s4|dk�rV|dk�rF|| }|dd…|f }|dk�rr||k�rr|}�qþ|}|}||k�rˆ�qþt|ƒ}~t||ƒ�r¢�qþ|dk�ràt|ƒD ]*}
t|
||ƒ�r´t|
|ƒ |d7 }�q¸�q´~t | |¡¡}|d7 }t|ƒ}~|dk�r$t|ƒ|| k�r$�qþt |¡ddd	… d|t|ƒ …  ¡ }~|dk�ršt |d|… |¡ ¡ �rv�qþt ||¡}t ||  || f¡}t|ƒD ] }t||| ƒ|	dd…|f< �q¢|d|… t |d|… |¡  }t ||f¡}|d7 }qìt||ƒ}|||||fS )
að  
    Compute a lower bound of the 1-norm of a sparse matrix.

    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 matrix.
    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#   NrP   )r   r	   r   r
   rR   r8   r&   rL   rG   r%   Zintpr   r   r7   r4   r   r3   rE   r5   rT   Úlenr/   Zin1dÚallZconcatenater   )r   rU   r   r   rV   rW   r   r   r   r1   r9   Zind_histZest_oldr\   rX   rY   r2   Zmagsr   r[   Zind_bestr   ZS_oldr]   r^   Úseenr)   Znew_indr   r    r    r!   r   D  sŽ    )








(
"

r   )r   r   FF)N)Ú__doc__Únumpyr
   Zscipy.sparse.linalgr   Ú__all__r   r.   r3   r5   r7   r   r<   rE   rG   rL   rO   r_   r   r    r    r    r!   Ú<module>   s$   
n



g