
    Pg              !          d Z ddlmZmZmZ ddlZddlmZmZ ddl	m
Z
mZ dgZd Zd Zd	 Zd$d
Zd$dZd Zd Z G d dej(                  j*                        Z	 	 	 	 	 	 	 	 	 	 	 	 	 d%dedee   dee   dee   dee   dee   dee   dee   dee   dee   dddeeeef      deeeef      deeeef      deeef   fdZ	 	 	 	 	 	 	 	 	 	 	 	 	 d%dedee   dee   dee   dee   dee   dee   dee   dee   dee   dddeeeef      deeeef      deeeef      deeef   fd Z G d! d"      Zej<                  Zd# Z y)&z@Locally Optimal Block Preconditioned Conjugate Gradient methods.    )DictOptionalTupleN)_linalg_utilsTensor)handle_torch_functionhas_torch_functionlobpcgc           
         |j                  d      |j                  d      z
  }|j                  dd      j                  t        d             |j	                  d       |j
                  j                         }t        j                  |t        j                  t        j                  |       t        j                  ||      |z  z   |            }|S )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           T/var/www/html/suriana-translation/venv/lib/python3.12/site-packages/torch/_lobpcg.py$_symeig_backward_complete_eigenspacer%      s    	B!++b/)AJJBRJ &&uU|4FF2J 
	B
,,	5<<((05<<F3Ka3OOQSTC J    c           	         | j                   d   }t        | j                         }|dxx   dz  cc<   | j                  |      }d|d<   d|d<   t        d|dz         D ]q  }| j                  r|j                         n|}|j                  d||z
  |dz         }|| j                  d|dz
  d      |j                  d||z
  dz   |dz         z  z  }|}s |j                  dd|dz         S )ad  
    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_rootsr8      s    RJU[[) bQ//"34KKK 1j1n% & 271D1D+++-+$$RaQ?u||BAq)K,>,>
Q"AE-
 
 	
 &&" b!Z!^44r&   c                     |j                         }t        | j                  d      dz
  dd      D ]  } |||| d|f         } |S )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   sR    2 


C499R=1$b"- /ac1f./Jr&   c                 h   d }| t        j                  |j                  d      |j                  d      |j                  |j                        j
                  g dgt        t        |j                  dd             z  |j                  d      |j                  d       }t        | |||      S )z~
    Evaluates `poly(x)` for the (batched) matrix input `x`.
    Check out `_polynomial_value` function for more details.
    c                     |j                  |       }|j                  dd      j                  |j                  d             |S )Nr   r   r   )r   r   add_r   curr_poly_valr<   
poly_coeffr#   s       r$   r>   z,_matrix_polynomial_value.<locals>.transitiono   s;    hh}%"2&++J,@,@,DE
r&   Nr   dtypedevicer)   r   )
r   eyer:   rH   rI   viewlenr+   r*   r@   r;   r<   r=   r>   s       r$   _matrix_polynomial_valuerN   h   s    
 UYYFF2Jr
!''!((

$Is4-..I12I=>VVBZI
 T1j*==r&   c                 |    d }|*|j                  d      j                  |j                        }t        | |||      S )z~
    Evaluates `poly(x)` for the (batched) vector input `x`.
    Check out `_polynomial_value` function for more details.
    c                 R    t        j                  |j                  d      ||       }|S )Nr   )r   addcmulr   rD   s       r$   r>   z,_vector_polynomial_value.<locals>.transition   s$    mmJ004aG
r&   r)   )new_onesexpandr*   r@   rM   s       r$   _vector_polynomial_valuerT   |   s<     ZZ]))!''2
T1j*==r&   c           	      t   |j                   j                         }|j                  |       }|j                  dd      j	                  d       t        j                  |j                        }|j                  t        j                  g |j                  d d |j                  d      |j                  d      z
  |j                  |j                  |            }	|	j                   j                         }
t        |      }|}|j                  |j                        }t        d|j                  d            D ]=  }t        |d|d f   |      }|||j!                  d      z  z  }|j                  |      }? t#        ||      }t        j                  |
t        j                  ||	            }|r
dz  dk(  rdnd}t
        j$                  j'                  ||z        }t)        | ||||      }||	j                  |t        j*                  |
j                  |      |      z        j                  |      z  }|S )Nr   r   r   r)   )rH   rI   	generator.r(   )r   r   r   r   rC   r   	GeneratorrI   randnr*   r:   rH   r8   r,   r-   rT   r   rN   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)* 6)*S!"W*=qA&)9)9")===
88$456 /z1=O "'5<<9" .5!a%1*bB##(<<#8#8'*DD$ 
 /vvq!Q
