
    tKg~<                         d Z ddlZddlmZ dgZddZd Zed        Zed        Z	d	 Z
d
 Zd Zd ZddZd Zd Zd Zd Zy)zSparse block 1-norm estimator.
    N)aslinearoperator
onenormestc                    t        |       } | j                  d   | j                  d   k7  rt        d      | j                  d   }||k\  rt        j                  t        |       j                  t        j                  |                  }|j                  ||fk7  r"t        ddt        |j                        z         t        |      j                  d      }|j                  |fk7  r"t        ddt        |j                        z         t        j                  |      }t        ||      }	|dd|f   }
||   }nt        | | j                  ||      \  }}	}
}}|s|r|f}|r||	fz  }|r||
fz  }|S |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 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results                  c/home/alanp/www/video.onchill/myenv/lib/python3.12/site-packages/scipy/sparse/linalg/_onenormest.pyr   r      sx   T 	AwwqzQWWQZLMM
 	

AAvZZ 0 3 : :2;;q> JK
1v%.'#j.>.>*??A A:***2!&.'#l.@.@*AAC C99\*a*q({#8$(8ACCE(J%Q6: IqdNFqdNF
    c                      d fd}|S )z
    Decorator for an elementwise function, to apply it blockwise along
    first dimension, to avoid excessive memory usage in temporaries.
       c                 B   | j                   d   k  r |       S  | d        }t        j                  | j                   d   f|j                   dd  z   |j                        }||d  ~t	        | j                   d         D ]  } | ||z          |||z     |S )Nr   r   dtype)r	   r   zerosr,   range)xy0yj
block_sizefuncs       r&   wrapperz%_blocked_elementwise.<locals>.wrapper   s    771:
"7Nan%B!''!*!"5RXXFAAkzN:qwwqz:>$(1Qz\):$;!AjL! ?Hr'    )r4   r5   r3   s   ` @r&   _blocked_elementwiser7   y   s    
 J
 Nr'   c                 f    | j                         }d||dk(  <   |t        j                  |      z  }|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Ys     r&   sign_round_upr<      s2     	
AAa1fINAHr'   c                 V    t        j                  t        j                  |       d      S )Nr   r   )r   maxr   )r:   s    r&   _max_abs_axis1r?      s    66"&&)!$$r'   c           	          d}d }t        d| j                  d   |      D ]<  }t        j                  t        j                  | |||z          d      }||}8||z  }> |S )Nr)   r   r   )r.   r	   r   r   r   )r:   r3   rr2   r1   s        r&   _sum_abs_axis0rB      se    JA1aggaj*-FF266!Aa
l+,159AFA . Hr'   c                 F    t        j                  | t              }d||<   |S )Nr+   r   )r   r-   float)r   ir    s      r&   r   r      s     
% AAaDHr'   c                     | j                   dk7  s| j                  |j                  k7  rt        d      | j                  d   }t        j                  | |      |k(  S )Nr   z2expected conformant vectors with entries in {-1,1}r   )ndimr	   r
   r   dot)r    r!   r   s      r&   vectors_are_parallelrI      sL     	vv{agg(MNN	
A66!Q<1r'   c                 h    | j                   D ]"  t        fd|j                   D              r" y y)Nc              3   6   K   | ]  }t        |        y wNrI   .0r!   r    s     r&   	<genexpr>z;every_col_of_X_is_parallel_to_a_col_of_Y.<locals>.<genexpr>   s     ;s!'1-s   FT)Tany)r:   r;   r    s     @r&   (every_col_of_X_is_parallel_to_a_col_of_YrT      s+    SS;qss;;  r'   c                     j                   \  }}d d | f   t        fdt        |       D              ry|t        fd|j                  D              ryy)Nc              3   D   K   | ]  }t        d d |f           y wrL   rM   )rO   r2   r:   r    s     r&   rP   z*column_needs_resampling.<locals>.<genexpr>   s"     
>X1QT7+Xs    Tc              3   6   K   | ]  }t        |        y wrL   rM   rN   s     r&   rP   z*column_needs_resampling.<locals>.<genexpr>   s     73a#Aq)3rQ   F)r	   rS   r.   rR   )rE   r:   r;   r   r   r    s    `   @r&   column_needs_resamplingrX      sQ     77DAq	!Q$A

