
    VpfZ"                        d Z ddlmZ ddlmZ ddlZddlZddlmZ ddl	Z	ddl	m
Z
 ddlmZ ddlmZ  ej        e	j        d	          	 ddd            Z ej        e	j        d	          	 	 	 	 ddd            ZdS ) u  A JIT-compatible library for QDWH-based singular value decomposition.

QDWH is short for QR-based dynamically weighted Halley iteration. The Halley
iteration implemented through QR decompositions is numerically stable and does
not require solving a linear system involving the iteration matrix or
computing its inversion. This is desirable for multicore and heterogeneous
computing systems.

References:
Nakatsukasa, Yuji, and Nicholas J. Higham.
"Stable and efficient spectral divide and conquer algorithms for the symmetric
eigenvalue decomposition and the SVD." SIAM Journal on Scientific Computing 35,
no. 3 (2013): A1325-A1349.
https://epubs.siam.org/doi/abs/10.1137/120876605

Nakatsukasa, Yuji, Zhaojun Bai, and François Gygi.
"Optimizing Halley's iteration for computing the matrix polar decomposition."
SIAM Journal on Matrix Analysis and Applications 31, no. 5 (2010): 2700-2720.
https://epubs.siam.org/doi/abs/10.1137/090774999
    )annotations)SequenceN)Any)lax)core)            )static_argnumsar   	hermitianbool
compute_uvmax_iterationsintsubset_by_indextuple[int, int] | NonereturnAny | Sequence[Any]c                   t           j                            | ||          \  }}}}t           j                            ||d          \  }}	t	          j        |	d          }	t	          j        |	d          }
|	|
         }|s|S |dd|
f         }||z  }d t          t	          j        | j	                  j
                  }|d	         | j        d
         |z  |d         z  k    }d }fd}t          j        ||||f          \  }}|||fS )ab  Singular value decomposition for m x n matrix and m >= n.

  Args:
    a: A matrix of shape `m x n` with `m >= n`.
    hermitian: True if `a` is Hermitian.
    compute_uv: Whether to also compute `u` and `v` in addition to `s`.
    max_iterations: The predefined maximum number of iterations of QDWH.

  Returns:
    A 3-tuple (`u`, `s`, `v`), where `u` is a unitary matrix of shape `m x n`,
    `s` is vector of length `n` containing the singular values in the descending
    order, `v` is a unitary matrix of shape `n x n`, and
    `a = (u * s) @ v.T.conj()`. For `compute_uv=False`, only `s` is returned.
  )is_hermitianr   F)r   sort_eigenvaluesg        T)
descendingNc                    t           j                            | d          \  } }| t          j        t          j        t          j        |          dk    dd                    z  } | S )NFfull_matricesr   r   )r   linalgqrjnpdiagwhere)u_outrs     P/var/www/html/nettyfy-visnx/env/lib/python3.11/site-packages/jax/_src/lax/svd.pycorrect_rank_deficiencyz;_svd_tall_and_square_input.<locals>.correct_rank_deficiencye   sQ    z}}U%}88HE1CHSYsx{{a'7B??@@@EL    r   r   r   c                    | d         S )Nr    argss    r&   <lambda>z,_svd_tall_and_square_input.<locals>.<lambda>l   s
    Q r(   c                *     | d                   dfS )Nr   Fr*   )r,   r'   s    r&   r-   z,_svd_tall_and_square_input.<locals>.<lambda>m   s    00a995A r(   )r   r   qdwheighr!   maximumargsortfloatfinfodtypeepsshape
while_loop)r   r   r   r   r   u_ph_vssort_idxs_outv_outr$   r6   do_correctioncond_fbody_fr'   s                     @r&   _svd_tall_and_square_inputrD   1   s>   . i !  ,#q!Q
 
5 
 
 
$!Q 
k!S! [t,,,(
H+%	 L AAAxK.%
+%  
 	ci  $%%#)qwqzC/%(::-&AAAA&^FFUM,BCC(%
	r(   )r   r	   r
   r      TF
   r   c                   t          j        t          |d          }t          j        t          |d          }t          j        t          |d          }t          j        t          |d          }|t	          |          dk    rt          d          t          j        |d                   t          j        |d	                   f}|d         |d	         k    rt          d
          |d         dk     rt          d          | j        \  }}||k     r|n|}|d	         |k    rt          d          |r|d|fk    rt          d          ||d	         z
  ||d         z
  f}| j        \  }}d}	||k     r%| j	        
                                } | j        \  }}d}	d}
