
    קgM*                     ~    d dl Z d dlZd dlmZ d dlmZ d dlmZmZ d dl	m
Z
 dgZd Zd Zd	 Z G d
 de          ZdS )    N)constraints)Distribution)_standard_normallazy_property)_sizeMultivariateNormalc                 x    t          j        | |                    d                                        d          S )a  
    Performs a batched matrix-vector product, with compatible but different batch shapes.

    This function takes as input `bmat`, containing :math:`n \times n` matrices, and
    `bvec`, containing length :math:`n` vectors.

    Both `bmat` and `bvec` may have any number of leading dimensions, which correspond
    to a batch shape. They are not necessarily assumed to have the same batch shape,
    just ones which can be broadcasted.
    )torchmatmul	unsqueezesqueeze)bmatbvecs     c/var/www/html/ai-engine/env/lib/python3.11/site-packages/torch/distributions/multivariate_normal.py	_batch_mvr      s0     <dnnR001199"===    c                    |                     d          }|j        dd         }t          |          }|                                 dz
  }||z
  }||z   }|d|z  z   }|j        d|         }	t	          | j        dd         |j        |d                   D ]\  }
}|	||
z  |
fz  }	|	|fz  }	|                    |	          }t          t          |                    t          t          ||d                    z   t          t          |dz   |d                    z   |gz   }|                    |          }|                     d||          }|                    d|                     d          |          }|                    ddd          }t          j
                            ||d                              d                              d          }|                                }|                    |j        dd                   }t          t          |                    }t          |          D ]}|||z   ||z   gz  }|                    |          }|                    |          S )	aK  
    Computes the squared Mahalanobis distance :math:`\mathbf{x}^\top\mathbf{M}^{-1}\mathbf{x}`
    for a factored :math:`\mathbf{M} = \mathbf{L}\mathbf{L}^\top`.

    Accepts batches for both bL and bx. They are not necessarily assumed to have the same batch
    shape, but `bL` one should be able to broadcasted to `bx` one.
    r
   N      r   Fupper)sizeshapelendimzipreshapelistrangepermuter   linalgsolve_triangularpowsumt)bLbxnbx_batch_shapebx_batch_dimsbL_batch_dimsouter_batch_dimsold_batch_dimsnew_batch_dimsbx_new_shapesLsxpermute_dimsflat_Lflat_xflat_x_swapM_swapM
permuted_Mpermute_inv_dimsi
reshaped_Ms                         r   _batch_mahalanobisr>      s    	AXcrc]N ''MFFHHqLM$}4%5N%M(99N8---.LbhssmRX.>r.A%BCC ' 'Br2&QDL	L	!	!B 	U#$$%%
u%~q99
:
:	;
u%)>1==
>
>	? 
	  
L	!	!BZZAq!!FZZFKKNNA..F..Aq))K%%fk%GGKKANNRRSUVV  	

A 28CRC=))JE"23344=!! G G-1>A3EFF##$455Jn---r   c                 X   t           j                            t          j        | d                    }t          j        t          j        |d          dd          }t          j        | j        d         | j        | j                  }t           j        	                    ||d          }|S )N)r   r
   r   r
   dtypedeviceFr   )
r   r#   choleskyflip	transposeeyer   rA   rB   r$   )PLfL_invIdLs        r   _precision_to_scale_trilrL   N   s    			uz!X66	7	7BOEJr844b"==E	172;agah	?	?	?B%%eRu%==AHr   c                   H    e Zd ZdZej        ej        ej        ej        dZej        Z	dZ
	 	 	 	 d fd	Zd fd	Zed             Zed             Zed	             Zed
             Zed             Zed             Z ej                    fdedej        fdZd Zd Z xZS )r   a  
    Creates a multivariate normal (also called Gaussian) distribution
    parameterized by a mean vector and a covariance matrix.

    The multivariate normal distribution can be parameterized either
    in terms of a positive definite covariance matrix :math:`\mathbf{\Sigma}`
    or a positive definite precision matrix :math:`\mathbf{\Sigma}^{-1}`
    or a lower-triangular matrix :math:`\mathbf{L}` with positive-valued
    diagonal entries, such that
    :math:`\mathbf{\Sigma} = \mathbf{L}\mathbf{L}^\top`. This triangular matrix
    can be obtained via e.g. Cholesky decomposition of the covariance.

    Example:

        >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_LAPACK)
        >>> # xdoctest: +IGNORE_WANT("non-deterministic")
        >>> m = MultivariateNormal(torch.zeros(2), torch.eye(2))
        >>> m.sample()  # normally distributed with mean=`[0,0]` and covariance_matrix=`I`
        tensor([-0.2102, -0.5429])

    Args:
        loc (Tensor): mean of the distribution
        covariance_matrix (Tensor): positive-definite covariance matrix
        precision_matrix (Tensor): positive-definite precision matrix
        scale_tril (Tensor): lower-triangular factor of covariance, with positive-valued diagonal

    Note:
        Only one of :attr:`covariance_matrix` or :attr:`precision_matrix` or
        :attr:`scale_tril` can be specified.

        Using :attr:`scale_tril` will be more efficient: all computations internally
        are based on :attr:`scale_tril`. If :attr:`covariance_matrix` or
        :attr:`precision_matrix` is passed instead, it is only used to compute
        the corresponding lower triangular matrices using a Cholesky decomposition.
    )loccovariance_matrixprecision_matrix
