ó
î&]\c        
   @` s  d  Z  d d l m Z m Z m Z d d l Z d d l m Z d d l	 m
 Z
 d d l m Z m Z m Z m Z m Z d d l m Z m Z d g Z d	 „  Z d
 „  Z d „  Z d „  Z d „  Z d e d „ Z d „  Z d d d d d e d e e d „	 Z d S(   s  
Pure SciPy implementation of Locally Optimal Block Preconditioned Conjugate
Gradient Method (LOBPCG), see
https://bitbucket.org/joseroman/blopex

License: BSD

Authors: Robert Cimrman, Andrew Knyazev

Examples in tests directory contributed by Nils Wagner.
i    (   t   divisiont   print_functiont   absolute_importN(   t   assert_allclose(   t   xrange(   t   invt   eight
   cho_factort	   cho_solvet   cholesky(   t   aslinearoperatort   LinearOperatort   lobpcgc         C` s!   d d l  m } | | |  ƒ d  S(   Ni    (   t   savetxt(   t   numpyR   (   t   art   fileNameR   (    (    sF   lib/python2.7/site-packages/scipy/sparse/linalg/eigen/lobpcg/lobpcg.pyt   save   s    c         C` s   d d l  m } |  |  j j ƒ  } | | d ƒ } t j t d | d | | |  d ƒ ƒ ƒ } | | k r™ t d | | | f ƒ t d | | f ƒ n  d S(   sP   
    Report if `M` is not a hermitian matrix given the tolerances `a`, `b`.
    i    (   t   normi   i
   s7   matrix %s is not sufficiently Hermitian for a=%d, b=%d:s   condition: %.e < %eN(   t   scipy.linalgR   t   Tt   conjt   npt   spacingt   maxt   print(   t   Mt   at   bt   nameR   t   mdt   nmdt   tol(    (    sF   lib/python2.7/site-packages/scipy/sparse/linalg/eigen/lobpcg/lobpcg.pyt   _report_nonhermitian   s    -c         C` sF   |  j  d k r |  St j |  d t ƒ} |  j d d f | _ | Sd S(   sm   
    If the input array is 2D return it, if it is 1D, append a dimension,
    making it a column vector.
    i   t   copyi    i   N(   t   ndimR   t   arrayt   Falset   shape(   R   t   aux(    (    sF   lib/python2.7/site-packages/scipy/sparse/linalg/eigen/lobpcg/lobpcg.pyt   as2d0   s
    c         C` s[   |  d k r- d „  } t | | d | ƒ} n t |  ƒ } | j | k rW t d ƒ ‚ n  | S(   sî   Takes a dense numpy array or a sparse matrix or
    a function and makes an operator performing matrix * blockvector
    products.

    Examples
    --------
    >>> A = _makeOperator( arrayA, (n, n) )
    >>> vectorB = A( vectorX )

    c         S` s   |  S(   N(    (   t   x(    (    sF   lib/python2.7/site-packages/scipy/sparse/linalg/eigen/lobpcg/lobpcg.pyt   identI   s    t   matmats   operator has invalid shapeN(   t   NoneR   R
   R&   t
   ValueError(   t   operatorInputt   expectedShapeR*   t   operator(    (    sF   lib/python2.7/site-packages/scipy/sparse/linalg/eigen/lobpcg/lobpcg.pyt   _makeOperator=   s    	c         C` sD   t  j | j j ƒ  |  ƒ } t | | ƒ } |  t  j | | ƒ 8}  d S(   s   Changes blockVectorV in place.N(   R   t   dotR   R   R   (   t   blockVectorVt   factYBYt   blockVectorBYt   blockVectorYt   gramYBVt   tmp(    (    sF   lib/python2.7/site-packages/scipy/sparse/linalg/eigen/lobpcg/lobpcg.pyt   _applyConstraintsU   s    c         C` s½   | d  k r0 |  d  k	 r' |  | ƒ } q0 | } n  t j | j j ƒ  | ƒ } t | ƒ } t | d t ƒ} t j | | ƒ } |  d  k	 rœ t j | | ƒ } n  | r¯ | | | f S| | f Sd  S(   Nt   overwrite_a(   R,   R   R2   R   R   R	   R   t   True(   t   BR3   t   blockVectorBVt   retInvRt   gramVBV(    (    sF   lib/python2.7/site-packages/scipy/sparse/linalg/eigen/lobpcg/lobpcg.pyt   _b_orthonormalize\   s    	c         C` s>   t  j |  ƒ } | r0 | d | d d … } n
 | |  } | S(   s?   Get `num` indices into `_lambda` depending on `largest` option.Ni   iÿÿÿÿ(   R   t   argsort(   t   _lambdat   numt   largestt   ii(    (    sF   lib/python2.7/site-packages/scipy/sparse/linalg/eigen/lobpcg/lobpcg.pyt	   _get_indxo   s
    
i   c   D      C` sX  | } | } | } | } | d
 k	 r4 | j d } n d } t | j ƒ d k r^ t d ƒ ‚ n  | j \ } } | | k rˆ t d ƒ ‚ n  t |  | | f ƒ }  t | | | f ƒ } t | | | f ƒ } | | d | k  rÅ| d
 k	 rö t d ƒ ‚ n  | r| | | d f } n d | d f } |  t j | ƒ ƒ } | d
 k rJd
 n | t j | ƒ ƒ } t | | d | d	 t	 ƒ\ } } | r»| d
 d
 d … } | d
 d
 … d
 d
 d … f } n  | | f S| d
 k rçt j
 d ƒ | } n  t | | ƒ } | r¿d } | d
 k r| d 7} n
 | d 7} | d 7} | d
 k rH| d 7} n  | d 7} | d | 7} | d | 7} | d
 k r‡| d 7} n+ | d k r¤| d | 7} n | d | 7} t | ƒ n  | d
 k	 rM| d
 k	 ræ| | ƒ } n | } t j | j j ƒ  | ƒ } y t | ƒ } Wn t k
 r6t d ƒ ‚ n Xt | | | | ƒ n  t | | ƒ \ } } |  | ƒ } t j | j j ƒ  | ƒ } t | d	 t	 ƒ\ } } t | | | ƒ } | | } t j | d
 d
 … | f ƒ } t j | | ƒ } t j | | ƒ } | d
 k	 r!t j | | ƒ } n  t j | f d t ƒ}  | g }! g  }" | }# t j | d |  j ƒ}$ t j | d |  j ƒ}% d
 }& d
 }' d
 }( xýt | ƒ D]ï}) | d k rÀt d |) ƒ n  | | t j d
 d
 … f } | | }* t j |* j ƒ  |* d ƒ } t j
 | ƒ }+ |" j |+ ƒ t j |+ | k t t	 ƒ } |  | @}  | d k r]t |  ƒ n  |  j ƒ  }, |, |# k r–|, }# t j |, d |  j ƒ}$ n  |, d k r¦Pn  | d k rÜt d |, ƒ t d | ƒ t d |+ ƒ n  | d k rõt | ƒ n  t  |* d
 d
 … |  f ƒ }- |) d k rtt  |& d
 d
 … |  f ƒ }. t  |' d
 d
 … |  f ƒ }/ t  |( d
 d
 … |  f ƒ }0 n  | d
 k	 r| |- ƒ }- n  | d
 k	 r±t |- | | | ƒ n  t | |- ƒ } | \ }- }1 |  |- ƒ }2 |) d k r t | |. |0 d t ƒ} | \ }. }0 }3 t j |/ |3 ƒ }/ n  t j | j j ƒ  |2 ƒ }4 t j |- j j ƒ  |2 ƒ }5 t j | j j ƒ  |1 ƒ }6 |) d k r¬t j | j j ƒ  |/ ƒ }7 t j |- j j ƒ  |/ ƒ }8 t j |. j j ƒ  |/ ƒ }9 t j | j j ƒ  |0 ƒ }: t j |- j j ƒ  |0 ƒ }; t j! t j" | ƒ |4 |7 g |4 j j ƒ  |5 |8 g |7 j j ƒ  |8 j j ƒ  |9 g g ƒ }< t j! |% |6 |: g |6 j j ƒ  |$ |; g |: j j ƒ  |; j j ƒ  |$ g g ƒ }= n] t j! t j" | ƒ |4 g |4 j j ƒ  |5 g g ƒ }< t j! |% |6 g |6 j j ƒ  |$ g g ƒ }= | d k r>	t# |< d  d d! ƒ t# |= d  d d" ƒ n  | d k rg	t$ |< d! ƒ t$ |= d" ƒ n  t |< |= d	 t	 ƒ\ } } t | | | ƒ } | d k r­	t | ƒ n  | | } | d
 d
 … | f } |! j | ƒ | d k rö	t d# | ƒ n  | d k r
t | ƒ n  |) d k r¿
| |  }> | | | |, !}? | | |, }@ t j |- |? ƒ }A |A t j |. |@ ƒ 7}A t j |2 |? ƒ }B |B t j |/ |@ ƒ 7}B t j |1 |? ƒ }C |C t j |0 |@ ƒ 7}C nJ | |  }> | | }? t j |- |? ƒ }A t j |2 |? ƒ }B t j |1 |? ƒ }C | d k r6t |A ƒ t |B ƒ t |C ƒ n  t j | |> ƒ |A } t j | |> ƒ |B } t j | |> ƒ |C } |A |B |C }& }' }( qW| | t j d
 d
 … f } | | }* t j |* j ƒ  |* d ƒ } t j
 | ƒ }+ | d k rt d$ | ƒ t d% |+ ƒ n  |	 r7|
 r'| | |! |" f S| | |! f Sn |
 rJ| | |" f S| | f Sd
 S(&   sî  Locally Optimal Block Preconditioned Conjugate Gradient Method (LOBPCG)

    LOBPCG is a preconditioned eigensolver for large symmetric positive
    definite (SPD) generalized eigenproblems.

    Parameters
    ----------
    A : {sparse matrix, dense matrix, LinearOperator}
        The symmetric linear operator of the problem, usually a
        sparse matrix.  Often called the "stiffness matrix".
    X : array_like
        Initial approximation to the k eigenvectors. If A has
        shape=(n,n) then X should have shape shape=(n,k).
    B : {dense matrix, sparse matrix, LinearOperator}, optional
        the right hand side operator in a generalized eigenproblem.
        by default, B = Identity
        often called the "mass matrix"
    M : {dense matrix, sparse matrix, LinearOperator}, optional
        preconditioner to A; by default M = Identity
        M should approximate the inverse of A
    Y : array_like, optional
        n-by-sizeY matrix of constraints, sizeY < n
        The iterations will be performed in the B-orthogonal complement
        of the column-space of Y. Y must be full rank.

    Returns
    -------
    w : array
        Array of k eigenvalues
    v : array
        An array of k eigenvectors.  V has the same shape as X.

    Other Parameters
    ----------------
    tol : scalar, optional
        Solver tolerance (stopping criterion)
        by default: tol=n*sqrt(eps)
    maxiter : integer, optional
        maximum number of iterations
        by default: maxiter=min(n,20)
    largest : bool, optional
        when True, solve for the largest eigenvalues, otherwise the smallest
    verbosityLevel : integer, optional
        controls solver output.  default: verbosityLevel = 0.
    retLambdaHistory : boolean, optional
        whether to return eigenvalue history
    retResidualNormsHistory : boolean, optional
        whether to return history of residual norms

    Examples
    --------

    Solve A x = lambda B x with constraints and preconditioning.

    >>> from scipy.sparse import spdiags, issparse
    >>> from scipy.sparse.linalg import lobpcg, LinearOperator
    >>> n = 100
    >>> vals = [np.arange(n, dtype=np.float64) + 1]
    >>> A = spdiags(vals, 0, n, n)
    >>> A.toarray()
    array([[   1.,    0.,    0., ...,    0.,    0.,    0.],
           [   0.,    2.,    0., ...,    0.,    0.,    0.],
           [   0.,    0.,    3., ...,    0.,    0.,    0.],
           ...,
           [   0.,    0.,    0., ...,   98.,    0.,    0.],
           [   0.,    0.,    0., ...,    0.,   99.,    0.],
           [   0.,    0.,    0., ...,    0.,    0.,  100.]])

    Constraints.

    >>> Y = np.eye(n, 3)

    Initial guess for eigenvectors, should have linearly independent
    columns. Column dimension = number of requested eigenvalues.

    >>> X = np.random.rand(n, 3)

    Preconditioner -- inverse of A (as an abstract linear operator).

    >>> invA = spdiags([1./vals[0]], 0, n, n)
    >>> def precond( x ):
    ...     return invA  * x
    >>> M = LinearOperator(matvec=precond, shape=(n, n), dtype=float)

    Here, ``invA`` could of course have been used directly as a preconditioner.
    Let us then solve the problem:

    >>> eigs, vecs = lobpcg(A, X, Y=Y, M=M, tol=1e-4, maxiter=40, largest=False)
    >>> eigs
    array([ 4.,  5.,  6.])

    Note that the vectors passed in Y are the eigenvectors of the 3 smallest
    eigenvalues. The results returned are orthogonal to those.

    Notes
    -----
    If both retLambdaHistory and retResidualNormsHistory are True,
    the return tuple has the following format
    (lambda, V, lambda history, residual norms history).

    In the following ``n`` denotes the matrix size and ``m`` the number
    of required eigenvalues (smallest or largest).

    The LOBPCG code internally solves eigenproblems of the size 3``m`` on every
    iteration by calling the "standard" dense eigensolver, so if ``m`` is not
    small enough compared to ``n``, it does not make sense to call the LOBPCG
    code, but rather one should use the "standard" eigensolver,
    e.g. numpy or scipy function in this case.
    If one calls the LOBPCG algorithm for 5``m``>``n``,
    it will most likely break internally, so the code tries to call the standard
    function instead.

    It is not that n should be large for the LOBPCG to work, but rather the
    ratio ``n``/``m`` should be large. It you call the LOBPCG code with ``m``=1
    and ``n``=10, it should work, though ``n`` is small. The method is intended
    for extremely large ``n``/``m``, see e.g., reference [28] in
    https://arxiv.org/abs/0705.2626

    The convergence speed depends basically on two factors:

    1.  How well relatively separated the seeking eigenvalues are
        from the rest of the eigenvalues.
        One can try to vary ``m`` to make this better.

    2.  How well conditioned the problem is. This can be changed by using proper
        preconditioning. For example, a rod vibration test problem (under tests
        directory) is ill-conditioned for large ``n``, so convergence will be
        slow, unless efficient preconditioning is used.
        For this specific problem, a good simple preconditioner function would
        be a linear solve for A, which is easy to code since A is tridiagonal.

    *Acknowledgements*

    lobpcg.py code was written by Robert Cimrman.
    Many thanks belong to Andrew Knyazev, the author of the algorithm,
    for lots of advice and support.

    References
    ----------
    .. [1] A. V. Knyazev (2001),
           Toward the Optimal Preconditioned Eigensolver: Locally Optimal
           Block Preconditioned Conjugate Gradient Method.
           SIAM Journal on Scientific Computing 23, no. 2,
           pp. 517-541. :doi:`10.1137/S1064827500366124`

    .. [2] A. V. Knyazev, I. Lashuk, M. E. Argentati, and E. Ovchinnikov (2007),
           Block Locally Optimal Preconditioned Eigenvalue Xolvers (BLOPEX)
           in hypre and PETSc.  https://arxiv.org/abs/0705.2626

    .. [3] A. V. Knyazev's C and MATLAB implementations:
           https://bitbucket.org/joseroman/blopex

    i   i    i   s$   expected rank-2 array for argument Xs,   X column dimension exceeds the row dimensioni   s3   The dense eigensolver does not support constraints.t   eigvalst   check_finiteNiÿÿÿÿgVçž¯Ò<s   Solving t   standardt   generalizeds    eigenvalue problem witht   outs    preconditioning

s   matrix size %d
s   block size %d

s   No constraints

s   %d constraints

s   %d constraint

s,   cannot handle linearly dependent constraintst   dtypes   iteration %ds   current block size:s   eigenvalue:s   residual norms:i
   R>   i   t   gramAt   gramBs   lambda:s   final eigenvalue:s   final residual norms:(%   R,   R&   t   lenR-   R1   t   NotImplementedErrorR   t   eyeR   R%   t   sqrtt   minR   R2   R   R   R   t	   ExceptionR9   R@   RF   t   asarrayt   onest   boolRL   R   t   newaxist   sumt	   conjugatet   appendt   whereR;   R(   t   bmatt   diagR!   R   (D   t   At   XR<   R   t   YR    t   maxiterRD   t   verbosityLevelt   retLambdaHistoryt   retResidualNormsHistoryt   blockVectorXR6   t   residualTolerancet   maxIterationst   sizeYt   nt   sizeXRG   t   A_denset   B_denset   valst   vecsR'   R5   t   gramYBYt   blockVectorBXt   blockVectorAXt   gramXAXRB   t   eigBlockVectorRE   t
   activeMaskt   lambdaHistoryt   residualNormsHistoryt   previousBlockSizeR*   t   ident0t   blockVectorPt   blockVectorAPt   blockVectorBPt   iterationNumbert   blockVectorRt   residualNormst   currentBlockSizet   activeBlockVectorRt   activeBlockVectorPt   activeBlockVectorAPt   activeBlockVectorBPt   activeBlockVectorBRt   activeBlockVectorARt   invRt   xawt   wawt   xbwt   xapt   wapt   papt   xbpt   wbpRM   RN   t   eigBlockVectorXt   eigBlockVectorRt   eigBlockVectorPt   ppt   appt   bpp(    (    sF   lib/python2.7/site-packages/scipy/sparse/linalg/eigen/lobpcg/lobpcg.pyR   y   s‚   ž'!"




	

	'*






(    t   __doc__t
   __future__R    R   R   R   R   t   numpy.testingR   t   scipy._lib.sixR   R   R   R   R   R   R	   t   scipy.sparse.linalgR
   R   t   __all__R   R!   R(   R1   R9   R,   R%   R@   RF   R;   R   (    (    (    sF   lib/python2.7/site-packages/scipy/sparse/linalg/eigen/lobpcg/lobpcg.pyt   <module>   s$   (								