
    gߣ                         d Z ddlZddlZddlmZmZmZmZm	Z	m
Z
 ddlmZ ddlmZ dgZd Zd Zd	 Zdd
Zd Z	 	 ddZd Zd Z	 	 	 	 	 	 	 	 	 	 ddZy)a  
Locally Optimal Block Preconditioned Conjugate Gradient Method (LOBPCG).

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.  :arxiv:`0705.2626`

.. [3] A. V. Knyazev's C and MATLAB implementations:
       https://github.com/lobpcg/blopex
    N)inveigh
cho_factor	cho_solvecholeskyLinAlgError)LinearOperator)issparselobpcgc                 R   ddl m} | | j                  j                         z
  } ||d      }dt	        j
                  | j                        j                  z  }t        || || d      z        }||kD  r4t        j                  d| d| j                   d| d| d		t        d
       yy)zA
    Report if `M` is not a Hermitian matrix given its type.
    r   )norm   
   zMatrix z of the type z is not Hermitian: condition: z < z fails.   
stacklevelN)scipy.linalgr   TconjnpfinfodtypeepsmaxwarningswarnUserWarning)Mnamer   mdnmdtols         [/var/www/html/venv/lib/python3.12/site-packages/scipy/sparse/linalg/_eigen/lobpcg/lobpcg.py_report_nonhermitianr$      s     "	
QSSXXZB
r1+C
rxx $$
$C
c3a#
$C
Syv]177) 45C51a	     c                 ~    | j                   dk(  r| S t        j                  |       }| j                  d   df|_        |S )zm
    If the input array is 2D return it, if it is 1D, append a dimension,
    making it a column vector.
       r   r   )ndimr   asarrayshape)arauxs     r#   _as2dr-   /   s:    
 
ww!|	jjnXXa[!$	
r%   c                 4      y t               r fdS  fdS )Nc                      |       S N vms    r#   <lambda>z_makeMatMat.<locals>.<lambda>@   s    1 r%   c                     | z  S r0   r1   r2   s    r#   r5   z_makeMatMat.<locals>.<lambda>B   s    Q r%   )callable)r4   s   `r#   _makeMatMatr8   <   s    y	!r%   c                 `   | j                   d   rR| j                  d   |j                  d   k(  r3| j                  |j                  k(  rt        j                  | ||        | S 	 t        j                  | ||        | S # t
        $ r' |rt        j                  dt        d       | |z  } Y | S w xY w)zPerform 'np.matmul' in-place if possible.

    If some sufficient conditions for inplace matmul are met, do so.
    Otherwise try inplace update and fall back to overwrite if that fails.
    CARRAYr   )outz>Inplace update of x = x @ y failed, x needs to be overwritten.   r   )	flagsr*   r   r   matmul	Exceptionr   r   r   )xyverbosityLevels      r#   _matmul_inplacerC   E   s     	wwxQWWQZ1771:5!''QWW:L 			!QA H		IIa" H  	1A
 AAH	s   #A= =,B-,B-c                 f    |j                   j                         | z  }t        ||      }| ||z  z  } y)zChanges blockVectorV in-place.N)r   r   r   )blockVectorVfactYBYblockVectorBYblockVectorYYBVtmps         r#   _applyConstraintsrK   a   s4    
//


 <
/C
GS
!CL3&&Lr%   c                 *   |M| |}nH	  | |      }|j                  |j                  k7  r&t        d|j                   d|j                   d	      |j                  j                         |z  }	 t        |d
      }t        |d
      }t        |||      }| t        |||      }|||fS # t         $ r1}|r%t        j                  d| dt        d       Y d}~yY d}~d}~ww xY w# t        $ r! |rt        j                  dt        d       Y yw xY w)z@in-place B-orthonormalize the given block vector using Cholesky.N(Secondary MatMul call failed with error

