
    "g                        d dl Zd dlZd dlmZ d dlmZ d dlm	Z	 d dl
mZ  ej                  dej                  z        Z ej                  d      Z ej                  ej                        ZdZd Zd"d	Zd#d
Z G d d      Z G d d      Z G d d      ZdZdZdZdZeeedZeeedZ G d de      Z e       Z G d de      Z dZ!dZ"dZ#e!e"edZ$de#edZ% G d de      Z& G d d e      Z' e&       Z(d!D ]d  Z)e&jT                  e)   Z+e'jT                  e)   Z, ejZ                  e+j\                  e%      e,_.         ejZ                  e+j\                  e$      e+_.        f y)$    N)doccer)gammaln)check_random_state)mvn   a  random_state : {None, int, np.random.RandomState, np.random.Generator}, optional
    Used for drawing random variates.
    If `seed` is `None` the `~np.random.RandomState` singleton is used.
    If `seed` is an int, a new ``RandomState`` instance is used, seeded
    with seed.
    If `seed` is already a ``RandomState`` or ``Generator`` instance,
    then that object is used.
    Default is None.
c                 N    | j                         } | j                  dk(  r| d   } | S )z`
    Remove single-dimensional entries from array and convert to scalar,
    if necessary.

    r    )squeezendim)outs    e/var/www/dash_apps/app1/venv/lib/python3.12/site-packages/statsmodels/compat/_scipy_multivariate_t.py_squeeze_outputr       s(     ++-C
xx1}"gJ    c                     ||}|dv rN| j                   j                  j                         }ddd}||   t        j                  |      j
                  z  }|t        j                  t        |             z  }|S )a  
    Determine which eigenvalues are "small" given the spectrum.

    This is for compatibility across various linear algebra functions
    that should agree about whether or not a Hermitian matrix is numerically
    singular and what is its numerical matrix rank.
    This is designed to be compatible with scipy.linalg.pinvh.

    Parameters
    ----------
    spectrum : 1d ndarray
        Array of eigenvalues of a Hermitian matrix.
    cond, rcond : float, optional
        Cutoff for small eigenvalues.
        Singular values smaller than rcond * largest_eigenvalue are
        considered zero.
        If None or -1, suitable machine precision is used.

    Returns
    -------
    eps : float
        Magnitude cutoff for numerical negligibility.

    )Ng     @@g    .A)fd)dtypecharlowernpfinfoepsmaxabs)spectrumcondrcondtfactorr   s         r   _eigvalsh_to_epsr!   ,   so    2 zNN%%'%ay288A;??*
H&
&CJr   c                     t        j                  | D cg c]  }t        |      |k  rdnd|z   c}t              S c c}w )a  
    A helper function for computing the pseudoinverse.

    Parameters
    ----------
    v : iterable of numbers
        This may be thought of as a vector of eigenvalues or singular values.
    eps : float
        Values with magnitude no greater than eps are considered negligible.

    Returns
    -------
    v_pinv : 1d float ndarray
        A vector of pseudo-inverted numbers.

    r      r   )r   arrayr   float)vr   xs      r   _pinv_1dr)   O   s6    " 88!<Q#a&C-QQqS0<EJJ<s   =c                   ,    e Zd ZdZ	 	 ddZed        Zy)_PSDaN  
    Compute coordinated functions of a symmetric positive semidefinite matrix.

    This class addresses two issues.  Firstly it allows the pseudoinverse,
    the logarithm of the pseudo-determinant, and the rank of the matrix
    to be computed using one call to eigh instead of three.
    Secondly it allows these functions to be computed in a way
    that gives mutually compatible results.
    All of the functions are computed with a common understanding as to
    which of the eigenvalues are to be considered negligibly small.
    The functions are designed to coordinate with scipy.linalg.pinvh()
    but not necessarily with np.linalg.det() or with np.linalg.matrix_rank().

    Parameters
    ----------
    M : array_like
        Symmetric positive semidefinite matrix (2-D).
    cond, rcond : float, optional
        Cutoff for small eigenvalues.
        Singular values smaller than rcond * largest_eigenvalue are
        considered zero.
        If None or -1, suitable machine precision is used.
    lower : bool, optional
        Whether the pertinent array data is taken from the lower
        or upper triangle of M. (Default: lower)
    check_finite : bool, optional
        Whether to check that the input matrices contain only finite
        numbers. Disabling may give a performance gain, but may result
        in problems (crashes, non-termination) if the inputs do contain
        infinities or NaNs.
    allow_singular : bool, optional
        Whether to allow a singular matrix.  (Default: True)

    Notes
    -----
    The arguments are similar to those of scipy.linalg.pinvh().

    Nc                 0   t         j                  j                  |||      \  }}t        |||      }	t	        j
                  |      |	 k  rt        d      |||	kD     }
t        |
      t        |      k  r!|st        j                  j                  d      t        ||	      }t	        j                  |t	        j                  |            }t        |
      | _        || _        t	        j                  t	        j                  |
            | _        d | _        y )N)r   check_finitez.the input matrix must be positive semidefinitezsingular matrix)scipylinalgeighr!   r   min
ValueErrorlenLinAlgErrorr)   multiplysqrtrankUsumloglog_pdet_pinv)selfMr   r   r   r-   allow_singularsur   r   s_pinvr8   s                r   __init__z_PSD.__init__   s    
 ||  %l K1q$.66!9tMNNa#gJq6CF?>))''(9::!S!KK2776?+ F	rvvay) 
r   c                     | j                   9t        j                  | j                  | j                  j                        | _         | j                   S N)r<   r   dotr8   Tr=   s    r   pinvz	_PSD.pinv   s4    ::1DJzzr   )NNTTT)__name__
__module____qualname____doc__rC   propertyrI   r	   r   r   r+   r+   c   s)    %N 8<370  r   r+   c                   ^     e Zd ZdZd fd	Zed        Zej                  d        Zd Z xZ	S )multi_rv_genericzd
    Class which encapsulates common functionality between all multivariate
    distributions.

    c                 B    t         |           t        |      | _        y rE   )superrC   r   _random_stater=   seed	__class__s     r   rC   zmulti_rv_generic.__init__   s    /5r   c                     | j                   S )a   Get or set the RandomState object for generating random variates.

        This can be either None, int, a RandomState instance, or a
        np.random.Generator instance.

        If None (or np.random), use the RandomState singleton used by
        np.random.
        If already a RandomState or Generator instance, use it.
        If an int, use a new RandomState instance seeded with seed.

        )rS   rH   s    r   random_statezmulti_rv_generic.random_state   s     !!!r   c                 $    t        |      | _        y rE   r   rS   r=   rU   s     r   rX   zmulti_rv_generic.random_state   s    /5r   c                 4    |t        |      S | j                  S rE   rZ   )r=   rX   s     r   _get_random_statez"multi_rv_generic._get_random_state   s    #%l33%%%r   rE   )
rJ   rK   rL   rM   rC   rN   rX   setterr]   __classcell__rV   s   @r   rP   rP      s@    
6 " " 6 6&r   rP   c                   D    e Zd ZdZed        Zej                  d        Zy)multi_rv_frozenzj
    Class which encapsulates common functionality between all frozen
    multivariate distributions.
    c                 .    | j                   j                  S rE   )_distrS   rH   s    r   rX   zmulti_rv_frozen.random_state   s    zz'''r   c                 8    t        |      | j                  _        y rE   )r   rd   rS   r[   s     r   rX   zmulti_rv_frozen.random_state   s    #5d#;

 r   N)rJ   rK   rL   rM   rN   rX   r^   r	   r   r   rb   rb      s5     ( ( < <r   rb   a   mean : array_like, optional
    Mean of the distribution (default zero)
cov : array_like, optional
    Covariance matrix of the distribution (default one)
allow_singular : bool, optional
    Whether to allow a singular covariance matrix.  (Default: False)
a2  Setting the parameter `mean` to `None` is equivalent to having `mean`
    be the zero-vector. The parameter `cov` can be a scalar, in which case
    the covariance matrix is the identity times that value, a vector of
    diagonal entries for the covariance matrix, or a two-dimensional
    array_like.
     z>See class definition for a detailed description of parameters.)_mvn_doc_default_callparams_mvn_doc_callparams_note_doc_random_statec                   |     e Zd ZdZd fd	ZddZd Zd Zd ZddZ	ddZ
d	 Z	 	 dd
Z	 	 ddZddZddZ xZS )multivariate_normal_gena  
    A multivariate normal random variable.

    The `mean` keyword specifies the mean. The `cov` keyword specifies the
    covariance matrix.

    Methods
    -------
    ``pdf(x, mean=None, cov=1, allow_singular=False)``
        Probability density function.
    ``logpdf(x, mean=None, cov=1, allow_singular=False)``
        Log of the probability density function.
    ``cdf(x, mean=None, cov=1, allow_singular=False, maxpts=1000000*dim, abseps=1e-5, releps=1e-5)``
        Cumulative distribution function.
    ``logcdf(x, mean=None, cov=1, allow_singular=False, maxpts=1000000*dim, abseps=1e-5, releps=1e-5)``
        Log of the cumulative distribution function.
    ``rvs(mean=None, cov=1, size=1, random_state=None)``
        Draw random samples from a multivariate normal distribution.
    ``entropy()``
        Compute the differential entropy of the multivariate normal.

    Parameters
    ----------
    x : array_like
        Quantiles, with the last axis of `x` denoting the components.
    %(_mvn_doc_default_callparams)s
    %(_doc_random_state)s

    Alternatively, the object may be called (as a function) to fix the mean
    and covariance parameters, returning a "frozen" multivariate normal
    random variable:

    rv = multivariate_normal(mean=None, cov=1, allow_singular=False)
        - Frozen object with the same methods but holding the given
          mean and covariance fixed.

    Notes
    -----
    %(_mvn_doc_callparams_note)s

    The covariance matrix `cov` must be a (symmetric) positive
    semi-definite matrix. The determinant and inverse of `cov` are computed
    as the pseudo-determinant and pseudo-inverse, respectively, so
    that `cov` does not need to have full rank.

    The probability density function for `multivariate_normal` is

    .. math::

        f(x) = \frac{1}{\sqrt{(2 \pi)^k \det \Sigma}}
               \exp\left( -\frac{1}{2} (x - \mu)^T \Sigma^{-1} (x - \mu) \right),

    where :math:`\mu` is the mean, :math:`\Sigma` the covariance matrix,
    and :math:`k` is the dimension of the space where :math:`x` takes values.

    .. versionadded:: 0.14.0

    Examples
    --------
    >>> import matplotlib.pyplot as plt
    >>> from scipy.stats import multivariate_normal

    >>> x = np.linspace(0, 5, 10, endpoint=False)
    >>> y = multivariate_normal.pdf(x, mean=2.5, cov=0.5); y
    array([ 0.00108914,  0.01033349,  0.05946514,  0.20755375,  0.43939129,
            0.56418958,  0.43939129,  0.20755375,  0.05946514,  0.01033349])
    >>> fig1 = plt.figure()
    >>> ax = fig1.add_subplot(111)
    >>> ax.plot(x, y)

    The input quantiles can be any shape of array, as long as the last
    axis labels the components.  This allows us for instance to
    display the frozen pdf for a non-isotropic random variable in 2D as
    follows:

    >>> x, y = np.mgrid[-1:1:.01, -1:1:.01]
    >>> pos = np.dstack((x, y))
    >>> rv = multivariate_normal([0.5, -0.2], [[2.0, 0.3], [0.3, 0.5]])
    >>> fig2 = plt.figure()
    >>> ax2 = fig2.add_subplot(111)
    >>> ax2.contourf(x, y, rv.pdf(pos))

    c                 v    t         |   |       t        j                  | j                  t
              | _        y rE   )rR   rC   r   	docformatrM   mvn_docdict_paramsrT   s     r   rC   z multivariate_normal_gen.__init__T  s)    ''6HIr   c                      t        ||||      S )z
        Create a frozen multivariate normal distribution.

        See `multivariate_normal_frozen` for more information.

        )r?   rU   )multivariate_normal_frozen)r=   meancovr?   rU   s        r   __call__z multivariate_normal_gen.__call__X  s     *$9G/35 	5r   c                 D   |l|B|d}nt        j                  |t              }|j                  dk  rd}nX|j                  d   }nHt        j                  |t              }|j
                  }n t        j                  |      st        d      |t        j                  |      }t        j                  |t              }|d}t        j                  |t              }|dk(  rd|_        d|_        |j                  dk7  s|j                  d   |k7  rt        d	|z        |j                  dk(  r|t        j                  |      z  }n|j                  dk(  rt        j                  |      }n|j                  dk(  rx|j                  ||fk7  rg|j                  \  }}||k7  r#d
t        |j                        z  }t        |      d}|t        |j                        t        |      fz  }t        |      |j                  dkD  rt        d|j                  z        |||fS )z
        Infer dimensionality from mean or covariance matrix, ensure that
        mean and covariance are full vector resp. matrix.

        r#   r$   r   r   z.Dimension of random variable must be a scalar.      ?r#   r#   r#   z+Array 'mean' must be a vector of length %d.HArray 'cov' must be square if it is two dimensional, but cov.shape = %s.zTDimension mismatch: array 'cov' is of shape %s, but 'mean' is a vector of length %d.>Array 'cov' must be at most two-dimensional, but cov.ndim = %d)r   asarrayr&   r   shapesizeisscalarr2   zeroseyediagstrr3   )r=   dimrq   rr   rowscolsmsgs          r   _process_parametersz+multivariate_normal_gen._process_parametersc  s    ;|;C**S6Cxx!|!iilzz$e4ii;;s#  "- . .
 <88C=Dzz$e,;CjjE*!8DJCI99>TZZ]c1J ! " "88q=s#CXX]''#,CXX]syyS#J6JD$t|.03CII? S/!?S^SY77S/!XX\ 247HH= > > D#~r   c                    t        j                  |t              }|j                  dk(  r|t         j                     }|S |j                  dk(  r5|dk(  r|ddt         j                  f   }|S |t         j                  ddf   }|S zm
        Adjust quantiles array so that last axis labels the components of
        each data point.

        r$   r   r#   Nr   rz   r&   r   newaxisr=   r(   r   s      r   _process_quantilesz*multivariate_normal_gen._process_quantiles  sy     JJq&66Q;"**A  VVq[axam$  bjj!m$r   c                     ||z
  }t        j                  t        j                  t        j                  ||            d      }d|t        z  |z   |z   z  S )a  
        Parameters
        ----------
        x : ndarray
            Points at which to evaluate the log of the probability
            density function
        mean : ndarray
            Mean of the distribution
        prec_U : ndarray
            A decomposition such that np.dot(prec_U, prec_U.T)
            is the precision matrix, i.e. inverse of the covariance matrix.
        log_det_cov : float
            Logarithm of the determinant of the covariance matrix
        rank : int
            Rank of the covariance matrix.

        Notes
        -----
        As this function does no argument checking, it should not be
        called directly; use 'logpdf' instead.

        r   axisg      )r   r9   squarerF   _LOG_2PI)r=   r(   rq   prec_Ulog_det_covr7   devmahas           r   _logpdfzmultivariate_normal_gen._logpdf  sJ    . $hvvbiisF 342>th4t;<<r   c                     | j                  d||      \  }}}| j                  ||      }t        ||      }| j                  |||j                  |j
                  |j                        }t        |      S )a  
        Log of the multivariate normal probability density function.

        Parameters
        ----------
        x : array_like
            Quantiles, with the last axis of `x` denoting the components.
        %(_mvn_doc_default_callparams)s

        Returns
        -------
        pdf : ndarray or scalar
            Log of the probability density function evaluated at `x`

        Notes
        -----
        %(_mvn_doc_callparams_note)s

        Nr?   )r   r   r+   r   r8   r;   r7   r   r=   r(   rq   rr   r?   r   psdr   s           r   logpdfzmultivariate_normal_gen.logpdf  si    ( 11$cBT3##As+3~6ll1dCEE3<<Bs##r   c           	         | j                  d||      \  }}}| j                  ||      }t        ||      }t        j                  | j                  |||j                  |j                  |j                              }t        |      S )a  
        Multivariate normal probability density function.

        Parameters
        ----------
        x : array_like
            Quantiles, with the last axis of `x` denoting the components.
        %(_mvn_doc_default_callparams)s

        Returns
        -------
        pdf : ndarray or scalar
            Probability density function evaluated at `x`

        Notes
        -----
        %(_mvn_doc_callparams_note)s

        Nr   )
r   r   r+   r   expr   r8   r;   r7   r   r   s           r   pdfzmultivariate_normal_gen.pdf  sr    ( 11$cBT3##As+3~6ffT\\!T355#,,IJs##r   c                    	 t        j                  j                  t         j                         		fd}t        j                  |d|      }t        |      S )a  
        Parameters
        ----------
        x : ndarray
            Points at which to evaluate the cumulative distribution function.
        mean : ndarray
            Mean of the distribution
        cov : array_like
            Covariance matrix of the distribution
        maxpts: integer
            The maximum number of points to use for integration
        abseps: float
            Absolute error tolerance
        releps: float
            Relative error tolerance

        Notes
        -----
        As this function does no argument checking, it should not be
        called directly; use 'cdf' instead.

        .. versionadded:: 1.0.0

        c           	      @    t        j                  |       d   S )Nr   )r   mvnun)x_sliceabsepsrr   r   maxptsrq   relepss    r   <lambda>z.multivariate_normal_gen._cdf.<locals>.<lambda>  s)    5'4+166"CCD"F r   r   )r   fullr{   infapply_along_axisr   )
r=   r(   rq   rr   r   r   r   func1dr   r   s
     `````  @r   _cdfzmultivariate_normal_gen._cdf  sL    2 