GC 7>>'


Z(*F
	

 fRjC Jr&   c                     |j                  d      |j                  d      k(  rt        | ||||      S t        | |||||      S )Nr   r   )r:   r%   ri   )r   r   r   r   r    r\   s         r$   _symeig_backwardrk      sB    vvbzQVVBZ3FFAq!LL2661aGTTr&   c            "           e Zd Ze	 	 	 	 	 	 	 	 	 	 	 	 	 ddedee   dee   dee   dee   dee   dee   d	ee   d
ee   dee	   dddee
e	ef      dee
e	ef      dee
e	ef      deeef   fd       Zed        Zy)LOBPCGAutogradFunctionNr   r?   BXniKnitertolr\   methodtrackerortho_iparamsortho_fparamsortho_bparamsreturnc                     |j                   s|j                         n|}||j                   s|j                         n|}t        |||||||||	|
||||      \  }}| j                  ||||       |	| _        ||fS N)	is_sparser   _lobpcgsave_for_backwardr\   )ctxr   r?   rn   ro   rp   rq   rr   rs   r\   rt   ru   rv   rw   rx   r   r    s                    r$   forwardzLOBPCGAutogradFunction.forward  s    ( $%;;ALLNQ='({{A
1" 	aAq)!tr&   c                    d x}}d gdz  }| j                   \  }}}}	| j                  }
|j                  s|&|j                  r| j                  d   rt	        d      |j
                  t        j                  t        j                  fv s.|7|j
                  t        j                  t        j                  fv rt	        d      |t	        d      |
d}
|t        |||||	|
      }||d<   ||d<   t        |      S )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
ValueErrorrH   r   	complex64
complex128rk   tuple)r   r   r   A_gradB_gradgradsr   rn   r   r    r\   s              r$   backwardzLOBPCGAutogradFunction.backward/  s   &&
1a++ ;;1=Q[[S=Q=QRS=T8 
 GG)9)9::}EOOU-=-=>>8  =L  ?G 9%ffaAwGF aaU|r&   NNNNNNNNNNNNN)__name__
__module____qualname__staticmethodr   r   intr   boolstrr   r   r   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?   rn   ro   rp   rq   rr   rs   r\   rt   ru   rv   rw   rx   ry   c                    t         j                  j                         sq| |||f}t        t	        t
        |            j                  t         j                  t        d      f      s*t        |      rt        t        || |||||||||	|
|||      S t         j                  j                         sd| j                  s|{|j                  ro| | j                  z   dz  }|||j                  z   dz  nd}t        j                  ||||||||||	|
|||      S | j                  s||j                  rt!        d      t#        | |||||||||	|
|||      S )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?   rn   ro   rp   rq   rr   rs   r\   rt   ru   rv   rw   rx   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?   rn   ro   rp   rq   rr   rs   r\   rt   ru   rv   rw   rx   
tensor_opsA_symB_syms                    r$   r
   r
   Y  s{   @ 99!!#Ar]
3tZ()22\\4:&
 ,(+++! & ++-??q} XNE'(}QXN4E)// " ??q}8  					
 r&   c                 <
   | j                   d   | j                   d   k(  sJ | j                          |6| j                   |j                   k(  sJ | j                   |j                   f       t        j                  |       }| j                  }|*t        j
                  dt        j                  di|   }|dz  }| j                   d   }||dn|j                   d   n|}|||n|n|j                   d   }|d|z  k  rt        d| d	| d
      |	dn|	}	||||dn|d}d|i}d|dn|i}|	dk(  r||j                  |       ||j                  |       ||j                  |       |j                  dd      |d<   |j                  dd      |d<   |j                  d|      |d<   |j                  d|      |d<   |j                  d|      |d<   |j                  dd      |d<   t        j                  j                         st        t        _        t        | j                         dkD  r"t!        t	        j"                  t	        j$                  | j                   d d                   }| j'                  |f| j                   dd  z         }|"|j'                  |f| j                   dd  z         nd }|"|j'                  |f|j                   dd  z         nd }t	        j(                  ||f||      }t	        j(                  |||f||      }t+        |      D ]  }||   }|||   nd }|t	        j,                  ||f||      n||   }t        |j                         dk(  r|j                   ||fk(  sJ |j                   ||ff       ||d<   t        ||||||||	|
	      }|j/                          |j0                  d | ||<   |j2                  d d d |f   ||<    t        j                  j                         st4        t        _        |j'                  | j                   d d |fz         |j'                  | j                   d d ||fz         fS |t	        j,                  ||f||      n|}t        |j                         dk(  r|j                   ||fk(  sJ |j                   ||ff       t        | |||||||	|
	      }|j/                          t        j                  j                         st4        t        _        |j0                  d | |j2                  d d d |f   fS )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  )mrp   r?   rr   rs   r\   Tortho_i_maxortho_j_max	ortho_tolortho_tol_droportho_tol_replaceortho_use_dropFr(   rG   batch_index)r*   _utilsget_floating_dtyperI   r   float32float64r   updategetr   r   LOBPCG_call_trackerLOBPCGcall_trackerrL   r   prodtensorreshapeemptyr-   rX   runEro   LOBPCG_call_tracker_orig) r   r?   rn   ro   rp   rq   rr   rs   r\   rt   ru   rv   rw   rx   rH   rI   fepsr   iparamsfparamsbparamsNbAbBbXbEbXretr5   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uV<Q1IU6Bq 	'AAB.AdBCE:QF%?SUVWSX  rxx=A%"((q!f*<Prxx!Q>PP<%&GM"BBGWgvw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Aq!R'7FGLF
