
    8h'                         S SK r S SKJr  S SKrS SKJr  S SKJr  S SKJr  S SK	J
r
Jr  S SKJrJr  S SKJr  S	/rS
 rS rS r " S S	\5      rg)    N)Optional)Tensor)constraints)Distribution)_batch_mahalanobis	_batch_mv)_standard_normallazy_property)_sizeLowRankMultivariateNormalc                 8   U R                  S5      nU R                  UR                  S5      -  n[        R                  " X05      R                  5       nUR                  SX"-  5      SS2SSUS-   24==   S-  ss'   [        R                  R                  U5      $ )zw
Computes Cholesky of :math:`I + W.T @ inv(D) @ W` for a batch of matrices :math:`W`
and a batch of vectors :math:`D`.
N   )	sizemT	unsqueezetorchmatmul
contiguousviewlinalgcholesky)WDmWt_DinvKs        i/var/www/fran/franai/venv/lib/python3.13/site-packages/torch/distributions/lowrank_multivariate_normal.py_batch_capacitance_trilr       s|    
 	
r
AddQ[[_$GW ++-AFF2quaAEk"a'"<<  ##    c                     SUR                  SSS9R                  5       R                  S5      -  UR                  5       R                  S5      -   $ )z
Uses "matrix determinant lemma"::
    log|W @ W.T + D| = log|C| + log|D|,
where :math:`C` is the capacitance matrix :math:`I + W.T @ inv(D) @ W`, to compute
the log determinant.
   r   r   )dim1dim2)diagonallogsum)r   r   capacitance_trils      r   _batch_lowrank_logdetr*      sP     ((br(:>>@DDRHH1557;;
L  r!   c                     U R                   UR                  S5      -  n[        XB5      nUR                  S5      U-  R	                  S5      n[        X55      nXg-
  $ )z
Uses "Woodbury matrix identity"::
    inv(W @ W.T + D) = inv(D) - inv(D) @ W @ inv(C) @ W.T @ inv(D),
where :math:`C` is the capacitance matrix :math:`I + W.T @ inv(D) @ W`, to compute the squared
Mahalanobis distance :math:`x.T @ inv(W @ W.T + D) @ x`.
r   r#   r   )r   r   r   powr(   r   )r   r   xr)   r   	Wt_Dinv_xmahalanobis_term1mahalanobis_term2s           r   _batch_lowrank_mahalanobisr1   )   sV     ddQ[[_$G'%IqA**2.*+;G00r!   c                     ^  \ rS rSrSr\R                  \R                  " \R                  S5      \R                  " \R                  S5      S.r
\R                  rSr SS\S	\S
\S\\   SS4
U 4S jjjrSU 4S jjr\S\4S j5       r\S\4S j5       r\S\4S j5       r\S\4S j5       r\S\4S j5       r\S\4S j5       r\R6                  " 5       4S\S\4S jjrS rS rSr U =r!$ )r   7   a  
Creates a multivariate normal distribution with covariance matrix having a low-rank form
parameterized by :attr:`cov_factor` and :attr:`cov_diag`::

    covariance_matrix = cov_factor @ cov_factor.T + cov_diag

Example:
    >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_LAPACK)
    >>> # xdoctest: +IGNORE_WANT("non-deterministic")
    >>> m = LowRankMultivariateNormal(
    ...     torch.zeros(2), torch.tensor([[1.0], [0.0]]), torch.ones(2)
    ... )
    >>> m.sample()  # normally distributed with mean=`[0,0]`, cov_factor=`[[1],[0]]`, cov_diag=`[1,1]`
    tensor([-0.2102, -0.5429])

Args:
    loc (Tensor): mean of the distribution with shape `batch_shape + event_shape`
    cov_factor (Tensor): factor part of low-rank form of covariance matrix with shape
        `batch_shape + event_shape + (rank,)`
    cov_diag (Tensor): diagonal part of low-rank form of covariance matrix with shape
        `batch_shape + event_shape`

Note:
    The computation for determinant and inverse of covariance matrix is avoided when
    `cov_factor.shape[1] << cov_factor.shape[0]` thanks to `Woodbury matrix identity
    <https://en.wikipedia.org/wiki/Woodbury_matrix_identity>`_ and
    `matrix determinant lemma <https://en.wikipedia.org/wiki/Matrix_determinant_lemma>`_.
    Thanks to these formulas, we just need to compute the determinant and inverse of
    the small size "capacitance" matrix::

        capacitance = I + cov_factor.T @ inv(cov_diag) @ cov_factor
r#   r   )loc
cov_factorcov_diagTNr4   r5   r6   validate_argsreturnc           	        > UR                  5       S:  a  [        S5      eUR                  SS  nUR                  5       S:  a  [        S5      eUR                  SS U:w  a  [        SUS    S	35      eUR                  SS  U:w  a  [        S
U 35      eUR                  S5      nUR                  S5      n [        R
                  " XbU5      u  o`l        nUS   U l        US   U l	        U R                  R                  S S n	X l
        X0l        [        X#5      U l        [        T
U ]=  XUS9  g ! [         a8  n[        SUR                   SUR                   SUR                   35      UeS nAff = f)Nr   z%loc must be at least one-dimensional.r   r#   zScov_factor must be at least two-dimensional, with optional leading batch dimensionsr   z2cov_factor must be a batch of matrices with shape r   z x mz/cov_diag must be a batch of vectors with shape zIncompatible batch shapes: loc z, cov_factor z, cov_diag ).r   r7   )dim
ValueErrorshaper   r   broadcast_tensorsr5   RuntimeErrorr4   r6   _unbroadcasted_cov_factor_unbroadcasted_cov_diagr    _capacitance_trilsuper__init__)selfr4   r5   r6   r7   event_shapeloc_	cov_diag_ebatch_shape	__class__s             r   rD   "LowRankMultivariateNormal.__init__a   s    779q=DEEiin>>a9  Br"k1D[QR^DTTXY  >>"#+-A+O  }}R &&r*		/4/F/F)0,D/9 <!&)hhnnSb))3&'/$!8!NO  	1#))M*JZJZI[[fgogugufvw	s   8D/ /
E193E,,E1c                 .  > U R                  [        U5      n[        R                  " U5      nXR                  -   nU R
                  R                  U5      Ul        U R                  R                  U5      Ul        U R                  R                  X@R                  R                  SS  -   5      Ul        U R                  Ul
        U R                  Ul        U R                  Ul        [        [        U];  XR                  SS9  U R                  Ul        U$ )Nr   Fr:   )_get_checked_instancer   r   SizerF   r4   expandr6   r5   r=   r@   rA   rB   rC   rD   _validate_args)rE   rJ   	_instancenew	loc_shaperK   s        r   rP    LowRankMultivariateNormal.expand   s    (()BINjj-"2"22	((//),}}++I6//	OO<Q<QRTRU<V0VW(,(F(F%&*&B&B# $ 6 6'6)) 	7 	
 "00
r!   c                     U R                   $ Nr4   rE   s    r   meanLowRankMultivariateNormal.mean       xxr!   c                     U R                   $ rW   rX   rY   s    r   modeLowRankMultivariateNormal.mode   r\   r!   c                     U R                   R                  S5      R                  S5      U R                  -   R	                  U R
                  U R                  -   5      $ )Nr#   r   )r@   r,   r(   rA   rP   _batch_shape_event_shaperY   s    r   variance"LowRankMultivariateNormal.variance   sN     **..q155b9D<X<XX
&""T%6%66
7	8r!   c                    U R                   S   nU R                  R                  5       R                  S5      nU R                  U-  n[
        R                  " X3R                  5      R                  5       nUR                  SX-  5      S S 2S S US-   24==   S-  ss'   U[
        R                  R                  U5      -  nUR                  U R                  U R                   -   U R                   -   5      $ )Nr   r   r   )rb   rA   sqrtr   r@   r   r   r   r   r   r   r   rP   ra   )rE   ncov_diag_sqrt_unsqueeze
Dinvsqrt_Wr   
scale_trils         r   rj   $LowRankMultivariateNormal.scale_tril   s     a "&">">"C"C"E"O"OPR"S336MM
LL]]3>>@	r15!XAX+&!+&,u||/D/DQ/GG
   1 11D4E4EE
 	
r!   c                    [         R                  " U R                  U R                  R                  5      [         R                  " U R
                  5      -   nUR                  U R                  U R                  -   U R                  -   5      $ rW   )	r   r   r@   r   
diag_embedrA   rP   ra   rb   )rE   covariance_matrixs     r   rn   +LowRankMultivariateNormal.covariance_matrix   su    !LL**D,J,J,M,M
T99:; !'' 1 11D4E4EE
 	
r!   c                    U R                   R                  U R                  R                  S5      -  n[        R
                  R                  U R                  USS9n[        R                  " U R                  R                  5       5      UR                  U-  -
  nUR                  U R                  U R                  -   U R                  -   5      $ )Nr   F)upper)r@   r   rA   r   r   r   solve_triangularrB   rm   
reciprocalrP   ra   rb   )rE   r   Aprecision_matrixs       r   ru   *LowRankMultivariateNormal.precision_matrix   s     **--**44R89 	 LL))$*@*@'QV)WT99DDFG!$$QR(R 	  && 1 11D4E4EE
 	
r!   sample_shapec                    U R                  U5      nUS S U R                  R                  SS  -   n[        X0R                  R
                  U R                  R                  S9n[        X R                  R
                  U R                  R                  S9nU R                  [        U R                  U5      -   U R                  R                  5       U-  -   $ )Nr   )dtypedevice)_extended_shaper5   r=   r	   r4   ry   rz   r   r@   rA   rf   )rE   rw   r=   W_shapeeps_Weps_Ds         r   rsample!LowRankMultivariateNormal.rsample   s    $$\2*t44RS99 txxW hhnnTXX__UHH66>?**//1E9:	
r!   c                    U R                   (       a  U R                  U5        XR                  -
  n[        U R                  U R
                  UU R                  5      n[        U R                  U R
                  U R                  5      nSU R                  S   [        R                  " S[        R                  -  5      -  U-   U-   -  $ )Ng      r   r#   )rQ   _validate_sampler4   r1   r@   rA   rB   r*   rb   mathr'   pi)rE   valuediffMlog_dets        r   log_prob"LowRankMultivariateNormal.log_prob   s    !!%(xx&**((""	
 (**((""

 t((+dhhq477{.CCgMPQQRRr!   c                 D   [        U R                  U R                  U R                  5      nSU R                  S   S[
        R                  " S[
        R                  -  5      -   -  U-   -  n[        U R                  5      S:X  a  U$ UR                  U R                  5      $ )Ng      ?r   g      ?r#   )r*   r@   rA   rB   rb   r   r'   r   lenra   rP   )rE   r   Hs      r   entropy!LowRankMultivariateNormal.entropy   s    '**((""

 4$$Q'3!dgg+1F+FG'QRt  !Q&H88D--..r!   )rB   rA   r@   r6   r5   r4   rW   )"__name__
__module____qualname____firstlineno____doc__r   real_vectorindependentrealpositivearg_constraintssupporthas_rsampler   r   boolrD   rP   propertyrZ   r^   r
   rc   rj   rn   ru   r   rO   r   r   r   r   __static_attributes____classcell__)rK   s   @r   r   r   7   sy   D &&!--k.>.>B++K,@,@!DO
 %%GK )-)P)P )P 	)P
  ~)P 
)P )PV  f   f   8& 8 8
 
F 
 
  
6 
 
 
& 
 
  -2JJL 	
E 	
V 	
S"
/ 
/r!   )r   typingr   r   r   torch.distributionsr    torch.distributions.distributionr   'torch.distributions.multivariate_normalr   r   torch.distributions.utilsr	   r
   torch.typesr   __all__r    r*   r1   r    r!   r   <module>r      sG        + 9 Q E  '
'	$	1D/ D/r!   