RVVG,F F!!&"a0s##r   c           
          | j                  d||      \  }}}| j                  ||      }t        ||       |sd|z  }t        j                  | j                  ||||||            }	|	S )a  
        Log of the multivariate normal cumulative distribution function.

        Parameters
        ----------
        x : array_like
            Quantiles, with the last axis of `x` denoting the components.
        %(_mvn_doc_default_callparams)s
        maxpts: integer, optional
            The maximum number of points to use for integration
            (default `1000000*dim`)
        abseps: float, optional
            Absolute error tolerance (default 1e-5)
        releps: float, optional
            Relative error tolerance (default 1e-5)

        Returns
        -------
        cdf : ndarray or scalar
            Log of the cumulative distribution function evaluated at `x`

        Notes
        -----
        %(_mvn_doc_callparams_note)s

        .. versionadded:: 1.0.0

        Nr   @B )r   r   r+   r   r:   r   
r=   r(   rq   rr   r?   r   r   r   r   r   s
             r   logcdfzmultivariate_normal_gen.logcdf#  sl    < 11$cBT3##As+S0s]FffTYYq$VVVDE
r   c                     | j                  d||      \  }}}| j                  ||      }t        ||       |sd|z  }| j                  ||||||      }	|	S )a  
        Multivariate normal cumulative distribution function.

        Parameters
        ----------
        x : array_like
            Quantiles, with the last axis of `x` denoting the components.
        %(_mvn_doc_default_callparams)s
        maxpts: integer, optional
            The maximum number of points to use for integration
            (default `1000000*dim`)
        abseps: float, optional
            Absolute error tolerance (default 1e-5)
        releps: float, optional
            Relative error tolerance (default 1e-5)

        Returns
        -------
        cdf : ndarray or scalar
            Cumulative distribution function evaluated at `x`

        Notes
        -----
        %(_mvn_doc_callparams_note)s

        .. versionadded:: 1.0.0

        Nr   r   )r   r   r+   r   r   s
             r   cdfzmultivariate_normal_gen.cdfJ  sc    < 11$cBT3##As+S0s]Fii4fff=