scale_trilTNc                    |                                 dk     rt          d          |d u|d uz   |d uz   dk    rt          d          |t|                                 dk     rt          d          t          j        |j        d d         |j        d d                   }|                    |dz             | _        n|t|                                 dk     rt          d	          t          j        |j        d d         |j        d d                   }|                    |dz             | _        ns|                                 dk     rt          d
          t          j        |j        d d         |j        d d                   }|                    |dz             | _        |                    |dz             | _	        | j	        j        dd          }t                                          |||           |	|| _        d S |&t          j                            |          | _        d S t          |          | _        d S )Nr   z%loc must be at least one-dimensional.zTExactly one of covariance_matrix or precision_matrix or scale_tril may be specified.r   zZscale_tril matrix must be at least two-dimensional, with optional leading batch dimensionsr   r
   )r
   r
   zZcovariance_matrix must be at least two-dimensional, with optional leading batch dimensionszYprecision_matrix must be at least two-dimensional, with optional leading batch dimensions)r
   validate_args)r   
ValueErrorr   broadcast_shapesr   expandrQ   rO   rP   rN   super__init___unbroadcasted_scale_trilr#   rC   rL   )	selfrN   rO   rP   rQ   rT   batch_shapeevent_shape	__class__s	           r   rY   zMultivariateNormal.__init__   s{    7799q==DEEET)j.DED(
  f   !~~!## =    01A#2#1F	RUSURUWWK(//h0FGGDOO* $$&&** =    0!',cin K &7%=%=kH>T%U%UD""##%%)) =    0 &ss+SYss^ K %5$;$;K(<R$S$SD!::kE122hnRSS)kOOO!-7D****-2\-B-BCT-U-UD***-EFV-W-WD***r   c                 \   |                      t          |          }t          j        |          }|| j        z   }|| j        z   | j        z   }| j                            |          |_        | j        |_        d| j        v r| j	                            |          |_	        d| j        v r| j
                            |          |_
        d| j        v r| j                            |          |_        t          t          |                              || j        d           | j        |_        |S )NrO   rQ   rP   FrS   )_get_checked_instancer   r   Sizer]   rN   rW   rZ   __dict__rO   rQ   rP   rX   rY   _validate_args)r[   r\   	_instancenew	loc_shape	cov_shaper^   s         r   rW   zMultivariateNormal.expand   s   (();YGGj--$"22	$"22T5EE	(//),,(,(F%$-//$($:$A$A)$L$LC!4=((!_33I>>CN..#'#8#?#?	#J#JC  #&&//) 	0 	
 	
 	
 "0
r   c                 `    | j                             | j        | j        z   | j        z             S N)rZ   rW   _batch_shape_event_shaper[   s    r   rQ   zMultivariateNormal.scale_tril   s3    -44 11D4EE
 
 	
r   c                     t          j        | j        | j        j                                      | j        | j        z   | j        z             S ri   )r   r   rZ   mTrW   rj   rk   rl   s    r   rO   z$MultivariateNormal.covariance_matrix   sE    |*D,J,M
 

&"T%669JJ
K
K	Lr   c                     t          j        | j                                      | j        | j        z   | j        z             S ri   )r   cholesky_inverserZ   rW   rj   rk   rl   s    r   rP   z#MultivariateNormal.precision_matrix   s>    %d&DEELL 11D4EE
 
 	
r   c                     | j         S ri   rN   rl   s    r   meanzMultivariateNormal.mean   	    xr   c                     | j         S ri   rr   rl   s    r   modezMultivariateNormal.mode   rt   r   c                     | j                             d                              d                              | j        | j        z             S )Nr   r
   )rZ   r%   r&   rW   rj   rk   rl   s    r   variancezMultivariateNormal.variance   s@     *..q11SWWVD%(99::	
r   sample_shapereturnc                     |                      |          }t          || j        j        | j        j                  }| j        t          | j        |          z   S )Nr@   )_extended_shaper   rN   rA   rB   r   rZ   )r[   ry   r   epss       r   rsamplezMultivariateNormal.rsample   sK    $$\22uDHN48?SSSx)D$BCHHHHr   c                 j   | j         r|                     |           || j        z
  }t          | j        |          }| j                            dd                                                              d          }d| j        d         t          j        dt          j
        z            z  |z   z  |z
  S )Nr   r
   dim1dim2g      r   r   )rc   _validate_samplerN   r>   rZ   diagonallogr&   rk   mathpi)r[   valuediffr9   half_log_dets        r   log_probzMultivariateNormal.log_prob   s     	)!!%(((txt=tDD*33"3EEIIKKOOPRSS 	 t(+dhq47{.C.CCaGH<WWr   c                 \   | j                             dd                                                              d          }d| j        d         z  dt          j        dt
          j        z            z   z  |z   }t          | j                  dk    r|S |	                    | j                  S )Nr   r
   r   g      ?r   g      ?r   )
rZ   r   r   r&   rk   r   r   r   rj   rW   )r[   r   Hs      r   entropyzMultivariateNormal.entropy  s    *33"3EEIIKKOOPRSS 	 $#A&&#TW0E0E*EFUt !!Q&&H88D-...r   )NNNNri   )__name__
__module____qualname____doc__r   real_vectorpositive_definitelower_choleskyarg_constraintssupporthas_rsamplerY   rW   r   rQ   rO   rP   propertyrs   rv   rx   r   ra   r   Tensorr~   r   r   __classcell__)r^   s   @r   r   r   W   s       " "H &(:'9!0	 O %GK
 7X 7X 7X 7X 7X 7Xr     & 
 
 ]

 L L ]L
 
 
 ]

   X   X 
 
 X
 -7EJLL I IE IU\ I I I I
X X X/ / / / / / /r   )r   r   torch.distributionsr    torch.distributions.distributionr   torch.distributions.utilsr   r   torch.typesr   __all__r   r>   rL   r    r   r   <module>r      s      + + + + + + 9 9 9 9 9 9 E E E E E E E E        
 > > >/. /. /.d  r/ r/ r/ r/ r/ r/ r/ r/ r/ r/r   