
    [Th              !          S r SSKJr  SSKrSSKJrJr  SSKJrJ	r	  S/r
S rS rS	 rS$S
 jrS$S jrS rS r " S S\R$                  R&                  5      r             S%S\S\\   S\\   S\\   S\\   S\\   S\\   S\\   S\\   S\\   SSS\\\\4      S\\\\4      S\\\\4      S\\\4   4S jjr             S%S\S\\   S\\   S\\   S\\   S\\   S\\   S\\   S\\   S\\   SSS\\\\4      S\\\\4      S\\\\4      S\\\4   4S  jjr " S! S"5      r\R<                  rS# r g)&z@Locally Optimal Block Preconditioned Conjugate Gradient methods.    )OptionalN)_linalg_utilsTensor)handle_torch_functionhas_torch_functionlobpcgc           
         UR                  S5      UR                  S5      -
  nUR                  SSS9R                  [        S5      5        UR	                  S5        UR
                  R                  5       n[        R                  " U[        R                  " [        R                  " U 5      [        R                  " Xa5      U-  -   U5      5      nU$ )Ndim1dim2inf)
	unsqueezediagonalfill_floatpow_mT
contiguoustorchmatmul
diag_embed)D_gradU_gradADUFUtress           E/var/www/auris/envauris/lib/python3.13/site-packages/torch/_lobpcg.py$_symeig_backward_complete_eigenspacer#      s    	B!++b/)AJJBRJ &&uU|4FF2J 
	B
,,	5<<((05<<3Ka3OOQSTC J    c           	         U R                   S   n[        U R                   5      nUS==   S-  ss'   U R                  U5      nSUS'   SUS'   [        SUS-   5       Ht  nU R                  (       a  UR                  5       OUnUR                  SX-
  US-   5      nX`R                  SUS-
  S5      UR                  SX-
  S-   US-   5      -  -  nUnMv     UR                  SSUS-   5      $ )aH  
Given the `roots` of a polynomial, find the polynomial's coefficients.

If roots = (r_1, ..., r_n), then the method returns
coefficients (a_0, a_1, ..., a_n (== 1)) so that
p(x) = (x - r_1) * ... * (x - r_n)
     = x^n + a_{n-1} * x^{n-1} + ... a_1 * x_1 + a_0

Note: for better performance requires writing a low-level kernel
r         ).r   ).r   )shapelist	new_zerosrangerequires_gradclonenarrow)roots
poly_orderpoly_coeffs_shapepoly_coeffsipoly_coeffs_newouts          r"   $_polynomial_coefficients_given_rootsr6      s    RJU[[) bQ//"34KKK 1j1n% 271D1D+++-+$$RQ?||BAq)K,>,>
"AE-
 
 	
 & &" b!Z!^44r$   c                     UR                  5       n[        U R                  S5      S-
  SS5       H  nU" XAU SU4   5      nM     U$ )a  
A generic method for computing poly(x) using the Horner's rule.

Args:
  poly (Tensor): the (possibly batched) 1D Tensor representing
                 polynomial coefficients such that
                 poly[..., i] = (a_{i_0}, ..., a{i_n} (==1)), and
                 poly(x) = poly[..., 0] * zero_power + ... + poly[..., n] * x^n

  x (Tensor): the value (possible batched) to evalate the polynomial `poly` at.

  zero_power (Tensor): the representation of `x^0`. It is application-specific.

  transition (Callable): the function that accepts some intermediate result `int_val`,
                         the `x` and a specific polynomial coefficient
                         `poly[..., k]` for some iteration `k`.
                         It basically performs one iteration of the Horner's rule
                         defined as `x * int_val + poly[..., k] * zero_power`.
                         Note that `zero_power` is not a parameter,
                         because the step `+ poly[..., k] * zero_power` depends on `x`,
                         whether it is a vector, a matrix, or something else, so this
                         functionality is delegated to the user.
r   r&   .)r-   r+   size)polyx
zero_power
transitionr!   ks         r"   _polynomial_valuer>   I   sK    2 


C499R=1$b"-c1f. .Jr$   c                 b   S nUc  [         R                  " UR                  S5      UR                  S5      UR                  UR                  S9R
                  " / S/[        [        UR                  SS 5      5      -  QUR                  S5      PUR                  S5      P76 n[        XX#5      $ )zr
Evaluates `poly(x)` for the (batched) matrix input `x`.
Check out `_polynomial_value` function for more details.
c                     UR                  U 5      nUR                  SSS9R                  UR                  S5      5        U$ )Nr
   r   r   )r   r   add_r   curr_poly_valr:   
poly_coeffr!   s       r"   r<   ,_matrix_polynomial_value.<locals>.transitiono   s;    hh}%"2&++J,@,@,DE
r$   Nr   dtypedevicer'   r
   )
r   eyer8   rG   rH   viewlenr)   r(   r>   r9   r:   r;   r<   s       r"   _matrix_polynomial_valuerM   h   s    
 YYFF2Jr
!''!((

$ Is4-..I12I=>VVBZI
 Tj==r$   c                 z    S nUc*  UR                  S5      R                  UR                  5      n[        XX#5      $ )zr
Evaluates `poly(x)` for the (batched) vector input `x`.
Check out `_polynomial_value` function for more details.
c                 R    [         R                  " UR                  S5      X5      nU$ )Nr   )r   addcmulr   rB   s       r"   r<   ,_vector_polynomial_value.<locals>.transition   s"    mmJ004aG
r$   r'   )new_onesexpandr(   r>   rL   s       r"   _vector_polynomial_valuerT   |   s8     ZZ]))!''2
Tj==r$   c           	      z   UR                   R                  5       nUR                  U5      * nUR                  SSS9R	                  S5        [
        R                  " UR                  5      nUR                  [
        R                  " / UR                  S S QUR                  S5      UR                  S5      -
  P7UR                  UR                  US95      n	U	R                   R                  5       n
[        U5      nUnUR                  UR                  5      n[        SUR                  S5      5       H=  n[        USUS 24   U5      nXUR!                  S5      -  -  nUR                  U5      nM?     [#        X5      n[
        R                  " U
[
        R                  " UU	5      5      nU(       a  WS-  S:X  a  SOSn[
        R$                  R'                  UU-  5      n[)        XX#U5      nUU	R                  U[
        R*                  " U
R                  U5      U5      -  5      R                  U5      -  nU$ )Nr
   r   r   r'   )rG   rH   	generator.r&   )r   r   r   r   rA   r   	GeneratorrH   randnr(   r8   rG   r6   r*   r+   rT   r   rM   linalgcholeskyr#   cholesky_solve)r   r   r   r   r   largestr    proj_U_orthogenU_ortho	U_ortho_t
chr_poly_DU_grad_projected
series_accr=   poly_Dchr_poly_D_at_Achr_poly_D_at_A_to_U_orthochr_poly_D_at_A_to_U_ortho_signchr_poly_D_at_A_to_U_ortho_Lr!   s                        r"   #_symeig_backward_partial_eigenspaceri      s	    
	BHHRL=Lr+003 //!((
#C !!4aggcrl4AFF2J34''88		
G 

%%'I
 6a8J< !++,<,B,BCJ1joob)*)*S!"W*=qA)9)9")===
88$45 + /z=O "'5<<9" .5!a%1*bB##(<<#8#8'*DD$ 
 /vqQ
GC 7>>'


Z(*F
	

 fRjC Jr$   c                 ~    UR                  S5      UR                  S5      :X  a  [        XX#U5      $ [        XX#XE5      $ )Nr   r
   )r8   r#   ri   )r   r   r   r   r   r\   s         r"   _symeig_backwardrk      s8    vvbzQVVBZ3FA!LL261TTr$   c            "          \ rS rSr\             SS\S\\   S\\   S\\   S\\   S\\   S	\\   S
\\   S\\	   S\\
   SSS\\\
\4      S\\\
\4      S\\\
\	4      S\\\4   4S jj5       r\S 5       rSrg)LOBPCGAutogradFunction   Nr   r=   BXniKnitertolr\   methodtrackerortho_iparamsortho_fparamsortho_bparamsreturnc                    UR                   (       d  UR                  5       OUnUb#  UR                   (       d  UR                  5       OUn[        UUUUUUUUU	U
UUUU5      u  nnU R                  XUU5        Xl        UU4$ N)	is_sparser   _lobpcgsave_for_backwardr\   )ctxr   r=   ro   rp   rq   rr   rs   rt   r\   ru   rv   rw   rx   ry   r   r   s                    r"   forwardLOBPCGAutogradFunction.forward  s    ( $%;;ALLNQ='({{A
1" 	aAq)!tr$   c                    S =p4S /S-  nU R                   u  pgpU R                  n
UR                  (       d(  Ub0  UR                  (       a  U R                  S   (       a  [	        S5      eUR
                  [        R                  [        R                  4;   d1  Ub9  UR
                  [        R                  [        R                  4;   a  [	        S5      eUb  [	        S5      eU
c  Sn
Uc  [        XXhX5      nX5S'   XES'   [        U5      $ )N   r&   zWlobpcg.backward does not support sparse input yet.Note that lobpcg.forward does though.zXlobpcg.backward does not support complex input yet.Note that lobpcg.forward does though.z:lobpcg.backward does not support backward with B != I yet.Tr   )saved_tensorsr\   r}   needs_input_grad
ValueErrorrG   r   	complex64
complex128rk   tuple)r   r   r   A_gradB_gradgradsr   ro   r   r   r\   s              r"   backwardLOBPCGAutogradFunction.backward/  s   &&
a++ ;;1=Q[[S=Q=QRS=T8 
 GG)9)9::}EOOU-=-=>>8  =L  ?G 9%faAGF aaU|r$    NNNNNNNNNNNNN)__name__
__module____qualname____firstlineno__staticmethodr   r   intr   boolstrdictr   r   r   __static_attributes__r   r$   r"   rm   rm      s>     ""###"& $264837++ C=+ F	+
 F+ C=+ V+ }+ e_+ $+ + +  S#X/+  S%Z 01+  S$Y0+  
vv~	!+ +Z & &r$   rm   r   r=   ro   rp   rq   rr   rs   rt   r\   ru   rv   rw   rx   ry   rz   c                    [         R                  R                  5       (       dv  XX54n[        [	        [
        U5      5      R                  [         R                  [        S5      45      (       d,  [        U5      (       a  [        [        UU UUUUUUUUU	U
UUUS9$ [         R                  R                  5       (       do  U R                  (       d  UbZ  UR                  (       aI  X R                  -   S-  nUb  X"R                  -   S-  OSn[        R                  UUUUUUUUUU	U
UUU5      $ O0U R                  (       d  Ub  UR                  (       a  [!        S5      e[#        U UUUUUUUUU	U
UUU5      $ )a]  Find the k largest (or smallest) eigenvalues and the corresponding
eigenvectors of a symmetric positive definite generalized
eigenvalue problem using matrix-free LOBPCG methods.

This function is a front-end to the following LOBPCG algorithms
selectable via `method` argument:

  `method="basic"` - the LOBPCG method introduced by Andrew
  Knyazev, see [Knyazev2001]. A less robust method, may fail when
  Cholesky is applied to singular input.

  `method="ortho"` - the LOBPCG method with orthogonal basis
  selection [StathopoulosEtal2002]. A robust method.

Supported inputs are dense, sparse, and batches of dense matrices.

.. note:: In general, the basic method spends least time per
  iteration. However, the robust methods converge much faster and
  are more stable. So, the usage of the basic method is generally
  not recommended but there exist cases where the usage of the
  basic method may be preferred.

.. warning:: The backward method does not support sparse and complex inputs.
  It works only when `B` is not provided (i.e. `B == None`).
  We are actively working on extensions, and the details of
  the algorithms are going to be published promptly.

.. warning:: While it is assumed that `A` is symmetric, `A.grad` is not.
  To make sure that `A.grad` is symmetric, so that `A - t * A.grad` is symmetric
  in first-order optimization routines, prior to running `lobpcg`
  we do the following symmetrization map: `A -> (A + A.t()) / 2`.
  The map is performed only when the `A` requires gradients.

Args:

  A (Tensor): the input tensor of size :math:`(*, m, m)`

  B (Tensor, optional): the input tensor of size :math:`(*, m,
              m)`. When not specified, `B` is interpreted as
              identity matrix.

  X (tensor, optional): the input tensor of size :math:`(*, m, n)`
              where `k <= n <= m`. When specified, it is used as
              initial approximation of eigenvectors. X must be a
              dense tensor.

  iK (tensor, optional): the input tensor of size :math:`(*, m,
              m)`. When specified, it will be used as preconditioner.

  k (integer, optional): the number of requested
              eigenpairs. Default is the number of :math:`X`
              columns (when specified) or `1`.

  n (integer, optional): if :math:`X` is not specified then `n`
              specifies the size of the generated random
              approximation of eigenvectors. Default value for `n`
              is `k`. If :math:`X` is specified, the value of `n`
              (when specified) must be the number of :math:`X`
              columns.

  tol (float, optional): residual tolerance for stopping
             criterion. Default is `feps ** 0.5` where `feps` is
             smallest non-zero floating-point number of the given
             input tensor `A` data type.

  largest (bool, optional): when True, solve the eigenproblem for
             the largest eigenvalues. Otherwise, solve the
             eigenproblem for smallest eigenvalues. Default is
             `True`.

  method (str, optional): select LOBPCG method. See the
             description of the function above. Default is
             "ortho".

  niter (int, optional): maximum number of iterations. When
             reached, the iteration process is hard-stopped and
             the current approximation of eigenpairs is returned.
             For infinite iteration but until convergence criteria
             is met, use `-1`.

  tracker (callable, optional) : a function for tracing the
             iteration process. When specified, it is called at
             each iteration step with LOBPCG instance as an
             argument. The LOBPCG instance holds the full state of
             the iteration process in the following attributes:

               `iparams`, `fparams`, `bparams` - dictionaries of
               integer, float, and boolean valued input
               parameters, respectively

               `ivars`, `fvars`, `bvars`, `tvars` - dictionaries
               of integer, float, boolean, and Tensor valued
               iteration variables, respectively.

               `A`, `B`, `iK` - input Tensor arguments.

               `E`, `X`, `S`, `R` - iteration Tensor variables.

             For instance:

               `ivars["istep"]` - the current iteration step
               `X` - the current approximation of eigenvectors
               `E` - the current approximation of eigenvalues
               `R` - the current residual
               `ivars["converged_count"]` - the current number of converged eigenpairs
               `tvars["rerr"]` - the current state of convergence criteria

             Note that when `tracker` stores Tensor objects from
             the LOBPCG instance, it must make copies of these.

             If `tracker` sets `bvars["force_stop"] = True`, the
             iteration process will be hard-stopped.

  ortho_iparams, ortho_fparams, ortho_bparams (dict, optional):
             various parameters to LOBPCG algorithm when using
             `method="ortho"`.

Returns:

  E (Tensor): tensor of eigenvalues of size :math:`(*, k)`

  X (Tensor): tensor of eigenvectors of size :math:`(*, m, k)`

References:

  [Knyazev2001] Andrew V. Knyazev. (2001) Toward the Optimal
  Preconditioned Eigensolver: Locally Optimal Block Preconditioned
  Conjugate Gradient Method. SIAM J. Sci. Comput., 23(2),
  517-541. (25 pages)
  https://epubs.siam.org/doi/abs/10.1137/S1064827500366124

  [StathopoulosEtal2002] Andreas Stathopoulos and Kesheng
  Wu. (2002) A Block Orthogonalization Procedure with Constant
  Synchronization Requirements. SIAM J. Sci. Comput., 23(6),
  2165-2182. (18 pages)
  https://epubs.siam.org/doi/10.1137/S1064827500370883

  [DuerschEtal2018] Jed A. Duersch, Meiyue Shao, Chao Yang, Ming
  Gu. (2018) A Robust and Efficient Implementation of LOBPCG.
  SIAM J. Sci. Comput., 40(5), C655-C676. (22 pages)
  https://epubs.siam.org/doi/abs/10.1137/17M1129830

N)r=   ro   rp   rq   rr   rs   rt   r\   ru   rv   rw   rx   ry   r&   zScript and require grads is not supported atm.If you just want to do the forward, use .detach()on A and B before calling into lobpcg)r   jitis_scriptingsetmaptypeissubsetr   r   r   r   _jit_internalr,   r   rm   applyRuntimeErrorr~   )r   r=   ro   rp   rq   rr   rs   rt   r\   ru   rv   rw   rx   ry   
tensor_opsA_symB_syms                    r"   r   r   Y  s   @ 99!!##A]
3tZ()22\\4:&
 
 ,,(+++! & ++--??q} XNE'(}QXN4E)// " ??q}8  					
 r$   c                 x
   U R                   S   U R                   S   :X  d   U R                   5       eUb7  U R                   UR                   :X  d   U R                   UR                   45       e[        R                  " U 5      nU R                  nUc*  [        R
                  S[        R                  S0U   nUS-  nU R                   S   nUc  Uc  SOUR                   S   OUnUc  Uc  UOUOUR                   S   nUSU-  :  a  [        SU S	U S
35      eU	c  SOU	n	UUUUc  SOUS.nSU0nSUc  SOU0nU	S:X  a  Ub  UR                  U5        Ub  UR                  U5        Ub  UR                  U5        UR                  SS5      US'   UR                  SS5      US'   UR                  SU5      US'   UR                  SU5      US'   UR                  SU5      US'   UR                  SS5      US'   [        R                  R                  5       (       d  [        [        l        [        U R                   5      S:  Ga'  [!        [        R"                  " [        R$                  " U R                   S S 5      5      5      nU R'                  U4U R                   SS  -   5      nUb"  UR'                  U4U R                   SS  -   5      OS nUb"  UR'                  U4UR                   SS  -   5      OS n[        R(                  " UU4XS9n[        R(                  " UUU4XS9n[+        U5       H  nUU   nUb  UU   OS nUc  [        R,                  " UU4XS9OUU   n[        UR                   5      S:X  a  UR                   UU4:X  d   UR                   UU445       eUUS'   [        UUUUUUUX5	      nUR/                  5         UR0                  S U UU'   UR2                  S S 2S U24   UU'   M     [        R                  R                  5       (       d  [4        [        l        UR'                  U R                   S S U4-   5      UR'                  U R                   S S UU4-   5      4$ Uc  [        R,                  " UU4XS9OUn[        UR                   5      S:X  a  UR                   UU4:X  d   UR                   UU445       e[        XX5UUUX5	      nUR/                  5         [        R                  R                  5       (       d  [4        [        l        UR0                  S U UR2                  S S 2S U24   4$ )Nr
   r   g+i)+>g(ƹ<g      ?r'      z?LPBPCG algorithm is not applicable when the number of A rows (=z;) is smaller than 3 x the number of requested eigenpairs (=)orthoi  )mrq   r=   rs   rt   r\   Tortho_i_maxortho_j_max	ortho_tolortho_tol_droportho_tol_replaceortho_use_dropFr&   rF   batch_index)r(   _utilsget_floating_dtyperH   r   float32float64r   updategetr   r   LOBPCG_call_trackerLOBPCGcall_trackerrK   r   prodtensorreshapeemptyr+   rX   runErp   LOBPCG_call_tracker_orig) r   r=   ro   rp   rq   rr   rs   rt   r\   ru   rv   rw   rx   ry   rG   rH   fepsr   iparamsfparamsbparamsNbAbBbXbEbXretr3   A_B_X_workers                                    r"   r~   r~   F  s   " 772;!''"+%.qww.%}ww!''!5AGGQWW#55!%%a(EXXF
{wx@GCi	A-.YaiQWWR[AA#$9aiQ!''"+A1q5yMaS QIIJ1N
 	

 WFF E	G 	sG '/$w?G$NN=)$NN=)$NN=)!(]A!>!(]A!>&{{;<$+KK0@#$F !'.{{3F'L#$$+KK0@%$H !99!!##1
177|a

5<<567YYtaggbcl*+/0}QYYtaggbcl*+$/0}QYYtaggbcl*+$[[!Qu<Q1IUBqAAB.AdBCE:QF%?SUVWSX  rxx=A%"((q!f*<Prxx!Q>PP<%&GM"BBGWgvWFJJLHHRaLBqExx2A2E!H  yy%%''":Fzz!''#2,!-.aggcrlaQRV>S0TTT;<9QF%7!Aqww<1QF!2EQWWq!f4EE2A!'7FLF
JJL99!!##688BQ<!RaR%((r$   c                      \ rS rSrSrS\\   S\\   S\S\\   S\\\	4   S\\\
4   S	\\\4   S
\SSSS4S jrS rS rS rS rS rS r\R(                  R*                  S 5       rS rS rS rS\S\S\
S\4S jrS rSrg)r   i  zWorker class of LOBPCG methods.r   ro   rp   rr   r   r   r   ru   rv   Nrz   c
                    Xl         X l        X@l        XPl        X`l        Xpl        Xl        Xl        US   n
US   nX0l        [        R                  " U4UR                  UR                  S9U l        [        R                  " X4UR                  UR                  S9U l        [        R                  " U
SU-  4UR                  UR                  S9U l        0 U l        SS0U l        SS0U l        SS	0U l        g )
Nr   rq   rF   r   istepr   _        F)r   ro   rr   r   r   r   ru   rv   rp   r   zerosrG   rH   r   RStvarsivarsfvarsbvars)selfr   ro   rp   rr   r   r   r   ru   rv   r   rq   s               r"   __init__LOBPCG.__init__  s     CLCL aTBaV177188DaQZqwwqxxH(*
&-q\
(+Sz
'*El
r$   c                    S/nUSU R                    3/-  nUSU R                   3/-  nUSU R                   3/-  nUSU R                   3/-  nUSU R                   3/-  nUSU R
                   3/-  nUSU R                   3/-  nUS	U R                   3/-  nUS
U R                   3/-  nUSU R                   3/-  nUSU R                   3/-  nUSU R                   3/-  nSnU H
  nX#S-   -  nM     U$ )NzLOPBCG:z
  iparams=z
  fparams=z
  bparams=z  ivars=z  fvars=z  bvars=z  tvars=z  A=z  B=z  iK=z  X=z  E= 
)r   r   r   r   r   r   r   r   ro   rr   rp   r   )r   linesrlines       r"   __str__LOBPCG.__str__  sE   Jt||n-..Jt||n-..Jt||n-..HTZZL)**HTZZL)**HTZZL)**HTZZL)**D/""D/""E$''#$$D/""D/""DA r$   c                 Z   U R                   S   S:X  Ga(  [        [        R                  " U R                  5      5      nUS-  n[        [        R                  " [
        R                  " U R                  U R                  5      5      5      U-  n[        [        R                  " [
        R                  " U R                  U R                  5      5      5      U-  nXR                  S'   X0R                  S'   X@R                  S'   U R                  S   U R                   S'   SU R                   S	'   SU R                   S
'   U R                  S:X  a  U R                  5         OU R                  5         U R                   S   S-
  U R                   S'   U R                   S   S-   U R                   S'   g)z#Set and update iteration variables.r   r   r   X_normA_normB_normrs   iterations_leftconverged_countconverged_endr   r'   N)r   r   r   normrp   r   r   r   ro   r   r   ru   _update_ortho_update_basic)r   r   iX_normr   r   s        r"   r   LOBPCG.update  s@   ::g!#5::dff-.FbjG5::fmmDFFDFF&CDEOF5::fmmDFFDFF&CDEOF#)JJx #)JJx #)JJx ,0LL,ADJJ(),-DJJ()*+DJJ';;'!  (,

3D(E(I

$%"jj1A5

7r$   c                     [         R                  nU" U R                  U R                  5      U" U R                  U R                  5      U R
                  -  -
  U l        g)z"Update residual R from A, B, X, E.N)r   r   r   rp   ro   r   r   )r   mms     r"   update_residualLOBPCG.update_residual  s>    ]]DFFDFF#b&8466&AAr$   c                 
   U R                   S   nU R                  S   nU R                  S   nU R                  S   nU R                  U R                  U R
                  pvn[        R                  " USS5      [        R                  " USS5      X5SUR                  S    U-  -   -  S-  -  nUR                  U:  n	S	n
U	 H  nU(       d    O	U
S
-  n
M     X:  d   SU SU
 S35       eXR                   S'   XR                  S'   U
$ )zDetermine the number of converged eigenpairs using backward stable
convergence criterion, see discussion in Sec 4.3 of [DuerschEtal2018].

Users may redefine this method for custom convergence criteria.
r   rt   r   r   r&   )r   Nr   r   r'   z(the number of converged eigenpairs (was z, got z) cannot decreasererr)r   r   r   r   rp   r   r   r   r(   realr   )r   
prev_countrt   r   r   r   rp   r   r   	convergedcountbs               r"   update_converged_countLOBPCG.update_converged_count  s    ZZ 12
ll5!H%H%&&$&&$&&aJJq!T"zz!Q%Maggbk2BV2K)KLQSST 	 IIO	A QJE  " 	
6zl&O`a	
" ).

$%!

6r$   c                     U R                   R                  SS5      =(       d8    U R                  S   S:H  =(       d    U R                  S   U R                  S   :  $ )zReturn True to stop iterations.

Note that tracker (if defined) can force-stop iterations by
setting ``worker.bvars['force_stop'] = True``.

force_stopFr   r   r   r=   )r   r   r   r   r   s    r"   stop_iterationLOBPCG.stop_iteration%  sT     JJNN</ Bzz+,1Bzz+,S0AA	
r$   c                    U R                  5         [        R                  R                  5       (       d  U R                  b  U R                  5         U R                  5       (       dh  U R                  5         [        R                  R                  5       (       d  U R                  b  U R                  5         U R                  5       (       d  Mg  gg)zRun LOBPCG iterations.

Use this method as a template for implementing LOBPCG
iteration scheme with custom tracker that is compatible with
TorchScript.
N)r   r   r   r   rv   r   r  r  s    r"   r   
LOBPCG.run1  s     	yy%%''DLL,D%%''KKM99))++0H!!#	 %%''r$   c                     g)zInterface for tracking iteration process in Python mode.

Tracking the iteration process is disabled in TorchScript
mode. In fact, one should specify tracker=None when JIT
compiling functions using lobpcg.
Nr   r  s    r"   r   LOBPCG.call_trackerC  s    r$   c                    [         R                  nU R                  S   nU R                  S   nU R                  S   nU R                  S   nU R                  S   S:X  GaK  U R                  U R                  5      n[        R                  " [        R                  " U R                  U R                  5      U5      n[        R                  " Xu5      u  pU" U R                  U" Xi5      5      U R                  SS& XR                  SS& Sn
U R                  5         U R                  5       nU R                  U R                  SSU24'   [        R                  " U R                  U R                   5      nXJ-   UR"                  S	   -   =U R                  S'   nXR                  SS2XJ-   U24'   gU R                  SS2X224   nU R                  U5      n[        R                  " [        R                  " U R                  U5      U5      n[        R                  " Xu5      u  pU" X" XiSS2SXC-
  24   5      5      U R                  SS2US24'   USXC-
   U R                  US& U" X" XiSS2US
U-  U-
  24   5      5      nUR"                  S	   n
U R                  5         U R                  5       nU R                  U R                  SSU24'   XR                  SS2XDU
-   24'   [        R                  " U R                  U R                   SS2US24   5      nXJ-   UR"                  S	   -   =U R                  S'   nXR                  SS2XJ-   U24'   g)zD
Update or initialize iteration variables when `method == "basic"`.
r   r   rq   r\   r   r   N.r   r&   )r   r   r   r   r   _get_rayleigh_ritz_transformrp   r   qformr   symeigr   r   r  r   rr   r   r(   )r   r   nsncrq   r\   RiMr   ZnpWS_E_Ps                  r"   r   LOBPCG._update_basicO  s    \\ZZ(ZZ)*LL,,y)::g!#22466:BV\\$&&$&&92>A==,DA4662b9-DFF1IFF1IB  ",,.B"ffDFF37Odggtvv.A/0v/CCDJJ'"%&FF1afrk>"25!B2226BV\\$&&"5r:AMM!-EBBrQ!&[>$:;DFF1bc6NXqv,DFF23K2r"1q1urz> 1234AB  ",,.B"ffDFF37O$%FF1ab&j=!dggtvvaf~6A/0v/CCDJJ'"%&FF1afrk>"r$   c                 h   [         R                  nU R                  S   nU R                  S   nU R                  S   nU R                  S   nU R                  S   S:X  Ga1  U R                  U R                  5      n[        R                  " [        R                  " U R                  U R                  5      U5      n[        R                  " Xu5      u  pU" U R                  U" Xi5      5      U l        U R                  5         Sn
U R                  5       nU R                  U R                  SS2SU24'   U R                  U R                  U R                  5      nXJ-   UR                   S   -   =o R                  S'   XR                  SS2XJ-   U24'   gU R                  SS2X224   n[        R                  " [        R                  " U R                  U5      U5      u  pU" XSS2SXC-
  24   5      U R                  SS2US24'   USXC-
   U R"                  US& U" X" U	SS2XC-
  S24   [        R$                  " U	SXC-
  2XC-
  S24   R&                  5      5      5      nUR                   S   n
U R                  5         U R                  5       nU R                  U R                  SS2SU24'   XR                  SS2XDU
-   24'   U R                  U R                  SS2US24   U R                  SS2SXJ-   24   5      nXJ-   UR                   S   -   =o R                  S'   XR                  SS2XJ-   U24'   g)	zD
Update or initialize iteration variables when `method == "ortho"`.
r   r   rq   r\   r   r   Nr   )r   r   r   r   r   r  rp   r   r  r   r  r   r  r   
_get_orthor   r(   r   basisr   )r   r   r  r  rq   r\   r  r  _Er  r  r  r  r  r  s                  r"   r   LOBPCG._update_orthoz  s    \\ZZ(ZZ)*LL,,y)::g!#22466:BV\\$&&$&&92>AMM!-EB2	*DF  "B,,.B FFDFF1bqb5M/A/0v/CCBO,%&FF1afrk>" 25!BMM&,,tvvr":GDEB  a16kN3DFF1bc6NXqv,DFF23K2r!AqvxK.&,,q161689K7L7O7O*PQRAB   ",,.B !FFDFF1bqb5M$%FF1ab&j=!q"#vq(AF({0CDA/0v/CCBO,%&FF1afrk>"r$   c                 P   U R                   n[        R                  " X!5      nUR                  SSS5      S-  nUR	                  UR
                  S   S5      n[        R                  R                  X4-  U-  SS9n[        R                  R                  XdR                  5       SSS	9$ )
a  Return a transformation matrix that is used in Rayleigh-Ritz
procedure for reducing a general eigenvalue problem :math:`(S^TAS)
C = (S^TBS) C E` to a standard eigenvalue problem :math: `(Ri^T
S^TAS Ri) Z = Z E` where `C = Ri Z`.

.. note:: In the original Rayleight-Ritz procedure in
  [DuerschEtal2018], the problem is formulated as follows::

    SAS = S^T A S
    SBS = S^T B S
    D = (<diagonal matrix of SBS>) ** -1/2
    R^T R = Cholesky(D SBS D)
    Ri = D R^-1
    solve symeig problem Ri^T SAS Ri Z = Theta Z
    C = Ri Z

  To reduce the number of matrix products (denoted by empty
  space between matrices), here we introduce element-wise
  products (denoted by symbol `*`) so that the Rayleight-Ritz
  procedure becomes::

    SAS = S^T A S
    SBS = S^T B S
    d = (<diagonal of SBS>) ** -1/2    # this is 1-d column vector
    dd = d d^T                         # this is 2-d matrix
    R^T R = Cholesky(dd * SBS)
    Ri = R^-1 * d                      # broadcasting
    solve symeig problem Ri^T SAS Ri Z = Theta Z
    C = Ri Z

  where `dd` is 2-d matrix that replaces matrix products `D M
  D` with one element-wise product `M * dd`; and `d` replaces
  matrix product `D M` with element-wise product `M *
  d`. Also, creating the diagonal matrix `D` is avoided.

Args:
S (Tensor): the matrix basis for the search subspace, size is
            :math:`(m, n)`.

Returns:
Ri (tensor): upper-triangular transformation matrix of size
             :math:`(n, n)`.

r   r
   r         r'   T)upperF)r"  left)ro   r   r  r   r   r(   r   rY   rZ   solve_triangularr   )r   r   ro   SBSd_rowd_colr   s          r"   r  #LOBPCG._get_rayleigh_ritz_transform  s    Z FFll1 QB'4/ekk!na0LL!!3;%"7t!D||,,!E - 
 	
r$   r   droptauc                 v   [         R                  " U5      S:X  a  U$ [        R                  " U R                  U5      nUR                  SSS5      n[         R                  " [        U5      S:g  5      n[        U5      S:X  d   U5       e[        US   5      [        U5      :  a  USS2US   4   n[         R                  " U5      S:X  a  U$ [        R                  " U R                  U5      nUR                  SSS5      n[         R                  " [        U5      S:g  5      n[        US   5      [        U5      :X  d   eUS-  R                  UR                  S   S5      nXG-  UR                  -  n[        R                  " U5      u  pU[        U	5      R                  5       -  nU(       aI  [         R                  " X:  5      n[        U5      S:X  d   U5       eXS      n	U
SS2US   4   n
X|S      nOX[         R                  " X:  5      S   '   [         R                  " XR                  -  XS-  -  5      $ )ak  Return B-orthonormal U.

.. note:: When `drop` is `False` then `svqb` is based on the
          Algorithm 4 from [DuerschPhD2015] that is a slight
          modification of the corresponding algorithm
          introduced in [StathopolousWu2002].

Args:

  U (Tensor) : initial approximation, size is (m, n)
  drop (bool) : when True, drop columns that
             contribution to the `span([U])` is small.
  tau (float) : positive tolerance

Returns:

  U (Tensor) : B-orthonormal columns (:math:`U^T B U = I`), size
               is (m, n1), where `n1 = n` if `drop` is `False,
               otherwise `n1 <= n`.

r   r
   r   r   r'   Nr!  )r   numelr   r  ro   r   whereabsrK   r   r(   r   r  maxr   )r   r   r)  r*  UBUdnzr'  DUBUDr   r  tkeeps                r"   	_get_svqbLOBPCG._get_svqb  s   , ;;q>QHll4661%LLB# [[Q3'2w!|R|r!u:A!RU(A{{1~",,tvvq)CQB'ASVs]+Br!u:Q''' D!!!''!*a0(}}U##a&**,;;qu%Dt9>'4'>q'
A!T!W*Aq'NE)*u{{15!1%&||AL!g+66r$   c           
      *   [         R                  n[        R                  nU R                  S   nU R                  S   nU R                  S   nU R                  S   nU R                  S   n	U R                  S   n
U R
                  S   n[        U R                  R                  5       5       HN  nUR                  S5      (       d  M  UR                  S	5      (       d  M3  U R                  R                  U5        MP     U R                  R                  S
S5        U R                  R                  SS5        [         R                  " U" U R                  U5      5      nU" U R                  U5      nU" UR                  U5      nS=nn[!        U	5       GH]  nX" X/5      -
  nSnUn[!        U
5       GHS  nU(       a  U R#                  UUU5      nSnUnOU R#                  USU5      n[         R$                  " U5      S:X  a$  UU R                  S
'   UU R                  S'   Us  s  $ U" U R                  U5      nU" UR                  U5      n[         R                  " U5      n[         R                  " U5      nU[         R&                  " UR(                  S   UR*                  UR,                  S9-
  n[         R                  " U5      n[/        U5      [/        UU-  5      S-  -  nSU SU S3nUU R                  U'   UU:  d  GMT    O   U" UR                  U5      n[         R                  " U5      n[         R                  " U5      n[/        U5      [/        UU-  5      S-  -  nSU S3nUU R                  U'   UU:  a    OtXQR(                  S   UR(                  S   -   :  d  GM  U R                  nUc   e[1        SUR(                  S    SUR(                  S    SUR(                  S    S35      e   UU R                  S
'   UU R                  S'   U$ )aA  Return B-orthonormal U with columns are B-orthogonal to V.

.. note:: When `bparams["ortho_use_drop"] == False` then
          `_get_ortho` is based on the Algorithm 3 from
          [DuerschPhD2015] that is a slight modification of
          the corresponding algorithm introduced in
          [StathopolousWu2002]. Otherwise, the method
          implements Algorithm 6 from [DuerschPhD2015]

.. note:: If all U columns are B-collinear to V then the
          returned tensor U will be empty.

Args:

  U (Tensor) : initial approximation, size is (m, n)
  V (Tensor) : B-orthogonal external basis, size is (m, k)

Returns:

  U (Tensor) : B-orthonormal columns (:math:`U^T B U = I`)
               such that :math:`V^T B U=0`, size is (m, n1),
               where `n1 = n` if `drop` is `False, otherwise
               `n1 <= n`.
r   r   r   r   r   r   r   ortho__rerrortho_ir   ortho_jFTr   )rH   rG   zortho_UBUmI_rerr[z, ]zortho_VBU_rerr[z$Overdetermined shape of U: #B-cols(=z) >= #U-cols(=z) + #V-cols(=z) must hold)r   r   r   r   r   r   r)   r   keys
startswithendswithpopr   r   ro   r   r+   r6  r,  rI   r(   rH   rG   r   r   )r   r   Vr   mm_Br   	tau_orthotau_droptau_replacei_maxj_maxuse_dropvkeyBV_normBUVBUr3   jr)  tau_svqbr0  U_normBU_normr   R_normr   VBU_normro   s                               r"   r  LOBPCG._get_ortho  s   2 \\}}LLLL-	<< 01ll#67]+]+ << 01 *+Dx((T]]7-C-C

t$ , 	

y!$

y!$**T$&&!_-$&&!_rl	AuABqJADH5\q$9AD*Hq%=A;;q>Q&,-DJJy),-DJJy)H$&&!_rlA**R.%))CIIbM#**CIIVVAV}uWv-='>"'DD*1#Rs!4#'

4 )#/ "0 QTT2,Czz#HZZ]F?U7V+;%<%BBD$QCq)D#DJJti772;,, FF}$} !!"^AGGBK=VWV]V]^`VaUbbmo S Z !"

9 !

9r$   )r   ro   r   r   r   rp   r   r   r   r   rr   r   r   ru   rv   r   )r   r   r   r   __doc__r   r   r   r   r   r   r   r   r   r   r   r  r  r   r   r   unusedr   r   r   r  r6  r  r   r   r$   r"   r   r     s   ) 3F 3 F 3 	 3
 V 3 c3h 3 c5j! 3 c4i 3  3  3 
 3D&6,B
>

$$ YY )'V+'Z5
n;76 ;7 ;7E ;7f ;7z_r$   r   c                 &    U R                  U 5        g r|   )rv   r  s    r"   r   r     s    LLr$   r|   r   )!rU  typingr   r   r   r   r   torch.overridesr   r   __all__r#   r6   r>   rM   rT   ri   rk   autogradFunctionrm   r   r   r   r   r   r   r   r~   r   r   r   r   r   r$   r"   <module>r]     s   F   1 E *'5T>>(>"hVUVU^^44 Vv " .204/3jj}j j 	j
 }j 	j C=j 
%j d^j SMj j DcN+j De,-j DdO,j 66>j^ " .204/3j)j)}j) j) 	j)
 }j) 	j) C=j) 
%j) d^j) SMj) j) DcN+j) De,-j) DdO,j) 66>j)ZG GX ".. r$   