r   c                     | j                  d||      \  }}}| j                  |      }|j                  |||      }t        |      S )a  
        Draw random samples from a multivariate normal distribution.

        Parameters
        ----------
        %(_mvn_doc_default_callparams)s
        size : integer, optional
            Number of samples to draw (default 1).
        %(_doc_random_state)s

        Returns
        -------
        rvs : ndarray or scalar
            Random variates of size (`size`, `N`), where `N` is the
            dimension of the random variable.

        Notes
        -----
        %(_mvn_doc_callparams_note)s

        N)r   r]   multivariate_normalr   )r=   rq   rr   r|   rX   r   r   s          r   rvszmultivariate_normal_gen.rvsq  sM    , 11$cBT3--l;..tS$?s##r   c                     | j                  d||      \  }}}t        j                  j                  dt        j                  z  t        j
                  z  |z        \  }}d|z  S )aP  
        Compute the differential entropy of the multivariate normal.

        Parameters
        ----------
        %(_mvn_doc_default_callparams)s

        Returns
        -------
        h : scalar
            Entropy of the multivariate normal distribution

        Notes
        -----
        %(_mvn_doc_callparams_note)s

        Nr         ?)r   r   r/   slogdetpie)r=   rq   rr   r   _logdets         r   entropyzmultivariate_normal_gen.entropy  sV    $ 11$cBT3II%%a"%%i"$$&6&<=	6V|r   rE   )Nr#   FN)Nr#   F)Nr#   FNh㈵>r   )Nr#   r#   N)Nr#   )rJ   rK   rL   rM   rC   rs   r   r   r   r   r   r   r   r   r   r   r_   r`   s   @r   rk   rk      s_    RhJ	5=~$=6$4$4$@ HL#'%N EI $%N$8r   rk   c                   >    e Zd Z	 	 d	dZd Zd Zd Zd Zd