r<   r   )NNN
The shape z; of the orthogonalized matrix not preserved
and changed to , after multiplying by the secondary matrix.
Toverwrite_arB   zCholesky has failed.)r?   r   r   r   r*   
ValueErrorr   r   r   r   rC   r   )BrE   blockVectorBVrB   eVBVs         r#   _b_orthonormalizerY   h   sK    9(M	, !, ""l&8&88  !3!3 4 5&&3&9&9%: ;CD  ..


-
/C s-#4(&#)
 =+s-M ]C//=  ,!MMC#R!#
 , ",>   MM&   s)   B+ .<C( +	C%4"C  C%('DDc                 Z    t        j                  |       }|r|d| dz
  d   }|S |d| }|S )z?Get `num` indices into `_lambda` depending on `largest` option.Nr   )r   argsort)_lambdanumlargestiis       r#   	_get_indxra      sB    	G	B#" I XIr%   c                 :    |rt        | d       t        |d       y y )NgramAgramB)r$   )rc   rd   rB   s      r#   _handle_gramA_gramB_verbosityre      s    UG,UG, r%   c                 -   |}|}|}|}|d}|}d}|]t        |j                        dk7  r6t        j                  dt        |j                         dt        d       d}n|j                  d   }|t        d	      t        |j                        dk7  rt        d
      |j                  \  }}t        j                  |j                  t        j                        sOt        j                  d|j                   dt        d       t        j                  |t        j                        }|	r&t        j                  |dz   |f|j                        }|
r&t        j                  |dz   |f|j                        }|rYd}||dz  }n|dz  }|dz  }||dz  }|dz  }|d|z  z  }|d|z  z  }||dz  }n|dkD  r	|d|z  z  }n|d|z  z  }t        |       ||z
  d|z  k  rt        j                  d| d| d| dt        d       t        ||      }|t        d      |r||z
  |dz
  f}nd|dz
  f}	 t!        | t"              r" | t        j$                  |t&                    } nt)        |       rK | t        j$                  |t&                    } | j                  ||fk7  rJt        d | j                   d!      t+        |       r| j-                         } nt        j                  |       } |	 t!        |t"              r" |t        j$                  |t&                    }nt)        |      rK |t        j$                  |t&                    }|j                  ||fk7  rJt        d |j                   d$      t+        |      r|j-                         }nt        j                  |      }	 t1        | ||d&'      \  }}|r|ddd(   }|ddddd(f   }||fS ||d*k  r?t        j2                  t        j4                  |j                        j6                        |z  }t9        |       } t9        |      }t9        |      }||G ||      }|j                  |j                  k7  r(t        d |j                   d+|j                   d,      |}|j:                  j=                         |z  }	 t?        |d-.      }tC        ||||       tE        |||0      \  }}}|t        d1       | |      }|j                  |j                  k7  r&t        d |j                   d2|j                   d3      |j:                  j=                         |z  } t1        | d&4      \  }!}"tG        |!||      }#|!|#   }!|	r	|!dddf<   t        j                  |"dd|#f         }"tI        ||"|0      }tI        ||"|0      }|tI        ||"|0      }t        jJ                  |ftL              }$d}%d}&d}'t        jN                  t        j4                  |j                        jP                        }(d(})d-}*d&}+d&},|)|k  
r~|)dz  })|||!t        jR                  ddf   z  }n||!t        jR                  ddf   z  }||z
  }-t        jT                  |-j=                         |-z  d      }t        j2                  t        jN                  |            }.|