|rQt          j                            | d          \  }}|ddd|f         }|dd|df         }|d|ddf         } d}
n/|d|z  k    r&t          j                            | d          \  }} d}
|s?t          j        d          5  t!          | ||||          cddd           S # 1 swxY w Y   t          j        d          5  t!          | ||||          \  |
r|z  ddd           n# 1 swxY w Y   |rt#          j        |f          t#          j        t#          j        |                     }d }fd}t          j        |||f          \  }|	rj	        
                                fS j	        
                                fS )a#  Singular value decomposition.

  Args:
    a: A matrix of shape `m x n`.
    full_matrices: If True, `u` and `vh` have the shapes `m x m` and `n x n`,
      respectively. If False, the shapes are `m x k` and `k x n`, respectively,
      where `k = min(m, n)`.
    compute_uv: Whether to also compute `u` and `v` in addition to `s`.
    hermitian: True if `a` is Hermitian.
    max_iterations: The predefined maximum number of iterations of QDWH.
    subset_by_index: Optional 2-tuple [start, end] indicating the range of
      indices of singular components to compute. For example, if
      ``subset_by_index`` = [0,2], then ``svd`` computes the two largest
      singular values (and their singular vectors if `compute_uv` is true.

  Returns:
    A 3-tuple (`u`, `s`, `vh`), where `u` and `vh` are unitary matrices,
    `s` is vector of length `k` containing the singular values in the
    non-increasing order, and `k = min(m, n)`. The shapes of `u` and `vh`
    depend on the value of `full_matrices`. For `compute_uv=False`,
    only `s` is returned.
  zbThe `full_matrices` argument must be statically specified to use `svd` within JAX transformations.z_The `compute_uv` argument must be statically specified to use `svd` within JAX transformations.z^The `hermitian` argument must be statically specified to use `svd` within JAX transformations.zcThe `max_iterations` argument must be statically specified to use `svd` within JAX transformations.Nr	   z*subset_by_index must be a tuple of size 2.r   r   z)Got empty index range in subset_by_index.z0Indices in subset_by_index must be non-negative.z0Index in subset_by_index[1] exceeds matrix size.z8full_matrices and subset_by_index cannot be both be set.FTr   gffffff?float32c                6    t          j        | d                   S )Nr   )r!   logical_notr+   s    r&   r-   zsvd.<locals>.<lambda>   s    Q00 r(   c                    t          j        d          t          j        t           j                  t          j        t           j                  t          j        t           j                  fS )NT)r!   array	full_likenan)r,   r?   r$   r@   s    r&   r-   zsvd.<locals>.<lambda>   sH    	ioo	mE37##	mE37##	mE37##	 r(   )r   concrete_or_errorr   r   len
ValueErroroperatorindexr7   Tconjr   r   r    jaxdefault_matmul_precisionrD   r!   hstackallisfiniter8   )r   r   r   r   r   r   mnrankis_flipreduce_to_squareq_fulla_fullq
u_out_null	is_finiterB   rC   r;   r?   r$   r@   s                      @@@r&   svdre   q   sb   > (
M ;< <- %
J ;< <* $
; ) )	; .  
?q  CDDD 	q)**q)**O q_Q///BCCCqAIJJJ7DAqA111DqD  IJJJ QI55
D   oa00$9K2KLO	
$!Q'UU	

A7DAqG Z]]1D]99NFFqqq"1"uA122Jrr111uA 	4!8||Z]]1E]22da	 		%i	0	0  '
Y
NO                
 #I..  4	9j./ E5%  %ie                ,Jz*++Egcl1oo&&)00&     & >fy%6 !UE5  *5%',,..))
	''s$   3III2JJ!$J!)N)r   r   r   r   r   r   r   r   r   r   r   r   )TFrF   N)r   r   r   r   r   r   r   r   r   r   r   r   r   r   )__doc__
__future__r   collections.abcr   	functoolsrR   typingr   rV   r   jax._srcr   	jax.numpynumpyr!   partialjitrD   re   r*   r(   r&   <module>rp      s4   * # " " " " " $ $ $ $ $ $            



                   37<888 /3= = = = 98=~ 37?;;; .2A( A( A( A( <;A( A( A(r(   