dZd Z	y)rp   Nc                    t        |      | _        | j                  j                  d||      \  | _        | _        | _        t        | j
                  |      | _        |sd| j                  z  }|| _        || _	        || _
        y)a  
        Create a frozen multivariate normal distribution.

        Parameters
        ----------
        mean : array_like, optional
            Mean of the distribution (default zero)
        cov : array_like, optional
            Covariance matrix of the distribution (default one)
        allow_singular : bool, optional
            If this flag is True then tolerate a singular
            covariance matrix (default False).
        seed : {None, int, `~np.random.RandomState`, `~np.random.Generator`}, optional
            This parameter defines the object to use for drawing random
            variates.
            If `seed` is `None` the `~np.random.RandomState` singleton is used.
            If `seed` is an int, a new ``RandomState`` instance is used, seeded
            with seed.
            If `seed` is already a ``RandomState`` or ``Generator`` instance,
            then that object is used.
            Default is None.
        maxpts: integer, optional
            The maximum number of points to use for integration of the
            cumulative distribution function (default `1000000*dim`)
        abseps: float, optional
            Absolute error tolerance for the cumulative distribution function
            (default 1e-5)
        releps: float, optional
            Relative error tolerance for the cumulative distribution function
            (default 1e-5)

        Examples
        --------
        When called with the default parameters, this will create a 1D random
        variable with mean 0 and covariance 1:

        >>> from scipy.stats import multivariate_normal
        >>> r = multivariate_normal()
        >>> r.mean
        array([ 0.])
        >>> r.cov
        array([[1.]])

        Nr   r   )rk   rd   r   r   rq   rr   r+   cov_infor   r   r   )r=   rq   rr   r?   rU   r   r   r   s           r   rC   z#multivariate_normal_frozen.__init__  sr    \ -T2