JJL99!!#688BQ<!RaR%((r&   c                       e Zd ZdZdee   dee   dedee   deeef   deee	f   deee
f   d	ed
dddfdZd Zd Zd Zd Zd Zd Zej&                  j(                  d        Zd Zd Zd Zdede
de	defdZd Zy)r   zWorker class of LOBPCG methods.r   rn   ro   rq   r   r   r   rt   ru   Nry   c
                    || _         || _        || _        || _        || _        || _        || _        |	| _        |d   }
|d   }|| _        t        j                  |f|j                  |j                        | _        t        j                  |
|f|j                  |j                        | _        t        j                  |
d|z  f|j                  |j                        | _        i | _        ddi| _        ddi| _        dd	i| _        y )
Nr   rp   rG   r   istepr   _        F)r   rn   rq   r   r   r   rt   ru   ro   r   zerosrH   rI   r   RStvarsivarsfvarsbvars)selfr   rn   ro   rq   r   r   r   rt   ru   r   rp   s               r$   __init__zLOBPCG.__init__  s     CLCL aTBaV177188DaQZqwwqxxH(*
&-q\
(+Sz
'*El
r&   c                    dg}|d| j                    gz  }|d| j                   gz  }|d| j                   gz  }|d| j                   gz  }|d| j                   gz  }|d| j
                   gz  }|d| j                   gz  }|d	| j                   gz  }|d
| j                   gz  }|d| j                   gz  }|d| j                   gz  }|d| j                   gz  }d}|D ]
  }||dz   z  } |S )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   rn   rq   ro   r   )r   linesrlines       r$   __str__zLOBPCG.__str__  sL   Jt||n-..Jt||n-..Jt||n-..HTZZL)**HTZZL)**HTZZL)**HTZZL)**D/""D/""E$''#$$D/""D/"" 	DA	r&   c                 R   | j                   d   dk(  r&t        t        j                  | j                              }|dz  }t        t        j                  t        j                  | j                  | j                                    |z  }t        t        j                  t        j                  | j                  | j                                    |z  }|| j                  d<   || j                  d<   || j                  d<   | j                  d   | j                   d<   d| j                   d	<   d| j                   d
<   | j                  dk(  r| j                          n| j                          | j                   d   dz
  | j                   d<   | j                   d   dz   | j                   d<   y)z#Set and update iteration variables.r   r   r   X_normA_normB_normrr   iterations_leftconverged_countconverged_endr   r)   N)r   r   r   normro   r   r   r   rn   r   r   rt   _update_ortho_update_basic)r   r   iX_normr   r   s        r$   r   zLOBPCG.update  sF   ::g!#5::dff-.FbjG5::fmmDFFDFF&CDEOF5::fmmDFFDFF&CDEOF#)DJJx #)DJJx #)DJJx ,0LL,ADJJ(),-DJJ()*+DJJ';;'!  (,

3D(E(I

$%"jj1A5

7r&   c                     t         j                  } || j                  | j                         || j                  | j                        | j
                  z  z
  | _        y)z"Update residual R from A, B, X, E.N)r   r   r   ro   rn   r   r   )r   mms     r$   update_residualzLOBPCG.update_residual  s>    ]]DFFDFF#b&8466&AAr&   c                     | j                   d   }| j                  d   }| j                  d   }| j                  d   }| j                  | j                  | j
                  }}}t        j                  |dd      t        j                  |dd      ||d|j                  d    |z  z   z  dz  z  }|j                  |k  }	d	}
|	D ]  }|s n|
d
z  }
 |
|k\  sJ d| d|
 d       |
