
    Αi5                       S SK Jr  S SKrS SKrS SKJr  S SKJr  S SKJ	r	J
r
  S SKrS SKJrJr  S SKJr  S SKJr  S S	KJr  S S
KJr  \	(       a  S SKJr  S SKJr  S/rS rSS jrSS jr SS jrSSS jjr " S S\R@                  5      r!g)    )annotationsN)Sequence)reduce)TYPE_CHECKINGLiteral)
check_typeconvert_dtype)Variable)distribution)Beta)in_dynamic_mode)Tensor)_DTypeLiteralLKJCholeskyc                p   [         R                  " [        R                  U R                  S9n[         R
                  " SUS-   U R                  S9n[         R                  " U R                  S5      SU-
  S-  -   5      n[         R                  " USS9nXS-
  -  S-  [         R                  " U5      -  U-   $ )zO
Computes the multivariate log gamma function for input `a` and dimension `p`.
dtype      axis   )
paddle	to_tensormathpir   arangelgamma	unsqueezesumlog)apr   jgammaln_termsgammaln_sums         `/var/www/html/banglarbhumi/venv/lib/python3.13/site-packages/paddle/distribution/lkj_cholesky.pymvlgammar)   %   s     
		$''	1BaQagg.AMM!++b/QUaK"?@M**]4KQK!Ovzz"~-;;    c                    [         R                  " X 4SS9n[         R                  " X!S9n[         R                  " USS9u  pEUR	                  5       UR	                  5       4$ )zc
Returns the indices of the lower triangular part of an n x n matrix, including the k-th diagonal.
int32r   diagonalT)as_tuple)r   onestrilnonzeroflatten)nkfull_matrixtril_matrixrowscolss         r(   tril_indicesr:   0   sM     ++qfG4K++k6Kd;JD<<>4<<>))r*   c                    [         R                  " [         R                  " U 5      US9n[         R                  " XR	                  S5      5      nU$ )zt
Extracts the lower triangular part of the input matrix or batch of matrices `x`, including the specified diagonal.
r-   bool)r   r1   	ones_likemasked_selectastype)xr.   	tril_masktril_elementss       r(   matrix_to_trilrC   :   s@     F,,Q/(CI((,<,<V,DEMr*   c                   X2-  n/ UQU[        [        R                  US5      -  PUPUP7n[        R                  " [        R
                  " U5      [        R
                  " U5      5      u  pX:  n
[        R                  " X   X   /SS9n[        R                  " XSS9n[        R
                  " U5      R                  S5      R                  US/5      n[        R                  " X/SS9n[        R                  " USS2S4   5      nX   n[        R                  " XaU4U R                  S9n[        R                  " UX5      R                  U5      nU$ )zP
Constructs a batch of lower triangular matrices from a given input tensor `p`.
r   r   r   Nshaper   )r   operatormulr   meshgridr   stackrepeat_interleaver    tileconcatargsortzerosr   scatter_nd_addreshape)	p_flattendimlast_dimflatten_shapesample_shapediagshape0output_shaper8   r9   masklower_indicesrepeated_lower_indicesindex0index_matrixsorted_indicesmatrixs                    r(   vec_to_tril_matrixra   C   sE    &F	&|Q77 	 		L s!3V]]35GHJD;DLL$*dj!9BM#55A ]]6",,Q/44h]CF==&!AJL ^^LA$67N/L \\c 2)//JF""6<CKKF Mr*   c           	        U R                   SS nU R                   S   nX* :  d  X:  a  [        SU SU*  SUS-
   S35      e[        R                  " [        R                  " U5      [        R                  " U5      5      u  pEX-   U:  nX1-   X1-   S-   -  S	-  nX'4-  n[        R
                  " X`R                   5      n[        R                  " X5      R                  U5      nU$ )
z
Convert a `D x D` matrix or a batch of matrices into a (batched) vector
which comprises of lower triangular elements from the matrix in row order.
Nr   zdiag (z) provided is outside [z, r   z].r   )rF   
ValueErrorr   rI   r   broadcast_tor>   rQ   )	matrW   	out_shaper4   r8   r9   rA   vec_lenvecs	            r(   tril_matrix_to_vecrj   j   s    
 		#2I		"AbyDI6$'>rd"QUG2NOOq!16==3CDJDt#IxAHqL)Q.GI ##Iyy9I


s
.
6
6y
ACJr*   c                     ^  \ rS rSr% SrS\S'   S\S'   S\S'   S	\S
'      S       SU 4S jjjrSS jrSS jr/ 4SS jjr	SS jr
SrU =r$ )r      a.  
The LKJCholesky class represents the LKJ distribution over Cholesky factors of correlation matrices.
This class implements the LKJ distribution over Cholesky factors of correlation matrices, as described in
Lewandowski, Kurowicka, and Joe (2009). It supports two sampling methods: "onion" and "cvine".