r	|.|)ddf<   t        jT                  t        jN                  |.            |z  }/|/|(k  r|/}(|)}|}n|/d|z  |(z  kD  rd-}+ | |      }|j                  |j                  k7  r&t        d |j                   d5|j                   d3      |G ||      }|j                  |j                  k7  r&t        d |j                   d5|j                   d,      t        jV                  |.|kD  d-d&      }#|$|#z  }$|$jU                         }0|r8t        d6|)        t        d7|0        t        d8|!        t        d9|.        |0dk(  rntY        |-dd|$f         }1|)dkD  r8tY        |%dd|$f         }2tY        |&dd|$f         }3|tY        |'dd|$f         }4| ||1      }1|tC        |1|       |$|1||j:                  j=                         |1z  z  z
  }1n#|1||j:                  j=                         |1z  z  z
  }1tE        ||1|0      }|\  }1}5}|1(t        j                  d:|) d;|. d<| d=t        d       n | |1      }6|)dkD  rA|tE        |24|0      }|\  }2}4}7ntE        |2|0      }|\  }2}}7|2tI        3|7|0      }3|+}*nd-}*|6j                  d>k(  rd}8n<t        j2                  t        j4                  |1j                        j6                        }8|.jQ                         |8kD  r|,sd&},nd-},||}|1}5|*s2}4t        jZ                  |j:                  j=                         |6      }9t        jZ                  |1j:                  j=                         |6      }:|6j                  };|,r|:|:j:                  j=                         z   dz  }:t        jZ                  |j:                  j=                         |      } | | j:                  j=                         z   dz  } t        jZ                  |j:                  j=                         |      }<t        jZ                  |1j:                  j=                         |5      }=t        jZ                  |j:                  j=                         |5      }>nkt        j\                  |!      j_                  |;      } t        j$                  ||;      }<t        j$                  |0|;      }=t        j                  ||0f|;      }>|*s?t        jZ                  |j:                  j=                         3      }?t        jZ                  |1j:                  j=                         |3      }@t        jZ                  2j:                  j=                         |3      }At        jZ                  |j:                  j=                         4      }Bt        jZ                  |1j:                  j=                         |4      }C|,rOA|Aj:                  j=                         z   dz  }At        jZ                  |2j:                  j=                         |4      }Dnt        j$                  |0|;      }Dt        j`                  | |9|?g|9j:                  j=                         |:@g|?j:                  j=                         |@j:                  j=                         Agg      }Et        j`                  |<|>Bg|>j:                  j=                         |=Cg|Bj:                  j=                         |Cj:                  j=                         Dgg      }Ftc        |E|F|       	 t1        EFd&4      \  }!}"|*rt        j`                  | |9g|9j:                  j=                         |:gg      }Et        j`                  |<|>g|>j:                  j=                         |=gg      }Ftc        |E|F|       	 t1        EFd&4      \  }!}"tG        |!||      }#|!|#   }!|"dd|#f   }"|	r|!|)dz   ddf<   |C|*s|"d| }G|"|||0z    }H|"||0z   d }It        jZ                  |1|H      }J|Jt        jZ                  2|I      z  }Jt        jZ                  |6|H      }K|Kt        jZ                  3|I      z  }Kt        jZ                  |5|H      }L|Lt        jZ                  4|I      z  }LnL|"d| }G|"|d }Ht        jZ                  |1|H      }Jt        jZ                  |6|H      }Kt        jZ                  |5|H      }Lt        jZ                  |G      Jz   }t        jZ                  ||G      Kz   }t        jZ                  ||G      Lz   }|J|K|L}'}&}%n|*st|"d| }G|"|||0z    }H|"||0z   d }It        jZ                  |1|H      }J|Jt        jZ                  2|I      z  }Jt        jZ                  |6|H      }K|Kt        jZ                  3|I      z  }Kn6|"d| }G|"|d }Ht        jZ                  |1|H      }Jt        jZ                  |6|H      }Kt        jZ                  |G      Jz   }t        jZ                  ||G      Kz   }|J|K}&}%|)|k  r
~|||!t        jR                  ddf   z  }n||!t        jR                  ddf   z  }||z
  }-t        jT                  |-j=                         |-z  d      }t        j2                  t        jN                  |            }.|	r|!|)dz   ddf<   |