| j                   d<   || j                  d<   |
S )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   rs   r   r   r(   )r   Nr   r   r)   z(the number of converged eigenpairs (was z, got z) cannot decreasererr)r   r   r   r   ro   r   r   r   r*   realr   )r   
prev_countrs   r   r   r   ro   r   r   	convergedcountbs               r$   update_converged_countzLOBPCG.update_converged_count  s'    ZZ 12
ll5!H%H%&&$&&$&&a1JJq!T"zz!Q%!Maggbk2BV2K)KLQSST 	 IIO	 	A QJE	 Z	a5j\wN_`	a(-

$%!

6r&   c                     | j                   j                  dd      xs3 | j                  d   dk(  xs | j                  d   | j                  d   k\  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_iterationzLOBPCG.stop_iteration%  sT     JJNN</ Bzz+,1Bzz+,S0AA	
r&   c                 p   | j                          t        j                  j                         s| j                  | j                          | j                         s\| j                          t        j                  j                         s| j                  | j                          | j                         s[yy)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   ru   r   r   r   s    r$   r   z
LOBPCG.run1  sz     	yy%%'DLL,D%%'KKM99))+0H!!#	 %%'r&   c                      y)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   zLOBPCG.call_trackerC  s    r&   c                    t         j                  }| j                  d   }| j                  d   }| j                  d   }| j                  d   }| j                  d   dk(  rN| j                  | j                        }t        j                  t        j                  | j                  | j                        |      }t        j                  ||      \  }}	 || j                   |||	            | j                  dd || j                  dd d}
| j                          | j                         }| j                  | j                  dd|f<   t        j                  | j                  | j                         }||
z   |j"                  d	   z   x| j                  d<   }|| j                  dd||
z   |f<   y| j                  dd||f   }| j                  |      }t        j                  t        j                  | j                  |      |      }t        j                  ||      \  }}	 || |||	ddd||z
  f               | j                  dd|df<   |d||z
   | j                  |d  || |||	dd|d
|z  |z
  f               }|j"                  d	   }
| j                          | j                         }| j                  | j                  dd|f<   || j                  dd|||
z   f<   t        j                  | j                  | j                   dd|df         }||
z   |j"                  d	   z   x| j                  d<   }|| j                  dd||
z   |f<   y)zT
        Update or initialize iteration variables when `method == "basic"`.
        r   r   rp   r\   r   r   N.r   r(   )r   r   r   r   r   _get_rayleigh_ritz_transformro   r   qformr   symeigr   r   r   r   rq   r   r*   r   r   nsncrp   r\   RiMr   ZnpWS_E_Ps                  r$   r   zLOBPCG._update_basicO  s    \\ZZ(ZZ)*LL,,y)::g!#22466:BV\\$&&$&&92>A==G,DAq4662b!9-DFF1IDFF1IB  ",,.B"ffDFF37Odggtvv.A/02v/CCDJJ'"%&DFF1a"frk>"2b5!B2226BV\\$&&"5r:AMM!W-EBBr1Q!b&[>$:;DFF1bc6NXq2v,DFF23K2r"a1q1urz> 1234AB  ",,.B"ffDFF37O$%DFF1a!b&j=!dggtvvaf~6A/02v/CCDJJ'"%&DFF1a"frk>"r&   c                    t         j                  }| j                  d   }| j                  d   }| j                  d   }| j                  d   }| j                  d   dk(  r5| j                  | j                        }t        j                  t        j                  | j                  | j                        |      }t        j                  ||      \  }}	 || j                   |||	            | _        | j                          d}
| j                         }| j                  | j                  ddd|f<   | j                  | j                  | j                        }||
z   |j                   d   z   x}| j                  d<   || j                  dd||
z   |f<   y| j                  dd||f   }t        j                  t        j                  | j                  |      |      \  }}	 |||	ddd||z
  f         | j                  dd|df<   |d||z
   | j"                  |d  || ||	dd||z
  df   t        j$                  |	d||z
  ||z
  df   j&                                    }|j                   d   }
| j                          | j                         }| j                  | j                  ddd|f<   || j                  dd|||
z   f<   | j                  | j                  dd|df   | j                  ddd||
z   f         }||
z   |j                   d   z   x}| j                  d<   || j                  dd||
z   |f<   y)	zT
        Update or initialize iteration variables when `method == "ortho"`.
        r   r   rp   r\   r   r   Nr   )r   r   r   r   r   r   ro   r   r   r   r  r   r   r   