Args:
    dim (int): The dimension of the correlation matrices.
    concentration (float, optional): The concentration parameter of the LKJ distribution. Default is 1.0.
    sample_method (str, optional): The sampling method to use, either "onion" or "cvine". Default is "onion".

Example:
    .. code-block:: pycon

        >>> import paddle

        >>> dim = 3
        >>> lkj = paddle.distribution.LKJCholesky(dim=dim)
        >>> sample = lkj.sample()
        >>> sample.shape
        paddle.Size([3, 3])
r   concentrationr   r   intrS   Literal['onion', 'cvine']sample_methodc           	       > [        5       (       dl  [        US[        [        [        R
                  R                  4S5        [        US[        [        [        [        [        R
                  R                  4S5        U R                  U5      (       a!  X l        [        UR                  5      U l        O2U R                  U5      u  U l        [        R                  " 5       U l        Xl        U R                   S:  d  [#        SU S35      e[%        U R                   [        5      (       d  ['        SU S35      e[        5       (       a3  [        R(                  " U R                  S:  5      (       d  [#        S	5      eX0l        U R                  R,                  nX4nU R                  S
U R                   S-
  -  -   n[        R.                  " U R                   S-
  U R                  R                  S9nUS:X  ab  [        R0                  " [        R2                  " SUR                  S9U/5      nUS
-   nUR5                  S5      S
U-  -
  n	[7        X5      U l        OuUS:X  ad  [;        [        R<                  " S
U-  U R                   S-
  U R                   S-
  /5      5      n
UR5                  S5      U
-
  n[7        X5      U l        O[#        S5      e[>        TU ]  XE5        g )NrS   r   rm   r   z3Expected dim greater than or equal to 2. Found dim=.z)Expected dim to be an integer. Found dim=r   z,The arg of `concentration` must be positive.      ?r   r   onion)r   r   cvinez-`method` should be one of 'cvine' or 'onion'.)!r   r   rn   r
   r   pirValuefloatlisttuple_validate_argsrm   r	   r   
_to_tensorget_default_dtyperS   rd   
isinstance	TypeErrorallrp   rF   r   rM   rO   r    r   _betarC   re   super__init__)selfrS   rm   rp   batch_shapeevent_shapemarginal_concoffset
beta_conc1
beta_conc0offset_tril	beta_conc	__class__s               r(   r   LKJCholesky.__init__   sh      h

 0 01	 eXvzz/?/?@	 }--!.&}':':;DJ#'??=#A T113DJxx1}EcU!L  DHHc**GuANOO::d001455 !OPP*((..j **SDHHqL-AAHHqL$$**

 G#]]d&,,7@F  #J&004sV|CJj5DJg%(##C&L488a<A2NOK &//3kAIi3DJLMM2r*   c                   U R                   R                  U5      R                  S5      n[        R                  " U R                  U5      UR                  S9R                  S5      nX3R                  SSS9-  nUSSS2SS24   n/ [        UR                  SS 5      QSPU R                  P7n[        R                  " XdR                  S	9n[        R                  " Xu/SS
9n[        R                  " U5      U-  n[        R                  " UR                  5      R                   n	[        R"                  " S[        R$                  " US-  SS
9-
  U	S9R                  5       n
U[        R&                  " U
5      -  nU$ )zGenerate a sample using the "onion" method.

Args:
    sample_shape (tuple): The shape of the samples to be generated.

Returns:
    w (Tensor): The Cholesky factor of the sampled correlation matrix.
r   r   T)r   keepdim.r   Nrc   rE   r   r   )min)r   sampler    r   randn_extend_shaper   r1   normrz   rF   rS   rO   rM   sqrtfinfotinyclipr!   
diag_embed)r   rV   yu_normalu_hypersphereu_hypersphere_other
zero_shapezero_rowweps
diag_elemss              r(   _onionLKJCholesky._onion   sC    JJl+55b9 <<|,AGG

$r( 	
 !==b$=#GG ,CQJ7Du]00"56DD488D
<<j8K8KLx&EBOKKN]* ll177#(([[VZZ12%>!>CHMMO
	Vz**r*   c                   U R                   R                  U5      R                  S5      nSU-  S-
  nU R                  S:X  a  UR                  S5      nU R                  U R                  S-
  -  S-  nU[	        [
        R                  US5      -  n[        U R                  R                  5      S:w  a  XPR                  R                  S   -  nUR                  U45      n[        UU R                  UUUS5      n[        R                  " UR                  5      R                  n[        R                   " USU-   SU-
  S9nUS-  n[        R"                  " [        R$                  " SU-
  5      SS9n	SS/U	R&                  S-
  -  SS/-   n
[        R(                  R*                  R-                  U	SS	S24   U
S
SS9nU[        R.                  " UR                  S   UR                  S   5      -  nX{-  nU$ )zGenerate a sample using the "cvine" method.

Args:
    sample_shape (tuple): The shape of the samples to be generated.

Returns:
    r (Tensor): The Cholesky factor of the sampled correlation matrix.
r   r   r   rc   r   )r   max)rS   .Nconstant      ?)padmodevalue)r   r   r    rS   r   rG   rH   lenrm   rF   rQ   ra   r   r   r   r   r   cumprodr   ndimnn
functionalr   eye)r   rV   beta_samplepartial_correlationrT   rU   r   rzz1m_cumprod_sqrt	pad_widthz1m_cumprod_sqrt_shifteds               r(   _cvineLKJCholesky._cvine  s    jj''5??C+o188q="5"?"?"C 88txx!|,1 6(,,a#HHt!!''(A-//55b99M199=:JK0HH
 ll;,,-22KK+"s(!c'K qD!>>&++a!e*<"E F.33a78Aq6A	#)99#7#7#;#;S#2#X&	 $< $
  	
VZZ%%b)+>+D+DR+H
 	
 (r*   c                x   [        U[        5      (       d  [        S5      eU R                  S:X  a  U R	                  U5      nOU R                  U5      n[        U5      nUR                  U R                  R                  5        UR                  U R                  U R                  /5        UR                  U5      $ )z6Generate a sample using the specified sampling method.z%sample shape must be Sequence object.rt   )r~   r   r   rp   r   r   ry   extendrm   rF   rS   rQ   )r   rV   resrY   s       r(   r   LKJCholesky.sample?  s    ,11CDD(++l+C++l+CL)D..445TXXtxx01{{<((r*   c                b   [         R                  " USSSS9SSS24   n[         R                  " SU R                  S-   U R                  R
                  S	9nSU R                  S-
  R                  S5      -  U R                  -   U-
  n[         R                  " U[         R                  " U5      -  SS
9nU R                  S-
  nU R                  SU-  -   n[         R                  " U5      U-  n[        US-
  U5      nSU-  [        R                  " [        R                  5      -  n	X-   U-
  n
XJ-
  $ )aU  Compute the log probability density of the given Cholesky factor under the LKJ distribution.

Args:
    value (Tensor): The Cholesky factor of the correlation matrix for which the log probability density is to be computed.

Returns:
    log_prob (Tensor): The log probability density of the given Cholesky factor under the LKJ distribution.
r   r   rc   )r   axis1axis2.r   Nr   r   r   rs   )r   r.   r   rS   rm   r   r    r!   r"   r   r)   r   r   )r   r   r   orderunnormalized_log_pdfdm1alphadenominator	numeratorpi_constantnormalize_terms              r(   log_probLKJCholesky.log_probO  s    __U1BbIG

 aAT5G5G5M5MNT''!+66r::TXXEM  &zzFJJz** 

 hhl""S3Y.mmE*S0US[#.	 Ci$((477"33 %0;>#44r*   )r   rm   rS   r   rp   )r   r   rt   )rS   rn   rm   rx   rp   ro   returnNone)rV   zSequence[int]r   r   )r   r   r   r   )__name__
__module____qualname____firstlineno____doc____annotations__r   r   r   r   r   __static_attributes____classcell__)r   s   @r(   r   r      s    , 	H,, "3:	B3B3 B3 1	B3
 
B3 B3H$L7r 46 ) #5 #5r*   )r   ) r   )rf   r   rW   rn   r   r   )"
__future__r   r   rG   collections.abcr   	functoolsr   typingr   r   r   paddle.base.data_feederr   r	   paddle.base.frameworkr
   paddle.distributionr   paddle.distribution.betar   paddle.frameworkr   r   paddle._typing.dtype_liker   __all__r)   r:   rC   ra   rj   Distributionr   r   r*   r(   <module>r      sr    #   $  )  = * , ) ,7 /<* DE$N,r5,++ r5r*   