r|.|)dz   ddf<   t        jT                  t        jN                  |.            |z  }/|/|(k  r	|/}(|)dz   }|}t        jP                  t        jN                  |.            |kD  r,t        j                  dC|) dD|. dE| dF| dG|( dHt        d       |rt        dI|!        t        dJ|.        |}|tC        ||        | |      }|j                  |j                  k7  r&t        d |j                   dK|j                   d3      t        jZ                  |j:                  j=                         |      } |}|G ||      }|j                  |j                  k7  r&t        d |j                   dK|j                   d,      t        jZ                  |j:                  j=                         |      }<tc        | |<|       | | j:                  j=                         z   dz  } |<|<j:                  j=                         z   dz  }<	 t1        | |<d&4      \  }!}"tG        |!||      }#|!|#   }!t        j                  |"dd|#f         }"t        jZ                  ||"      }t        jZ                  ||"      }|1t        jZ                  ||"      }||!t        jR                  ddf   z  }n||!t        jR                  ddf   z  }||z
  }-t        jT                  |-j=                         |-z  d      }t        j2                  t        jN                  |            }.|	r|!|dz   ddf<   |
r|.|dz   ddf<   |	rd|dz   ddf   }|
rd|dz   ddf   }t        jP                  t        jN                  |.            |kD  r#t        j                  dM|. dE| d=t        d       |rt        dN|!        t        dO|.        |	rNt        jd                  t        j                  |      d         }|D Mcg c]  }Mt        jf                  |M       }}M|
rNt        jd                  t        j                  |      d         }|D Mcg c]  }Mt        jf                  |M       }}M|	r|
r|!|fS |!|fS |
r|!|fS |!|fS # t.        $ r}t/        d"| d#      d}~ww xY w# t.        $ r}t/        d%| d#      d}~ww xY w# t.        $ r}t/        d)| d#      d}~ww xY w# t@        $ r}t        d/      |d}~ww xY w# t@        $ r2}|r#t        j                  d?|) d@| dAt        d       d-}*Y d}~d}~ww xY w# t@        $ r.}t        j                  d?|) dB| d#t        d       Y d}~d}~ww xY w# t@        $ r}t        dL      |d}~ww xY wc c}Mw c c}Mw )Pam,  Locally Optimal Block Preconditioned Conjugate Gradient Method (LOBPCG).

    LOBPCG is a preconditioned eigensolver for large real symmetric and complex
    Hermitian definite generalized eigenproblems.

    Parameters
    ----------
    A : {sparse matrix, ndarray, LinearOperator, callable object}
        The Hermitian linear operator of the problem, usually given by a
        sparse matrix.  Often called the "stiffness matrix".
    X : ndarray, float32 or float64
        Initial approximation to the ``k`` eigenvectors (non-sparse).
        If `A` has ``shape=(n,n)`` then `X` must have ``shape=(n,k)``.
    B : {sparse matrix, ndarray, LinearOperator, callable object}
        Optional. By default ``B = None``, which is equivalent to identity.
        The right hand side operator in a generalized eigenproblem if present.
        Often called the "mass matrix". Must be Hermitian positive definite.
    M : {sparse matrix, ndarray, LinearOperator, callable object}
        Optional. By default ``M = None``, which is equivalent to identity.
        Preconditioner aiming to accelerate convergence.
    Y : ndarray, float32 or float64, default: None
        An ``n-by-sizeY`` ndarray of constraints with ``sizeY < n``.
        The iterations will be performed in the ``B``-orthogonal complement
        of the column-space of `Y`. `Y` must be full rank if present.
    tol : scalar, optional
        The default is ``tol=n*sqrt(eps)``.
        Solver tolerance for the stopping criterion.
    maxiter : int, default: 20
        Maximum number of iterations.
    largest : bool, default: True
        When True, solve for the largest eigenvalues, otherwise the smallest.
    verbosityLevel : int, optional
        By default ``verbosityLevel=0`` no output.
        Controls the solver standard/screen output.
    retLambdaHistory : bool, default: False
        Whether to return iterative eigenvalue history.
    retResidualNormsHistory : bool, default: False
        Whether to return iterative history of residual norms.
    restartControl : int, optional.
        Iterations restart if the residuals jump ``2**restartControl`` times
        compared to the smallest recorded in ``retResidualNormsHistory``.
        The default is ``restartControl=20``, making the restarts rare for
        backward compatibility.

    Returns
    -------
    lambda : ndarray of the shape ``(k, )``.
        Array of ``k`` approximate eigenvalues.
    v : ndarray of the same shape as ``X.shape``.
        An array of ``k`` approximate eigenvectors.
    lambdaHistory : ndarray, optional.
        The eigenvalue history, if `retLambdaHistory` is ``True``.
    ResidualNormsHistory : ndarray, optional.
        The history of residual norms, if `retResidualNormsHistory`
        is ``True``.

    Notes
    -----
    The iterative loop runs ``maxit=maxiter`` (20 if ``maxit=None``)
    iterations at most and finishes earlier if the tolerance is met.
    Breaking backward compatibility with the previous version, LOBPCG
    now returns the block of iterative vectors with the best accuracy rather
    than the last one iterated, as a cure for possible divergence.

    If ``X.dtype == np.float32`` and user-provided operations/multiplications
    by `A`, `B`, and `M` all preserve the ``np.float32`` data type,
    all the calculations and the output are in ``np.float32``.

    The size of the iteration history output equals to the number of the best
    (limited by `maxit`) iterations plus 3: initial, final, and postprocessing.

    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 ``k`` the number
    of required eigenvalues (smallest or largest).

    The LOBPCG code internally solves eigenproblems of the size ``3k`` on every
    iteration by calling the dense eigensolver `eigh`, so if ``k`` is not
    small enough compared to ``n``, it makes no sense to call the LOBPCG code.
    Moreover, if one calls the LOBPCG algorithm for ``5k > n``, it would likely
    break internally, so the code calls the standard function `eigh` instead.
    It is not that ``n`` should be large for the LOBPCG to work, but rather the
    ratio ``n / k`` should be large. It you call LOBPCG with ``k=1``
    and ``n=10``, it works though ``n`` is small. The method is intended
    for extremely large ``n / k``.

    The convergence speed depends basically on three factors:

    1. Quality of the initial approximations `X` to the seeking eigenvectors.
       Randomly distributed around the origin vectors work well if no better
       choice is known.

    2. Relative separation of the desired eigenvalues from the rest
       of the eigenvalues. One can vary ``k`` to improve the separation.

    3. Proper preconditioning to shrink the spectral spread.
       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.

    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. :arxiv:`0705.2626`

    .. [3] A. V. Knyazev's C and MATLAB implementations:
           https://github.com/lobpcg/blopex

    Examples
    --------
    Our first example is minimalistic - find the largest eigenvalue of
    a diagonal matrix by solving the non-generalized eigenvalue problem
    ``A x = lambda x`` without constraints or preconditioning.

    >>> import numpy as np
    >>> from scipy.sparse import spdiags
    >>> from scipy.sparse.linalg import LinearOperator, aslinearoperator
    >>> from scipy.sparse.linalg import lobpcg

    The square matrix size is

    >>> n = 100

    and its diagonal entries are 1, ..., 100 defined by

    >>> vals = np.arange(1, n + 1).astype(np.int16)

    The first mandatory input parameter in this test is
    the sparse diagonal matrix `A`
    of the eigenvalue problem ``A x = lambda x`` to solve.

    >>> A = spdiags(vals, 0, n, n)
    >>> A = A.astype(np.int16)
    >>> 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]], shape=(100, 100), dtype=int16)

    The second mandatory input parameter `X` is a 2D array with the
    row dimension determining the number of requested eigenvalues.
    `X` is an initial guess for targeted eigenvectors.
    `X` must have linearly independent columns.
    If no initial approximations available, randomly oriented vectors
    commonly work best, e.g., with components normally distributed
    around zero or uniformly distributed on the interval [-1 1].
    Setting the initial approximations to dtype ``np.float32``
    forces all iterative values to dtype ``np.float32`` speeding up
    the run while still allowing accurate eigenvalue computations.

    >>> k = 1
    >>> rng = np.random.default_rng()
    >>> X = rng.normal(size=(n, k))
    >>> X = X.astype(np.float32)

    >>> eigenvalues, _ = lobpcg(A, X, maxiter=60)
    >>> eigenvalues
    array([100.], dtype=float32)

    `lobpcg` needs only access the matrix product with `A` rather
    then the matrix itself. Since the matrix `A` is diagonal in
    this example, one can write a function of the matrix product
    ``A @ X`` using the diagonal values ``vals`` only, e.g., by
    element-wise multiplication with broadcasting in the lambda-function

    >>> A_lambda = lambda X: vals[:, np.newaxis] * X

    or the regular function

    >>> def A_matmat(X):
    ...     return vals[:, np.newaxis] * X

    and use the handle to one of these callables as an input

    >>> eigenvalues, _ = lobpcg(A_lambda, X, maxiter=60)
    >>> eigenvalues
    array([100.], dtype=float32)
    >>> eigenvalues, _ = lobpcg(A_matmat, X, maxiter=60)
    >>> eigenvalues
    array([100.], dtype=float32)

    The traditional callable `LinearOperator` is no longer
    necessary but still supported as the input to `lobpcg`.
    Specifying ``matmat=A_matmat`` explicitly improves performance. 

    >>> A_lo = LinearOperator((n, n), matvec=A_matmat, matmat=A_matmat, dtype=np.int16)
    >>> eigenvalues, _ = lobpcg(A_lo, X, maxiter=80)
    >>> eigenvalues
    array([100.], dtype=float32)

    The least efficient callable option is `aslinearoperator`:

    >>> eigenvalues, _ = lobpcg(aslinearoperator(A), X, maxiter=80)
    >>> eigenvalues
    array([100.], dtype=float32)

    We now switch to computing the three smallest eigenvalues specifying

    >>> k = 3
    >>> X = np.random.default_rng().normal(size=(n, k))

    and ``largest=False`` parameter

    >>> eigenvalues, _ = lobpcg(A, X, largest=False, maxiter=90)
    >>> print(eigenvalues)  
    [1. 2. 3.]

    The next example illustrates computing 3 smallest eigenvalues of
    the same matrix `A` given by the function handle ``A_matmat`` but
    with constraints and preconditioning.

    Constraints - an optional input parameter is a 2D array comprising
    of column vectors that the eigenvectors must be orthogonal to

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

    The preconditioner acts as the inverse of `A` in this example, but
    in the reduced precision ``np.float32`` even though the initial `X`
    and thus all iterates and the output are in full ``np.float64``.

    >>> inv_vals = 1./vals
    >>> inv_vals = inv_vals.astype(np.float32)
    >>> M = lambda X: inv_vals[:, np.newaxis] * X

    Let us now solve the eigenvalue problem for the matrix `A` first
    without preconditioning requesting 80 iterations

    >>> eigenvalues, _ = lobpcg(A_matmat, X, Y=Y, largest=False, maxiter=80)
    >>> eigenvalues
    array([4., 5., 6.])
    >>> eigenvalues.dtype
    dtype('float64')

    With preconditioning we need only 20 iterations from the same `X`

    >>> eigenvalues, _ = lobpcg(A_matmat, X, Y=Y, M=M, largest=False, maxiter=20)
    >>> eigenvalues
    array([4., 5., 6.])

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

    The primary matrix `A` may be indefinite, e.g., after shifting
    ``vals`` by 50 from 1, ..., 100 to -49, ..., 50, we still can compute
    the 3 smallest or largest eigenvalues.

    >>> vals = vals - 50
    >>> X = rng.normal(size=(n, k))
    >>> eigenvalues, _ = lobpcg(A_matmat, X, largest=False, maxiter=99)
    >>> eigenvalues
    array([-49., -48., -47.])
    >>> eigenvalues, _ = lobpcg(A_matmat, X, largest=True, maxiter=99)
    >>> eigenvalues
    array([50., 49., 48.])

    N   r   r'   z2Expected rank-2 array for argument Y, instead got z&, so ignore it and use no constraints.r   r   z-The mandatory initial matrix X cannot be Nonez$expected rank-2 array for argument XzData type for argument X is z0, which is not inexact, so casted to np.float32.)r   r<   zSolving standardgeneralizedz eigenvalue problem withr;   z preconditioning