(,

(F(F<@$)M%$)TXTXXnEtxx'Fr   c                 .   | j                   j                  || j                        }| j                   j                  || j                  | j
                  j                  | j
                  j                  | j
                  j                        }t        |      S rE   )
rd   r   r   r   rq   r   r8   r;   r7   r   r=   r(   r   s      r   r   z!multivariate_normal_frozen.logpdf  sg    JJ))!TXX6jj  DIIt}}!%!7!79K9KMs##r   c                 J    t        j                  | j                  |            S rE   r   r   r   r=   r(   s     r   r   zmultivariate_normal_frozen.pdf      vvdkk!n%%r   c                 J    t        j                  | j                  |            S rE   )r   r:   r   r   s     r   r   z!multivariate_normal_frozen.logcdf  s    vvdhhqk""r   c                    | j                   j                  || j                        }| j                   j                  || j                  | j
                  | j                  | j                  | j                        }t        |      S rE   )
rd   r   r   r   rq   rr   r   r   r   r   r   s      r   r   zmultivariate_normal_frozen.cdf  sZ    JJ))!TXX6jjooaDHHdkk4;;"kk+s##r   c                 f    | j                   j                  | j                  | j                  ||      S rE   )rd   r   rq   rr   r=   r|   rX   s      r   r   zmultivariate_normal_frozen.rvs  s#    zz~~dii4FFr   c                 ~    | j                   j                  }| j                   j                  }d|t        dz   z  |z   z  S )z
        Computes the differential entropy of the multivariate normal.

        Returns
        -------
        h : scalar
            Entropy of the multivariate normal distribution

        r   r#   )r   r;   r7   r   )r=   r;   r7   s      r   r   z"multivariate_normal_frozen.entropy  s;     ==))}}!!dhl+h677r   )Nr#   FNNr   r   r#   N)
