
    sh'                         S SK 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)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        ڃ/Users/tiagomarins/Projetos/claudeai/copy_bank/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_mahalanobisr0   (   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U 4S 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\R2                  " 5       4S\S	\4S jjrS rS rSrU =r$ )r   6   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_diagTc           	        > 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   validate_args)dim
ValueErrorshaper   r   broadcast_tensorsr4   RuntimeErrorr3   r5   _unbroadcasted_cov_factor_unbroadcasted_cov_diagr   _capacitance_trilsuper__init__)selfr3   r4   r5   r8   event_shapeloc_	cov_diag_ebatch_shape	__class__s             r   rB   "LowRankMultivariateNormal.__init__`   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   Fr7   )_get_checked_instancer   r   SizerD   r3   expandr5   r4   r;   r>   r?   r@   rA   rB   _validate_args)rC   rH   	_instancenew	loc_shaperI   s        r   rN    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    returnc                     U R                   $ Nr3   rC   s    r   meanLowRankMultivariateNormal.mean       xxr    c                     U R                   $ rV   rW   rX   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'   r?   rN   _batch_shape_event_shaperX   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   )ra   r?   sqrtr   r>   r   r   r   r   r   r   r   rN   r`   )rC   ncov_diag_sqrt_unsqueeze
Dinvsqrt_Wr   
scale_trils         r   ri   $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      $ rV   )	r   r   r>   r   
diag_embedr?   rN   r`   ra   )rC   covariance_matrixs     r   rm   +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   r?   r   r   r   solve_triangularr@   rl   
reciprocalrN   r`   ra   )rC   r   Aprecision_matrixs       r   rt   *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_shaper4   r;   r   r3   rx   ry   r   r>   r?   re   )rC   rv   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"   )rO   _validate_sampler3   r0   r>   r?   r@   r)   ra   mathr&   pi)rC   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>   r?   r@   ra   r   r&   r   lenr`   rN   )rC   r   Hs      r   entropy!LowRankMultivariateNormal.entropy   s    '**((""

 4$$Q'3!dgg+1F+FG'QRt  !Q&H88D--..r    )r@   r?   r>   r5   r4   r3   rV   ) __name__
__module____qualname____firstlineno____doc__r   real_vectorindependentrealpositivearg_constraintssupporthas_rsamplerB   rN   propertyr   rY   r]   r	   rb   ri   rm   rt   r   rM   r
   r~   r   r   __static_attributes____classcell__)rI   s   @r   r   r   6   s5   D &&!--k.>.>B++K,@,@!DO
 %%GK#PJ  f   f   8& 8 8
 
F 
 
  
6 
 
 
& 
 
  -2JJL 	
E 	
V 	
S"
/ 
/r    )r   r   r   torch.distributionsr    torch.distributions.distributionr   'torch.distributions.multivariate_normalr   r   torch.distributions.utilsr   r	   torch.typesr
   __all__r   r)   r0   r    r    r   <module>r      sD       + 9 Q E  '
'	$	1~/ ~/r    