zmatrix size %d
zblock size %d

zNo constraints

z%d constraints

z%d constraint

   zThe problem size z minus the constraints size z) is too small relative to the block size zd. Using a dense eigensolver instead of LOBPCG iterations.No output of the history of the iterations.z3The dense eigensolver does not support constraints.rO   z> of the primary matrix
defined by a callable object is wrong.
z&Primary MatMul call failed with error
rN   z@ of the secondary matrix
defined by a callable object is wrong.
rM   F)subset_by_indexcheck_finiter[   z$Dense eigensolver failed with error
g        z0 of the constraint not preserved
and changed to rP   TrQ   zLinearly dependent constraintsrS   z)Linearly dependent initial approximationsz< of the initial approximations not preserved
and changed to z* after multiplying by the primary matrix.
)rl   z7 of the restarted iterate not preserved
and changed to z
iteration zcurrent block size: zeigenvalue(s):
zresidual norm(s):
zFailed at iteration z with accuracies z'
 not reaching the requested tolerance .float32zeigh failed at iteration z 
with error z causing a restart.
z with error
zExited at iteration z with accuracies 
z&
not reaching the requested tolerance z.
Use iteration z instead with accuracy 
z.
zFinal iterative eigenvalue(s):
z"Final iterative residual norm(s):
z< of the postprocessing iterate not preserved
and changed to z(eigh has failed in lobpcg postprocessingz'Exited postprocessing with accuracies 
z$Final postprocessing eigenvalue(s):
zFinal residual norm(s):
)4lenr*   r   r   r   rT   r   
issubdtyper   inexactr)   rn   zerosprintminNotImplementedError
isinstancer	   eyeintr7   r
   toarrayr?   r   sqrtr   r   r8   r   r   r   r   rK   rY   ra   rC   onesboolabsr   newaxissumwherer-   dotdiagastypeblockre   vsplitsqueeze)NAXrU   r   Yr"   maxiterr_   rB   retLambdaHistoryretResidualNormsHistoryrestartControlblockVectorXbestblockVectorXrH   residualTolerancebestIterationNumbersizeYnsizeXlambdaHistoryresidualNormsHistoryr,   eigvalsrW   valsvecsrG   gramYBYblockVectorBX_blockVectorAXgramXAXr]   eigBlockVectorr`   