rJ   rK   rL   rC   r   r   r   r   r   r   r	   r   r   rp   rp     s-    DH266p$&#$G8r   rp   a  
loc : array_like, optional
    Location of the distribution. (default ``0``)
shape : array_like, optional
    Positive semidefinite matrix of the distribution. (default ``1``)
df : float, optional
    Degrees of freedom of the distribution; must be greater than zero.
    If ``np.inf`` then results are multivariate normal. The default is ``1``.
allow_singular : bool, optional
    Whether to allow a singular matrix. (default ``False``)
a  Setting the parameter `loc` to ``None`` is equivalent to having `loc`
be the zero-vector. The parameter `shape` can be a scalar, in which case
the shape matrix is the identity times that value, a vector of
diagonal entries for the shape matrix, or a two-dimensional array_like.
)_mvt_doc_default_callparams_mvt_doc_callparams_noteri   c                   Z     e Zd ZdZd
 fd	Z	 	 ddZddZddZd ZddZ	d Z
d	 Z xZS )multivariate_t_gena	  
    A multivariate t-distributed random variable.

    The `loc` parameter specifies the location. The `shape` parameter specifies
    the positive semidefinite shape matrix. The `df` parameter specifies the
    degrees of freedom.

    In addition to calling the methods below, the object itself may be called
    as a function to fix the location, shape matrix, and degrees of freedom
    parameters, returning a "frozen" multivariate t-distribution random.

    Methods
    -------
    ``pdf(x, loc=None, shape=1, df=1, allow_singular=False)``
        Probability density function.
    ``logpdf(x, loc=None, shape=1, df=1, allow_singular=False)``
        Log of the probability density function.
    ``rvs(loc=None, shape=1, df=1, size=1, random_state=None)``
        Draw random samples from a multivariate t-distribution.

    Parameters
    ----------
    x : array_like
        Quantiles, with the last axis of `x` denoting the components.
    %(_mvt_doc_default_callparams)s
    %(_doc_random_state)s

    Notes
    -----
    %(_mvt_doc_callparams_note)s
    The matrix `shape` must be a (symmetric) positive semidefinite matrix. The
    determinant and inverse of `shape` are computed as the pseudo-determinant
    and pseudo-inverse, respectively, so that `shape` does not need to have
    full rank.

    The probability density function for `multivariate_t` is

    .. math::

        f(x) = \frac{\Gamma(\nu + p)/2}{\Gamma(\nu/2)\nu^{p/2}\pi^{p/2}|\Sigma|^{1/2}}
               \exp\left[1 + \frac{1}{\nu} (\mathbf{x} - \boldsymbol{\mu})^{\top}
               \boldsymbol{\Sigma}^{-1}
               (\mathbf{x} - \boldsymbol{\mu}) \right]^{-(\nu + p)/2},

    where :math:`p` is the dimension of :math:`\mathbf{x}`,
    :math:`\boldsymbol{\mu}` is the :math:`p`-dimensional location,
    :math:`\boldsymbol{\Sigma}` the :math:`p \times p`-dimensional shape
    matrix, and :math:`\nu` is the degrees of freedom.

    .. versionadded:: 1.6.0

    Examples
    --------
    >>> import matplotlib.pyplot as plt
    >>> from scipy.stats import multivariate_t
    >>> x, y = np.mgrid[-1:3:.01, -2:1.5:.01]
    >>> pos = np.dstack((x, y))
    >>> rv = multivariate_t([1.0, -0.5], [[2.1, 0.3], [0.3, 1.5]], df=2)
    >>> fig, ax = plt.subplots(1, 1)
    >>> ax.set_aspect('equal')
    >>> plt.contourf(x, y, rv.pdf(pos))

    c                     t         |   |       t        j                  | j                  t
              | _        t        |      | _        y)z
        Initialize a multivariate t-distributed random variable.

        Parameters
        ----------
        seed : Random state.

        N)rR   rC   r   rm   rM   mvt_docdict_paramsr   rS   rT   s     r   rC   zmultivariate_t_gen.__init__i  s8     	''6HI/5r   c                 f    |t         j                  k(  rt        ||||      S t        |||||      S )zs
        Create a frozen multivariate t-distribution. See
        `multivariate_t_frozen` for parameters.

        )rq   rr   r?   rU   )locr{   dfr?   rU   )r   r   rp   multivariate_t_frozen)r=   r   r{   r   r?   rU   s         r   rs   zmultivariate_t_gen.__call__v  sB     <-3E=K379 9 %Eb4BO 	Or   c           	         | j                  |||      \  }}}}| j                  ||      }t        ||      }| j                  |||j                  |j
                  |||j                        }t        j                  |      S )al  
        Multivariate t-distribution probability density function.

        Parameters
        ----------
        x : array_like
            Points at which to evaluate the probability density function.
        %(_mvt_doc_default_callparams)s

        Returns
        -------
        pdf : Probability density function evaluated at `x`.

        Examples
        --------
        >>> from scipy.stats import multivariate_t
        >>> x = [0.4, 5]
        >>> loc = [0, 1]
        >>> shape = [[1, 0.1], [0.1, 1]]
        >>> df = 7
        >>> multivariate_t.pdf(x, loc, shape, df)
        array([0.00075713])

        r   )	r   r   r+   r   r8   r;   r7   r   r   )	r=   r(   r   r{   r   r?   r   
shape_infor   s	            r   r   zmultivariate_t_gen.pdf  sx    2 #66sE2FS%##As+%?
ajllJ4G4G!:??4vvf~r   c           	          | j                  |||      \  }}}}| j                  ||      }t        |      }| j                  |||j                  |j
                  |||j                        S )a  
        Log of the multivariate t-distribution probability density function.

        Parameters
        ----------
        x : array_like
            Points at which to evaluate the log of the probability density
            function.
        %(_mvt_doc_default_callparams)s

        Returns
        -------
        logpdf : Log of the probability density function evaluated at `x`.

        Examples
        --------
        >>> from scipy.stats import multivariate_t
        >>> x = [0.4, 5]
        >>> loc = [0, 1]
        >>> shape = [[1, 0.1], [0.1, 1]]
        >>> df = 7
        >>> multivariate_t.logpdf(x, loc, shape, df)
        array([-7.1859802])

        See Also
        --------
        pdf : Probability density function.

        )r   r   r+   r   r8   r;   r7   )r=   r(   r   r{   r   r   r   s          r   r   zmultivariate_t_gen.logpdf  sj    < #66sE2FS%##As+%[
||AsJLL*2E2Er3&OO- 	-r   c                    |t         j                  k(  rt        j                  |||||      S ||z
  }t        j                  t        j
                  ||            j                  d      }	d||z   z  }
