
    `i^                         d dl Z d dlZd dlZd dlmZ d dlmZ d Zd Zd Z	d Z
d Zd Zdd
Zd ZddZ	 	 	 	 ddZdS )    N)linalgc                     t           j                            |           }t          j        t          j        |                    rt
          j        j        |S )zk
    Wrapper around `cupy.linalg.cholesky` that raises LinAlgError if there are
    NaNs in the output
    )cupyr   choleskyanyisnannumpyLinAlgError)BRs     u/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/cupyx/scipy/sparse/linalg/_lobpcg.py	_choleskyr      sC    
 	QAx
1 'l&&H    c                 (   t          |           }t          | d                   }ddg}t          |          D ])}|dxx         | |         d         j        d         z  cc<   *t          |          D ])}|dxx         | d         |         j        d         z  cc<   *t          j        d | D              }t          d | D                       }t          d | D                       }|r|sdnd}	t          j        t          |          ||	          }
d}d}d}d}t          |          D ]i}|| |         d         j        d         z   }d}t          |          D ]7}|| |         |         j        d         z   }| |         |         |
||||f<   |}8|}j|
S )	ze
    Helper function to create a block matrix in cupy from a list
    of smaller 2D dense arrays
    r      c                 &    g | ]}|D ]	}|j         
S  dtype.0	list_iterarrs      r   
<listcomp>z_bmat.<locals>.<listcomp>%   sG     K K K(	K K9<  #y K K K Kr   c              3   :   K   | ]}|D ]}|j         d          V  dS )F_CONTIGUOUSNflagsr   s      r   	<genexpr>z_bmat.<locals>.<genexpr>(   Q       4 4	)24 4"% )N+ 4 4 4 4 4 4 4r   c              3   :   K   | ]}|D ]}|j         d          V  dS )C_CONTIGUOUSNr   r   s      r   r   z_bmat.<locals>.<genexpr>*   r    r   FC)r   order)lenrangeshaper   result_typeallemptytuple)list_objn_rowsn_colsfinal_shapeijr   F_orderC_orderr%   resultstart_idx_rowstart_idx_colend_idx_rowend_idx_cols                  r   _bmatr:      s   
 ]]F!Fa&K6]] 2 2A(1+a..q116]] 2 2A(1+a..q11 K K,4K K K LE  4 44 4 4 4 4G 4 44 4 4 4 4G373CCEZk**%uEEEFMMKK6]] $ $#hqk!n&:1&==v 	( 	(A'(1+a.*>q*AAK19!Q =, +-. /'MM#Mr   c                 |   | | j                                         z
  }t          j        |d          }dt	          j        | j                  j        z  }|t          dt          t          j        | d                              z  }||k    r0t          j        d| d| j         d| d| d	t          d	           d
S d
S )zA
    Report if `M` is not a hermitian matrix given its type.
    r   
   zMatrix z of the type z is not Hermitian: condition: z < z fails.   )
stacklevelN)Tconjr   normr   finfor   epsmaxfloatwarningswarnUserWarning)Mnamemdnmdtols        r   _report_nonhermitianrN   ?   s    
 
QSXXZZB
+b!

C
tz!'""&
&C3q%Aq))**+++C
Syy/d / / / // /"%/ / /A	' 	' 	' 	' 	' 	' yr   c                 t    | j         dk    r| S t          j        | d          }| 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.
       F)copyr   r   )ndimr   arrayr(   )arauxs     r   _as2drV   P   s?    
 
w!||	j%(((Xa[!$	
r   c                 j    | dS t          j        |           }|j        |k    rt          d          |S )zTakes a dense numpy array or a sparse matrix or
    a function and makes an operator performing matrix * blockvector
    products.
    Nzoperator has invalid shape)splinalgaslinearoperatorr(   
ValueError)operatorInputexpectedShapeoperators      r   _makeOperatorr^   ]   s@    
 t,];;~&&5666Or   c                     t          j        |j                                        |           }t	          j        ||          }| t          j        ||          z  } dS )zChanges blockVectorV in place.N)r   dotr?   r@   r   solve)blockVectorVYBYblockVectorBYblockVectorYYBVtmps         r   _applyConstraintsrh   m   sN    
(=?''))<
8
8C ,sC
 
 CDH\3///LLLr   Fc                    |                     d          t          j        |j                  j        z   }||z  }||  | |          }n|}n||z  }t          j        |j                                        |          }	 t          |          }t          j
        |j                  }t          j        ||          }| t          j        ||          }nd}n # t          j	        j        $ r	 d}d}d}Y nw xY w|r||||fS ||fS )z7B-orthonormalize the given block vector using Cholesky.r   )axisN)rD   r   rB   r   rC   matmulr?   r@   r   r   invr	   r
   )r   rb   blockVectorBVretInvRnormalizationVBVs         r   _b_orthonormalizerq   v   s4    $$ %  *\/0045M-/L=AlOOMM(MM%5
+ln))++]
;
;Cnnj{<55= Ks;;MM M<#      +]C>>]**s    AC C54C5c                 f    t          j        |           }|r|d| dz
  d         }n
|d|         }|S )z?Get `num` indices into `_lambda` depending on `largest` option.Nr   )r   argsort)_lambdanumlargestiis       r   	_get_indxry      sC    	g		B #"XIr   c                 d   |t          j        |           \  }}||fS t          |          }t          j        |          }t          j        |j                  }t          j        |t          j        | |                    }t          j        |          \  }}t          j        ||          }||fS )z
    Helper function for converting a generalized eigenvalue problem
    A(X) = lambda(B(X)) to standard eigen value problem using cholesky
    transformation
    )r   eighr   rl   r?   r   rk   )	Ar   valsvecsr   RTiRir#   eigVecs	            r   _eighr      s     	y[^^
dTz!A
*Q--C	ACBCQ++,,AQJD$[T""F<r   Tc                    |}|}|}|d}||j         d         }nd}t          |j                   dk    rt          d          |j         \  }}r^d}||dz  }n|d	z  }|d
z  }||dz  }|dz  }|d|z  z  }|d|z  z  }||dz  }n|dk    r	|d|z  z  }n|d|z  z  }t          |           t	          | ||f          } t	          |||f          }t	          |||f          }||z
  d|z  k     rt          ||          }|t          d           | t          j        || j	                            }|dn# |t          j        ||j	                            }t          ||          \  }}|r|ddd         }|dddddf         }|d|         }|ddd|f         }||fS ||dk    rt          j        d          |z  }|N| ||          }n|}t          j        |j                                        |          }t          ||||           t!          ||          \  }} | |          }t          j        |j                                        |          }t          |          \  }}t#          |||          }||         }t          j        |dd|f                   }t          j        ||          }t          j        ||          }|t          j        ||          }t          j        |ft(                    }|g}g } |}!t          j        || j	                  }"t          j        || j	                  }#d}$d}%d}&d}'d}(d})|'|k     
r|'dz  }'|||t          j        ddf         z  }n||t          j        ddf         z  }||z
  }*t          j        |*                                |*z  d          }t          j        |          }+|                     |+           t          j        |+|k    dd          }||z  }t3          |                                          },|,|!k    r|,}!t          j        |,| j	                  }"|,dk    r	nԉdk    rHt          d|'z             t          d|,            t          d|            t          d|+            dk    rt          |           t5          |*dd|f                   }-|'dk    rMt5          |$dd|f                   }.t5          |%dd|f                   }/|t5          |&dd|f                   }0| ||-          }-|t          |-|||           |C|-t          j        |t          j        |j                                        |-                    z
  }-nB|-t          j        |t          j        |j                                        |-                    z
  }-t!          ||-          }|\  }-}1 | |-          }2|'dk    rW|t!          ||.|0d          }|\  }.}0}3}4nt!          ||.d          }|\  }.}5}3}4|.|/|4z  }/t          j        |/|3          }/d}(nd}(|2j	        d k    rd}6n|-j	        d k    rd!}6nd"}6|+                                |6k    r|)sd})nd})||}|-}1|(s|.}0t          j        |j                                        |2          }7t          j        |-j                                        |2          }8|)r|8|8j                                        z   dz  }8t          j        |j                                        |          }||j                                        z   dz  }t          j        |j                                        |          }9t          j        |-j                                        |1          }:t          j        |j                                        |1          };nOt          j        |          }|#}9|"}:t          j        t3          |          t3          |,          f| j	                  };fd#}<|(s)t          j        |j                                        |/          }=t          j        |-j                                        |/          }>t          j        |.j                                        |/          }?t          j        |j                                        |0          }@t          j        |-j                                        |0          }A|)rL|?|?j                                        z   dz  }?t          j        |.j                                        |0          }Bn|"}Bt?          ||7|=g|7j                                        |8|>g|=j                                        |>j                                        |?gg          }Ct?          |9|;|@g|;j                                        |:|Ag|@j                                        |Aj                                        |Bgg          }D |<|C|D           	 t          |C|D          \  }}n# t@          j!        j"        $ r d}(Y nw xY w|(rt?          ||7g|7j                                        |8gg          }Ct?          |9|;g|;j                                        |:gg          }D |<|C|D           	 t          |C|D          \  }}n'# t@          j!        j"        $ r t          d$          w xY wt#          |||          }dk    rt          |           t          |           ||         }|dd|f         }|                    |           dk    rt          d%|           dk    rt          |           ||(s|d|         }E||||,z            }F|||,z   d         }Gt          j        |-|F          }H|Ht          j        |.|G          z  }Ht          j        |2|F          }I|It          j        |/|G          z  }It          j        |1|F          }J|Jt          j        |0|G          z  }JnS|d|         }E||d         }Ft          j        |-|F          }Ht          j        |2|F          }It          j        |1|F          }Jdk    r-t          |H           t          |I           t          |J           t          j        ||E          |Hz   }t          j        ||E          |Iz   }t          j        ||E          |Jz   }|H|I|J}&}%}$n|(s|d|         }E||||,z            }F|||,z   d         }Gt          j        |-|F          }H|Ht          j        |.|G          z  }Ht          j        |2|F          }I|It          j        |/|G          z  }In>|d|         }E||d         }Ft          j        |-|F          }Ht          j        |2|F          }Idk    rt          |H           t          |I           t          j        ||E          |Hz   }t          j        ||E          |Iz   }|H|I}%}$|'|k     
|||t          j        ddf         z  }n||t          j        ddf         z  }||z
  }*t          j        |*                                |*z  d          }t          j        |          }+dk    r$t          d&|            t          d'|+            dk    r$t          d(|            t          d)|+            |	r|
r|||| fS |||fS |
r||| fS ||fS )*a  Locally Optimal Block Preconditioned Conjugate Gradient Method (LOBPCG)

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

    Args:
        A (array-like): The symmetric linear operator of the problem,
            usually a sparse matrix. Can be of the following types
            - cupy.ndarray
            - cupyx.scipy.sparse.csr_matrix
            - cupy.scipy.sparse.linalg.LinearOperator
        X (cupy.ndarray): Initial approximation to the ``k``
            eigenvectors (non-sparse). If `A` has ``shape=(n,n)``
            then `X` should have shape ``shape=(n,k)``.
        B (array-like): The right hand side operator in a generalized
            eigenproblem. By default, ``B = Identity``.
            Can be of following types:
            - cupy.ndarray
            - cupyx.scipy.sparse.csr_matrix
            - cupy.scipy.sparse.linalg.LinearOperator
        M (array-like): Preconditioner to `A`; by default ``M = Identity``.
            `M` should approximate the inverse of `A`.
            Can be of the following types:
            - cupy.ndarray
            - cupyx.scipy.sparse.csr_matrix
            - cupy.scipy.sparse.linalg.LinearOperator
        Y (cupy.ndarray):
            `n-by-sizeY` matrix of constraints (non-sparse), `sizeY < n`
            The iterations will be performed in the B-orthogonal complement
            of the column-space of Y. Y must be full rank.
        tol (float):
            Solver tolerance (stopping criterion).
            The default is ``tol=n*sqrt(eps)``.
        maxiter (int):
            Maximum number of iterations.  The default is ``maxiter = 20``.
        largest (bool):
            When True, solve for the largest eigenvalues,
            otherwise the smallest.
        verbosityLevel (int):
            Controls solver output.  The default is ``verbosityLevel=0``.
        retLambdaHistory (bool):
            Whether to return eigenvalue history.  Default is False.
        retResidualNormsHistory (bool):
            Whether to return history of residual norms.  Default is False.

    Returns:
        tuple:
            - `w` (cupy.ndarray): Array of ``k`` eigenvalues
            - `v` (cupy.ndarray) An array of ``k`` eigenvectors.
              `v` has the same shape as `X`.
            - `lambdas` (list of cupy.ndarray): The eigenvalue history,
              if `retLambdaHistory` is True.
            - `rnorms` (list of cupy.ndarray): The history of residual norms,
              if `retResidualNormsHistory` is True.

    .. seealso:: :func:`scipy.sparse.linalg.lobpcg`

    .. note::
        If both ``retLambdaHistory`` and ``retResidualNormsHistory`` are `True`
        the return tuple has the following format
        ``(lambda, V, lambda history, residual norms history)``.
    N   r   r   rP   z$expected rank-2 array for argument XzSolving standardgeneralizedz eigenvalue problem withoutz preconditioning

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

zNo constraints

z%d constraints

z%d constraint

   z3The dense eigensolver does not support constraints.r   rs   g        gV瞯<TFziteration %dzcurrent block size: zeigenvalue(s):
zresidual norm(s):
r<   )rn   float32g-C6?g:0yE>c                     dk    r t          | d           t          |d           dk    rPt          j        dt          j        |                      t          j        dt          j        |                     d S d S )Nr   gramAgramBr<   z	gramA.txtz	gramB.txt)rN   r	   savetxtr   asnumpy)r   r   verbosityLevels     r   _handle_gramA_gramB_verbosityz-lobpcg.<locals>._handle_gramA_gramB_verbosity  s    !!$UG444$UG444""k4<+>+>???k4<+>+>????? #"r   z$eigh has failed in lobpcg iterationszlambda:zFinal iterative eigenvalue(s):
z"Final iterative residual norm(s):
z$Final postprocessing eigenvalue(s):
zFinal residual norm(s):
)#r(   r&   rZ   printr^   minNotImplementedErrorr   eyer   r   sqrtr`   r?   r@   rh   rq   ry   asarrayonesboolnewaxissumappendwhereintrV   rk   rD   diagzerosr:   r	   r   r
   )Kr|   Xr   rI   YrM   maxiterrw   r   retLambdaHistoryretResidualNormsHistoryblockVectorXre   residualTolerancesizeYnsizeXrU   A_denseB_denser}   r~   rd   gramYBYblockVectorBXblockVectorAXgramXAXru   eigBlockVectorrx   