activeMaskblockVectorPblockVectorAPblockVectorBPsmallestResidualNormiterationNumberrestartforcedRestartexplicitGramFlagblockVectorRresidualNormsresidualNormcurrentBlockSizeactiveBlockVectorRactiveBlockVectorPactiveBlockVectorAPactiveBlockVectorBPactiveBlockVectorBRactiveBlockVectorARinvRmyepsgramXARgramRAR	gramDtypegramXBXgramRBRgramXBRgramXAPgramRAPgramPAPgramXBPgramRBPgramPBPrc   rd   eigBlockVectorXeigBlockVectorReigBlockVectorPppappbppisN                                                                                 r#   r   r      s   x L#L!E|!!"a'MMD|))*+ ,78 	  L &&q)E HII
<!#?@@!!HAu ==++RZZ8*<+=+=*> ?= >A	

 zz,bjjA'A+u!5'3'9'9;!xx1e(<.:.@.@ B 9:C= C))95LC%%!A%%"U**''Cqy+e33*U22c
	E	a%i s">ug F77<g >:; A	
 E1#%E 
 5y!a%(G%!)nG	!^,bffQc*+!bffQc*+77q!f$$$QWWI .C D  !IIKJJqM =a0"&&#./Aa["&&#./Aww1a&(((	 2G H  a[		A