t        |
      }t        d|z        }|dz  t        j                  |t         j                  z        z  }d|z  }|
 t        j                  dd|z  |	z  z         z  }t        ||z
  |z
  |z
  |z         S )aB  Utility method `pdf`, `logpdf` for parameters.

        Parameters
        ----------
        x : ndarray
            Points at which to evaluate the log of the probability density
            function.
        loc : ndarray
            Location of the distribution.
        prec_U : ndarray
            A decomposition such that `np.dot(prec_U, prec_U.T)` is the inverse
            of the shape matrix.
        log_pdet : float
            Logarithm of the determinant of the shape matrix.
        df : float
            Degrees of freedom of the distribution.
        dim : int
            Dimension of the quantiles x.
        rank : int
            Rank of the shape matrix.

        Notes
        -----
        As this function does no argument checking, it should not be called
        directly; use 'logpdf' instead.

        r   r   r   g       @r#   ru   )r   r   r   r   r   rF   r9   r   r:   r   r   )r=   r(   r   r   r;   r   r   r7   r   r   r   ABCDEs                   r   r   zmultivariate_t_gen._logpdf  s    8 <&..q#vxNN#gyyV,-11r1:28AJC"HFRVVBJ''(NBRUdN*++q1uqy1}q011r   c                    | j                  |||      \  }}}}|t        |      }n| j                  }t        j                  |      rt        j
                  |      }n|j                  ||      |z  }|j                  t        j                  |      ||      }	||	t        j                  |      dddf   z  z   }
t        |
      S )a  
        Draw random samples from a multivariate t-distribution.

        Parameters
        ----------
        %(_mvt_doc_default_callparams)s
        size : integer, optional
            Number of samples to draw (default 1).
        %(_doc_random_state)s

        Returns
        -------
        rvs : ndarray or scalar
            Random variates of size (`size`, `P`), where `P` is the
            dimension of the random variable.

        Examples
        --------
        >>> from scipy.stats import multivariate_t
        >>> x = [0.4, 5]
        >>> loc = [0, 1]
        >>> shape = [[1, 0.1], [0.1, 1]]
        >>> df = 7
        >>> multivariate_t.rvs(loc, shape, df)
        array([[0.93477495, 3.00408716]])

        N)r|   )r   r   rS   r   isinfones	chisquarer   r~   r6   r   )r=   r   r{   r   r|   rX   r   rngr(   zsampless              r   r   zmultivariate_t_gen.rvs  s    B #66sE2FS%#$\2C$$C88B<Abt,r1A##BHHSM5t#DBGGAJq$w///w''r   c                    t        j                  |t              }|j                  dk(  r|t         j                     }|S |j                  dk(  r5|dk(  r|ddt         j                  f   }|S |t         j                  ddf   }|S r   r   r   s      r   r   z%multivariate_t_gen._process_quantiles#  sy     JJq&66Q;"**A  VVq[axam$  bjj!m$r   c                    |;|9t        j                  dt              }t        j                  dt              }d}n|Rt        j                  |t              }|j                  dk  rd}n|j                  d   }t        j
                  |      }n|=t        j                  |t              }|j                  }t        j                  |      }nBt        j                  |t              }t        j                  |t              }|j                  }|dk(  rd|_        d|_        |j                  dk7  s|j                  d   |k7  rt        d|z        |j                  dk(  r|t        j                  |      z  }n|j                  dk(  rt        j                  |      }n|j                  dk(  rx|j                  ||fk7  rg|j                  \  }}||k7  r#dt        |j                        z  }t        |      d	}|t        |j                        t        |      fz  }t        |      |j                  dkD  rt        d