activeMasklambdaHistoryresidualNormsHistorypreviousBlockSizeidentident0blockVectorPblockVectorAPblockVectorBPiterationNumberrestartexplicitGramFlagblockVectorRresidualNormscurrentBlockSizeactiveBlockVectorRactiveBlockVectorPactiveBlockVectorAPactiveBlockVectorBPactiveBlockVectorBRactiveBlockVectorARinvRnormal_myepsgramXARgramRARgramXBXgramRBRgramXBRr   gramXAPgramRAPgramPAPgramXBPgramRBPgramPBPr   r   eigBlockVectorXeigBlockVectorReigBlockVectorPppappbppsK           `                                                                  r   lobpcgr      s&   F LL"1%
<!##?@@@!HAu 9:CC= C))95LC%%!A%%"U**''CCqyy+e33*U22c


a!Q  Aa!Q  Aa!Q  A	E	a%i   E1#% 'F G G G !DHQag...//)$$48AQW+E+E+E)F)F 7G,,
d 	!":D44R4=DFUF|AAAvvITz!'8C'?'? Ie,,q0 =AlOOMM(M (<>..00-@@ 	,MMM #4A|"D"DL- AlOOMh|~**,,m<<G#GnnG^	7E7	+	+BbkG\.B"788N8L.99LH]N;;M}?? E84000JIMHU!'***EXe17+++F
 LMMOG
G
#
#1='$,/"::CCqqq!99C$s*h|((**\91==	###M222Z(994GG"_
z~~//00000 0H-QW===Eq  A.?2333;)9;;<<<.W..///777888B.!!!"<:#>??Q!&|AAAzM'B!C!C"'aaam(D"E"E}&+M!!!Z-,H&I&I#=!"#5!6!6 #0%}lD D D =!3+l"%mo&:&:&<&<&8: :; ;"; "4L K(;(;(=(=(:< <= ="=  #56625//a 233Q}'+=(;TK K KHKE"$7vv'+=tLLL693"AtV!-&9F&B#&*h/BD&I&I# $	11EE%22EEE&&/?&$  $ 9(M"4 9&8# (<>..002EFF(-/44668KLL 	0!1!11Q6Gh|~2244mDDG!1!11Q6Gh|~2244mDDGh1388::24 4Gh|~22446IJJGGi((GGGj#e**c2B.C.C!D'(w0 0 0G	@ 	@ 	@ 	@ 	@  	h|~22446IJJGh1388::24 4Gh1388::24 4Gh|~22446IJJGh1388::24 4G  "WY^^%5%55:(#5#7#<#<#>#>#68 8  GWg6#INN,,gw?#INN,,ginn.>.>HJ K KE GWg6#INN,,gw?#INN,,ginn.>.>HJ K KE *)%777*/u*=*='<+     	IGW-#INN,,g68 9 9EGW-#INN,,g68 9 9E *)%777I*/u*=*='<+ I I I !GHHHI ww//B"III'NNN"+'2.W%%%B)W%%%B.!!! = E"0%"8"0u1A8B 2B #C"09I1I1J1J"KX0/BBdh1?CCCh2ODDtx 3_EEEh2ODDtx 3_EEE"0%"8"0"8X0/BBh2ODDh2ODD""b			c


c


8L/BBRGL H]ODDsJM H]ODDsJM9;S#-LL  E"0%"8"0u1A8B 2B #C"09I1I1J1J"KX0/BBdh1?CCCh2ODDtx 3_EEE"0%"8"0"8X0/BBh2ODD""b			c


8L/BBRGL H]ODDsJM*,c-LI G
#
#L 	}gdlAAAo66 WT\111_55 3&L
(<$$&&5q
9
9CIcNNM:::;;;CMCCDDD ?g??@@@9-99::: 	)" 	8L-9MMML-77" 	)L*>>>L((s   )h= =ii k $k8)NF)N)	NNNNNTr   FF)rF   r	   r   cupy.linalgr   cupyx.scipy.sparserX   r   r:   rN   rV   r^   rh   rq   ry   r   r   r   r   r   <module>r      s            2 1 1 1 1 1  % % %P' ' '"
 
 
   0 0 0 +  +  +  +F     & "!();@	k) k) k) k) k) k)r   