1A	a.5+02JD$ DbDzAttG}: 	!'8C'?GGBHH\-?-?$@$D$DEIAAAAAA =lOM""l&8&88  !3!3 4 5&&3&9&9%: ;CD  )M ..%%'-7	F d;G 	,M &7	<&8"L-DEE lOMl000++, -+112 39:
 	
 nn!!#m3G"7?G^	7E7	+BbkG%adZZq"u 56N"n%L $~%M 	}'>)
 %.J
 LMM66"((<+=+=">"B"BCOGM
G
#1='"**a-"88CQ!77C$s*ff\&&(<7;s,"7D !!34vvbff]34u<..#/ "1+A~-0DDD MlOM""l&8&88  !3!3 4 5&&3&9&9%: ;AB  } !, &&,*<*<<$$\%7%7$8 9**7*=*=)> ?GH  XXm&77uE"_
%>>+J/01()9(:;<$WI./'78q "<:#>?Q!&|AzM'B!C"'am(D"E}&+M!Z-,H&I#=!"#5!6 #0%+*, =!3%%'*<<>"
 "4$$&);;="  !.B582/%MM&&77H / "./q2 	  23Q}')+>#1 AD="$7'+=7EG.1+"At!-&5'#1'# ( $$	1EGGBHH%7%=%=>BBCE&/?$  $ 9(M"4&8# &&,,.0CD&&+--2246IJ'--	!11Q6Gff\^^002MBG!11Q6Gff\^^002MBGff/11668:MNGff\^^0024GHGggg&--i8GffU)4Gff-Y?Ghh'78	JGff\^^0024GHGff/11668:MNGff/11668:MNGff\^^0024GHGff/11668:MNG"WYY^^%55:&&!3!5!5!:!:!<!46 &&!1CHHgw/YY^^%w8YY^^%wyy~~'7AE HHgw/YY^^%w8YY^^%wyy~~'7AE *%G*.u/4<A+C' HHw0799>>3CW2MNOEHHw0799>>3CW2MNOE)%G*.u/4<A+C' ww/"+'2.4;M/A-q01 ="0%"8"0169I1I#K"09I1I1J"KVV.@bff/AAff0/Brvv1?CCff0/Brvv1?CC"0%"8"0"8VV.@ff0/Bff0/B66,@2ELFF=/BSHMFF=/BSHM9;S#-L "0%"8"0169I1I#K"09I1I1J"KVV.@bff/AAff0/Brvv1?CC"0%"8"0"8VV.@ff0/B66,@2ELFF=/BSHM*,c-L{ G