|j                  z        |d}n0|dk  rt        d      t        j                  |      rt        d      ||||fS )z
        Infer dimensionality from location array and shape matrix, handle
        defaults, and ensure compatible dimensions.

        r   r$   r#   r   rv   rw   z*Array 'loc' must be a vector of length %d.rx   zSDimension mismatch: array 'cov' is of shape %s, but 'loc' is a vector of length %d.ry   z'df' must be greater than zero.z8'df' is 'nan' but must be greater than zero or 'np.inf'.)r   rz   r&   r   r{   r~   r|   r   r2   r   r   r3   isnan)r=   r   r{   r   r   r   r   r   s           r   r   z&multivariate_t_gen._process_parameters3  s1    ;5=**Qe,CJJq.EC[JJuE2EzzA~kk!n((3-C]**S.C((CFF3KEJJuE2E**S.C((C!8CI EK88q=CIIaLC/I ! " "::?BFF3K'EZZ1_GGENEZZ1_c
!:JD$t|.03EKK0@A S/!>S-s3x88S/!ZZ!^ 249JJ? @ @ :B1W>??XXb\WXXC""r   rE   Nr#   r#   FN)Nr#   r#   F)Nr#   r#   )Nr#   r#   r#   N)rJ   rK   rL   rM   rC   rs   r   r   r   r   r   r   r_   r`   s   @r   r   r   (  s@    >@6 @EO@"-H)2V.(` ;#r   r   c                   ,    e Zd Z	 	 ddZd Zd ZddZy)r   Nc                     t        |      | _        | j                  j                  |||      \  }}}}||||f\  | _        | _        | _        | _        t        ||      | _        y)a  
        Create a frozen multivariate t distribution.

        Parameters
        ----------
        %(_mvt_doc_default_callparams)s

        Examples
        --------
        >>> loc = np.zeros(3)
        >>> shape = np.eye(3)
        >>> df = 10
        >>> dist = multivariate_t(loc, shape, df)
        >>> dist.rvs()
        array([[ 0.81412036, -1.53612361,  0.42199647]])
        >>> dist.pdf([1, 1, 1])
        array([0.01237803])

        r   N)	r   rd   r   r   r   r{   r   r+   r   )r=   r   r{   r   r?   rU   r   s          r   rC   zmultivariate_t_frozen.__init__s  s^    * (-
"jj<<S%LS%25sE22E/$(DJu^Dr   c           	      L   | j                   j                  || j                        }| j                  j                  }| j                  j
                  }| j                   j                  || j                  ||| j                  | j                  | j                  j                        S rE   )
rd   r   r   r   r8   r;   r   r   r   r7   )r=   r(   r8   r;   s       r   r   zmultivariate_t_frozen.logpdf  sv    JJ))!TXX6OO??++zz!!!TXXq(DGGTXX"&//"6"68 	8r   c                 J    t        j                  | j                  |            S rE   r   r   s     r   r   zmultivariate_t_frozen.pdf  r   r   c                 ~    | j                   j                  | j                  | j                  | j                  ||      S )N)r   r{   r   r|   rX   )rd   r   r   r{   r   r   s      r   r   zmultivariate_t_frozen.rvs  s6    zz~~$(($(JJ!%#'+7	  9 	9r   r   r   )rJ   rK   rL   rC   r   r   r   r	   r   r   r   r   q  s    ?DE48&9r   r   )r   r   r   )NN)r   )/numpyr   scipy.linalgr.   
scipy._libr   scipy.specialr   scipy._lib._utilr   scipy.statsr   r:   r   r   _LOG_2_LOG_PIri   r   r!   r)   r+   rP   rb   rg   rh   _mvn_doc_frozen_callparams_mvn_doc_frozen_callparams_notern   mvn_docdict_noparamsrk   r   rp   r   r   _mvt_doc_frozen_callparams_noter   mvt_docdict_noparamsr   r   multivariate_tname__dict__methodmethod_frozenrm   rM   r	   r   r   <module>r     s      ! / 266!bee)	
"&&-	 	 FK(D DN!& !&H< <      I   $? 8*  $> ?* b. bJ ./ Z8 Z8|
   E   $? 8*  $& ?* F#) F#R
+9O +9\ $%
 % JD((.F)2248M,F,,V^^-ACM%V%%fnn6HIFNJr   