>U1X
>>}713377r'   c                 |    t         j                  j                  dd|j                  d         dz  dz
  |d d | f<   y )Nr      sizer   )r   randomrandintr	   )rE   r:   s     r&   resample_columnr_      s7    ii11771:6q81<AadGr'   c                 <    t        j                  | |      xs | |k  S rL   )r   allclose)abs     r&   less_than_or_closerd      s    ;;q!'Q'r'   c           	      h   t        |       }t        |      }|j                  d   }t        j                  ||f      }|dkD  r6t        j                  j                  dd||dz
  f      dz  dz
  |ddddf<   |t        |      z  }d}d}d}	t        |      }
	 t        j                  |j                  |            }t        |      }t        j                  |      }|j                          |ddd   }t        |      }t        j                  |j                  |            }t        |      }|	dk\  r<t        t!        |      t        j"                  |dd|f   |dd|f               r	 ||
fS t        j$                  |      ddd   d| }
||
   }t        |      D ]  }t'        ||
|         |dd|f<    |	dk\  r:t        |d   |d         st)        d      t        |d   |d         st)        d      |	dk\  r-t        |      D ]  }t        ||   ||         rt)        d	       |}|}|	dz  }	)
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   rZ   r[   Nzinvariant (2.2) is violated   zinvariant (2.3) is violated)r   r	   r   onesr]   r^   rD   r.   r   r   rB   r   sortr<   r?   rd   r>   rH   argsortr   r   )r   ATr   A_linear_operatorAT_linear_operatorr   r:   g_prevh_prevkindr;   gbest_jSZhr2   s                     r&   _algorithm_2_2rw      s>   N )+)"-"A 	AA1u99$$QAaC$9!;a?!QR%qMA FF	A
(C
JJ(//2311	ddG!JJ)00341 6!#a&"&&1f9qF|*LM2 c6M1 jjmDbD!"1%cFqA'3q62AadG  6%fQi; =>>%fQi16 =>> 61X)!A$q	:#$ABB 
 	QU r'   c                    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kD  rXt        d|      D ]  }
t        |
|	        t        |      D ]-  }
t        |
|	      st        |
|	       |dz  }t        |
|	      r/ |	t        |      z  }	t        j                  dt        j                        }d}t        j                  ||ft
              }d}d}	 t        j                  |j                  |	            }|dz  }t        |      }t        j                  |      }t        j                  |      }||kD  s|dk(  r|dk\  r||   }|dd|f   }|dk\  r	||k  r|}n|}|}||kD  rnt!        |      }~t#        ||      rn|dkD  r=t        |      D ]/  }
t        |
||      st        |
|       |dz  }t        |
||      r1 ~t        j                  |j                  |            }|dz  }t%        |      }~|dk\  rt        |      |   k(  rnt        j&                  |      ddd	   d|t)        |      z    j+                         }~|dkD  r\t        j,                  |d| |      j/                         rnt        j,                  ||      }t        j0                  ||    ||   f      }t        |      D ]  }t3        |||         |	dd|f<    |d| t        j,                  |d| |          }t        j0                  ||f      }|dz  };t3        |      }||||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.

    rZ   z$at least two iterations are requiredr   zat least one column is requiredr   z't should be smaller than the order of Ar+   Nrf   )r   r
   r	   r   rh   rD   r.   r_   rX   r-   intpr   r   rB   r>   r   r<   rT   r?   rj   lenr9   isinallconcatenater   )r   rk   r   r   rl   rm   r   r#   r$   r:   rE   ind_histest_oldrt   rp   rq   r;   magsr"   rs   ind_bestr!   S_oldru   rv   seenr2   new_indr    s                                r&   r   r   D  s   R )+)"-qy?@@1u:;;	
AAvBCC FJ 	Ae$A 	1uq!A Aq!  qA)!Q/1%a
 *!Q/ 
 qMAxx)HG
!Qu%A	A
C
JJ(//23!a ffTl4=AFAvv;!V)A6cWnCu9!3Au=q5 1X-aE:#Aq)!OJ .aE:  JJ)0034!16c!f(+ jjmDbD!"21S]?388:q5 wws2Aw)--/ 773)D..#te*c$i!89CqA'3q62AadG  bq'2773r7H556>>8W"56	Q{ | 	!X&A1fj((r'   )rZ      FFrL   )__doc__numpyr   scipy.sparse.linalgr   __all__r   r7   r<   r?   rB   r   rI   rT   rX   r_   rd   rw   r   r6   r'   r&   <module>r      s     0 .k\*    % %	=(dNO)r'   