#~ 	}gbjj!m44WRZZ]33 3&L
&&""$|3Q
7CGGBFF3K(M07o)1,-7D_q0!3466"&&/058L**+-1'	vvbff]#$'88"?"33Fo 44E3F G011J#$C	)
 A	
 0	:;3M?CD#L,!'&	( lOMl000++, -+112 39:
 	
 ff\^^((*M:G M},,"4"44\//0 1""/"5"5!6 7?@  ff\^^((*M:G!'7NC))Q.G))Q.GL"&w'.49#; 
7E7	+BbkGZZq"u 56N66,7LFF=.9M}}n=gbjj!m44WRZZ]33 3&L
&&""$|3Q
7CGGBFF3K(M4;)A-q01;H014a78%%!A%%q(*3%!A%%q( * 
vvbff]#$'886o 44E3FaI A		
 5gY?@)-9:		--1H1KL0=>1A>>!yy)=)+2F)G)J L7KL!

1LL"L-9MMML-77"L*>>>L((S  	9#R 	(  ?c    	7#R 	B  	F=>AE	FH  	!MM3O3D E&&'S(=?# 	*  //@cA
 Z  LCD!KL^ ?  Ms   7B9AV9 3B9AW -+AW9 +AX 8AX6 ?AY4 MAZ. T1A[VA[V9	AWWAWWAWW	AW6W"AW1W1AW6W9	AXXAXXAXX	AX3X"AX.X.AX3X6	AY1X?'AY,Y,AY1Y4	AZ+Y=#AZ&Z&AZ+Z.	A[Z7A[[A[)r   )Nr   )
NNNNNTr   FFrg   )__doc__r   numpyr   r   r   r   r   r   r   r   scipy.sparse.linalgr	   scipy.sparser
   __all__r$   r-   r8   rC   rK   rY   ra   re   r   r1   r%   r#   <module>r      s   &  1 1 . !*"
8' 6:%&. b- 

!l)r%   