_get_orthor   r*   r   basisr   r  s                  r$   r   zLOBPCG._update_orthoz  s    \\ZZ(ZZ)*LL,,y)::g!#22466:BV\\$&&$&&92>A==G,DAq2q	*DF  "B,,.B FFDFF1bqb5M/A/02v/CCBO,%&DFF1a"frk>" 2b5!BMM&,,tvvr":GDEB  Aa1r6kN3DFF1bc6NXq2v,DFF23K2r!Aq2vxK.&,,q1r61r689K7L7O7O*PQRAB   ",,.B !FFDFF1bqb5M$%DFF1a!b&j=!q"#vq(AF({0CDA/02v/CCBO,%&DFF1a"frk>"r&   c                    | j                   }t        j                  }t        j                  ||      }|j                  ddd      dz  }|j                  |j                  d   d      }t        j                  j                  ||z  |z  d      }t        j                  j                  ||j                         dd	      S )
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)rn   r   r   r   r   r   r   r*   rY   rZ   solve_triangularr   )r   r   rn   r   SBSd_rowd_colr   s           r$   r   z#LOBPCG._get_rayleigh_ritz_transform  s    Z FF\\ll1a QB'4/ekk!na0LL!!3;%"7t!D||,,u!E - 
 	
r&   r    droptauc                 ^   t        j                  |      dk(  r|S t        j                  | j                  |      }|j                  ddd      }t        j                  t        |      dk7        }t        |      dk(  sJ |       t        |d         t        |      k  r|dd|d   f   }t        j                  |      dk(  r|S t        j                  | j                  |      }|j                  ddd      }t        j                  t        |      dk7        }t        |d         t        |      k(  sJ |dz  j                  |j                  d   d      }||z  |j                  z  }t        j                  |      \  }	}
|t        |	      j                         z  }|rJt        j                  |	|kD        }t        |      dk(  sJ |       |	|d      }	|
dd|d   f   }
||d      }n||	t        j                  |	|k        d   <   t        j                  ||j                  z  |
|	dz  z        S )a  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   rn   r   whereabsrL   r   r*   r   r  maxr   )r   r    r  r  UBUdnzr  DUBUDr   r  tkeeps                r$   	_get_svqbz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(}}U#1#a&**,;;q1u%Dt9>'4'>$q'
A!T!W*A$q'NE)*Au{{1q5!1%&||AL!ag+66r&   c           
         t         j                  }t        j                  }| j                  d   }| j                  d   }| j                  d   }| j                  d   }| j                  d   }	| j                  d   }
| j
                  d   }t        | j                  j                               D ]A  }|j                  d      s|j                  d	      s'| j                  j                  |       C | j                  j                  d
d       | j                  j                  dd       t        j                   || j                  |            } || j                  |      } ||j                  |      }dx}}d}t!        |	      D ]O  }| |||      z
  }d}|}t!        |
      D ]I  }|r| j#                  |||      }d}|}n| j#                  |d|      }t        j$                  |      dk(  r$|| j                  d
<   || j                  d<   |c c S  || j                  |      } ||j                  |      }t        j                  |      }t        j                  |      }|t        j&                  |j(                  d   |j*                  |j,                        z
  }t        j                  |      }t/        |      t/        ||z        dz  z  }d| d| d}|| j                  |<   ||k  sJ n  ||j                  |      }t        j                  |      }t        j                  |      }t/        |      t/        ||z        dz  z  }d| d}|| j                  |<   ||k  r nq||j(                  d   |j(                  d   z   k  s| j                  }|J t1        d|j(                  d    d|j(                  d    d|j(                  d    d       || j                  d
<   || j                  d<   |S )a  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_jr   FTr   )rI   rH   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   rn   r   r-   r%  r  rJ   r*   rI   rH   r   r   )r   r    Vr   mm_Br   	tau_orthotau_droptau_replacei_maxj_maxuse_dropvkeyBV_normBUVBUr5   jstatsr  tau_svqbr  U_normBU_normr   R_normr   VBU_normrn   s                                r$   r  zLOBPCG._get_ortho  s   2 \\}}LLLL-	<< 01ll#67]+]+ << 01 *+ 	%Dx(T]]7-C

t$	% 	

y!$

y!$**T$&&!_-$&&!_rl	Au ,	ABq#J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1772;,, FF}$} !!"^AGGBK=VWV]V]^`VaUbbmo S,	Z !"

9 !

9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   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6
p;76 ;7 ;7E ;7f ;7z`r&   r   c                 &    | j                  |        y r{   )ru   r   s    r$   r   r     s    LLr&   r{   r   )!rC  typingr   r   r   r   r   r   r   torch.overridesr   r	   __all__r%   r8   r@   rN   rT   ri   rk   autogradFunctionrm   r   r   r   r   r
   r}   r   r   r   r   r   r&   r$   <module>rK     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I I\ ".. r&   