a
    BCCf                    @   s  d dl Z d dlZd dlZd dlmZ d dlmZm	Z	m
Z
mZmZmZmZmZ d dlmZmZ d dlmZmZ ddlmZ ddlmZ dd	lmZmZmZ dd
lmZ ddl m!Z! d dl"m#Z# g dZ$e%dej& Z'e%dZ(e%ej&Z)dZ*dd Z+dddZ,dddZ-G dd dZ.G dd dZ/G dd dZ0dZ1dZ2dZ3d Z4e1e2e*d!Z5e3e4e*d!Z6G d"d# d#e/Z7e7 Z8G d$d% d%e0Z9d&D ]:Z:e7j;e: Z<e9j;e: Z=e>e<j?e6e=_?e>e<j?e5e<_?qd'Z@d(ZAdZBd ZCe@eAe*d)ZDeBeCe*d)ZEG d*d+ d+e/ZFeF ZGG d,d- d-e0ZHd.D ]:Z:eFj;e: Z<eHj;e: Z=e>e<j?eEe=_?e>e<j?eDe<_?qd/ZIdZJd ZKeIe*d0ZLeJe*d0ZMd1d2 ZNd3d4 ZOd5d6 ZPG d7d8 d8e/ZQeQ ZRG d9d: d:e0ZSd;D ]:Z:eQj;e: Z<eSj;e: Z=e>e<j?eMe=_?e>e<j?eLe<_?qd<ZTdZUdZVd ZWeTeUe*d=ZXeVeWe*d=ZYG d>d? d?e/ZZeZ Z[G d@dA dAe0Z\dBD ]:Z:eZj;e: Z<e\j;e: Z=e>e<j?eYe=_?e>e<j?eXe<_?q@G dCdD dDeZZ]e] Z^G dEdF dFe0Z_dGD ]:Z:e]j;e: Z<e\j;e: Z=e>e<j?eYe=_?e>e<j?eXe<_?qdHZ`dIZadZbd Zce`eae*d=Zdebece*d=ZeG dJdK dKe/Zfef ZgG dLdM dMe0ZhdND ]:Z:efj;e: Z<ehj;e: Z=e>e<j?eee=_?e>e<j?ede<_?q4G dOdP dPe/Ziei ZjG dQdR dRe0ZkG dSdT dTe/Zlel ZmG dUdV dVe0ZnG dWdX dXe/Zoeo ZpG dYdZ dZe0ZqG d[d\ d\e/Zrer ZsG d]d^ d^e0Ztd_Zud`Zvd Zweueve*daZxdewe*daZyG dbdc dce/ZzG ddde dee0Z{ez Z|dfD ]:Z:ezj;e: Z<e{j;e: Z=e>e<j?eye=_?e>e<j?exe<_?qVdgZ}dhZ~dZd Ze}e~e*d=Zeee*d=ZG didj dje/Ze ZG dkdl dle0ZdmD ]:Z:ej;e: Z<ej;e: Z=e>e<j?ee=_?e>e<j?ee<_?qG dndo doe/Ze ZG dpdq dqe0ZdrZdsZdtZdue Zd Ze*eeeedvZe Zeddedw ddxdyZeee dzD ]2Z:ej;e: Z<ej;e: Z=ee=ee<j? ee<e qG d{d| d|e/Ze ZG d}d~ d~e0Zdd ZdZdZd Zee*dZee*dZdddZG dd de/Ze ZG dd de0ZdD ]:Z:ej;e: Z<ej;e: Z=e>e<j?ee=_?e>e<j?ee<_?qXG dd de/Ze ZG dd de0ZdS )    N)doccer)gammalnpsimultigammalnxlogyentrbetalniveloggamma)check_random_state
_lazywhere)drotget_blas_funcs   )norm)binom)_mvn_covariance_rcont_qmvt)directional_stats)root_scalar)multivariate_normalmatrix_normal	dirichletdirichlet_multinomialwishart
invwishartmultinomialspecial_ortho_grouportho_grouprandom_correlationunitary_groupmultivariate_tmultivariate_hypergeomrandom_tableuniform_directionvonmises_fisher   a  seed : {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                 C   s   |   } | jdkr| d } | S )z_
    Remove single-dimensional entries from array and convert to scalar,
    if necessary.
    r    )squeezendimoutr*   r*   U/var/www/html/django/DPS/env/lib/python3.9/site-packages/scipy/stats/_multivariate.py_squeeze_output5   s    
r0   c                 C   sT   |dur|}|dv r>| j j }ddd}|| t|j }|tt|  }|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.

    N)N     @@g    .A)fd)dtypecharlowernpZfinfoepsmaxabs)Zspectrumcondrcondtfactorr9   r*   r*   r/   _eigvalsh_to_eps@   s    
r@   h㈵>c                    s   t j fdd| D tdS )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.

    c                    s$   g | ]}t | krd nd| qS )r   r   )r;   ).0xr9   r*   r/   
<listcomp>r       z_pinv_1d.<locals>.<listcomp>r5   )r8   arrayfloat)vr9   r*   rD   r/   _pinv_1db   s    rK   c                   @   s.   e Zd ZdZd
ddZdd Zedd	 ZdS )_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().

    NTc                 C   s   t || _tjj|||d\}}t|||}	t ||	 k rJd}
t|
|||	k }t	|t	|k rz|szd}
t j
|
t||	}t |t |}d|	 | _|d d ||	kf | _t	|| _|| _t t || _d | _d S )Nr7   check_finitez9The input matrix must be symmetric positive semidefinite.zUWhen `allow_singular is False`, the input matrix must be symmetric positive definite.r2   )r8   asarray_Mscipylinalgeighr@   min
ValueErrorlenZLinAlgErrorrK   multiplysqrtr9   VrankUsumloglog_pdet_pinv)selfMr<   r=   r7   rN   allow_singularsur9   msgr4   Zs_pinvr[   r*   r*   r/   __init__   s$    


z_PSD.__init__c                 C   s$   t jj|| j dd}|| jk }|S )zJ
        Check whether x lies in the support of the distribution.
        r1   axis)r8   rR   r   rY   r9   )r`   rC   ZresidualZ
in_supportr*   r*   r/   _support_mask   s    
z_PSD._support_maskc                 C   s$   | j d u rt| j| jj| _ | j S N)r_   r8   dotr[   Tr`   r*   r*   r/   pinv   s    
z	_PSD.pinv)NNTTT)__name__
__module____qualname____doc__rf   ri   propertyrn   r*   r*   r*   r/   rL   u   s   '  
!rL   c                       sD   e Zd ZdZd
 fdd	Zedd Zejdd Zdd	 Z  Z	S )multi_rv_genericzc
    Class which encapsulates common functionality between all multivariate
    distributions.
    Nc                    s   t    t|| _d S rj   )superrf   r   _random_stater`   seed	__class__r*   r/   rf      s    
zmulti_rv_generic.__init__c                 C   s   | j S )a   Get or set the Generator object for generating random variates.

        If `seed` is None (or `np.random`), the `numpy.random.RandomState`
        singleton is used.
        If `seed` is an int, a new ``RandomState`` instance is used,
        seeded with `seed`.
        If `seed` is already a ``Generator`` or ``RandomState`` instance then
        that instance is used.

        )rv   rm   r*   r*   r/   random_state   s    zmulti_rv_generic.random_statec                 C   s   t || _d S rj   r   rv   rw   r*   r*   r/   r{      s    c                 C   s   |d urt |S | jS d S rj   r|   r`   r{   r*   r*   r/   _get_random_state   s    z"multi_rv_generic._get_random_state)N)
ro   rp   rq   rr   rf   rs   r{   setterr~   __classcell__r*   r*   ry   r/   rt      s   

rt   c                   @   s*   e Zd ZdZedd Zejdd ZdS )multi_rv_frozenzj
    Class which encapsulates common functionality between all frozen
    multivariate distributions.
    c                 C   s   | j jS rj   )_distrv   rm   r*   r*   r/   r{      s    zmulti_rv_frozen.random_statec                 C   s   t || j_d S rj   )r   r   rv   rw   r*   r*   r/   r{      s    N)ro   rp   rq   rr   rs   r{   r   r*   r*   r*   r/   r      s
   
r   aV  mean : array_like, default: ``[0]``
    Mean of the distribution.
cov : array_like or `Covariance`, default: ``[1]``
    Symmetric positive (semi)definite covariance matrix of the distribution.
allow_singular : bool, default: ``False``
    Whether to allow a singular covariance matrix. This is ignored if `cov` is
    a `Covariance` object.
a5  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, a two-dimensional array_like,
or a `Covariance` object.
 z>See class definition for a detailed description of parameters.)_mvn_doc_default_callparams_mvn_doc_callparams_note_doc_random_statec                       s   e Zd ZdZd& fdd	Zd'ddZd(d
dZdd Zdd Zdd Z	dd Z
d)ddZd*ddZdd Zd+ddddZd,ddddZd-d d!Zd.d"d#Zd/d$d%Z  ZS )0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, lower_limit=None)
        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(mean=None, cov=1)
        Compute the differential entropy of the multivariate normal.
    fit(x, fix_mean=None, fix_cov=None)
        Fit a multivariate normal distribution to data.

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

    Notes
    -----
    %(_mvn_doc_callparams_note)s

    The covariance matrix `cov` may be an instance of a subclass of
    `Covariance`, e.g. `scipy.stats.CovViaPrecision`. If so, `allow_singular`
    is ignored.

    Otherwise, `cov` must be a symmetric positive semidefinite
    matrix when `allow_singular` is True; it must be (strictly) positive
    definite when `allow_singular` is False.
    Symmetry is not checked; only the lower triangular portion is used.
    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,
    :math:`k` the rank of :math:`\Sigma`. In case of singular :math:`\Sigma`,
    SciPy extends this definition according to [1]_.

    .. versionadded:: 0.14.0

    References
    ----------
    .. [1] Multivariate Normal Distribution - Degenerate Case, Wikipedia,
           https://en.wikipedia.org/wiki/Multivariate_normal_distribution#Degenerate_case

    Examples
    --------
    >>> import numpy as np
    >>> 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)
    >>> plt.show()

    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.

    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))

    Nc                    s    t  | t| jt| _d S rj   )ru   rf   r   	docformatrr   mvn_docdict_paramsrw   ry   r*   r/   rf     s    z multivariate_normal_gen.__init__r   Fc                 C   s   t ||||dS )zzCreate a frozen multivariate normal distribution.

        See `multivariate_normal_frozen` for more information.
        )rb   rx   )multivariate_normal_frozen)r`   meancovrb   rx   r*   r*   r/   __call__  s    z multivariate_normal_gen.__call__Tc                 C   sP   t |tjr| ||S | d||\}}}t||d}t|}|||fS dS )z
        Infer dimensionality from mean or covariance matrix, ensure that
        mean and covariance are full vector resp. matrix.
        Nrb   )
isinstancer   Z
Covariance_process_parameters_Covariance_process_parameters_psdrL   	CovViaPSD)r`   r   r   rb   dimZpsd
cov_objectr*   r*   r/   _process_parameters  s    
z+multivariate_normal_gen._process_parametersc              
   C   s~   |j d }|d u rtdgn|}d| d|f }zt||}W n. tyr } zt||W Y d }~n
d }~0 0 |||fS )Nr1           z(`cov` represents a covariance matrix in z9 dimensions,and so `mean` must be broadcastable to shape )shaper8   rH   Zbroadcast_torU   )r`   r   r   r   messageer*   r*   r/   r     s    
 z6multivariate_normal_gen._process_parameters_Covariancec                 C   s  |d u r^|d u rH|d u rd}q\t j|td}|jdk r<d}q\|jd }qpt j|td}|j}nt |sptd|d u rt |}t j|td}|d u rd}t j|td}|dkr|	d}|	dd}|jdks|jd |krtd| |jdkr|t 
| }n|jdkr t |}n~|jdkr|j||fkr|j\}}||kr`dt|j }nd	}|t|jt|f }t|n|jdkrtd
|j |||fS )Nr   rG   r)   r   z.Dimension of random variable must be a scalar.      ?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)r8   rO   rI   r,   r   sizeisscalarrU   zerosreshapeeyediagstrrV   )r`   r   r   r   rowscolsre   r*   r*   r/   r     sV    






z/multivariate_normal_gen._process_parameters_psdc                 C   s`   t j|td}|jdkr$|t j }n8|jdkr\|dkrJ|ddt jf }n|t jddf }|S l
        Adjust quantiles array so that last axis labels the components of
        each data point.
        rG   r   r   Nr8   rO   rI   r,   newaxisr`   rC   r   r*   r*   r/   _process_quantiles  s    

z*multivariate_normal_gen._process_quantilesc                 C   sj   |j |j }}|| }|jdkr<|dtjf }|dtjf }tjt||dd}d|t | |  S )a  Log of the multivariate normal probability density function.

        Parameters
        ----------
        x : ndarray
            Points at which to evaluate the log of the probability
            density function
        mean : ndarray
            Mean of the distribution
        cov_object : Covariance
            An object representing the Covariance matrix

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

        r   .r1   rg         )	r^   rZ   r,   r8   r   r\   squareZwhiten_LOG_2PI)r`   rC   r   r   Zlog_det_covrZ   devmahar*   r*   r/   _logpdf  s    
zmultivariate_normal_gen._logpdfc           
      C   sf   |  |||}|\}}}| ||}| |||}t|j|k r^|||  }	t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

        )	r   r   r   r8   anyrZ   ri   infr0   
r`   rC   r   r   rb   paramsr   r   r.   out_of_boundsr*   r*   r/   logpdf  s    
zmultivariate_normal_gen.logpdfc           
      C   sh   |  |||}|\}}}| ||}t| |||}t|j|k r`|||  }	d||	< 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

        r   )	r   r   r8   expr   r   rZ   ri   r0   r   r*   r*   r/   pdf5  s    
zmultivariate_normal_gen.pdfc                    s   |du rt jt j n|}t ||\}	}
|	|
k }d|jdd }|
 |	  }
}	|	| |
|  |
|< |	|< |jd t j|
|	fdd} fdd}t |d|| }t	|S )a  Multivariate normal cumulative distribution function.

        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
        lower_limit : array_like, optional
            Lower limit of integration of the cumulative distribution function.
            Default is negative infinity. Must be broadcastable with `x`.

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


        .. versionadded:: 1.0.0

        Nr1   rg   c              	      s*   t | d  | d   d S Nr   )r   Zmvnun)limitsabsepsr   maxptsr   nrelepsr*   r/   func1d~  s
    z,multivariate_normal_gen._cdf.<locals>.func1d)
r8   fullr   r   broadcast_arraysr\   copyconcatenateapply_along_axisr0   )r`   rC   r   r   r   r   r   lower_limitr7   bai_swapsignsr   r   r.   r*   r   r/   _cdfQ  s    
zmultivariate_normal_gen._cdfrA   r   c             	   C   st   |  |||}	|	\}
}}|j}| ||
}|s6d|
 }| |||||||}t|dk rb|d n|}t|}|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)
        lower_limit : array_like, optional
            Lower limit of integration of the cumulative distribution function.
            Default is negative infinity. Must be broadcastable with `x`.

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

        Notes
        -----
        %(_mvn_doc_callparams_note)s

        .. versionadded:: 1.0.0

        @B r                   )r   
covariancer   r   r8   r   r]   )r`   rC   r   r   rb   r   r   r   r   r   r   r   cdfr.   r*   r*   r/   logcdf  s     

zmultivariate_normal_gen.logcdfc             	   C   sP   |  |||}	|	\}
}}|j}| ||
}|s6d|
 }| |||||||}|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)
        lower_limit : array_like, optional
            Lower limit of integration of the cumulative distribution function.
            Default is negative infinity. Must be broadcastable with `x`.

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

        Notes
        -----
        %(_mvn_doc_callparams_note)s

        .. versionadded:: 1.0.0

        r   )r   r   r   r   )r`   rC   r   r   rb   r   r   r   r   r   r   r   r.   r*   r*   r/   r     s     
zmultivariate_normal_gen.cdfc           
      C   s   |  ||\}}}| |}t|tjrF|j}||||}t|}nH|pNt }t	
|s`|f}t||jd f }|j|d}	|||	 }|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

        r1   r   )r   r~   r   r   r   r   r   r0   tupler8   iterabler   normalZcolorize)
r`   r   r   r   r{   r   r   r.   r   rC   r*   r*   r/   rvs  s    



zmultivariate_normal_gen.rvsc                 C   s*   |  ||\}}}d|jtd  |j  S )aG  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

              ?r   )r   rZ   r   r^   )r`   r   r   r   r   r*   r*   r/   entropy   s    zmultivariate_normal_gen.entropyc                 C   s   t |}|jdkrtd|j\}}|durVt |}|j|fkrPd}t||}n|jdd}|durt |}|j||fkrd}t|tj	j
|ddd	\}}	t|}
t ||
 k rd
}t||}n|| }|j| | }||fS )a#  Fit a multivariate normal distribution to data.

        Parameters
        ----------
        x : ndarray (m, n)
            Data the distribution is fitted to. Must have two axes.
            The first axis of length `m` represents the number of vectors
            the distribution is fitted to. The second axis of length `n`
            determines the dimensionality of the fitted distribution.
        fix_mean : ndarray(n, )
            Fixed mean vector. Must have length `n`.
        fix_cov: ndarray (n, n)
            Fixed covariance matrix. Must have shape `(n, n)`.

        Returns
        -------
        mean : ndarray (n, )
            Maximum likelihood estimate of the mean vector
        cov : ndarray (n, n)
            Maximum likelihood estimate of the covariance matrix

        r)   z`x` must be two-dimensional.Nzd`fix_mean` must be a one-dimensional array the same length as the dimensionality of the vectors `x`.r   rg   zn`fix_cov` must be a two-dimensional square array of same side length as the dimensionality of the vectors `x`.TrM   z2`fix_cov` must be symmetric positive semidefinite.)r8   rO   r,   rU   r   
atleast_1dr   Z
atleast_2drQ   rR   rS   r@   rT   rl   )r`   rC   Zfix_meanZfix_covZ	n_vectorsr   re   r   rc   rd   r9   r   Zcentered_datar*   r*   r/   fit  s2    




zmultivariate_normal_gen.fit)N)Nr   FN)T)Nr   F)Nr   F)Nr   FNrA   rA   )Nr   FNrA   rA   )Nr   r   N)Nr   )NN)ro   rp   rq   rr   rf   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r*   r*   ry   r/   r   !  s0   b
	
9

4  -  )
%
r   c                   @   s`   e Zd ZdddZedd Zd	d
 Zdd ZddddZddddZ	dddZ
dd ZdS )r   Nr   FrA   c                 C   sX   t || _| j|||\| _| _| _|p0| jj| _|sBd| j }|| _|| _	|| _
dS )af  Create a frozen multivariate normal distribution.

        Parameters
        ----------
        mean : array_like, default: ``[0]``
            Mean of the distribution.
        cov : array_like, default: ``[1]``
            Symmetric positive (semi)definite covariance matrix of the
            distribution.
        allow_singular : bool, default: ``False``
            Whether to allow a singular covariance matrix.
        seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
            If `seed` is None (or `np.random`), the `numpy.random.RandomState`
            singleton is used.
            If `seed` is an int, a new ``RandomState`` instance is used,
            seeded with `seed`.
            If `seed` is already a ``Generator`` or ``RandomState`` instance
            then that instance is used.
        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.]])

        r   N)r   r   r   r   r   r   Z_allow_singularrb   r   r   r   )r`   r   r   rb   rx   r   r   r   r*   r*   r/   rf   Z  s    +

z#multivariate_normal_frozen.__init__c                 C   s   | j jS rj   )r   r   rm   r*   r*   r/   r     s    zmultivariate_normal_frozen.covc                 C   s`   | j || j}| j || j| j}t| jj| jk rX| j	|| j  }tj
 ||< t|S rj   )r   r   r   r   r   r   r8   r   rZ   ri   r   r0   )r`   rC   r.   r   r*   r*   r/   r     s    z!multivariate_normal_frozen.logpdfc                 C   s   t | |S rj   r8   r   r   r`   rC   r*   r*   r/   r     s    zmultivariate_normal_frozen.pdfr   c                C   s6   | j ||d}t|dk r$|d n|}t|}|S )Nr   r   r   )r   r8   r   r]   )r`   rC   r   r   r.   r*   r*   r/   r     s    
z!multivariate_normal_frozen.logcdfc             	   C   s<   | j || j}| j || j| jj| j| j| j	|}t
|S rj   )r   r   r   r   r   r   r   r   r   r   r0   )r`   rC   r   r.   r*   r*   r/   r     s    zmultivariate_normal_frozen.cdfc                 C   s   | j | j| j||S rj   )r   r   r   r   r`   r   r{   r*   r*   r/   r     s    zmultivariate_normal_frozen.rvsc                 C   s$   | j j}| j j}d|td  |  S )zComputes the differential entropy of the multivariate normal.

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

        r   r   )r   r^   rZ   r   )r`   r^   rZ   r*   r*   r/   r     s    	z"multivariate_normal_frozen.entropy)Nr   FNNrA   rA   )r   N)ro   rp   rq   rf   rs   r   r   r   r   r   r   r   r*   r*   r*   r/   r   Y  s     
5

r   )r   r   r   r   r   a  mean : array_like, optional
    Mean of the distribution (default: `None`)
rowcov : array_like, optional
    Among-row covariance matrix of the distribution (default: `1`)
colcov : array_like, optional
    Among-column covariance matrix of the distribution (default: `1`)
a  If `mean` is set to `None` then a matrix of zeros is used for the mean.
The dimensions of this matrix are inferred from the shape of `rowcov` and
`colcov`, if these are provided, or set to `1` if ambiguous.

`rowcov` and `colcov` can be two-dimensional array_likes specifying the
covariance matrices directly. Alternatively, a one-dimensional array will
be be interpreted as the entries of a diagonal matrix, and a scalar or
zero-dimensional array will be interpreted as this value times the
identity matrix.
)_matnorm_doc_default_callparams_matnorm_doc_callparams_noter   c                       st   e Zd ZdZd fdd	ZdddZdd	 Zd
d Zdd ZdddZ	dddZ
dddZdddZdd Z  ZS )matrix_normal_genaT  A matrix normal random variable.

    The `mean` keyword specifies the mean. The `rowcov` keyword specifies the
    among-row covariance matrix. The 'colcov' keyword specifies the
    among-column covariance matrix.

    Methods
    -------
    pdf(X, mean=None, rowcov=1, colcov=1)
        Probability density function.
    logpdf(X, mean=None, rowcov=1, colcov=1)
        Log of the probability density function.
    rvs(mean=None, rowcov=1, colcov=1, size=1, random_state=None)
        Draw random samples.
    entropy(rowcol=1, colcov=1)
        Differential entropy.

    Parameters
    ----------
    %(_matnorm_doc_default_callparams)s
    %(_doc_random_state)s

    Notes
    -----
    %(_matnorm_doc_callparams_note)s

    The covariance matrices specified by `rowcov` and `colcov` must be
    (symmetric) positive definite. If the samples in `X` are
    :math:`m \times n`, then `rowcov` must be :math:`m \times m` and
    `colcov` must be :math:`n \times n`. `mean` must be the same shape as `X`.

    The probability density function for `matrix_normal` is

    .. math::

        f(X) = (2 \pi)^{-\frac{mn}{2}}|U|^{-\frac{n}{2}} |V|^{-\frac{m}{2}}
               \exp\left( -\frac{1}{2} \mathrm{Tr}\left[ U^{-1} (X-M) V^{-1}
               (X-M)^T \right] \right),

    where :math:`M` is the mean, :math:`U` the among-row covariance matrix,
    :math:`V` the among-column covariance matrix.

    The `allow_singular` behaviour of the `multivariate_normal`
    distribution is not currently supported. Covariance matrices must be
    full rank.

    The `matrix_normal` distribution is closely related to the
    `multivariate_normal` distribution. Specifically, :math:`\mathrm{Vec}(X)`
    (the vector formed by concatenating the columns  of :math:`X`) has a
    multivariate normal distribution with mean :math:`\mathrm{Vec}(M)`
    and covariance :math:`V \otimes U` (where :math:`\otimes` is the Kronecker
    product). Sampling and pdf evaluation are
    :math:`\mathcal{O}(m^3 + n^3 + m^2 n + m n^2)` for the matrix normal, but
    :math:`\mathcal{O}(m^3 n^3)` for the equivalent multivariate normal,
    making this equivalent form algorithmically inefficient.

    .. versionadded:: 0.17.0

    Examples
    --------

    >>> import numpy as np
    >>> from scipy.stats import matrix_normal

    >>> M = np.arange(6).reshape(3,2); M
    array([[0, 1],
           [2, 3],
           [4, 5]])
    >>> U = np.diag([1,2,3]); U
    array([[1, 0, 0],
           [0, 2, 0],
           [0, 0, 3]])
    >>> V = 0.3*np.identity(2); V
    array([[ 0.3,  0. ],
           [ 0. ,  0.3]])
    >>> X = M + 0.1; X
    array([[ 0.1,  1.1],
           [ 2.1,  3.1],
           [ 4.1,  5.1]])
    >>> matrix_normal.pdf(X, mean=M, rowcov=U, colcov=V)
    0.023410202050005054

    >>> # Equivalent multivariate normal
    >>> from scipy.stats import multivariate_normal
    >>> vectorised_X = X.T.flatten()
    >>> equiv_mean = M.T.flatten()
    >>> equiv_cov = np.kron(V,U)
    >>> multivariate_normal.pdf(vectorised_X, mean=equiv_mean, cov=equiv_cov)
    0.023410202050005054

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

    >>> rv = matrix_normal(mean=None, rowcov=1, colcov=1)
    >>> # Frozen object with the same methods but holding the given
    >>> # mean and covariance fixed.

    Nc                    s    t  | t| jt| _d S rj   )ru   rf   r   r   rr   matnorm_docdict_paramsrw   ry   r*   r/   rf   S  s    zmatrix_normal_gen.__init__r   c                 C   s   t ||||dS )zoCreate a frozen matrix normal distribution.

        See `matrix_normal_frozen` for more information.

        rx   )matrix_normal_frozenr`   r   rowcovcolcovrx   r*   r*   r/   r   W  s    zmatrix_normal_gen.__call__c           
      C   s  |durFt j|td}|j}t|dkr0tdt |dkrFtdt j|td}|jdkr|durz|t |d  }q|t d }n|jdkrt 	|}|j}t|dkrtd|d |d krtd	|d dkrtd
|d }t j|td}|jdkr4|dur$|t |d  }n|t d }n|jdkrJt 	|}|j}t|dkrftd|d |d krtd|d dkrtd|d }|dur|d |krtd|d |krtdnt 
||f}||f}	|	|||fS )z
        Infer dimensionality from mean or covariance matrices. Handle
        defaults. Ensure compatible dimensions.
        NrG   r)   z%Array `mean` must be two dimensional.r   zArray `mean` has invalid shape.r   z(`rowcov` must be a scalar or a 2D array.zArray `rowcov` must be square.z!Array `rowcov` has invalid shape.z(`colcov` must be a scalar or a 2D array.zArray `colcov` must be square.z!Array `colcov` has invalid shape.z=Arrays `mean` and `rowcov` must have the same number of rows.z@Arrays `mean` and `colcov` must have the same number of columns.)r8   rO   rI   r   rV   rU   r   r,   identityr   r   )
r`   r   r   r   Z	meanshapeZrowshapenumrowsZcolshapenumcolsdimsr*   r*   r/   r   _  sZ    






z%matrix_normal_gen._process_parametersc                 C   sH   t j|td}|jdkr*|t jddf }|jdd |krDtd|S )zp
        Adjust quantiles array so that last two axes labels the components of
        each data point.
        rG   r)   NzJThe shape of array `X` is not compatible with the distribution parameters.)r8   rO   rI   r,   r   r   rU   )r`   Xr   r*   r*   r/   r     s    
z$matrix_normal_gen._process_quantilesc                 C   st   |\}}	t || dd}
t |jt |
|d}t jt jt |dddd}d||	 t |	|  ||  |  S )a  Log of the matrix normal probability density function.

        Parameters
        ----------
        dims : tuple
            Dimensions of the matrix variates
        X : ndarray
            Points at which to evaluate the log of the probability
            density function
        mean : ndarray
            Mean of the distribution
        row_prec_rt : ndarray
            A decomposition such that np.dot(row_prec_rt, row_prec_rt.T)
            is the inverse of the among-row covariance matrix
        log_det_rowcov : float
            Logarithm of the determinant of the among-row covariance matrix
        col_prec_rt : ndarray
            A decomposition such that np.dot(col_prec_rt, col_prec_rt.T)
            is the inverse of the among-column covariance matrix
        log_det_colcov : float
            Logarithm of the determinant of the among-column covariance matrix

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

        r1   r   r   rg   r   )r8   ZmoveaxisZ	tensordotrl   rk   r\   r   r   )r`   r   r   r   Zrow_prec_rtZlog_det_rowcovZcol_prec_rtZlog_det_colcovr   r   Zroll_devZ	scale_devr   r*   r*   r/   r     s    zmatrix_normal_gen._logpdfc           	   	   C   s`   |  |||\}}}}| ||}t|dd}t|dd}| ||||j|j|j|j}t|S )a  Log of the matrix normal probability density function.

        Parameters
        ----------
        X : array_like
            Quantiles, with the last two axes of `X` denoting the components.
        %(_matnorm_doc_default_callparams)s

        Returns
        -------
        logpdf : ndarray
            Log of the probability density function evaluated at `X`

        Notes
        -----
        %(_matnorm_doc_callparams_note)s

        Fr   )r   r   rL   r   r[   r^   r0   )	r`   r   r   r   r   r   rowpsdcolpsdr.   r*   r*   r/   r     s    zmatrix_normal_gen.logpdfc                 C   s   t | ||||S )a  Matrix normal probability density function.

        Parameters
        ----------
        X : array_like
            Quantiles, with the last two axes of `X` denoting the components.
        %(_matnorm_doc_default_callparams)s

        Returns
        -------
        pdf : ndarray
            Probability density function evaluated at `X`

        Notes
        -----
        %(_matnorm_doc_callparams_note)s

        r   )r`   r   r   r   r   r*   r*   r/   r     s    zmatrix_normal_gen.pdfc                 C   s   t |}| |||\}}}}tjj|dd}tjj|dd}| |}|j|d ||d fdddd}	|tj	d||	|dd }
|dkr|

|j}
|
S )	a  Draw random samples from a matrix normal distribution.

        Parameters
        ----------
        %(_matnorm_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`, `dims`), where `dims` is the
            dimension of the random matrices.

        Notes
        -----
        %(_matnorm_doc_callparams_note)s

        Tr7   r   r   r   r)   zjp,ipq,kq->ijk)optimize)intr   rQ   rR   choleskyr~   standard_normal	transposer8   einsumr   r   )r`   r   r   r   r   r{   r   ZrowcholZcolcholZstd_normr.   r*   r*   r/   r     s&    
zmatrix_normal_gen.rvsc                 C   sZ   t |jd |jd f}| |||\}}}}t|dd}t|dd}| ||j|jS )a  Log of the matrix normal probability density function.

        Parameters
        ----------
        rowcov : array_like, optional
            Among-row covariance matrix of the distribution (default: `1`)
        colcov : array_like, optional
            Among-column covariance matrix of the distribution (default: `1`)

        Returns
        -------
        entropy : float
            Entropy of the distribution

        Notes
        -----
        %(_matnorm_doc_callparams_note)s

        r   Fr   )r8   r   r   r   rL   _entropyr^   )r`   r   r   Z
dummy_meanr   _r   r   r*   r*   r/   r   .  s    zmatrix_normal_gen.entropyc                 C   s4   |\}}d| | dt   d| |  d| |  S Nr   r   )r   )r`   r   Zrow_cov_logdetZcol_cov_logdetr   pr*   r*   r/   r   K  s    
zmatrix_normal_gen._entropy)N)Nr   r   N)Nr   r   )Nr   r   )Nr   r   r   N)r   r   )ro   rp   rq   rr   rf   r   r   r   r   r   r   r   r   r   r   r*   r*   ry   r/   r     s   d
B&


)
r   c                   @   s<   e Zd ZdZdddZdd Zdd	 Zdd
dZdd ZdS )r   a  
    Create a frozen matrix normal distribution.

    Parameters
    ----------
    %(_matnorm_doc_default_callparams)s
    seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
        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`.

    Examples
    --------
    >>> import numpy as np
    >>> from scipy.stats import matrix_normal

    >>> distn = matrix_normal(mean=np.zeros((3,3)))
    >>> X = distn.rvs(); X
    array([[-0.02976962,  0.93339138, -0.09663178],
           [ 0.67405524,  0.28250467, -0.93308929],
           [-0.31144782,  0.74535536,  1.30412916]])
    >>> distn.pdf(X)
    2.5160642368346784e-05
    >>> distn.logpdf(X)
    -10.590229595124615
    Nr   c                 C   sN   t || _| j|||\| _| _| _| _t| jdd| _t| jdd| _	d S )NFr   )
r   r   r   r   r   r   r   rL   r   r   r   r*   r*   r/   rf   s  s
    
zmatrix_normal_frozen.__init__c              	   C   sD   | j || j}| j | j|| j| jj| jj| jj| jj}t	|S rj   )
r   r   r   r   r   r   r[   r^   r   r0   )r`   r   r.   r*   r*   r/   r   z  s    zmatrix_normal_frozen.logpdfc                 C   s   t | |S rj   r   )r`   r   r*   r*   r/   r     s    zmatrix_normal_frozen.pdfc                 C   s   | j | j| j| j||S rj   )r   r   r   r   r   r   r*   r*   r/   r     s    zmatrix_normal_frozen.rvsc                 C   s   | j | j| jj| jjS rj   )r   r   r   r   r^   r   rm   r*   r*   r/   r     s    zmatrix_normal_frozen.entropy)Nr   r   N)r   N)	ro   rp   rq   rr   rf   r   r   r   r   r*   r*   r*   r/   r   T  s   

r   )r   r   r   r   zalpha : array_like
    The concentration parameters. The number of entries determines the
    dimensionality of the distribution.
)!_dirichlet_doc_default_callparamsr   c                 C   sB   t | } t | dkr"tdn| jdkr>td| j d| S )Nr   z%All parameters must be greater than 0r   z<Parameter vector 'a' must be one dimensional, but a.shape = .)r8   rO   rT   rU   r,   r   alphar*   r*   r/   _dirichlet_check_parameters  s    



r   c                 C   sv  t |}|jd d | jd krP|jd | jd krPtd| j d|j d|jd | jd krt dt |d g}|jdkrt ||}n"|jdkrt ||f}ntdt 	|dk rtdt 
|dkrtd	|dk}| dk }|j| jkrt j||jd
 d
d|j}t ||}t |r>tdt t |dd dk rrtdt |d |S )Nr   r   z|Vector 'x' must have either the same number of entries as, or one entry fewer than, parameter vector 'a', but alpha.shape = z and x.shape = r   r)   zUThe input must be one dimensional or a two dimensional matrix containing the entries.z8Each entry in 'x' must be greater than or equal to zero.z/Each entry in 'x' must be smaller or equal one.r1   rg   zJEach entry in 'x' must be greater than zero if its alpha is less than one.r   g&.>zOThe input vector 'x' must lie within the normal simplex. but np.sum(x, 0) = %s.)r8   rO   r   rU   rH   r\   r,   appendZvstackrT   r:   repeatr   logical_andr;   r   )r   rC   ZxkZxeq0Zalphalt1Zchkr*   r*   r/   _dirichlet_check_input  s<    
,


 
r  c                 C   s   t t| tt |  S )av  Internal helper function to compute the log of the useful quotient.

    .. math::

        B(\alpha) = \frac{\prod_{i=1}{K}\Gamma(\alpha_i)}
                         {\Gamma\left(\sum_{i=1}^{K} \alpha_i \right)}

    Parameters
    ----------
    %(_dirichlet_doc_default_callparams)s

    Returns
    -------
    B : scalar
        Helper quotient, internal use only

    )r8   r\   r   r   r*   r*   r/   _lnB  s    r  c                       sn   e Zd ZdZd fdd	ZdddZdd Zd	d
 Zdd Zdd Z	dd Z
dd Zdd ZdddZ  ZS )dirichlet_gena  A Dirichlet random variable.

    The ``alpha`` keyword specifies the concentration parameters of the
    distribution.

    .. versionadded:: 0.15.0

    Methods
    -------
    pdf(x, alpha)
        Probability density function.
    logpdf(x, alpha)
        Log of the probability density function.
    rvs(alpha, size=1, random_state=None)
        Draw random samples from a Dirichlet distribution.
    mean(alpha)
        The mean of the Dirichlet distribution
    var(alpha)
        The variance of the Dirichlet distribution
    cov(alpha)
        The covariance of the Dirichlet distribution
    entropy(alpha)
        Compute the differential entropy of the Dirichlet distribution.

    Parameters
    ----------
    %(_dirichlet_doc_default_callparams)s
    %(_doc_random_state)s

    Notes
    -----
    Each :math:`\alpha` entry must be positive. The distribution has only
    support on the simplex defined by

    .. math::
        \sum_{i=1}^{K} x_i = 1

    where :math:`0 < x_i < 1`.

    If the quantiles don't lie within the simplex, a ValueError is raised.

    The probability density function for `dirichlet` is

    .. math::

        f(x) = \frac{1}{\mathrm{B}(\boldsymbol\alpha)} \prod_{i=1}^K x_i^{\alpha_i - 1}

    where

    .. math::

        \mathrm{B}(\boldsymbol\alpha) = \frac{\prod_{i=1}^K \Gamma(\alpha_i)}
                                     {\Gamma\bigl(\sum_{i=1}^K \alpha_i\bigr)}

    and :math:`\boldsymbol\alpha=(\alpha_1,\ldots,\alpha_K)`, the
    concentration parameters and :math:`K` is the dimension of the space
    where :math:`x` takes values.

    Note that the `dirichlet` interface is somewhat inconsistent.
    The array returned by the rvs function is transposed
    with respect to the format expected by the pdf and logpdf.

    Examples
    --------
    >>> import numpy as np
    >>> from scipy.stats import dirichlet

    Generate a dirichlet random variable

    >>> quantiles = np.array([0.2, 0.2, 0.6])  # specify quantiles
    >>> alpha = np.array([0.4, 5, 15])  # specify concentration parameters
    >>> dirichlet.pdf(quantiles, alpha)
    0.2843831684937255

    The same PDF but following a log scale

    >>> dirichlet.logpdf(quantiles, alpha)
    -1.2574327653159187

    Once we specify the dirichlet distribution
    we can then calculate quantities of interest

    >>> dirichlet.mean(alpha)  # get the mean of the distribution
    array([0.01960784, 0.24509804, 0.73529412])
    >>> dirichlet.var(alpha) # get variance
    array([0.00089829, 0.00864603, 0.00909517])
    >>> dirichlet.entropy(alpha)  # calculate the differential entropy
    -4.3280162474082715

    We can also return random samples from the distribution

    >>> dirichlet.rvs(alpha, size=1, random_state=1)
    array([[0.00766178, 0.24670518, 0.74563305]])
    >>> dirichlet.rvs(alpha, size=2, random_state=2)
    array([[0.01639427, 0.1292273 , 0.85437844],
           [0.00156917, 0.19033695, 0.80809388]])

    Alternatively, the object may be called (as a function) to fix
    concentration parameters, returning a "frozen" Dirichlet
    random variable:

    >>> rv = dirichlet(alpha)
    >>> # Frozen object with the same methods but holding the given
    >>> # concentration parameters fixed.

    Nc                    s    t  | t| jt| _d S rj   )ru   rf   r   r   rr   dirichlet_docdict_paramsrw   ry   r*   r/   rf   b  s    zdirichlet_gen.__init__c                 C   s   t ||dS Nr   )dirichlet_frozenr`   r   rx   r*   r*   r/   r   f  s    zdirichlet_gen.__call__c                 C   s(   t |}| tt|d |jjd S )a  Log of the Dirichlet probability density function.

        Parameters
        ----------
        x : ndarray
            Points at which to evaluate the log of the probability
            density function
        %(_dirichlet_doc_default_callparams)s

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

        r   r   )r  r8   r\   r   rl   )r`   rC   r   lnBr*   r*   r/   r   i  s    zdirichlet_gen._logpdfc                 C   s&   t |}t||}| ||}t|S )ay  Log of the Dirichlet probability density function.

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

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

        )r   r  r   r0   r`   rC   r   r.   r*   r*   r/   r   |  s    
zdirichlet_gen.logpdfc                 C   s,   t |}t||}t| ||}t|S )ak  The Dirichlet probability density function.

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

        Returns
        -------
        pdf : ndarray or scalar
            The probability density function evaluated at `x`.

        )r   r  r8   r   r   r0   r  r*   r*   r/   r     s    
zdirichlet_gen.pdfc                 C   s   t |}|t| }t|S )zMean of the Dirichlet distribution.

        Parameters
        ----------
        %(_dirichlet_doc_default_callparams)s

        Returns
        -------
        mu : ndarray or scalar
            Mean of the Dirichlet distribution.

        r   r8   r\   r0   )r`   r   r.   r*   r*   r/   r     s    zdirichlet_gen.meanc                 C   s6   t |}t|}|||  || |d   }t|S )zVariance of the Dirichlet distribution.

        Parameters
        ----------
        %(_dirichlet_doc_default_callparams)s

        Returns
        -------
        v : ndarray or scalar
            Variance of the Dirichlet distribution.

        r   r  )r`   r   alpha0r.   r*   r*   r/   var  s    
zdirichlet_gen.varc                 C   s@   t |}t|}|| }t|t|| |d  }t|S )zCovariance matrix of the Dirichlet distribution.

        Parameters
        ----------
        %(_dirichlet_doc_default_callparams)s

        Returns
        -------
        cov : ndarray
            The covariance matrix of the distribution.
        r   )r   r8   r\   r   outerr0   )r`   r   r  r   r   r*   r*   r/   r     s
    
zdirichlet_gen.covc                 C   s^   t |}t|}t|}|jd }||| tj|  t|d tj|  }t|S )a  
        Differential entropy of the Dirichlet distribution.

        Parameters
        ----------
        %(_dirichlet_doc_default_callparams)s

        Returns
        -------
        h : scalar
            Entropy of the Dirichlet distribution

        r   r   )	r   r8   r\   r  r   rQ   Zspecialr   r0   )r`   r   r  r
  Kr.   r*   r*   r/   r     s    

zdirichlet_gen.entropyr   c                 C   s    t |}| |}|j||dS )a  
        Draw random samples from a Dirichlet distribution.

        Parameters
        ----------
        %(_dirichlet_doc_default_callparams)s
        size : int, 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.

        r   )r   r~   r   )r`   r   r   r{   r*   r*   r/   r     s    
zdirichlet_gen.rvs)N)N)r   N)ro   rp   rq   rr   rf   r   r   r   r   r   r  r   r   r   r   r*   r*   ry   r/   r    s   k
r  c                   @   sP   e Zd ZdddZdd Zdd Zdd	 Zd
d Zdd Zdd Z	dddZ
dS )r  Nc                 C   s   t || _t|| _d S rj   )r   r   r  r   r	  r*   r*   r/   rf     s    
zdirichlet_frozen.__init__c                 C   s   | j || jS rj   )r   r   r   r   r*   r*   r/   r     s    zdirichlet_frozen.logpdfc                 C   s   | j || jS rj   )r   r   r   r   r*   r*   r/   r     s    zdirichlet_frozen.pdfc                 C   s   | j | jS rj   )r   r   r   rm   r*   r*   r/   r     s    zdirichlet_frozen.meanc                 C   s   | j | jS rj   )r   r  r   rm   r*   r*   r/   r  !  s    zdirichlet_frozen.varc                 C   s   | j | jS rj   )r   r   r   rm   r*   r*   r/   r   $  s    zdirichlet_frozen.covc                 C   s   | j | jS rj   )r   r   r   rm   r*   r*   r/   r   '  s    zdirichlet_frozen.entropyr   c                 C   s   | j | j||S rj   )r   r   r   r   r*   r*   r/   r   *  s    zdirichlet_frozen.rvs)N)r   N)ro   rp   rq   rf   r   r   r   r  r   r   r   r*   r*   r*   r/   r    s   
r  )r   r   r   r   r  r   r   zdf : int
    Degrees of freedom, must be greater than or equal to dimension of the
    scale matrix
scale : array_like
    Symmetric positive definite scale matrix of the distribution
)Z_doc_default_callparamsZ_doc_callparams_noter   c                       s   e Zd ZdZd, fdd	Zd-ddZdd Zd	d
 Zdd Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd Zdd  Zd!d" Zd.d$d%Zd&d' Zd(d) Zd*d+ Z  ZS )/wishart_genaq  A Wishart random variable.

    The `df` keyword specifies the degrees of freedom. The `scale` keyword
    specifies the scale matrix, which must be symmetric and positive definite.
    In this context, the scale matrix is often interpreted in terms of a
    multivariate normal precision matrix (the inverse of the covariance
    matrix). These arguments must satisfy the relationship
    ``df > scale.ndim - 1``, but see notes on using the `rvs` method with
    ``df < scale.ndim``.

    Methods
    -------
    pdf(x, df, scale)
        Probability density function.
    logpdf(x, df, scale)
        Log of the probability density function.
    rvs(df, scale, size=1, random_state=None)
        Draw random samples from a Wishart distribution.
    entropy()
        Compute the differential entropy of the Wishart distribution.

    Parameters
    ----------
    %(_doc_default_callparams)s
    %(_doc_random_state)s

    Raises
    ------
    scipy.linalg.LinAlgError
        If the scale matrix `scale` is not positive definite.

    See Also
    --------
    invwishart, chi2

    Notes
    -----
    %(_doc_callparams_note)s

    The scale matrix `scale` must be a symmetric positive definite
    matrix. Singular matrices, including the symmetric positive semi-definite
    case, are not supported. Symmetry is not checked; only the lower triangular
    portion is used.

    The Wishart distribution is often denoted

    .. math::

        W_p(\nu, \Sigma)

    where :math:`\nu` is the degrees of freedom and :math:`\Sigma` is the
    :math:`p \times p` scale matrix.

    The probability density function for `wishart` has support over positive
    definite matrices :math:`S`; if :math:`S \sim W_p(\nu, \Sigma)`, then
    its PDF is given by:

    .. math::

        f(S) = \frac{|S|^{\frac{\nu - p - 1}{2}}}{2^{ \frac{\nu p}{2} }
               |\Sigma|^\frac{\nu}{2} \Gamma_p \left ( \frac{\nu}{2} \right )}
               \exp\left( -tr(\Sigma^{-1} S) / 2 \right)

    If :math:`S \sim W_p(\nu, \Sigma)` (Wishart) then
    :math:`S^{-1} \sim W_p^{-1}(\nu, \Sigma^{-1})` (inverse Wishart).

    If the scale matrix is 1-dimensional and equal to one, then the Wishart
    distribution :math:`W_1(\nu, 1)` collapses to the :math:`\chi^2(\nu)`
    distribution.

    The algorithm [2]_ implemented by the `rvs` method may
    produce numerically singular matrices with :math:`p - 1 < \nu < p`; the
    user may wish to check for this condition and generate replacement samples
    as necessary.


    .. versionadded:: 0.16.0

    References
    ----------
    .. [1] M.L. Eaton, "Multivariate Statistics: A Vector Space Approach",
           Wiley, 1983.
    .. [2] W.B. Smith and R.R. Hocking, "Algorithm AS 53: Wishart Variate
           Generator", Applied Statistics, vol. 21, pp. 341-345, 1972.

    Examples
    --------
    >>> import numpy as np
    >>> import matplotlib.pyplot as plt
    >>> from scipy.stats import wishart, chi2
    >>> x = np.linspace(1e-5, 8, 100)
    >>> w = wishart.pdf(x, df=3, scale=1); w[:5]
    array([ 0.00126156,  0.10892176,  0.14793434,  0.17400548,  0.1929669 ])
    >>> c = chi2.pdf(x, 3); c[:5]
    array([ 0.00126156,  0.10892176,  0.14793434,  0.17400548,  0.1929669 ])
    >>> plt.plot(x, w)
    >>> plt.show()

    The input quantiles can be any shape of array, as long as the last
    axis labels the components.

    Alternatively, the object may be called (as a function) to fix the degrees
    of freedom and scale parameters, returning a "frozen" Wishart random
    variable:

    >>> rv = wishart(df=1, scale=1)
    >>> # Frozen object with the same methods but holding the given
    >>> # degrees of freedom and scale fixed.

    Nc                    s    t  | t| jt| _d S rj   ru   rf   r   r   rr   wishart_docdict_paramsrw   ry   r*   r/   rf     s    zwishart_gen.__init__c                 C   s   t |||S )zbCreate a frozen Wishart distribution.

        See `wishart_frozen` for more information.
        )wishart_frozenr`   dfscalerx   r*   r*   r/   r     s    zwishart_gen.__call__c                 C   s   |d u rd}t j|td}|jdkr6|t jt jf }n`|jdkrLt |}nJ|jdkr~|jd |jd ks~tdt|j n|jdkrtd|j |jd }|d u r|}n(t 	|stdn||d krtd	|||fS )
Nr   rG   r   r   r)   zLArray 'scale' must be square if it is two dimensional, but scale.scale = %s.zBArray 'scale' must be at most two-dimensional, but scale.ndim = %dz$Degrees of freedom must be a scalar.zNDegrees of freedom must be greater than the dimension of scale matrix minus 1.)
r8   rO   rI   r,   r   r   r   rU   r   r   )r`   r  r  r   r*   r*   r/   r     s.    





zwishart_gen._process_parametersc                 C   s^  t j|td}|jdkr:|t |ddddt jf  }|jdkr|dkrd|t jt jddf }nt |ddddt jf }n|jdkr|jd |jd kstdt	|j |ddddt jf }nP|jdkr|jd |jd kstdt	|j n|jdkrtd	|j |jdd ||fksZtd
||f d|jdd  d|S )r   rG   r   Nr   r)   zGQuantiles must be square if they are two dimensional, but x.shape = %s.   zeQuantiles must be square in the first two dimensions if they are three dimensional, but x.shape = %s.znQuantiles must be at most two-dimensional with an additional dimension for multiplecomponents, but x.ndim = %dz2Quantiles have incompatible dimensions: should be z, got r   )
r8   rO   rI   r,   r   r   r   r   rU   r   r   r*   r*   r/   r     s:    
"
 

zwishart_gen._process_quantilesc                 C   sV   t |}|jdkr |t j }n|jdkr>tdtt| | }t|}||fS )Nr   r   z_Size must be an integer or tuple of integers; thus must have dimension <= 1. Got size.ndim = %s)r8   rO   r,   r   rU   r   r   prod)r`   r   r   r   r*   r*   r/   _process_size  s    



zwishart_gen._process_sizec                 C   s  t |jd }t |j}t |jd }	t|jd D ]|}
| |dddd|
f \}||
< tj|df|dddd|
f |dddd|
f< |dddd|
f  |	|
< q:d|| d  | d|	  d| | t	 d| |  t
d| |  }|S )a  Log of the Wishart probability density function.

        Parameters
        ----------
        x : ndarray
            Points at which to evaluate the log of the probability
            density function
        dim : int
            Dimension of the scale matrix
        df : int
            Degrees of freedom
        scale : ndarray
            Scale matrix
        log_det_scale : float
            Logarithm of the determinant of the scale matrix
        C : ndarray
            Cholesky factorization of the scale matrix, lower triagular.

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

        r1   NTr   r   )r8   emptyr   range_cholesky_logdetrQ   rR   Z	cho_solvetrace_LOG_2r   )r`   rC   r   r  r  log_det_scaleC	log_det_xZscale_inv_xZtr_scale_inv_xir   r.   r*   r*   r/   r     s    $6 zwishart_gen._logpdfc                 C   sH   |  ||\}}}| ||}| |\}}| ||||||}t|S )a  Log of the Wishart probability density function.

        Parameters
        ----------
        x : array_like
            Quantiles, with the last axis of `x` denoting the components.
            Each quantile must be a symmetric positive definite matrix.
        %(_doc_default_callparams)s

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

        Notes
        -----
        %(_doc_callparams_note)s

        r   r   r  r   r0   r`   rC   r  r  r   r!  r   r.   r*   r*   r/   r   M  s
    zwishart_gen.logpdfc                 C   s   t | |||S )a  Wishart probability density function.

        Parameters
        ----------
        x : array_like
            Quantiles, with the last axis of `x` denoting the components.
            Each quantile must be a symmetric positive definite matrix.
        %(_doc_default_callparams)s

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

        Notes
        -----
        %(_doc_callparams_note)s

        r   r`   rC   r  r  r*   r*   r/   r   j  s    zwishart_gen.pdfc                 C   s   || S )aA  Mean of the Wishart distribution.

        Parameters
        ----------
        dim : int
            Dimension of the scale matrix
        %(_doc_default_callparams)s

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

        r*   r`   r   r  r  r*   r*   r/   _mean  s    zwishart_gen._meanc                 C   s(   |  ||\}}}| |||}t|S )zMean of the Wishart distribution.

        Parameters
        ----------
        %(_doc_default_callparams)s

        Returns
        -------
        mean : float
            The mean of the distribution
        r   r(  r0   r`   r  r  r   r.   r*   r*   r/   r     s    zwishart_gen.meanc                 C   s&   ||d kr|| d | }nd}|S )aA  Mode of the Wishart distribution.

        Parameters
        ----------
        dim : int
            Dimension of the scale matrix
        %(_doc_default_callparams)s

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

        r   Nr*   r`   r   r  r  r.   r*   r*   r/   _mode  s    zwishart_gen._modec                 C   s4   |  ||\}}}| |||}|dur0t|S |S )aE  Mode of the Wishart distribution

        Only valid if the degrees of freedom are greater than the dimension of
        the scale matrix.

        Parameters
        ----------
        %(_doc_default_callparams)s

        Returns
        -------
        mode : float or None
            The Mode of the distribution
        Nr   r,  r0   r*  r*   r*   r/   mode  s    zwishart_gen.modec                 C   s,   |d }|  }|t||7 }||9 }|S )aD  Variance of the Wishart distribution.

        Parameters
        ----------
        dim : int
            Dimension of the scale matrix
        %(_doc_default_callparams)s

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

        r)   diagonalr8   r  r`   r   r  r  r  r   r*   r*   r/   _var  s
    zwishart_gen._varc                 C   s(   |  ||\}}}| |||}t|S )zVariance of the Wishart distribution.

        Parameters
        ----------
        %(_doc_default_callparams)s

        Returns
        -------
        var : float
            The variance of the distribution
        r   r2  r0   r*  r*   r*   r/   r    s    zwishart_gen.varc                    s   ||d  d }j | d||f }tj fddt|D  |f|ddd  j}t|||f }	ttdddgt	| }
tj
|dd}||	|
| < t|}||	|
| < |	S )	ax  
        Parameters
        ----------
        n : integer
            Number of variates to generate
        shape : iterable
            Shape of the variates to generate
        dim : int
            Dimension of the scale matrix
        df : int
            Degrees of freedom
        random_state : {None, int, `numpy.random.Generator`,
                        `numpy.random.RandomState`}, optional

            If `seed` is None (or `np.random`), the `numpy.random.RandomState`
            singleton is used.
            If `seed` is an int, a new ``RandomState`` instance is used,
            seeded with `seed`.
            If `seed` is already a ``Generator`` or ``RandomState`` instance
            then that instance is used.

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

        r   r)   r   c                    s*   g | ]"}j  |d   d  dd qS )r   r   r   )	chisquarerB   r#  r  r   r{   r*   r/   rE   	  s   z-wishart_gen._standard_rvs.<locals>.<listcomp>Nr1   k)r   r   r8   r_r  rl   r   r   slicerV   tril_indicesZdiag_indices)r`   r   r   r   r  r{   n_trilZcovariancesZ	variancesAZsize_idxZtril_idxZdiag_idxr*   r6  r/   _standard_rvs  s(    
zwishart_gen._standard_rvsc           
      C   sR   |  |}| |||||}t|D ]&}t||| }	t|	|	j||< q&|S )a]  Draw random samples from a Wishart distribution.

        Parameters
        ----------
        n : integer
            Number of variates to generate
        shape : iterable
            Shape of the variates to generate
        dim : int
            Dimension of the scale matrix
        df : int
            Degrees of freedom
        C : ndarray
            Cholesky factorization of the scale matrix, lower triangular.
        %(_doc_random_state)s

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

        )r~   r>  r8   ndindexrk   rl   )
r`   r   r   r   r  r!  r{   r=  indexCAr*   r*   r/   _rvs"	  s    
zwishart_gen._rvsr   c           
      C   sL   |  |\}}| ||\}}}tjj|dd}| ||||||}	t|	S )a  Draw random samples from a Wishart distribution.

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

        Returns
        -------
        rvs : ndarray
            Random variates of shape (`size`) + (``dim``, ``dim``), where
            ``dim`` is the dimension of the scale matrix.

        Notes
        -----
        %(_doc_callparams_note)s

        Tr   r  r   rQ   rR   r   rB  r0   
r`   r  r  r   r{   r   r   r   r!  r.   r*   r*   r/   r   O	  s
    zwishart_gen.rvsc                    sj   d|d  | d| |d  t   td  | d | d  t fddt|D   d  |  S )a  Compute the differential entropy of the Wishart.

        Parameters
        ----------
        dim : int
            Dimension of the scale matrix
        df : int
            Degrees of freedom
        log_det_scale : float
            Logarithm of the determinant of the scale matrix

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

        r   r   c                    s$   g | ]}t d  d |d   qS )r   r   )r   r5  r  r*   r/   rE   	  rF   z(wishart_gen._entropy.<locals>.<listcomp>)r  r   r8   r\   r  )r`   r   r  r   r*   rE  r/   r   n	  s    
zwishart_gen._entropyc                 C   s.   |  ||\}}}| |\}}| |||S )a'  Compute the differential entropy of the Wishart.

        Parameters
        ----------
        %(_doc_default_callparams)s

        Returns
        -------
        h : scalar
            Entropy of the Wishart distribution

        Notes
        -----
        %(_doc_callparams_note)s

        r   r  r   r`   r  r  r   r   r   r*   r*   r/   r   	  s    zwishart_gen.entropyc                 C   s0   t jj|dd}dtt|  }||fS )a  Compute Cholesky decomposition and determine (log(det(scale)).

        Parameters
        ----------
        scale : ndarray
            Scale matrix.

        Returns
        -------
        c_decomp : ndarray
            The Cholesky decomposition of `scale`.
        logdet : scalar
            The log of the determinant of `scale`.

        Notes
        -----
        This computation of ``logdet`` is equivalent to
        ``np.linalg.slogdet(scale)``.  It is ~2x faster though.

        Tr   r)   )rQ   rR   r   r8   r\   r]   r0  )r`   r  Zc_decompZlogdetr*   r*   r/   r  	  s    zwishart_gen._cholesky_logdet)N)NNN)r   N)ro   rp   rq   rr   rf   r   r   r   r  r   r   r   r(  r   r,  r.  r2  r  r>  rB  r   r   r   r  r   r*   r*   ry   r/   r  T  s*   o
%.4-
r  c                   @   sT   e Zd ZdZdddZdd Zdd Zd	d
 Zdd Zdd Z	dddZ
dd ZdS )r  aX  Create a frozen Wishart distribution.

    Parameters
    ----------
    df : array_like
        Degrees of freedom of the distribution
    scale : array_like
        Scale matrix of the distribution
    seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
        If `seed` is None (or `np.random`), the `numpy.random.RandomState`
        singleton is used.
        If `seed` is an int, a new ``RandomState`` instance is used,
        seeded with `seed`.
        If `seed` is already a ``Generator`` or ``RandomState`` instance then
        that instance is used.

    Nc                 C   s>   t || _| j||\| _| _| _| j| j\| _| _d S rj   )	r  r   r   r   r  r  r  r!  r   r  r*   r*   r/   rf   	  s
    
zwishart_frozen.__init__c                 C   s8   | j || j}| j || j| j| j| j| j}t|S rj   )	r   r   r   r   r  r  r   r!  r0   r`   rC   r.   r*   r*   r/   r   	  s
    zwishart_frozen.logpdfc                 C   s   t | |S rj   r   r   r*   r*   r/   r   	  s    zwishart_frozen.pdfc                 C   s   | j | j| j| j}t|S rj   r   r(  r   r  r  r0   r`   r.   r*   r*   r/   r   	  s    zwishart_frozen.meanc                 C   s*   | j | j| j| j}|d ur&t|S |S rj   r   r,  r   r  r  r0   rJ  r*   r*   r/   r.  	  s    zwishart_frozen.modec                 C   s   | j | j| j| j}t|S rj   r   r2  r   r  r  r0   rJ  r*   r*   r/   r  	  s    zwishart_frozen.varr   c                 C   s4   | j |\}}| j ||| j| j| j|}t|S rj   r   r  rB  r   r  r!  r0   r`   r   r{   r   r   r.   r*   r*   r/   r   	  s
    zwishart_frozen.rvsc                 C   s   | j | j| j| jS rj   r   r   r   r  r   rm   r*   r*   r/   r   	  s    zwishart_frozen.entropy)N)r   N)ro   rp   rq   rr   rf   r   r   r   r.  r  r   r   r*   r*   r*   r/   r  	  s   

r  )r   r   r   r.  r  r   r   c                       s   e Zd ZdZd$ fdd	Zd%ddZdd Zd	d
 Zdd Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zd&ddZd d! Zd"d# Z  ZS )'invwishart_genac  An inverse Wishart random variable.

    The `df` keyword specifies the degrees of freedom. The `scale` keyword
    specifies the scale matrix, which must be symmetric and positive definite.
    In this context, the scale matrix is often interpreted in terms of a
    multivariate normal covariance matrix.

    Methods
    -------
    pdf(x, df, scale)
        Probability density function.
    logpdf(x, df, scale)
        Log of the probability density function.
    rvs(df, scale, size=1, random_state=None)
        Draw random samples from an inverse Wishart distribution.
    entropy(df, scale)
        Differential entropy of the distribution.

    Parameters
    ----------
    %(_doc_default_callparams)s
    %(_doc_random_state)s

    Raises
    ------
    scipy.linalg.LinAlgError
        If the scale matrix `scale` is not positive definite.

    See Also
    --------
    wishart

    Notes
    -----
    %(_doc_callparams_note)s

    The scale matrix `scale` must be a symmetric positive definite
    matrix. Singular matrices, including the symmetric positive semi-definite
    case, are not supported. Symmetry is not checked; only the lower triangular
    portion is used.

    The inverse Wishart distribution is often denoted

    .. math::

        W_p^{-1}(\nu, \Psi)

    where :math:`\nu` is the degrees of freedom and :math:`\Psi` is the
    :math:`p \times p` scale matrix.

    The probability density function for `invwishart` has support over positive
    definite matrices :math:`S`; if :math:`S \sim W^{-1}_p(\nu, \Sigma)`,
    then its PDF is given by:

    .. math::

        f(S) = \frac{|\Sigma|^\frac{\nu}{2}}{2^{ \frac{\nu p}{2} }
               |S|^{\frac{\nu + p + 1}{2}} \Gamma_p \left(\frac{\nu}{2} \right)}
               \exp\left( -tr(\Sigma S^{-1}) / 2 \right)

    If :math:`S \sim W_p^{-1}(\nu, \Psi)` (inverse Wishart) then
    :math:`S^{-1} \sim W_p(\nu, \Psi^{-1})` (Wishart).

    If the scale matrix is 1-dimensional and equal to one, then the inverse
    Wishart distribution :math:`W_1(\nu, 1)` collapses to the
    inverse Gamma distribution with parameters shape = :math:`\frac{\nu}{2}`
    and scale = :math:`\frac{1}{2}`.

    Instead of inverting a randomly generated Wishart matrix as described in [2],
    here the algorithm in [4] is used to directly generate a random inverse-Wishart
    matrix without inversion.

    .. versionadded:: 0.16.0

    References
    ----------
    .. [1] M.L. Eaton, "Multivariate Statistics: A Vector Space Approach",
           Wiley, 1983.
    .. [2] M.C. Jones, "Generating Inverse Wishart Matrices", Communications
           in Statistics - Simulation and Computation, vol. 14.2, pp.511-514,
           1985.
    .. [3] Gupta, M. and Srivastava, S. "Parametric Bayesian Estimation of
           Differential Entropy and Relative Entropy". Entropy 12, 818 - 843.
           2010.
    .. [4] S.D. Axen, "Efficiently generating inverse-Wishart matrices and
           their Cholesky factors", :arXiv:`2310.15884v1`. 2023.

    Examples
    --------
    >>> import numpy as np
    >>> import matplotlib.pyplot as plt
    >>> from scipy.stats import invwishart, invgamma
    >>> x = np.linspace(0.01, 1, 100)
    >>> iw = invwishart.pdf(x, df=6, scale=1)
    >>> iw[:3]
    array([  1.20546865e-15,   5.42497807e-06,   4.45813929e-03])
    >>> ig = invgamma.pdf(x, 6/2., scale=1./2)
    >>> ig[:3]
    array([  1.20546865e-15,   5.42497807e-06,   4.45813929e-03])
    >>> plt.plot(x, iw)
    >>> plt.show()

    The input quantiles can be any shape of array, as long as the last
    axis labels the components.

    Alternatively, the object may be called (as a function) to fix the degrees
    of freedom and scale parameters, returning a "frozen" inverse Wishart
    random variable:

    >>> rv = invwishart(df=1, scale=1)
    >>> # Frozen object with the same methods but holding the given
    >>> # degrees of freedom and scale fixed.

    Nc                    s    t  | t| jt| _d S rj   r  rw   ry   r*   r/   rf   r
  s    zinvwishart_gen.__init__c                 C   s   t |||S )znCreate a frozen inverse Wishart distribution.

        See `invwishart_frozen` for more information.

        )invwishart_frozenr  r*   r*   r/   r   v
  s    zinvwishart_gen.__call__c                 C   s  t |jd }t |jd }td|f}|dkrt|jd D ]N}	| |dddd|	f \}
||	< |d|
|ddd}t j|d	 ||	< qBn2t |d
 |dd< |d
 d	 |d
  |dd< d| | d|  d| | t	 d|| d  |   t
d| | }|S )a  Log of the inverse Wishart probability density function.

        Parameters
        ----------
        x : ndarray
            Points at which to evaluate the log of the probability
            density function.
        dim : int
            Dimension of the scale matrix
        df : int
            Degrees of freedom
        log_det_scale : float
            Logarithm of the determinant of the scale matrix
        C : ndarray
            Cholesky factorization of the scale matrix, lower triagular.

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

        r1   trsmr   Nr   r   Tsider7   r)   r   r   r   )r8   r  r   r   r  r  rR   r   r]   r  r   )r`   rC   r   r  r   r!  r"  Ztr_scale_x_invrR  r#  ZCxr=  r.   r*   r*   r/   r   ~
  s     $"zinvwishart_gen._logpdfc                 C   sF   |  ||\}}}| ||}| |\}}| |||||}t|S )a  Log of the inverse Wishart probability density function.

        Parameters
        ----------
        x : array_like
            Quantiles, with the last axis of `x` denoting the components.
            Each quantile must be a symmetric positive definite matrix.
        %(_doc_default_callparams)s

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

        Notes
        -----
        %(_doc_callparams_note)s

        r$  r%  r*   r*   r/   r   
  s
    zinvwishart_gen.logpdfc                 C   s   t | |||S )a  Inverse Wishart probability density function.

        Parameters
        ----------
        x : array_like
            Quantiles, with the last axis of `x` denoting the components.
            Each quantile must be a symmetric positive definite matrix.
        %(_doc_default_callparams)s

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

        Notes
        -----
        %(_doc_callparams_note)s

        r   r&  r*   r*   r/   r   
  s    zinvwishart_gen.pdfc                 C   s&   ||d kr||| d  }nd}|S )aI  Mean of the inverse Wishart distribution.

        Parameters
        ----------
        dim : int
            Dimension of the scale matrix
        %(_doc_default_callparams)s

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

        r   Nr*   r+  r*   r*   r/   r(  
  s    zinvwishart_gen._meanc                 C   s4   |  ||\}}}| |||}|dur0t|S |S )aX  Mean of the inverse Wishart distribution.

        Only valid if the degrees of freedom are greater than the dimension of
        the scale matrix plus one.

        Parameters
        ----------
        %(_doc_default_callparams)s

        Returns
        -------
        mean : float or None
            The mean of the distribution

        Nr)  r*  r*   r*   r/   r   
  s    zinvwishart_gen.meanc                 C   s   ||| d  S )aI  Mode of the inverse Wishart distribution.

        Parameters
        ----------
        dim : int
            Dimension of the scale matrix
        %(_doc_default_callparams)s

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

        r   r*   r'  r*   r*   r/   r,    s    zinvwishart_gen._modec                 C   s(   |  ||\}}}| |||}t|S )zMode of the inverse Wishart distribution.

        Parameters
        ----------
        %(_doc_default_callparams)s

        Returns
        -------
        mode : float
            The Mode of the distribution

        r-  r*  r*   r*   r/   r.    s    zinvwishart_gen.modec                 C   sv   ||d krn|| d |d  }|  }||| d t|| 7 }||| || d d  || d   }nd}|S )aL  Variance of the inverse Wishart distribution.

        Parameters
        ----------
        dim : int
            Dimension of the scale matrix
        %(_doc_default_callparams)s

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

        r  r   r)   Nr/  r1  r*   r*   r/   r2  $  s    *zinvwishart_gen._varc                 C   s4   |  ||\}}}| |||}|dur0t|S |S )aX  Variance of the inverse Wishart distribution.

        Only valid if the degrees of freedom are greater than the dimension of
        the scale matrix plus three.

        Parameters
        ----------
        %(_doc_default_callparams)s

        Returns
        -------
        var : float
            The variance of the distribution
        Nr3  r*  r*   r*   r/   r  <  s    zinvwishart_gen.varc                 C   s   t |||f }t j|dd\}}||d  d }	|jg ||	R d|d||f< t |}
|| d |
 }|j|g ||R dd |d|
|
f< |S )	a  
        Parameters
        ----------
        n : integer
            Number of variates to generate
        shape : iterable
            Shape of the variates to generate
        dim : int
            Dimension of the scale matrix
        df : int
            Degrees of freedom
        random_state : {None, int, `numpy.random.Generator`,
                        `numpy.random.RandomState`}, optional

            If `seed` is None (or `np.random`), the `numpy.random.RandomState`
            singleton is used.
            If `seed` is an int, a new ``RandomState`` instance is used,
            seeded with `seed`.
            If `seed` is already a ``Generator`` or ``RandomState`` instance
            then that instance is used.

        Returns
        -------
        A : ndarray
            Random variates of shape (`shape`) + (``dim``, ``dim``).
            Each slice `A[..., :, :]` is lower-triangular, and its
            inverse is the lower Cholesky factor of a draw from
            `invwishart(df, np.eye(dim))`.

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

        r1   r7  r   r)   r   .)r  r   r   )r8   r   r;  r   aranger4  )r`   r   r   r   r  r{   r=  Ztri_rowsZtri_colsr<  r   Zchi_dfsr*   r*   r/   _inv_standard_rvsO  s    $
z invwishart_gen._inv_standard_rvsc              	   C   s   |  |}| |||||}td|f}td|f}	t|jdd D ]\}
|dkr|d||
 |ddd}|	d||dddd	||
< qH|d
 ||
 d
  d ||
 d
< qH|S )ae  Draw random samples from an inverse Wishart distribution.

        Parameters
        ----------
        n : integer
            Number of variates to generate
        shape : iterable
            Shape of the variates to generate
        dim : int
            Dimension of the scale matrix
        df : int
            Degrees of freedom
        C : ndarray
            Cholesky factorization of the scale matrix, lower triagular.
        %(_doc_random_state)s

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

        rR  trmmNr   r   r   TrS  )rT  r7   Ztrans_arU  r)   )r~   rW  r   r8   r?  r   )r`   r   r   r   r  r!  r{   r=  rR  rX  r@  rA  r*   r*   r/   rB    s    
"zinvwishart_gen._rvsr   c           
      C   sL   |  |\}}| ||\}}}tjj|dd}| ||||||}	t|	S )a  Draw random samples from an inverse Wishart distribution.

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

        Returns
        -------
        rvs : ndarray
            Random variates of shape (`size`) + (``dim``, ``dim``), where
            ``dim`` is the dimension of the scale matrix.

        Notes
        -----
        %(_doc_callparams_note)s

        Tr   rC  rD  r*   r*   r/   r     s
    zinvwishart_gen.rvsc                    sv    fddt dd D }t|}td  d    dd  |t   d  d  t||d   S )Nc                    s   g | ]}d   |  qS )r   r*   r5  r  r   r*   r/   rE     rF   z+invwishart_gen._entropy.<locals>.<listcomp>r   r   r-   )r  r8   rO   r   r  r   r\   )r`   r   r  r   Zpsi_eval_pointsr*   rY  r/   r     s    
zinvwishart_gen._entropyc                 C   s.   |  ||\}}}| |\}}| |||S rj   rF  rG  r*   r*   r/   r     s    zinvwishart_gen.entropy)N)NNN)r   N)ro   rp   rq   rr   rf   r   r   r   r   r(  r   r,  r.  r2  r  rW  rB  r   r   r   r   r*   r*   ry   r/   rP  	  s"   s
+6+
	rP  c                   @   sP   e Zd ZdddZdd Zdd Zdd	 Zd
d Zdd ZdddZ	dd Z
dS )rQ  Nc                 C   sX   t || _| j||\| _| _| _tjj| jdd| _	dt
t
| j	  | _dS )aG  Create a frozen inverse Wishart distribution.

        Parameters
        ----------
        df : array_like
            Degrees of freedom of the distribution
        scale : array_like
            Scale matrix of the distribution
        seed : {None, int, `numpy.random.Generator`}, optional
            If `seed` is None the `numpy.random.Generator` singleton is used.
            If `seed` is an int, a new ``Generator`` instance is used,
            seeded with `seed`.
            If `seed` is already a ``Generator`` instance then that instance is
            used.

        Tr   r)   N)rP  r   r   r   r  r  rQ   rR   r   r!  r8   r\   r]   r0  r   r  r*   r*   r/   rf     s    
zinvwishart_frozen.__init__c                 C   s4   | j || j}| j || j| j| j| j}t|S rj   )r   r   r   r   r  r   r!  r0   rH  r*   r*   r/   r     s
    zinvwishart_frozen.logpdfc                 C   s   t | |S rj   r   r   r*   r*   r/   r     s    zinvwishart_frozen.pdfc                 C   s*   | j | j| j| j}|d ur&t|S |S rj   rI  rJ  r*   r*   r/   r     s    zinvwishart_frozen.meanc                 C   s   | j | j| j| j}t|S rj   rK  rJ  r*   r*   r/   r.  	  s    zinvwishart_frozen.modec                 C   s*   | j | j| j| j}|d ur&t|S |S rj   rL  rJ  r*   r*   r/   r    s    zinvwishart_frozen.varr   c                 C   s4   | j |\}}| j ||| j| j| j|}t|S rj   rM  rN  r*   r*   r/   r     s
    zinvwishart_frozen.rvsc                 C   s   | j | j| j| jS rj   rO  rm   r*   r*   r/   r     s    zinvwishart_frozen.entropy)N)r   N)ro   rp   rq   rf   r   r   r   r.  r  r   r   r*   r*   r*   r/   rQ    s   

rQ  )r   r   r   r.  r  r   zsn : int
    Number of trials
p : array_like
    Probability of a trial falling into each category; should sum to 1
a  `n` should be a nonnegative integer. Each element of `p` should be in the
interval :math:`[0,1]` and the elements should sum to 1. If they do not sum to
1, the last element of the `p` array is not used and is replaced with the
remaining probability left over from the earlier elements.
c                       s   e Zd ZdZd fdd	ZdddZddd	Zd
d Zdd Zdd Z	dd Z
dd Zdd Zdd Zdd ZdddZ  ZS ) multinomial_gena  A multinomial random variable.

    Methods
    -------
    pmf(x, n, p)
        Probability mass function.
    logpmf(x, n, p)
        Log of the probability mass function.
    rvs(n, p, size=1, random_state=None)
        Draw random samples from a multinomial distribution.
    entropy(n, p)
        Compute the entropy of the multinomial distribution.
    cov(n, p)
        Compute the covariance matrix of the multinomial distribution.

    Parameters
    ----------
    %(_doc_default_callparams)s
    %(_doc_random_state)s

    Notes
    -----
    %(_doc_callparams_note)s

    The probability mass function for `multinomial` is

    .. math::

        f(x) = \frac{n!}{x_1! \cdots x_k!} p_1^{x_1} \cdots p_k^{x_k},

    supported on :math:`x=(x_1, \ldots, x_k)` where each :math:`x_i` is a
    nonnegative integer and their sum is :math:`n`.

    .. versionadded:: 0.19.0

    Examples
    --------

    >>> from scipy.stats import multinomial
    >>> rv = multinomial(8, [0.3, 0.2, 0.5])
    >>> rv.pmf([1, 3, 4])
    0.042000000000000072

    The multinomial distribution for :math:`k=2` is identical to the
    corresponding binomial distribution (tiny numerical differences
    notwithstanding):

    >>> from scipy.stats import binom
    >>> multinomial.pmf([3, 4], n=7, p=[0.4, 0.6])
    0.29030399999999973
    >>> binom.pmf(3, 7, 0.4)
    0.29030400000000012

    The functions ``pmf``, ``logpmf``, ``entropy``, and ``cov`` support
    broadcasting, under the convention that the vector parameters (``x`` and
    ``p``) are interpreted as if each row along the last axis is a single
    object. For instance:

    >>> multinomial.pmf([[3, 4], [3, 5]], n=[7, 8], p=[.3, .7])
    array([0.2268945,  0.25412184])

    Here, ``x.shape == (2, 2)``, ``n.shape == (2,)``, and ``p.shape == (2,)``,
    but following the rules mentioned above they behave as if the rows
    ``[3, 4]`` and ``[3, 5]`` in ``x`` and ``[.3, .7]`` in ``p`` were a single
    object, and as if we had ``x.shape = (2,)``, ``n.shape = (2,)``, and
    ``p.shape = ()``. To obtain the individual elements without broadcasting,
    we would do this:

    >>> multinomial.pmf([3, 4], n=7, p=[.3, .7])
    0.2268945
    >>> multinomial.pmf([3, 5], 8, p=[.3, .7])
    0.25412184

    This broadcasting also works for ``cov``, where the output objects are
    square matrices of size ``p.shape[-1]``. For example:

    >>> multinomial.cov([4, 5], [[.3, .7], [.4, .6]])
    array([[[ 0.84, -0.84],
            [-0.84,  0.84]],
           [[ 1.2 , -1.2 ],
            [-1.2 ,  1.2 ]]])

    In this example, ``n.shape == (2,)`` and ``p.shape == (2, 2)``, and
    following the rules above, these broadcast as if ``p.shape == (2,)``.
    Thus the result should also be of shape ``(2,)``, but since each output is
    a :math:`2 \times 2` matrix, the result in fact has shape ``(2, 2, 2)``,
    where ``result[0]`` is equal to ``multinomial.cov(n=4, p=[.3, .7])`` and
    ``result[1]`` is equal to ``multinomial.cov(n=5, p=[.4, .6])``.

    Alternatively, the object may be called (as a function) to fix the `n` and
    `p` parameters, returning a "frozen" multinomial random variable:

    >>> rv = multinomial(n=7, p=[.3, .7])
    >>> # Frozen object with the same methods but holding the given
    >>> # degrees of freedom and scale fixed.

    See also
    --------
    scipy.stats.binom : The binomial distribution.
    numpy.random.Generator.multinomial : Sampling from the multinomial distribution.
    scipy.stats.multivariate_hypergeom :
        The multivariate hypergeometric distribution.
    Nc                    s    t  | t| jt| _d S rj   )ru   rf   r   r   rr   multinomial_docdict_paramsrw   ry   r*   r/   rf     s    zmultinomial_gen.__init__c                 C   s   t |||S )zjCreate a frozen multinomial distribution.

        See `multinomial_frozen` for more information.
        )multinomial_frozen)r`   r   r   rx   r*   r*   r/   r     s    zmultinomial_gen.__call__V瞯<c                 C   s   t j|t jdd}d|dddf jdd }t ||k}|| ||df< t j|dk dd}|t j|d	kddO }t j|tdd}|dk }||||B fS )
zReturns: n_, p_, npcond.

        n_ and p_ are arrays of the correct shape; npcond is a boolean array
        flagging values out of the domain.
        Tr5   r   r   .Nr1   rg   r   r   )r8   rH   float64r\   r;   r   r   )r`   r   r   r9   Z
p_adjustedZ
i_adjustedZpcondncondr*   r*   r/   r     s    z#multinomial_gen._process_parametersc                 C   s   t j|td}|jdkr td|jdkrZ|jd |jd ksZtd|jd |jd f t j||kdd}|t j|dk ddO }|t j|dd|kB }||fS )z}Returns: x_, xcond.

        x_ is an int array; xcond is a boolean array flagging values out of the
        domain.
        rG   r   zx must be an array.r1   zHSize of each quantile should be size of p: received %d, but expected %d.rg   )	r8   rO   r   r,   rU   r   r   r   r\   )r`   rC   r   r   xxr<   r*   r*   r/   r     s    
z"multinomial_gen._process_quantilesc                 C   s<   t |}|jdkr|||< n|r8|jdkr0|S ||d< |S )Nr   .r8   rO   r,   r`   resultr<   Z	bad_valuer*   r*   r/   _checkresult  s    



zmultinomial_gen._checkresultc                 C   s,   t |d tjt||t |d  dd S )Nr   r1   rg   )r   r8   r\   r   r`   rC   r   r   r*   r*   r/   _logpmf  s    zmultinomial_gen._logpmfc           	      C   s   |  ||\}}}| |||\}}| |||}|tj|jtjdB }| ||tj }|tj|jtjdB }| ||tj	S )a  Log of the Multinomial probability mass function.

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

        Returns
        -------
        logpmf : ndarray or scalar
            Log of the probability mass function evaluated at `x`

        Notes
        -----
        %(_doc_callparams_note)s
        rG   )
r   r   rg  r8   r   r   bool_re  r   nan)	r`   rC   r   r   npcondxcondrd  xcond_Znpcond_r*   r*   r/   logpmf  s    zmultinomial_gen.logpmfc                 C   s   t | |||S )a  Multinomial probability mass function.

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

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

        Notes
        -----
        %(_doc_callparams_note)s
        r8   r   rm  rf  r*   r*   r/   pmf  s    zmultinomial_gen.pmfc                 C   s4   |  ||\}}}|dtjf | }| ||tjS )zMean of the Multinomial distribution.

        Parameters
        ----------
        %(_doc_default_callparams)s

        Returns
        -------
        mean : float
            The mean of the distribution
        .)r   r8   r   re  ri  )r`   r   r   rj  rd  r*   r*   r/   r   *  s    zmultinomial_gen.meanc                 C   s~   |  ||\}}}|dtjtjf }|td| | }t|jd D ]&}|d||f  ||d|f  7  < qF| ||tjS )zCovariance matrix of the multinomial distribution.

        Parameters
        ----------
        %(_doc_default_callparams)s

        Returns
        -------
        cov : ndarray
            The covariance matrix of the distribution
        .z...j,...k->...jkr1   )r   r8   r   r   r  r   re  ri  )r`   r   r   rj  nnrd  r#  r*   r*   r/   r   :  s    $zmultinomial_gen.covc                 C   s   |  ||\}}}tjdt|d  }|tjt|dd }|t|d 8 }|dtjf }t|j|j|j d }| j	d| 7  _	tjt
|||t|d  dd| fd}| || |tjS )a  Compute the entropy of the multinomial distribution.

        The entropy is computed using this expression:

        .. math::

            f(x) = - \log n! - n\sum_{i=1}^k p_i \log p_i +
            \sum_{i=1}^k \sum_{x=0}^n \binom n x p_i^x(1-p_i)^{n-x} \log x!

        Parameters
        ----------
        %(_doc_default_callparams)s

        Returns
        -------
        h : scalar
            Entropy of the Multinomial distribution

        Notes
        -----
        %(_doc_callparams_note)s
        r   r1   rg   .)r   )r   r8   r9  r:   r\   r   r   r   r,   r   r   ro  re  ri  )r`   r   r   rj  rC   Zterm1Znew_axes_neededZterm2r*   r*   r/   r   Q  s    
zmultinomial_gen.entropyc                 C   s*   |  ||\}}}| |}||||S )a  Draw random samples from a Multinomial distribution.

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

        Returns
        -------
        rvs : ndarray or scalar
            Random variates of shape (`size`, `len(p)`)

        Notes
        -----
        %(_doc_callparams_note)s
        )r   r~   r   )r`   r   r   r   r{   rj  r*   r*   r/   r   x  s    
zmultinomial_gen.rvs)N)N)r]  )NN)ro   rp   rq   rr   rf   r   r   r   re  rg  rm  ro  r   r   r   r   r   r*   r*   ry   r/   rZ  F  s   h

 'rZ  c                   @   sL   e Zd ZdZdddZdd Zdd Zd	d
 Zdd Zdd Z	dddZ
dS )r\  aZ  Create a frozen Multinomial distribution.

    Parameters
    ----------
    n : int
        number of trials
    p: array_like
        probability of a trial falling into each category; should sum to 1
    seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
        If `seed` is None (or `np.random`), the `numpy.random.RandomState`
        singleton is used.
        If `seed` is an int, a new ``RandomState`` instance is used,
        seeded with `seed`.
        If `seed` is already a ``Generator`` or ``RandomState`` instance then
        that instance is used.
    Nc                    s<   t | _ j||\ _ _ _ fdd}| j_d S )Nc                    s    j  j jfS rj   )r   r   rj  )r   r   rm   r*   r/   r     s    z8multinomial_frozen.__init__.<locals>._process_parameters)rZ  r   r   r   r   rj  )r`   r   r   rx   r   r*   rm   r/   rf     s    
zmultinomial_frozen.__init__c                 C   s   | j || j| jS rj   )r   rm  r   r   r   r*   r*   r/   rm    s    zmultinomial_frozen.logpmfc                 C   s   | j || j| jS rj   )r   ro  r   r   r   r*   r*   r/   ro    s    zmultinomial_frozen.pmfc                 C   s   | j | j| jS rj   )r   r   r   r   rm   r*   r*   r/   r     s    zmultinomial_frozen.meanc                 C   s   | j | j| jS rj   )r   r   r   r   rm   r*   r*   r/   r     s    zmultinomial_frozen.covc                 C   s   | j | j| jS rj   )r   r   r   r   rm   r*   r*   r/   r     s    zmultinomial_frozen.entropyr   c                 C   s   | j | j| j||S rj   )r   r   r   r   r   r*   r*   r/   r     s    zmultinomial_frozen.rvs)N)r   N)ro   rp   rq   rr   rf   rm  ro  r   r   r   r   r*   r*   r*   r/   r\    s   

r\  )rm  ro  r   r   r   c                       s>   e Zd ZdZd fdd	ZdddZdd Zdd
dZ  ZS )special_ortho_group_gena	  A Special Orthogonal matrix (SO(N)) random variable.

    Return a random rotation matrix, drawn from the Haar distribution
    (the only uniform distribution on SO(N)) with a determinant of +1.

    The `dim` keyword specifies the dimension N.

    Methods
    -------
    rvs(dim=None, size=1, random_state=None)
        Draw random samples from SO(N).

    Parameters
    ----------
    dim : scalar
        Dimension of matrices
    seed : {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`.

    Notes
    -----
    This class is wrapping the random_rot code from the MDP Toolkit,
    https://github.com/mdp-toolkit/mdp-toolkit

    Return a random rotation matrix, drawn from the Haar distribution
    (the only uniform distribution on SO(N)).
    The algorithm is described in the paper
    Stewart, G.W., "The efficient generation of random orthogonal
    matrices with an application to condition estimators", SIAM Journal
    on Numerical Analysis, 17(3), pp. 403-409, 1980.
    For more information see
    https://en.wikipedia.org/wiki/Orthogonal_matrix#Randomization

    See also the similar `ortho_group`. For a random rotation in three
    dimensions, see `scipy.spatial.transform.Rotation.random`.

    Examples
    --------
    >>> import numpy as np
    >>> from scipy.stats import special_ortho_group
    >>> x = special_ortho_group.rvs(3)

    >>> np.dot(x, x.T)
    array([[  1.00000000e+00,   1.13231364e-17,  -2.86852790e-16],
           [  1.13231364e-17,   1.00000000e+00,  -1.46845020e-16],
           [ -2.86852790e-16,  -1.46845020e-16,   1.00000000e+00]])

    >>> import scipy.linalg
    >>> scipy.linalg.det(x)
    1.0

    This generates one random matrix from SO(3). It is orthogonal and
    has a determinant of 1.

    Alternatively, the object may be called (as a function) to fix the `dim`
    parameter, returning a "frozen" special_ortho_group random variable:

    >>> rv = special_ortho_group(5)
    >>> # Frozen object with the same methods but holding the
    >>> # dimension parameter fixed.

    See Also
    --------
    ortho_group, scipy.spatial.transform.Rotation.random

    Nc                    s   t  | t| j| _d S rj   ru   rf   r   r   rr   rw   ry   r*   r/   rf     s    z special_ortho_group_gen.__init__c                 C   s   t ||dS )zlCreate a frozen SO(N) distribution.

        See `special_ortho_group_frozen` for more information.
        r   )special_ortho_group_frozenr`   r   rx   r*   r*   r/   r     s    z special_ortho_group_gen.__call__c                 C   s2   |du s&t |r&|dks&|t|kr.td|S )5Dimension N must be specified; it cannot be inferred.Nr   zmDimension of rotation must be specified,
                                and must be a scalar greater than 1.r8   r   r   rU   r`   r   r*   r*   r/   r   !  s    &z+special_ortho_group_gen._process_parametersr   c                 C   s  |  |}t|}|dkr |fnd}| |}t|||f }t||dddddf< t||f }t|d D ]}|j||| f d}|ddddf }|ddddf }	t||		d}
|d 
 }t|dkt|d|d|f< |d  |d|f t|
 7  < |t|
|d	  |d d	  d
 d  }|ddd|df  t|ddd|df |	| 8  < qxd|d  |dddf jdd |d< ||ddddf 9 }|S )as  Draw random samples from SO(N).

        Parameters
        ----------
        dim : integer
            Dimension of rotation space (N).
        size : integer, optional
            Number of samples to draw (default 1).

        Returns
        -------
        rvs : ndarray or scalar
            Random size N-dimensional matrices, dimension (size, dim, dim)

        r   r*   .Nr   )r   r1   .r   r   r)          @.Nr1   rg   ).r1   )r~   r   r   r8   r  r   r  r   matmulr+   r   wheresignrX   r  )r`   r   r   r{   HDr   rC   ZxrowZxcolZnorm2Zx0r*   r*   r/   r   )  s(    

 "*>(zspecial_ortho_group_gen.rvs)N)NN)r   N	ro   rp   rq   rr   rf   r   r   r   r   r*   r*   ry   r/   rq    s
   I
rq  c                   @   s    e Zd ZdddZdddZdS )	rs  Nc                 C   s   t || _| j|| _dS )a  Create a frozen SO(N) distribution.

        Parameters
        ----------
        dim : scalar
            Dimension of matrices
        seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
            If `seed` is None (or `np.random`), the `numpy.random.RandomState`
            singleton is used.
            If `seed` is an int, a new ``RandomState`` instance is used,
            seeded with `seed`.
            If `seed` is already a ``Generator`` or ``RandomState`` instance
            then that instance is used.

        Examples
        --------
        >>> from scipy.stats import special_ortho_group
        >>> g = special_ortho_group(5)
        >>> x = g.rvs()

        N)rq  r   r   r   rt  r*   r*   r/   rf   q  s    
z#special_ortho_group_frozen.__init__r   c                 C   s   | j | j||S rj   r   r   r   r   r*   r*   r/   r     s    zspecial_ortho_group_frozen.rvs)NN)r   Nro   rp   rq   rf   r   r*   r*   r*   r/   rs  p  s   
rs  c                       s>   e Zd ZdZd fdd	ZdddZdd Zdd
dZ  ZS )ortho_group_gena  An Orthogonal matrix (O(N)) random variable.

    Return a random orthogonal matrix, drawn from the O(N) Haar
    distribution (the only uniform distribution on O(N)).

    The `dim` keyword specifies the dimension N.

    Methods
    -------
    rvs(dim=None, size=1, random_state=None)
        Draw random samples from O(N).

    Parameters
    ----------
    dim : scalar
        Dimension of matrices
    seed : {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`.

    Notes
    -----
    This class is closely related to `special_ortho_group`.

    Some care is taken to avoid numerical error, as per the paper by Mezzadri.

    References
    ----------
    .. [1] F. Mezzadri, "How to generate random matrices from the classical
           compact groups", :arXiv:`math-ph/0609050v2`.

    Examples
    --------
    >>> import numpy as np
    >>> from scipy.stats import ortho_group
    >>> x = ortho_group.rvs(3)

    >>> np.dot(x, x.T)
    array([[  1.00000000e+00,   1.13231364e-17,  -2.86852790e-16],
           [  1.13231364e-17,   1.00000000e+00,  -1.46845020e-16],
           [ -2.86852790e-16,  -1.46845020e-16,   1.00000000e+00]])

    >>> import scipy.linalg
    >>> np.fabs(scipy.linalg.det(x))
    1.0

    This generates one random matrix from O(3). It is orthogonal and
    has a determinant of +1 or -1.

    Alternatively, the object may be called (as a function) to fix the `dim`
    parameter, returning a "frozen" ortho_group random variable:

    >>> rv = ortho_group(5)
    >>> # Frozen object with the same methods but holding the
    >>> # dimension parameter fixed.

    See Also
    --------
    special_ortho_group
    Nc                    s   t  | t| j| _d S rj   rr  rw   ry   r*   r/   rf     s    zortho_group_gen.__init__c                 C   s   t ||dS )zcCreate a frozen O(N) distribution.

        See `ortho_group_frozen` for more information.
        r   )ortho_group_frozenrt  r*   r*   r/   r     s    zortho_group_gen.__call__c                 C   s2   |du s&t |r&|dks&|t|kr.td|S ru  Nr   zLDimension of rotation must be specified,and must be a scalar greater than 1.rv  rw  r*   r*   r/   r     s    &z#ortho_group_gen._process_parametersr   c                 C   s   |  |}t|}| |}|dkr*|fnd}|j|||f d}tj|\}}|jdddd}||t| dtj	d	d	f 9 }|S )
ar  Draw random samples from O(N).

        Parameters
        ----------
        dim : integer
            Dimension of rotation space (N).
        size : integer, optional
            Number of samples to draw (default 1).

        Returns
        -------
        rvs : ndarray or scalar
            Random size N-dimensional matrices, dimension (size, dim, dim)

        r   r*   r   r   r   r1   offsetZaxis1Zaxis2.N)
r~   r   r   r   r8   rR   qrr0  r;   r   r`   r   r   r{   zqrr4   r*   r*   r/   r     s    

 zortho_group_gen.rvs)N)NN)r   Nr  r*   r*   ry   r/   r    s
   B
r  c                   @   s    e Zd ZdddZdddZdS )	r  Nc                 C   s   t || _| j|| _dS )a  Create a frozen O(N) distribution.

        Parameters
        ----------
        dim : scalar
            Dimension of matrices
        seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
            If `seed` is None (or `np.random`), the `numpy.random.RandomState`
            singleton is used.
            If `seed` is an int, a new ``RandomState`` instance is used,
            seeded with `seed`.
            If `seed` is already a ``Generator`` or ``RandomState`` instance
            then that instance is used.

        Examples
        --------
        >>> from scipy.stats import ortho_group
        >>> g = ortho_group(5)
        >>> x = g.rvs()

        N)r  r   r   r   rt  r*   r*   r/   rf   
  s    
zortho_group_frozen.__init__r   c                 C   s   | j | j||S rj   r  r   r*   r*   r/   r   #  s    zortho_group_frozen.rvs)NN)r   Nr  r*   r*   r*   r/   r  	  s   
r  c                       sN   e Zd ZdZd fdd	ZdddZd	d
 Zdd Zdd ZdddZ	  Z
S )random_correlation_gena	  A random correlation matrix.

    Return a random correlation matrix, given a vector of eigenvalues.

    The `eigs` keyword specifies the eigenvalues of the correlation matrix,
    and implies the dimension.

    Methods
    -------
    rvs(eigs=None, random_state=None)
        Draw random correlation matrices, all with eigenvalues eigs.

    Parameters
    ----------
    eigs : 1d ndarray
        Eigenvalues of correlation matrix
    seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
        If `seed` is None (or `np.random`), the `numpy.random.RandomState`
        singleton is used.
        If `seed` is an int, a new ``RandomState`` instance is used,
        seeded with `seed`.
        If `seed` is already a ``Generator`` or ``RandomState`` instance
        then that instance is used.
    tol : float, optional
        Tolerance for input parameter checks
    diag_tol : float, optional
        Tolerance for deviation of the diagonal of the resulting
        matrix. Default: 1e-7

    Raises
    ------
    RuntimeError
        Floating point error prevented generating a valid correlation
        matrix.

    Returns
    -------
    rvs : ndarray or scalar
        Random size N-dimensional matrices, dimension (size, dim, dim),
        each having eigenvalues eigs.

    Notes
    -----

    Generates a random correlation matrix following a numerically stable
    algorithm spelled out by Davies & Higham. This algorithm uses a single O(N)
    similarity transformation to construct a symmetric positive semi-definite
    matrix, and applies a series of Givens rotations to scale it to have ones
    on the diagonal.

    References
    ----------

    .. [1] Davies, Philip I; Higham, Nicholas J; "Numerically stable generation
           of correlation matrices and their factors", BIT 2000, Vol. 40,
           No. 4, pp. 640 651

    Examples
    --------
    >>> import numpy as np
    >>> from scipy.stats import random_correlation
    >>> rng = np.random.default_rng()
    >>> x = random_correlation.rvs((.5, .8, 1.2, 1.5), random_state=rng)
    >>> x
    array([[ 1.        , -0.02423399,  0.03130519,  0.4946965 ],
           [-0.02423399,  1.        ,  0.20334736,  0.04039817],
           [ 0.03130519,  0.20334736,  1.        ,  0.02694275],
           [ 0.4946965 ,  0.04039817,  0.02694275,  1.        ]])
    >>> import scipy.linalg
    >>> e, v = scipy.linalg.eigh(x)
    >>> e
    array([ 0.5,  0.8,  1.2,  1.5])

    Nc                    s   t  | t| j| _d S rj   rr  rw   ry   r*   r/   rf   s  s    zrandom_correlation_gen.__init__vIh%<=Hz>c                 C   s   t ||||dS )zrCreate a frozen random correlation matrix.

        See `random_correlation_frozen` for more information.
        )rx   toldiag_tol)random_correlation_frozen)r`   eigsrx   r  r  r*   r*   r/   r   w  s    zrandom_correlation_gen.__call__c                 C   s   t j|td}|j}|jdks4|jd |ks4|dkr<tdt t || |kr\td|D ]}|| k r`tdq`||fS )NrG   r   r   z7Array 'eigs' must be a vector of length greater than 1.z-Sum of eigenvalues must equal dimensionality.z%All eigenvalues must be non-negative.)	r8   rO   rI   r   r,   r   rU   fabsr\   )r`   r  r  r   rC   r*   r*   r/   r     s     

z*random_correlation_gen._process_parametersc           
      C   s   |d }|d }|dkrdS t t|d ||  d}|t || | }dt d||   }|dkrpd}	n|| }	||	fS )a&  Computes a 2x2 Givens matrix to put 1's on the diagonal.

        The input matrix is a 2x2 symmetric matrix M = [ aii aij ; aij ajj ].

        The output matrix g is a 2x2 anti-symmetric matrix of the form
        [ c s ; -s c ];  the elements c and s are returned.

        Applying the output matrix to the input matrix (as b=g.T M g)
        results in a matrix with bii=1, provided tr(M) - det(M) >= 1
        and floating point issues do not occur. Otherwise, some other
        valid rotation is returned. When tr(M)==2, also bjj=1.

        r   r   )r   r   r)   )mathrX   r:   copysign)
r`   ZaiiZajjZaijZaiidZajjdddr>   crc   r*   r*   r/   _givens_to_1  s    z#random_correlation_gen._givens_to_1c                 C   s>  |j jr(|jtjkr(|jd |jd ks.t |jd }t|d D ]}|||f dkr\qDnb|||f dkrt|d |D ]}|||f dk rz qqzn(t|d |D ]}|||f dkr qq| |||f |||f |||f \}}|	 }t
|||| ||| d|| dddd t
|||| |||||ddd qD|S )z
        Given a psd matrix m, rotate to put one's on the diagonal, turning it
        into a correlation matrix.  This also requires the trace equal the
        dimensionality. Note: modifies input matrix
        r   r   T)r   ZoffxZincxZoffyZincyZoverwrite_xZoverwrite_y)flagsc_contiguousr5   r8   r_  r   rU   r  r  Zravelr   )r`   mr4   r#  jr  rc   mvr*   r*   r/   _to_corr  s4    
*zrandom_correlation_gen._to_corrc                 C   st   | j ||d\}}| |}tj||d}tt|t||j}| |}t	|
 d  |krptd|S )a  Draw random correlation matrices.

        Parameters
        ----------
        eigs : 1d ndarray
            Eigenvalues of correlation matrix
        tol : float, optional
            Tolerance for input parameter checks
        diag_tol : float, optional
            Tolerance for deviation of the diagonal of the resulting
            matrix. Default: 1e-7

        Raises
        ------
        RuntimeError
            Floating point error prevented generating a valid correlation
            matrix.

        Returns
        -------
        rvs : ndarray or scalar
            Random size N-dimensional matrices, dimension (size, dim, dim),
            each having eigenvalues eigs.

        r  )r{   r   z-Failed to generate a valid correlation matrix)r   r~   r!   r   r8   rk   r   rl   r  r;   r0  r:   RuntimeError)r`   r  r{   r  r  r   r  r*   r*   r/   r     s    

zrandom_correlation_gen.rvs)N)Nr  r  )Nr  r  )ro   rp   rq   rr   rf   r   r   r  r  r   r   r*   r*   ry   r/   r  '  s   K
!)r  c                   @   s    e Zd ZdddZd	ddZdS )
r  Nr  r  c                 C   s2   t || _|| _|| _| jj|| jd\}| _dS )ax  Create a frozen random correlation matrix distribution.

        Parameters
        ----------
        eigs : 1d ndarray
            Eigenvalues of correlation matrix
        seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
            If `seed` is None (or `np.random`), the `numpy.random.RandomState`
            singleton is used.
            If `seed` is an int, a new ``RandomState`` instance is used,
            seeded with `seed`.
            If `seed` is already a ``Generator`` or ``RandomState`` instance
            then that instance is used.
        tol : float, optional
            Tolerance for input parameter checks
        diag_tol : float, optional
            Tolerance for deviation of the diagonal of the resulting
            matrix. Default: 1e-7

        Raises
        ------
        RuntimeError
            Floating point error prevented generating a valid correlation
            matrix.

        Returns
        -------
        rvs : ndarray or scalar
            Random size N-dimensional matrices, dimension (size, dim, dim),
            each having eigenvalues eigs.
        r  N)r  r   r  r  r   r  )r`   r  rx   r  r  r   r*   r*   r/   rf     s    !
z"random_correlation_frozen.__init__c                 C   s   | j j| j|| j| jdS )N)r{   r  r  )r   r   r  r  r  r}   r*   r*   r/   r   -  s    zrandom_correlation_frozen.rvs)Nr  r  )Nr  r*   r*   r*   r/   r    s   
&r  c                       s>   e Zd ZdZd fdd	ZdddZdd Zdd
dZ  ZS )unitary_group_gena  A matrix-valued U(N) random variable.

    Return a random unitary matrix.

    The `dim` keyword specifies the dimension N.

    Methods
    -------
    rvs(dim=None, size=1, random_state=None)
        Draw random samples from U(N).

    Parameters
    ----------
    dim : scalar
        Dimension of matrices, must be greater than 1.
    seed : {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`.

    Notes
    -----
    This class is similar to `ortho_group`.

    References
    ----------
    .. [1] F. Mezzadri, "How to generate random matrices from the classical
           compact groups", :arXiv:`math-ph/0609050v2`.

    Examples
    --------
    >>> import numpy as np
    >>> from scipy.stats import unitary_group
    >>> x = unitary_group.rvs(3)

    >>> np.dot(x, x.conj().T)
    array([[  1.00000000e+00,   1.13231364e-17,  -2.86852790e-16],
           [  1.13231364e-17,   1.00000000e+00,  -1.46845020e-16],
           [ -2.86852790e-16,  -1.46845020e-16,   1.00000000e+00]])

    This generates one random matrix from U(3). The dot product confirms that
    it is unitary up to machine precision.

    Alternatively, the object may be called (as a function) to fix the `dim`
    parameter, return a "frozen" unitary_group random variable:

    >>> rv = unitary_group(5)

    See Also
    --------
    ortho_group

    Nc                    s   t  | t| j| _d S rj   rr  rw   ry   r*   r/   rf   m  s    zunitary_group_gen.__init__c                 C   s   t ||dS )zCreate a frozen (U(N)) n-dimensional unitary matrix distribution.

        See `unitary_group_frozen` for more information.
        r   )unitary_group_frozenrt  r*   r*   r/   r   q  s    zunitary_group_gen.__call__c                 C   s2   |du s&t |r&|dks&|t|kr.td|S r  rv  rw  r*   r*   r/   r   x  s    &z%unitary_group_gen._process_parametersr   c                 C   s   |  |}t|}| |}|dkr*|fnd}dtd |j|||f dd|j|||f d   }tj|\}}|j	dddd	}||t
| d
tjddf 9 }|S )ai  Draw random samples from U(N).

        Parameters
        ----------
        dim : integer
            Dimension of space (N).
        size : integer, optional
            Number of samples to draw (default 1).

        Returns
        -------
        rvs : ndarray or scalar
            Random size N-dimensional matrices, dimension (size, dim, dim)

        r   r*   r)   r   y              ?r   r   r1   r  .N)r~   r   r   r  rX   r   r8   rR   r  r0  r;   r   r  r*   r*   r/   r     s    

 zunitary_group_gen.rvs)N)NN)r   Nr  r*   r*   ry   r/   r  2  s
   :
r  c                   @   s    e Zd ZdddZdddZdS )	r  Nc                 C   s   t || _| j|| _dS )a  Create a frozen (U(N)) n-dimensional unitary matrix distribution.

        Parameters
        ----------
        dim : scalar
            Dimension of matrices
        seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
            If `seed` is None (or `np.random`), the `numpy.random.RandomState`
            singleton is used.
            If `seed` is an int, a new ``RandomState`` instance is used,
            seeded with `seed`.
            If `seed` is already a ``Generator`` or ``RandomState`` instance
            then that instance is used.

        Examples
        --------
        >>> from scipy.stats import unitary_group
        >>> x = unitary_group(3)
        >>> x.rvs()

        N)r  r   r   r   rt  r*   r*   r/   rf     s    
zunitary_group_frozen.__init__r   c                 C   s   | j | j||S rj   r  r   r*   r*   r/   r     s    zunitary_group_frozen.rvs)NN)r   Nr  r*   r*   r*   r/   r    s   
r  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_noter   c                       s   e Zd ZdZd fdd	ZdddZd d	d
Zd!ddZdd Zd"ddZ	d#ddddddZ
d$ddZd%ddZd&ddZdd Zdd Z  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.
    cdf(x, loc=None, shape=1, df=1, allow_singular=False, *,
        maxpts=None, lower_limit=None, random_state=None)
        Cumulative distribution function.
    rvs(loc=None, shape=1, df=1, size=1, random_state=None)
        Draw random samples from a multivariate t-distribution.
    entropy(loc=None, shape=1, df=1)
        Differential entropy of a multivariate t-distribution.

    Parameters
    ----------
    %(_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}}
               \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

    References
    ----------
    .. [1] Arellano-Valle et al. "Shannon Entropy and Mutual Information for
           Multivariate Skew-Elliptical Distributions". Scandinavian Journal
           of Statistics. Vol. 40, issue 1.

    Examples
    --------
    The object may be called (as a function) to fix the `loc`, `shape`,
    `df`, and `allow_singular` parameters, returning a "frozen"
    multivariate_t random variable:

    >>> import numpy as np
    >>> from scipy.stats import multivariate_t
    >>> rv = multivariate_t([1.0, -0.5], [[2.1, 0.3], [0.3, 1.5]], df=2)
    >>> # Frozen object with the same methods but holding the given location,
    >>> # scale, and degrees of freedom fixed.

    Create a contour plot of the PDF.

    >>> import matplotlib.pyplot as plt
    >>> x, y = np.mgrid[-1:3:.01, -2:1.5:.01]
    >>> pos = np.dstack((x, y))
    >>> fig, ax = plt.subplots(1, 1)
    >>> ax.set_aspect('equal')
    >>> plt.contourf(x, y, rv.pdf(pos))

    Nc                    s*   t  | t| jt| _t|| _dS )zInitialize a multivariate t-distributed random variable.

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

        N)ru   rf   r   r   rr   mvt_docdict_paramsr   rv   rw   ry   r*   r/   rf   :  s    zmultivariate_t_gen.__init__r   Fc                 C   s,   |t jkrt||||dS t|||||dS )zjCreate a frozen multivariate t-distribution.

        See `multivariate_t_frozen` for parameters.
        )r   r   rb   rx   )locr   r  rb   rx   )r8   r   r   multivariate_t_frozen)r`   r  r   r  rb   rx   r*   r*   r/   r   F  s    
zmultivariate_t_gen.__call__c           	   	   C   sT   |  |||\}}}}| ||}t||d}| |||j|j|||j}t|S )aZ  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)
        0.00075713

        r   )	r   r   rL   r   r[   r^   rZ   r8   r   )	r`   rC   r  r   r  rb   r   
shape_infor   r*   r*   r/   r   S  s    zmultivariate_t_gen.pdfc              	   C   sF   |  |||\}}}}| ||}t|}| |||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)
        -7.1859802

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

        )r   r   rL   r   r[   r^   rZ   )r`   rC   r  r   r  r   r  r*   r*   r/   r   r  s    zmultivariate_t_gen.logpdfc                 C   s   |t jkrt|||||S || }t t ||jdd}	d||  }
t|
}td| }|d t |t j	  }d| }|
 t dd| |	   }t
|| | | | 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.

        r1   rg   r   ry  r   r   )r8   r   r   r   r   rk   r\   r   r]   pir0   )r`   rC   r  Zprec_Ur^   r  r   rZ   r   r   r>   r=  Br!  r  Er*   r*   r/   r     s    
zmultivariate_t_gen._logpdfc	                    s   |d urt |n| js$d| | ||}|d u rJt|jtj n|}|| ||  }}t||\}	}
|	|
k }d|jdd }|
	 |		  }
}	|	| |
|  |
|< |	|< |jd tj
|
|	fdd} fdd}t|d|| }t|S )Ni  r1   rg   c                    s0   | d  | d   }}t  ||d S r   r   )r   r   r   r  r   r   rngr   r*   r/   r     s    z'multivariate_t_gen._cdf.<locals>.func1d)r   rv   r   r8   r   r   r   r   r\   r   r   r   r0   )r`   rC   r  r   r  r   r   r   r{   r   r   r   r   r   r   resr*   r  r/   r     s*    

zmultivariate_t_gen._cdfr   r   r{   c          
   
   C   s<   |  |||\}	}}}t||dj}| |||||	|||S )a  Multivariate t-distribution cumulative distribution function.

        Parameters
        ----------
        x : array_like
            Points at which to evaluate the cumulative distribution function.
        %(_mvt_doc_default_callparams)s
        maxpts : int, optional
            Maximum number of points to use for integration. The default is
            1000 times the number of dimensions.
        lower_limit : array_like, optional
            Lower limit of integration of the cumulative distribution function.
            Default is negative infinity. Must be broadcastable with `x`.
        %(_doc_random_state)s

        Returns
        -------
        cdf : ndarray or scalar
            Cumulative distribution 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.cdf(x, loc, shape, df)
        0.64798491

        r   )r   rL   rP   r   )
r`   rC   r  r   r  rb   r   r   r{   r   r*   r*   r/   r     s
    !zmultivariate_t_gen.cdfc                    sv   |t jkrtd |d S t|}d|j   fdd} fdd}|d d t |d	  }t||k||f||d
S )N)r   r   c                    sV   d| |  }d| }t | t | d|  t|tj   |t|t|     S )Nr   )r   r8   r]   r  r   )r   r  ZhalfsumZhalf_dfZ
shape_termr*   r/   regular  s    z,multivariate_t_gen._entropy.<locals>.regularc                    s   | t   | |  | | d  |d  d  | d | d  |d  d  | d| d  d| d   d  |d	  d
  | d d| d  d| d   d  |d  d    d S )Nr)   g                   r     g         
      g         r*   )r   r   )r   r  r  r*   r/   
asymptotic  s    *.z/multivariate_t_gen._entropy.<locals>.asymptoticd   r  r   )r3   f2)r8   r   r   r   rL   r^   r]   r   )r`   r   r  r   r  r  r  	thresholdr*   r  r/   r     s    


zmultivariate_t_gen._entropyc                 C   s$   |  d||\}}}}| |||S )zCalculate the differential entropy of a multivariate
        t-distribution.

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

        Returns
        -------
        h : float
            Differential entropy

        Nr   r   )r`   r  r   r  r   r*   r*   r/   r   0  s    zmultivariate_t_gen.entropyc                 C   s   |  |||\}}}}|dur(t|}n| j}t|rDt|}n|j||d| }|jt|||d}	||	t	|d   }
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]])

        Nr   rz  )r   r   rv   r8   isinfZonesr4  r   r   rX   r0   )r`   r  r   r  r   r{   r   r  rC   r  samplesr*   r*   r/   r   A  s     

zmultivariate_t_gen.rvsc                 C   s`   t j|td}|jdkr$|t j }n8|jdkr\|dkrJ|ddt jf }n|t jddf }|S r   r   r   r*   r*   r/   r   p  s    

z%multivariate_t_gen._process_quantilesc                 C   s  |du r2|du r2t jdtd}t jdtd}d}n|du rnt j|td}|jdk rXd}n
|jd }t |}nJ|du rt j|td}|j}t |}n"t j|td}t j|td}|j}|dkr|d}|dd}|jdks|jd |krt	d| |jdkr|t | }n|jdkr.t 
|}n~|jdkr|j||fkr|j\}}||krndt|j }nd}|t|jt|f }t	|n|jdkrt	d	|j |du rd}n(|dkrt	d
nt |rt	d||||fS )z
        Infer dimensionality from location array and shape matrix, handle
        defaults, and ensure compatible dimensions.
        Nr   rG   r   r)   z*Array 'loc' must be a vector of length %d.r   zSDimension mismatch: array 'cov' is of shape %s, but 'loc' is a vector of length %d.r   z'df' must be greater than zero.z8'df' is 'nan' but must be greater than zero or 'np.inf'.)r8   rO   rI   r,   r   r   r   r   r   rU   r   r   rV   isnan)r`   r  r   r  r   r   r   re   r*   r*   r/   r     s`    








z&multivariate_t_gen._process_parameters)N)Nr   r   FN)Nr   r   F)Nr   r   )NNN)Nr   r   F)r   r   )Nr   r   )Nr   r   r   N)ro   rp   rq   rr   rf   r   r   r   r   r   r   r   r   r   r   r   r   r*   r*   ry   r/   r    s&   R  


#+  
''
"

/r  c                   @   sJ   e Zd ZdddZdd Zddddd	d
Zdd ZdddZdd ZdS )r  Nr   Fc                 C   sP   t || _| j|||\}}}}||||f\| _| _| _| _t||d| _dS )a  Create a frozen multivariate t distribution.

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

        Examples
        --------
        >>> import numpy as np
        >>> from scipy.stats import multivariate_t
        >>> 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  r   r   r   r  r   r  rL   r  )r`   r  r   r  rb   rx   r   r*   r*   r/   rf     s    
zmultivariate_t_frozen.__init__c              	   C   sB   | j || j}| jj}| jj}| j || j||| j| j| jj	S rj   )
r   r   r   r  r[   r^   r   r  r  rZ   )r`   rC   r[   r^   r*   r*   r/   r     s    zmultivariate_t_frozen.logpdfr  c             
   C   s2   | j || j}| j || j| j| j| j|||S rj   )r   r   r   r   r  r   r  )r`   rC   r   r   r{   r*   r*   r/   r     s    zmultivariate_t_frozen.cdfc                 C   s   t | |S rj   r   r   r*   r*   r/   r     s    zmultivariate_t_frozen.pdfc                 C   s   | j j| j| j| j||dS )N)r  r   r  r   r{   )r   r   r  r   r  r   r*   r*   r/   r     s    
zmultivariate_t_frozen.rvsc                 C   s   | j | j| j| jS rj   )r   r   r   r  r   rm   r*   r*   r/   r     s    zmultivariate_t_frozen.entropy)Nr   r   FN)r   N)	ro   rp   rq   rf   r   r   r   r   r   r*   r*   r*   r/   r    s     

r  )r   r   r   r   r   zm : array_like
    The number of each type of object in the population.
    That is, :math:`m[i]` is the number of objects of
    type :math:`i`.
n : array_like
    The number of samples taken from the population.
a  `m` must be an array of positive integers. If the quantile
:math:`i` contains values out of the range :math:`[0, m_i]`
where :math:`m_i` is the number of objects of type :math:`i`
in the population or if the parameters are inconsistent with one
another (e.g. ``x.sum() != n``), methods return the appropriate
value (e.g. ``0`` for ``pmf``). If `m` or `n` contain negative
values, the result will contain ``nan`` there.
c                       s~   e Zd ZdZd fdd	ZdddZdd Zd	d
 Zdd Zdd Z	dd Z
dd Zdd Zdd Zdd ZdddZ  ZS )multivariate_hypergeom_gena  A multivariate hypergeometric random variable.

    Methods
    -------
    pmf(x, m, n)
        Probability mass function.
    logpmf(x, m, n)
        Log of the probability mass function.
    rvs(m, n, size=1, random_state=None)
        Draw random samples from a multivariate hypergeometric
        distribution.
    mean(m, n)
        Mean of the multivariate hypergeometric distribution.
    var(m, n)
        Variance of the multivariate hypergeometric distribution.
    cov(m, n)
        Compute the covariance matrix of the multivariate
        hypergeometric distribution.

    Parameters
    ----------
    %(_doc_default_callparams)s
    %(_doc_random_state)s

    Notes
    -----
    %(_doc_callparams_note)s

    The probability mass function for `multivariate_hypergeom` is

    .. math::

        P(X_1 = x_1, X_2 = x_2, \ldots, X_k = x_k) = \frac{\binom{m_1}{x_1}
        \binom{m_2}{x_2} \cdots \binom{m_k}{x_k}}{\binom{M}{n}}, \\ \quad
        (x_1, x_2, \ldots, x_k) \in \mathbb{N}^k \text{ with }
        \sum_{i=1}^k x_i = n

    where :math:`m_i` are the number of objects of type :math:`i`, :math:`M`
    is the total number of objects in the population (sum of all the
    :math:`m_i`), and :math:`n` is the size of the sample to be taken
    from the population.

    .. versionadded:: 1.6.0

    Examples
    --------
    To evaluate the probability mass function of the multivariate
    hypergeometric distribution, with a dichotomous population of size
    :math:`10` and :math:`20`, at a sample of size :math:`12` with
    :math:`8` objects of the first type and :math:`4` objects of the
    second type, use:

    >>> from scipy.stats import multivariate_hypergeom
    >>> multivariate_hypergeom.pmf(x=[8, 4], m=[10, 20], n=12)
    0.0025207176631464523

    The `multivariate_hypergeom` distribution is identical to the
    corresponding `hypergeom` distribution (tiny numerical differences
    notwithstanding) when only two types (good and bad) of objects
    are present in the population as in the example above. Consider
    another example for a comparison with the hypergeometric distribution:

    >>> from scipy.stats import hypergeom
    >>> multivariate_hypergeom.pmf(x=[3, 1], m=[10, 5], n=4)
    0.4395604395604395
    >>> hypergeom.pmf(k=3, M=15, n=4, N=10)
    0.43956043956044005

    The functions ``pmf``, ``logpmf``, ``mean``, ``var``, ``cov``, and ``rvs``
    support broadcasting, under the convention that the vector parameters
    (``x``, ``m``, and ``n``) are interpreted as if each row along the last
    axis is a single object. For instance, we can combine the previous two
    calls to `multivariate_hypergeom` as

    >>> multivariate_hypergeom.pmf(x=[[8, 4], [3, 1]], m=[[10, 20], [10, 5]],
    ...                            n=[12, 4])
    array([0.00252072, 0.43956044])

    This broadcasting also works for ``cov``, where the output objects are
    square matrices of size ``m.shape[-1]``. For example:

    >>> multivariate_hypergeom.cov(m=[[7, 9], [10, 15]], n=[8, 12])
    array([[[ 1.05, -1.05],
            [-1.05,  1.05]],
           [[ 1.56, -1.56],
            [-1.56,  1.56]]])

    That is, ``result[0]`` is equal to
    ``multivariate_hypergeom.cov(m=[7, 9], n=8)`` and ``result[1]`` is equal
    to ``multivariate_hypergeom.cov(m=[10, 15], n=12)``.

    Alternatively, the object may be called (as a function) to fix the `m`
    and `n` parameters, returning a "frozen" multivariate hypergeometric
    random variable.

    >>> rv = multivariate_hypergeom(m=[10, 20], n=12)
    >>> rv.pmf(x=[8, 4])
    0.0025207176631464523

    See Also
    --------
    scipy.stats.hypergeom : The hypergeometric distribution.
    scipy.stats.multinomial : The multinomial distribution.

    References
    ----------
    .. [1] The Multivariate Hypergeometric Distribution,
           http://www.randomservices.org/random/urn/MultiHypergeometric.html
    .. [2] Thomas J. Sargent and John Stachurski, 2020,
           Multivariate Hypergeometric Distribution
           https://python.quantecon.org/multi_hyper.html
    Nc                    s    t  | t| jt| _d S rj   )ru   rf   r   r   rr   mhg_docdict_paramsrw   ry   r*   r/   rf     s    z#multivariate_hypergeom_gen.__init__c                 C   s   t |||dS )zCreate a frozen multivariate_hypergeom distribution.

        See `multivariate_hypergeom_frozen` for more information.
        r   )multivariate_hypergeom_frozen)r`   r  r   rx   r*   r*   r/   r     s    z#multivariate_hypergeom_gen.__call__c              	   C   s   t |}t |}|jdkr(|t}|jdkr<|t}t |jt jsTtdt |jt jsltd|j	dkr~t
d|jdkr|dt jf }t ||\}}|jdkr|d }|dk }|jdd}|dk ||kB }|||||t j|dd|B fS )	Nr   z'm' must an array of integers.z'n' must an array of integers.z1'm' must be an array with at least one dimension..rx  r1   rg   )r8   rO   r   astyper   
issubdtyper5   integer	TypeErrorr,   rU   r   r   r\   r   )r`   r  r   mcondra   r`  r*   r*   r/   r     s*    








z.multivariate_hypergeom_gen._process_parametersc              	   C   s   t |}t |jt js"td|jdkr4td|jd |jd ksjtd|jd  d|jd  d|j	dkr|dt j
f }|dt j
f }t ||||\}}}}|j	dkr|d	 |d	  }}|dk ||kB }|||||t j|dd
|jdd
|kB fS )Nz'x' must an array of integers.r   z1'x' must be an array with at least one dimension.r1   z4Size of each quantile must be size of 'm': received z, but expected r   .rx  rg   )r8   rO   r  r5   r  r  r,   rU   r   r   r   r   r   r\   )r`   rC   ra   r  r   rk  r*   r*   r/   r     s*    





z-multivariate_hypergeom_gen._process_quantilesc                 C   s<   t |}|jdkr|||< n|r&|S |jdkr8|d S |S )Nr   r*   rb  rc  r*   r*   r/   re    s    



z'multivariate_hypergeom_gen._checkresultc           	      C   s   t j|t jd}t j|t jd}||  ||   }}||  ||   }}t|d dt|d || d  || < t|d dt|d || d  || < t j||< t j||< |jdd}|| S )NrG   r   r1   rg   )r8   Z
zeros_liker_  r   ri  r\   )	r`   rC   ra   r  r   mxcondr`  numZdenr*   r*   r/   rg    s    **

z"multivariate_hypergeom_gen._logpmfc                 C   s   |  ||\}}}}}}| ||||\}}}}}}	||B }
|tj|jtjdB }| |||||
|}|	tj|jtjdB }| ||tj }|tj|	jtjdB }| ||tj	S )a  Log of the multivariate hypergeometric probability mass function.

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

        Returns
        -------
        logpmf : ndarray or scalar
            Log of the probability mass function evaluated at `x`

        Notes
        -----
        %(_doc_callparams_note)s
        rG   )
r   r   r8   r   r   rh  rg  re  r   ri  )r`   rC   r  r   ra   r  r`  mncondrk  Zxcond_reducedr  rd  rl  Zmncond_r*   r*   r/   rm    s    z!multivariate_hypergeom_gen.logpmfc                 C   s   t | |||}|S )a  Multivariate hypergeometric probability mass function.

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

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

        Notes
        -----
        %(_doc_callparams_note)s
        rn  )r`   rC   r  r   r.   r*   r*   r/   ro    s    zmultivariate_hypergeom_gen.pmfc                 C   s   |  ||\}}}}}}|jdkr@|dtjf |dtjf  }}|dk}tjj||d}|||  }|jdkr|dtjf tj|jtjdB }| 	||tj
S )zMean of the multivariate hypergeometric distribution.

        Parameters
        ----------
        %(_doc_default_callparams)s

        Returns
        -------
        mean : array_like or scalar
            The mean of the distribution
        r   .maskrG   r   r   r8   r   mamasked_arrayr   r   rh  re  ri  )r`   r  r   ra   r   r  r<   mur*   r*   r/   r   -  s    

zmultivariate_hypergeom_gen.meanc                 C   s   |  ||\}}}}}}|jdkr@|dtjf |dtjf  }}|dk|d dk@ }tjj||d}|| | ||  | ||  |d  }|jdkr|dtjf tj|jtjdB }| 	||tj
S )aQ  Variance of the multivariate hypergeometric distribution.

        Parameters
        ----------
        %(_doc_default_callparams)s

        Returns
        -------
        array_like
            The variances of the components of the distribution.  This is
            the diagonal of the covariance matrix of the distribution
        r   .r   r  rG   r  )r`   r  r   ra   r   r  r<   outputr*   r*   r/   r  E  s    
(
zmultivariate_hypergeom_gen.varc           
      C   s  |  ||\}}}}}}|jdkrF|dtjtjf }|dtjtjf }|dk|d dk@ }tjj||d}| ||  |d  td|| |d  }|jdkr|d |d  }}|d }|jd }t|D ]v}	|||  |d|	f  ||d|	f   |d|	|	f< |d|	|	f |d  |d|	|	f< |d|	|	f |d  |d|	|	f< q|jdkrt|dtjtjf tj	|jtj
d	B }| ||tjS )
a  Covariance matrix of the multivariate hypergeometric distribution.

        Parameters
        ----------
        %(_doc_default_callparams)s

        Returns
        -------
        cov : array_like
            The covariance matrix of the distribution
        r   .r   r  z...i,...j->...ijr)   ).r   r   r1   rG   )r   r   r8   r   r  r  r   r   r  r   rh  re  ri  )
r`   r  r   ra   r   r  r<   r  r   r#  r*   r*   r/   r   ^  s0    


2 "zmultivariate_hypergeom_gen.covc                 C   s   |  ||\}}}}}}| |}|dur:t|tr:|f}|du rVtj|j|jd}ntj||jd f |jd}|}t|jd d D ]\}	||d|	f  }|dk}
|
 |j	|d|	f ||
 ||
 |d |d|	f< ||d|	f  }q||d|jd d f< |S )a  Draw random samples from a multivariate hypergeometric distribution.

        Parameters
        ----------
        %(_doc_default_callparams)s
        size : integer or iterable of integers, optional
            Number of samples to draw. Default is ``None``, in which case a
            single variate is returned as an array with shape ``m.shape``.
        %(_doc_random_state)s

        Returns
        -------
        rvs : array_like
            Random variates of shape ``size`` or ``m.shape``
            (if ``size=None``).

        Notes
        -----
        %(_doc_callparams_note)s

        Also note that NumPy's `multivariate_hypergeometric` sampler is not
        used as it doesn't support broadcasting.
        NrG   r1   r   .r   r   )
r   r~   r   r   r8   r  r   r5   r  Zhypergeometric)r`   r  r   r   r{   ra   r   r   remr  Zn0maskr*   r*   r/   r     s*    
zmultivariate_hypergeom_gen.rvs)N)N)NN)ro   rp   rq   rr   rf   r   r   r   re  rg  rm  ro  r   r  r   r   r   r*   r*   ry   r/   r  %  s   p
 
$&r  c                   @   sH   e Zd ZdddZdd Zdd Zdd	 Zd
d Zdd ZdddZ	dS )r  Nc                    sH   t | _ j||\ _ _ _ _ _ _ fdd}| j_d S )Nc                    s    j  j j j j jfS rj   )ra   r  r   r  r`  r  )r  r   rm   r*   r/   r     s    zCmultivariate_hypergeom_frozen.__init__.<locals>._process_parameters)	r  r   r   ra   r  r   r  r`  r  )r`   r  r   rx   r   r*   rm   r/   rf     s    
z&multivariate_hypergeom_frozen.__init__c                 C   s   | j || j| jS rj   )r   rm  r  r   r   r*   r*   r/   rm    s    z$multivariate_hypergeom_frozen.logpmfc                 C   s   | j || j| jS rj   )r   ro  r  r   r   r*   r*   r/   ro    s    z!multivariate_hypergeom_frozen.pmfc                 C   s   | j | j| jS rj   )r   r   r  r   rm   r*   r*   r/   r     s    z"multivariate_hypergeom_frozen.meanc                 C   s   | j | j| jS rj   )r   r  r  r   rm   r*   r*   r/   r    s    z!multivariate_hypergeom_frozen.varc                 C   s   | j | j| jS rj   )r   r   r  r   rm   r*   r*   r/   r     s    z!multivariate_hypergeom_frozen.covr   c                 C   s   | j j| j| j||dS )N)r   r{   )r   r   r  r   r   r*   r*   r/   r     s    z!multivariate_hypergeom_frozen.rvs)N)r   N)
ro   rp   rq   rf   rm  ro  r   r  r   r   r*   r*   r*   r/   r    s   
r  )rm  ro  r   r  r   r   c                       s   e Zd ZdZd fdd	ZddddZdd	 Zd
d Zdd ZddddddZ	e
dd Ze
dd Zedd Zedd Ze
dd Ze
dd Z  ZS )random_table_gena 	  Contingency tables from independent samples with fixed marginal sums.

    This is the distribution of random tables with given row and column vector
    sums. This distribution represents the set of random tables under the null
    hypothesis that rows and columns are independent. It is used in hypothesis
    tests of independence.

    Because of assumed independence, the expected frequency of each table
    element can be computed from the row and column sums, so that the
    distribution is completely determined by these two vectors.

    Methods
    -------
    logpmf(x)
        Log-probability of table `x` to occur in the distribution.
    pmf(x)
        Probability of table `x` to occur in the distribution.
    mean(row, col)
        Mean table.
    rvs(row, col, size=None, method=None, random_state=None)
        Draw random tables with given row and column vector sums.

    Parameters
    ----------
    %(_doc_row_col)s
    %(_doc_random_state)s

    Notes
    -----
    %(_doc_row_col_note)s

    Random elements from the distribution are generated either with Boyett's
    [1]_ or Patefield's algorithm [2]_. Boyett's algorithm has
    O(N) time and space complexity, where N is the total sum of entries in the
    table. Patefield's algorithm has O(K x log(N)) time complexity, where K is
    the number of cells in the table and requires only a small constant work
    space. By default, the `rvs` method selects the fastest algorithm based on
    the input, but you can specify the algorithm with the keyword `method`.
    Allowed values are "boyett" and "patefield".

    .. versionadded:: 1.10.0

    Examples
    --------
    >>> from scipy.stats import random_table

    >>> row = [1, 5]
    >>> col = [2, 3, 1]
    >>> random_table.mean(row, col)
    array([[0.33333333, 0.5       , 0.16666667],
           [1.66666667, 2.5       , 0.83333333]])

    Alternatively, the object may be called (as a function) to fix the row
    and column vector sums, returning a "frozen" distribution.

    >>> dist = random_table(row, col)
    >>> dist.rvs(random_state=123)
    array([[1., 0., 0.],
           [1., 3., 1.]])

    References
    ----------
    .. [1] J. Boyett, AS 144 Appl. Statist. 28 (1979) 329-332
    .. [2] W.M. Patefield, AS 159 Appl. Statist. 30 (1981) 91-97
    Nc                    s   t  | d S rj   ru   rf   rw   ry   r*   r/   rf   -  s    zrandom_table_gen.__init__r   c                C   s   t |||dS )z~Create a frozen distribution of tables with given marginals.

        See `random_table_frozen` for more information.
        r   )random_table_frozen)r`   rowcolrx   r*   r*   r/   r   0  s    zrandom_table_gen.__call__c                 C   s  |  ||\}}}t|}|jdk r.tdt|jtj}tjdd0 |slt	|
t|ksltdW d   n1 s0    Y  t|dk rtdtj|d	d
}tj|dd
}	|jd	 t|krtd|	jd	 t|krtdt|jdd }
tj	||kd	d
tj	|	|kd	d
@ }dd }tj||d	d
tj||d	d
 || tj||| dd
 |
|< tj |
| < |
d S )a  Log-probability of table to occur in the distribution.

        Parameters
        ----------
        %(_doc_x)s
        %(_doc_row_col)s

        Returns
        -------
        logpmf : ndarray or scalar
            Log of the probability mass function evaluated at `x`.

        Notes
        -----
        %(_doc_row_col_note)s

        If row and column marginals of `x` do not match `row` and `col`,
        negative infinity is returned.

        Examples
        --------
        >>> from scipy.stats import random_table
        >>> import numpy as np

        >>> x = [[1, 5, 1], [2, 3, 1]]
        >>> row = np.sum(x, axis=1)
        >>> col = np.sum(x, axis=0)
        >>> random_table.logpmf(x, row, col)
        -1.6306401200847027

        Alternatively, the object may be called (as a function) to fix the row
        and column vector sums, returning a "frozen" distribution.

        >>> d = random_table(row, col)
        >>> d.logpmf(x)
        -1.6306401200847027
        r)   z$`x` must be at least two-dimensionalignore)invalidz%`x` must contain only integral valuesNr   z)`x` must contain only non-negative valuesr1   rg   r   z"shape of `x` must agree with `row`z"shape of `x` must agree with `col`c                 S   s   t | d S )Nr   )r   )rC   r*   r*   r/   lnfacy  s    z&random_table_gen.logpmf.<locals>.lnfac)r1   r   r*   )r   r8   rO   r,   rU   r  r5   r  Zerrstateallr  r   r   r\   r   rV   r  r   )r`   rC   r  r  r  r  r   Zdtype_is_intr2c2r  r  r  r*   r*   r/   rm  7  s4    &

&$"zrandom_table_gen.logpmfc                 C   s   t | |||S )a  Probability of table to occur in the distribution.

        Parameters
        ----------
        %(_doc_x)s
        %(_doc_row_col)s

        Returns
        -------
        pmf : ndarray or scalar
            Probability mass function evaluated at `x`.

        Notes
        -----
        %(_doc_row_col_note)s

        If row and column marginals of `x` do not match `row` and `col`,
        zero is returned.

        Examples
        --------
        >>> from scipy.stats import random_table
        >>> import numpy as np

        >>> x = [[1, 5, 1], [2, 3, 1]]
        >>> row = np.sum(x, axis=1)
        >>> col = np.sum(x, axis=0)
        >>> random_table.pmf(x, row, col)
        0.19580419580419592

        Alternatively, the object may be called (as a function) to fix the row
        and column vector sums, returning a "frozen" distribution.

        >>> d = random_table(row, col)
        >>> d.pmf(x)
        0.19580419580419592
        rn  )r`   rC   r  r  r*   r*   r/   ro    s    &zrandom_table_gen.pmfc                 C   s"   |  ||\}}}t||| S )aA  Mean of distribution of conditional tables.
        %(_doc_mean_params)s

        Returns
        -------
        mean: ndarray
            Mean of the distribution.

        Notes
        -----
        %(_doc_row_col_note)s

        Examples
        --------
        >>> from scipy.stats import random_table

        >>> row = [1, 5]
        >>> col = [2, 3, 1]
        >>> random_table.mean(row, col)
        array([[0.33333333, 0.5       , 0.16666667],
               [1.66666667, 2.5       , 0.83333333]])

        Alternatively, the object may be called (as a function) to fix the row
        and column vector sums, returning a "frozen" distribution.

        >>> d = random_table(row, col)
        >>> d.mean()
        array([[0.33333333, 0.5       , 0.16666667],
               [1.66666667, 2.5       , 0.83333333]])
        )r   r8   r  )r`   r  r  r  r  r   r*   r*   r/   r     s    zrandom_table_gen.meanr   methodr{   c                C   sT   |  ||\}}}| |||\}}	| |}| ||||}
|
||||||	S )ag  Draw random tables with fixed column and row marginals.

        Parameters
        ----------
        %(_doc_row_col)s
        size : integer, optional
            Number of samples to draw (default 1).
        method : str, optional
            Which method to use, "boyett" or "patefield". If None (default),
            selects the fastest method for this input.
        %(_doc_random_state)s

        Returns
        -------
        rvs : ndarray
            Random 2D tables of shape (`size`, `len(row)`, `len(col)`).

        Notes
        -----
        %(_doc_row_col_note)s

        Examples
        --------
        >>> from scipy.stats import random_table

        >>> row = [1, 5]
        >>> col = [2, 3, 1]
        >>> random_table.rvs(row, col, random_state=123)
        array([[1., 0., 0.],
               [1., 3., 1.]])

        Alternatively, the object may be called (as a function) to fix the row
        and column vector sums, returning a "frozen" distribution.

        >>> d = random_table(row, col)
        >>> d.rvs(random_state=123)
        array([[1., 0., 0.],
               [1., 3., 1.]])
        )r   _process_size_shaper~   _process_rvs_methodr   )r`   r  r  r   r  r{   r  r  r   r   methr*   r*   r/   r     s
    (
zrandom_table_gen.rvsc                 C   s   t j| t jdd}t j|t jdd}t |dkr:tdt |dkrPtdt |dk rftdt |dk r|tdt |}|t |krtd	t |t | kstd
t |t |kstd|||fS )z
        Check that row and column vectors are one-dimensional, that they do
        not contain negative or non-integer entries, and that the sums over
        both vectors are equal.
        Tr^  r   z`row` must be one-dimensionalz`col` must be one-dimensionalr   z*each element of `row` must be non-negativez*each element of `col` must be non-negativez'sums over `row` and `col` must be equalz(each element of `row` must be an integerz(each element of `col` must be an integer)	r8   rH   Zint64r,   rU   r   r\   r  rO   )r  r  r  r  r   r*   r*   r/   r     s$    
z$random_table_gen._process_parametersc                 C   sf   t |t |f}| du r d|fS t| } t| jtjrHt| dk rPtdt| t	| | fS )zW
        Compute the number of samples to be drawn and the shape of the output
        Nr   r   z/`size` must be a non-negative integer or `None`)
rV   r8   r   r  r5   r  r   rU   r  r   )r   r  r  r   r*   r*   r/   r    s    
z$random_table_gen._process_size_shapec              	   C   sT   |  |||| j| jd}z
|| W S  tyN   td| dt| Y n0 d S )N)NZboyettZ	patefield'z!' not recognized, must be one of )_rvs_select_rvs_boyett_rvs_patefieldKeyErrorrU   set)clsr  r  r  r   Zknown_methodsr*   r*   r/   r  +  s    

z$random_table_gen._process_rvs_methodc                 C   s:   d}t |t | }||t|d  | kr4| jS | jS )Nr   r   )rV   r8   r]   r  r  )r  r  r  r   Zfacr8  r*   r*   r/   r  8  s
    zrandom_table_gen._rvs_selectc                 C   s   t | ||||S rj   )r   Z
rvs_rcont1r  r  Zntotr   r{   r*   r*   r/   r  A  s    zrandom_table_gen._rvs_boyettc                 C   s   t | ||||S rj   )r   Z
rvs_rcont2r  r*   r*   r/   r  E  s    zrandom_table_gen._rvs_patefield)N)ro   rp   rq   rr   rf   r   rm  ro  r   r   staticmethodr   r  classmethodr  r  r  r  r   r*   r*   ry   r/   r    s&   BK("0




r  c                   @   s<   e Zd ZddddZdd Zdd Zd	d
 ZdddZdS )r  Nr   c                   s2   t | _ j|| _ fdd}| j_d S )Nc                    s    j S rj   )_params)r  r  rm   r*   r/   r   S  s    z9random_table_frozen.__init__.<locals>._process_parameters)r  r   r   r  )r`   r  r  rx   r   r*   rm   r/   rf   N  s    
zrandom_table_frozen.__init__c                 C   s   | j |d d S rj   )r   rm  r   r*   r*   r/   rm  W  s    zrandom_table_frozen.logpmfc                 C   s   | j |d d S rj   )r   ro  r   r*   r*   r/   ro  Z  s    zrandom_table_frozen.pmfc                 C   s   | j d d S rj   )r   r   rm   r*   r*   r/   r   ]  s    zrandom_table_frozen.meanc                 C   s   | j jd d |||dS )Nr  )r   r   )r`   r   r  r{   r*   r*   r/   r   `  s    zrandom_table_frozen.rvs)NNN)ro   rp   rq   rf   rm  ro  r   r   r*   r*   r*   r/   r  M  s
   	r  zprow : array_like
    Sum of table entries in each row.
col : array_like
    Sum of table entries in each column.zx : array-like
   Two-dimensional table of non-negative integers, or a
   multi-dimensional array with the last two dimensions
   corresponding with the tables.zThe row and column vectors must be one-dimensional, not empty,
and each sum up to the same value. They cannot contain negative
or noninteger entries.z
Parameters
----------
)r   _doc_row_colZ_doc_x_doc_mean_params_doc_row_col_note)r  r  r  c                 C   s   t |p| j|| _d S rj   )r   r   rr   )objZdocdicttemplater*   r*   r/   _docfill  s    r  )rm  ro  r   r   c                       s>   e Zd ZdZd fdd	ZdddZdd Zdd	d
Z  ZS )uniform_direction_gena  A vector-valued uniform direction.

    Return a random direction (unit vector). The `dim` keyword specifies
    the dimensionality of the space.

    Methods
    -------
    rvs(dim=None, size=1, random_state=None)
        Draw random directions.

    Parameters
    ----------
    dim : scalar
        Dimension of directions.
    seed : {None, int, `numpy.random.Generator`,
            `numpy.random.RandomState`}, 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`.

    Notes
    -----
    This distribution generates unit vectors uniformly distributed on
    the surface of a hypersphere. These can be interpreted as random
    directions.
    For example, if `dim` is 3, 3D vectors from the surface of :math:`S^2`
    will be sampled.

    References
    ----------
    .. [1] Marsaglia, G. (1972). "Choosing a Point from the Surface of a
           Sphere". Annals of Mathematical Statistics. 43 (2): 645-646.

    Examples
    --------
    >>> import numpy as np
    >>> from scipy.stats import uniform_direction
    >>> x = uniform_direction.rvs(3)
    >>> np.linalg.norm(x)
    1.

    This generates one random direction, a vector on the surface of
    :math:`S^2`.

    Alternatively, the object may be called (as a function) to return a frozen
    distribution with fixed `dim` parameter. Here,
    we create a `uniform_direction` with ``dim=3`` and draw 5 observations.
    The samples are then arranged in an array of shape 5x3.

    >>> rng = np.random.default_rng()
    >>> uniform_sphere_dist = uniform_direction(3)
    >>> unit_vectors = uniform_sphere_dist.rvs(5, random_state=rng)
    >>> unit_vectors
    array([[ 0.56688642, -0.1332634 , -0.81294566],
           [-0.427126  , -0.74779278,  0.50830044],
           [ 0.3793989 ,  0.92346629,  0.05715323],
           [ 0.36428383, -0.92449076, -0.11231259],
           [-0.27733285,  0.94410968, -0.17816678]])
    Nc                    s   t  | t| j| _d S rj   rr  rw   ry   r*   r/   rf     s    zuniform_direction_gen.__init__c                 C   s   t ||dS )z}Create a frozen n-dimensional uniform direction distribution.

        See `uniform_direction` for more information.
        r   )uniform_direction_frozenrt  r*   r*   r/   r     s    zuniform_direction_gen.__call__c                 C   s6   |du s&t |r&|dk s&|t|kr.tdt|S )ru  Nr   zMDimension of vector must be specified, and must be an integer greater than 0.rv  rw  r*   r*   r/   r     s    &z)uniform_direction_gen._process_parametersc                 C   sD   |  |}|du r tjg td}t|}| |}t|||}|S )a{  Draw random samples from S(N-1).

        Parameters
        ----------
        dim : integer
            Dimension of space (N).
        size : int or tuple of ints, optional
            Given a shape of, for example, (m,n,k), m*n*k samples are
            generated, and packed in an m-by-n-by-k arrangement.
            Because each sample is N-dimensional, the output shape
            is (m,n,k,N). If no shape is specified, a single (N-D)
            sample is returned.
        random_state : {None, int, `numpy.random.Generator`,
                        `numpy.random.RandomState`}, optional

            Pseudorandom number generator state used to generate resamples.

            If `random_state` is ``None`` (or `np.random`), the
            `numpy.random.RandomState` singleton is used.
            If `random_state` is an int, a new ``RandomState`` instance is
            used, seeded with `random_state`.
            If `random_state` is already a ``Generator`` or ``RandomState``
            instance then that instance is used.

        Returns
        -------
        rvs : ndarray
            Random direction vectors

        NrG   )r~   r8   rH   r   r   r   _sample_uniform_direction)r`   r   r   r{   r  r*   r*   r/   r     s    


zuniform_direction_gen.rvs)N)NN)NNr  r*   r*   ry   r/   r    s
   A
r  c                   @   s    e Zd ZdddZdddZdS )r  Nc                 C   s   t || _| j|| _dS )a  Create a frozen n-dimensional uniform direction distribution.

        Parameters
        ----------
        dim : int
            Dimension of matrices
        seed : {None, int, `numpy.random.Generator`,
                `numpy.random.RandomState`}, optional

            If `seed` is None (or `np.random`), the `numpy.random.RandomState`
            singleton is used.
            If `seed` is an int, a new ``RandomState`` instance is used,
            seeded with `seed`.
            If `seed` is already a ``Generator`` or ``RandomState`` instance
            then that instance is used.

        Examples
        --------
        >>> from scipy.stats import uniform_direction
        >>> x = uniform_direction(3)
        >>> x.rvs()

        N)r  r   r   r   rt  r*   r*   r/   rf      s    
z!uniform_direction_frozen.__init__c                 C   s   | j | j||S rj   r  r   r*   r*   r/   r   ;  s    zuniform_direction_frozen.rvs)NN)NNr  r*   r*   r*   r/   r    s   
r  c                 C   s0   t || }||}|t jj|ddd }|S )z
    Private method to generate uniform directions
    Reference: Marsaglia, G. (1972). "Choosing a Point from the Surface of a
               Sphere". Annals of Mathematical Statistics. 43 (2): 645-646.
    r1   T)rh   Zkeepdims)r8   r   r   rR   r   )r   r   r{   Zsamples_shaper  r*   r*   r/   r  ?  s    
r  a"  alpha : array_like
    The concentration parameters. The number of entries along the last axis
    determines the dimensionality of the distribution. Each entry must be
    strictly positive.
n : int or array_like
    The number of trials. Each element must be a strictly positive integer.
)$_dirichlet_mn_doc_default_callparamsr   c              
   C   s  t | } t |}|d urzt || \}} W n2 tyb } zd}t||W Y d }~n
d }~0 0 t |}t |dk st ||krtd|}t | dkrtdt |}t |dkst ||krtd|}t j| dd}t ||\}}|d u r| ||fS | |||fS )Nz&`x` and `alpha` must be broadcastable.r   z,`x` must contain only non-negative integers.z*`alpha` must contain only positive values.z`n` must be a positive integer.r1   rg   )r8   rO   r   rU   floorr   r\   )r   r   rC   r   re   Zx_intZn_intZ	sum_alphar*   r*   r/   '_dirichlet_multinomial_check_parametersd  s*    

 

r  c                       sT   e Zd ZdZd fdd	ZdddZdd Zd	d
 Zdd Zdd Z	dd Z
  ZS )dirichlet_multinomial_gena|  A Dirichlet multinomial random variable.

    The Dirichlet multinomial distribution is a compound probability
    distribution: it is the multinomial distribution with number of trials
    `n` and class probabilities ``p`` randomly sampled from a Dirichlet
    distribution with concentration parameters ``alpha``.

    Methods
    -------
    logpmf(x, alpha, n):
        Log of the probability mass function.
    pmf(x, alpha, n):
        Probability mass function.
    mean(alpha, n):
        Mean of the Dirichlet multinomial distribution.
    var(alpha, n):
        Variance of the Dirichlet multinomial distribution.
    cov(alpha, n):
        The covariance of the Dirichlet multinomial distribution.

    Parameters
    ----------
    %(_dirichlet_mn_doc_default_callparams)s
    %(_doc_random_state)s

    See Also
    --------
    scipy.stats.dirichlet : The dirichlet distribution.
    scipy.stats.multinomial : The multinomial distribution.

    References
    ----------
    .. [1] Dirichlet-multinomial distribution, Wikipedia,
           https://www.wikipedia.org/wiki/Dirichlet-multinomial_distribution

    Examples
    --------
    >>> from scipy.stats import dirichlet_multinomial

    Get the PMF

    >>> n = 6  # number of trials
    >>> alpha = [3, 4, 5]  # concentration parameters
    >>> x = [1, 2, 3]  # counts
    >>> dirichlet_multinomial.pmf(x, alpha, n)
    0.08484162895927604

    If the sum of category counts does not equal the number of trials,
    the probability mass is zero.

    >>> dirichlet_multinomial.pmf(x, alpha, n=7)
    0.0

    Get the log of the PMF

    >>> dirichlet_multinomial.logpmf(x, alpha, n)
    -2.4669689491013327

    Get the mean

    >>> dirichlet_multinomial.mean(alpha, n)
    array([1.5, 2. , 2.5])

    Get the variance

    >>> dirichlet_multinomial.var(alpha, n)
    array([1.55769231, 1.84615385, 2.01923077])

    Get the covariance

    >>> dirichlet_multinomial.cov(alpha, n)
    array([[ 1.55769231, -0.69230769, -0.86538462],
           [-0.69230769,  1.84615385, -1.15384615],
           [-0.86538462, -1.15384615,  2.01923077]])

    Alternatively, the object may be called (as a function) to fix the
    `alpha` and `n` parameters, returning a "frozen" Dirichlet multinomial
    random variable.

    >>> dm = dirichlet_multinomial(alpha, n)
    >>> dm.pmf(x)
    0.08484162895927579

    All methods are fully vectorized. Each element of `x` and `alpha` is
    a vector (along the last axis), each element of `n` is an
    integer (scalar), and the result is computed element-wise.

    >>> x = [[1, 2, 3], [4, 5, 6]]
    >>> alpha = [[1, 2, 3], [4, 5, 6]]
    >>> n = [6, 15]
    >>> dirichlet_multinomial.pmf(x, alpha, n)
    array([0.06493506, 0.02626937])

    >>> dirichlet_multinomial.cov(alpha, n).shape  # both covariance matrices
    (2, 3, 3)

    Broadcasting according to standard NumPy conventions is supported. Here,
    we have four sets of concentration parameters (each a two element vector)
    for each of three numbers of trials (each a scalar).

    >>> alpha = [[3, 4], [4, 5], [5, 6], [6, 7]]
    >>> n = [[6], [7], [8]]
    >>> dirichlet_multinomial.mean(alpha, n).shape
    (3, 4, 2)

    Nc                    s    t  | t| jt| _d S rj   )ru   rf   r   r   rr   dirichlet_mn_docdict_paramsrw   ry   r*   r/   rf     s    z"dirichlet_multinomial_gen.__init__c                 C   s   t |||dS r  )dirichlet_multinomial_frozen)r`   r   r   rx   r*   r*   r/   r     s    z"dirichlet_multinomial_gen.__call__c                 C   s   t |||\}}}}tt|t|d  t||  }|t|| t|t|d   jdd7 }t|||jddktj  |d S )a  The log of the probability mass function.

        Parameters
        ----------
        x: ndarray
            Category counts (non-negative integers). Must be broadcastable
            with shape parameter ``alpha``. If multidimensional, the last axis
            must correspond with the categories.
        %(_dirichlet_mn_doc_default_callparams)s

        Returns
        -------
        out: ndarray or scalar
            Log of the probability mass function.

        r   r1   rg   r*   )r  r8   rO   r
   r\   Zplacer   )r`   rC   r   r   r   Sar.   r*   r*   r/   rm    s
    &,z dirichlet_multinomial_gen.logpmfc                 C   s   t | |||S )a  Probability mass function for a Dirichlet multinomial distribution.

        Parameters
        ----------
        x: ndarray
            Category counts (non-negative integers). Must be broadcastable
            with shape parameter ``alpha``. If multidimensional, the last axis
            must correspond with the categories.
        %(_dirichlet_mn_doc_default_callparams)s

        Returns
        -------
        out: ndarray or scalar
            Probability mass function.

        rn  )r`   rC   r   r   r*   r*   r/   ro    s    zdirichlet_multinomial_gen.pmfc                 C   s:   t ||\}}}|dtjf |dtjf  }}|| | S )zMean of a Dirichlet multinomial distribution.

        Parameters
        ----------
        %(_dirichlet_mn_doc_default_callparams)s

        Returns
        -------
        out: ndarray
            Mean of a Dirichlet multinomial distribution.

        .r  r8   r   r`   r   r   r   r  r*   r*   r/   r   $  s    zdirichlet_multinomial_gen.meanc                 C   sV   t ||\}}}|dtjf |dtjf  }}|| | d||   ||  d|  S )ab  The variance of the Dirichlet multinomial distribution.

        Parameters
        ----------
        %(_dirichlet_mn_doc_default_callparams)s

        Returns
        -------
        out: array_like
            The variances of the components of the distribution. This is
            the diagonal of the covariance matrix of the distribution.

        .r   r  r  r*   r*   r/   r  5  s    zdirichlet_multinomial_gen.varc           	      C   s   t ||\}}}t||}|dtjtjf |dtjtjf  }}|dddtjf |dtjddf  }| | |d  ||  d|  }t|jd }||d||f< |S )a  Covariance matrix of a Dirichlet multinomial distribution.

        Parameters
        ----------
        %(_dirichlet_mn_doc_default_callparams)s

        Returns
        -------
        out : array_like
            The covariance matrix of the distribution.

        .Nr)   r   r1   )r  r   r  r8   r   rV  r   )	r`   r   r   r   r  r  Zaiajr   iir*   r*   r/   r   G  s    &("zdirichlet_multinomial_gen.cov)N)N)ro   rp   rq   rr   rf   r   rm  ro  r   r  r   r   r*   r*   ry   r/   r    s   j
r  c                   @   s>   e Zd ZdddZdd Zdd Zdd	 Zd
d Zdd ZdS )r  Nc                 C   s*   t ||\}}}|| _|| _t|| _d S rj   )r  r   r   r  r   )r`   r   r   rx   r  r*   r*   r/   rf   d  s    z%dirichlet_multinomial_frozen.__init__c                 C   s   | j || j| jS rj   )r   rm  r   r   r   r*   r*   r/   rm  j  s    z#dirichlet_multinomial_frozen.logpmfc                 C   s   | j || j| jS rj   )r   ro  r   r   r   r*   r*   r/   ro  m  s    z dirichlet_multinomial_frozen.pmfc                 C   s   | j | j| jS rj   )r   r   r   r   rm   r*   r*   r/   r   p  s    z!dirichlet_multinomial_frozen.meanc                 C   s   | j | j| jS rj   )r   r  r   r   rm   r*   r*   r/   r  s  s    z dirichlet_multinomial_frozen.varc                 C   s   | j | j| jS rj   )r   r   r   r   rm   r*   r*   r/   r   v  s    z dirichlet_multinomial_frozen.cov)N)	ro   rp   rq   rf   rm  ro  r   r  r   r*   r*   r*   r/   r  c  s   
r  )rm  ro  r   r  r   c                       s   e Zd ZdZd& fdd	Zd'ddZdd	 Zd
d Zdd Zdd Z	d(ddZ
d)ddZdd Zdd Zdd Zdd Zdd Zd*ddZd d! Zd+d"d#Zd$d% Z  ZS ),vonmises_fisher_gena $  A von Mises-Fisher variable.

    The `mu` keyword specifies the mean direction vector. The `kappa` keyword
    specifies the concentration parameter.

    Methods
    -------
    pdf(x, mu=None, kappa=1)
        Probability density function.
    logpdf(x, mu=None, kappa=1)
        Log of the probability density function.
    rvs(mu=None, kappa=1, size=1, random_state=None)
        Draw random samples from a von Mises-Fisher distribution.
    entropy(mu=None, kappa=1)
        Compute the differential entropy of the von Mises-Fisher distribution.
    fit(data)
        Fit a von Mises-Fisher distribution to data.

    Parameters
    ----------
    mu : array_like
        Mean direction of the distribution. Must be a one-dimensional unit
        vector of norm 1.
    kappa : float
        Concentration parameter. Must be positive.
    seed : {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`.

    See Also
    --------
    scipy.stats.vonmises : Von-Mises Fisher distribution in 2D on a circle
    uniform_direction : uniform distribution on the surface of a hypersphere

    Notes
    -----
    The von Mises-Fisher distribution is a directional distribution on the
    surface of the unit hypersphere. The probability density
    function of a unit vector :math:`\mathbf{x}` is

    .. math::

        f(\mathbf{x}) = \frac{\kappa^{d/2-1}}{(2\pi)^{d/2}I_{d/2-1}(\kappa)}
               \exp\left(\kappa \mathbf{\mu}^T\mathbf{x}\right),

    where :math:`\mathbf{\mu}` is the mean direction, :math:`\kappa` the
    concentration parameter, :math:`d` the dimension and :math:`I` the
    modified Bessel function of the first kind. As :math:`\mu` represents
    a direction, it must be a unit vector or in other words, a point
    on the hypersphere: :math:`\mathbf{\mu}\in S^{d-1}`. :math:`\kappa` is a
    concentration parameter, which means that it must be positive
    (:math:`\kappa>0`) and that the distribution becomes more narrow with
    increasing :math:`\kappa`. In that sense, the reciprocal value
    :math:`1/\kappa` resembles the variance parameter of the normal
    distribution.

    The von Mises-Fisher distribution often serves as an analogue of the
    normal distribution on the sphere. Intuitively, for unit vectors, a
    useful distance measure is given by the angle :math:`\alpha` between
    them. This is exactly what the scalar product
    :math:`\mathbf{\mu}^T\mathbf{x}=\cos(\alpha)` in the
    von Mises-Fisher probability density function describes: the angle
    between the mean direction :math:`\mathbf{\mu}` and the vector
    :math:`\mathbf{x}`. The larger the angle between them, the smaller the
    probability to observe :math:`\mathbf{x}` for this particular mean
    direction :math:`\mathbf{\mu}`.

    In dimensions 2 and 3, specialized algorithms are used for fast sampling
    [2]_, [3]_. For dimensions of 4 or higher the rejection sampling algorithm
    described in [4]_ is utilized. This implementation is partially based on
    the geomstats package [5]_, [6]_.

    .. versionadded:: 1.11

    References
    ----------
    .. [1] Von Mises-Fisher distribution, Wikipedia,
           https://en.wikipedia.org/wiki/Von_Mises%E2%80%93Fisher_distribution
    .. [2] Mardia, K., and Jupp, P. Directional statistics. Wiley, 2000.
    .. [3] J. Wenzel. Numerically stable sampling of the von Mises Fisher
           distribution on S2.
           https://www.mitsuba-renderer.org/~wenzel/files/vmf.pdf
    .. [4] Wood, A. Simulation of the von mises fisher distribution.
           Communications in statistics-simulation and computation 23,
           1 (1994), 157-164. https://doi.org/10.1080/03610919408813161
    .. [5] geomstats, Github. MIT License. Accessed: 06.01.2023.
           https://github.com/geomstats/geomstats
    .. [6] Miolane, N. et al. Geomstats:  A Python Package for Riemannian
           Geometry in Machine Learning. Journal of Machine Learning Research
           21 (2020). http://jmlr.org/papers/v21/19-027.html

    Examples
    --------
    **Visualization of the probability density**

    Plot the probability density in three dimensions for increasing
    concentration parameter. The density is calculated by the ``pdf``
    method.

    >>> import numpy as np
    >>> import matplotlib.pyplot as plt
    >>> from scipy.stats import vonmises_fisher
    >>> from matplotlib.colors import Normalize
    >>> n_grid = 100
    >>> u = np.linspace(0, np.pi, n_grid)
    >>> v = np.linspace(0, 2 * np.pi, n_grid)
    >>> u_grid, v_grid = np.meshgrid(u, v)
    >>> vertices = np.stack([np.cos(v_grid) * np.sin(u_grid),
    ...                      np.sin(v_grid) * np.sin(u_grid),
    ...                      np.cos(u_grid)],
    ...                     axis=2)
    >>> x = np.outer(np.cos(v), np.sin(u))
    >>> y = np.outer(np.sin(v), np.sin(u))
    >>> z = np.outer(np.ones_like(u), np.cos(u))
    >>> def plot_vmf_density(ax, x, y, z, vertices, mu, kappa):
    ...     vmf = vonmises_fisher(mu, kappa)
    ...     pdf_values = vmf.pdf(vertices)
    ...     pdfnorm = Normalize(vmin=pdf_values.min(), vmax=pdf_values.max())
    ...     ax.plot_surface(x, y, z, rstride=1, cstride=1,
    ...                     facecolors=plt.cm.viridis(pdfnorm(pdf_values)),
    ...                     linewidth=0)
    ...     ax.set_aspect('equal')
    ...     ax.view_init(azim=-130, elev=0)
    ...     ax.axis('off')
    ...     ax.set_title(rf"$\kappa={kappa}$")
    >>> fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(9, 4),
    ...                          subplot_kw={"projection": "3d"})
    >>> left, middle, right = axes
    >>> mu = np.array([-np.sqrt(0.5), -np.sqrt(0.5), 0])
    >>> plot_vmf_density(left, x, y, z, vertices, mu, 5)
    >>> plot_vmf_density(middle, x, y, z, vertices, mu, 20)
    >>> plot_vmf_density(right, x, y, z, vertices, mu, 100)
    >>> plt.subplots_adjust(top=1, bottom=0.0, left=0.0, right=1.0, wspace=0.)
    >>> plt.show()

    As we increase the concentration parameter, the points are getting more
    clustered together around the mean direction.

    **Sampling**

    Draw 5 samples from the distribution using the ``rvs`` method resulting
    in a 5x3 array.

    >>> rng = np.random.default_rng()
    >>> mu = np.array([0, 0, 1])
    >>> samples = vonmises_fisher(mu, 20).rvs(5, random_state=rng)
    >>> samples
    array([[ 0.3884594 , -0.32482588,  0.86231516],
           [ 0.00611366, -0.09878289,  0.99509023],
           [-0.04154772, -0.01637135,  0.99900239],
           [-0.14613735,  0.12553507,  0.98126695],
           [-0.04429884, -0.23474054,  0.97104814]])

    These samples are unit vectors on the sphere :math:`S^2`. To verify,
    let us calculate their euclidean norms:

    >>> np.linalg.norm(samples, axis=1)
    array([1., 1., 1., 1., 1.])

    Plot 20 observations drawn from the von Mises-Fisher distribution for
    increasing concentration parameter :math:`\kappa`. The red dot highlights
    the mean direction :math:`\mu`.

    >>> def plot_vmf_samples(ax, x, y, z, mu, kappa):
    ...     vmf = vonmises_fisher(mu, kappa)
    ...     samples = vmf.rvs(20)
    ...     ax.plot_surface(x, y, z, rstride=1, cstride=1, linewidth=0,
    ...                     alpha=0.2)
    ...     ax.scatter(samples[:, 0], samples[:, 1], samples[:, 2], c='k', s=5)
    ...     ax.scatter(mu[0], mu[1], mu[2], c='r', s=30)
    ...     ax.set_aspect('equal')
    ...     ax.view_init(azim=-130, elev=0)
    ...     ax.axis('off')
    ...     ax.set_title(rf"$\kappa={kappa}$")
    >>> mu = np.array([-np.sqrt(0.5), -np.sqrt(0.5), 0])
    >>> fig, axes = plt.subplots(nrows=1, ncols=3,
    ...                          subplot_kw={"projection": "3d"},
    ...                          figsize=(9, 4))
    >>> left, middle, right = axes
    >>> plot_vmf_samples(left, x, y, z, mu, 5)
    >>> plot_vmf_samples(middle, x, y, z, mu, 20)
    >>> plot_vmf_samples(right, x, y, z, mu, 100)
    >>> plt.subplots_adjust(top=1, bottom=0.0, left=0.0,
    ...                     right=1.0, wspace=0.)
    >>> plt.show()

    The plots show that with increasing concentration :math:`\kappa` the
    resulting samples are centered more closely around the mean direction.

    **Fitting the distribution parameters**

    The distribution can be fitted to data using the ``fit`` method returning
    the estimated parameters. As a toy example let's fit the distribution to
    samples drawn from a known von Mises-Fisher distribution.

    >>> mu, kappa = np.array([0, 0, 1]), 20
    >>> samples = vonmises_fisher(mu, kappa).rvs(1000, random_state=rng)
    >>> mu_fit, kappa_fit = vonmises_fisher.fit(samples)
    >>> mu_fit, kappa_fit
    (array([0.01126519, 0.01044501, 0.99988199]), 19.306398751730995)

    We see that the estimated parameters `mu_fit` and `kappa_fit` are
    very close to the ground truth parameters.

    Nc                    s   t  | d S rj   r  rw   ry   r*   r/   rf   X  s    zvonmises_fisher_gen.__init__r   c                 C   s   t |||dS )zsCreate a frozen von Mises-Fisher distribution.

        See `vonmises_fisher_frozen` for more information.
        r   )vonmises_fisher_frozenr`   r  kapparx   r*   r*   r/   r   [  s    zvonmises_fisher_gen.__call__c                 C   s   t |}|jdkrtdt t j|ds8td|jdksJtdd}t |r`|dk rht|t	|dkr|td	|j}|||fS )
z~
        Infer dimensionality from mu and ensure that mu is a one-dimensional
        unit vector and kappa positive.
        r   z%'mu' must have one-dimensional shape.r   z%'mu' must be a unit vector of norm 1.z$'mu' must have at least two entries.z"'kappa' must be a positive scalar.r   r   zFor 'kappa=0' the von Mises-Fisher distribution becomes the uniform distribution on the sphere surface. Consider using 'scipy.stats.uniform_direction' instead.)
r8   rO   r,   rU   allcloserR   r   r   r   rI   )r`   r  r	  Zkappa_error_msgr   r*   r*   r/   r   b  s    


z'vonmises_fisher_gen._process_parametersc                 C   s>   |j d |krtdttjj|ddds:d}t|d S )Nr1   znThe dimensionality of the last axis of 'x' must match the dimensionality of the von Mises Fisher distribution.rg   r   8'x' must be unit vectors of norm 1 along last dimension.)r   rU   r8   r
  rR   r   )r`   rC   r   re   r*   r*   r/   _check_data_vs_distz  s
    z'vonmises_fisher_gen._check_data_vs_distc                 C   s>   d| }d|d  t | |t  t t|d | | S )Nr   r)   r   )r8   r]   r   r	   r`   r   r	  halfdimr*   r*   r/   _log_norm_factor  s    
z$vonmises_fisher_gen._log_norm_factorc                 C   s8   t |}| || t d||}| ||||  S )zLog of the von Mises-Fisher probability density function.

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

        zi,...i->...)r8   rO   r  r   r  )r`   rC   r   r  r	  Zdotproductsr*   r*   r/   r     s    
zvonmises_fisher_gen._logpdfc                 C   s"   |  ||\}}}| ||||S )a  Log of the von Mises-Fisher probability density function.

        Parameters
        ----------
        x : array_like
            Points at which to evaluate the log of the probability
            density function. The last axis of `x` must correspond
            to unit vectors of the same dimensionality as the distribution.
        mu : array_like, default: None
            Mean direction of the distribution. Must be a one-dimensional unit
            vector of norm 1.
        kappa : float, default: 1
            Concentration parameter. Must be positive.

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

        )r   r   r`   rC   r  r	  r   r*   r*   r/   r     s    zvonmises_fisher_gen.logpdfc                 C   s(   |  ||\}}}t| ||||S )a  Von Mises-Fisher probability density function.

        Parameters
        ----------
        x : array_like
            Points at which to evaluate the probability
            density function. The last axis of `x` must correspond
            to unit vectors of the same dimensionality as the distribution.
        mu : array_like
            Mean direction of the distribution. Must be a one-dimensional unit
            vector of norm 1.
        kappa : float
            Concentration parameter. Must be positive.

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

        )r   r8   r   r   r  r*   r*   r/   r     s    zvonmises_fisher_gen.pdfc                 C   sF   t |d |d }|j|||d}t jt |t |gdd}|S )z
        In 2D, the von Mises-Fisher distribution reduces to the
        von Mises distribution which can be efficiently sampled by numpy.
        This method is much faster than the general rejection
        sampling based algorithm.

        r   r   r   r1   rg   )r8   Zarctan2Zvonmisesstackcossin)r`   r  r	  r   r{   Z
mean_angleZangle_samplesr  r*   r*   r/   _rvs_2d  s    zvonmises_fisher_gen._rvs_2dc           	   	   C   s   |du rd}n|}| |}dt|d| td|   |  }tdt| }td||}tj|||d  ||d  gdd	}|du rt|}|S )
ah  
        Generate samples from a von Mises-Fisher distribution
        with mu = [1, 0, 0] and kappa. Samples then have to be
        rotated towards the desired mean direction mu.
        This method is much faster than the general rejection
        sampling based algorithm.
        Reference: https://www.mitsuba-renderer.org/~wenzel/files/vmf.pdf

        Nr   r   r   r)   rx  ).r   r1   rg   )	randomr8   r]   r   rX   r   r  r  r+   )	r`   r	  r   r{   Zsample_sizerC   tempZuniformcircler  r*   r*   r/   _rvs_3d  s    

(

zvonmises_fisher_gen._rvs_3dc                 C   s  |d }|dur,t |s |f}t|}nd}t d|d  |d  }d| | | }|dkr|d |d  |d	 d
 |d   }d| d|  }	||	 |t dt | dt |    }
d}t |f}d| }||k r|j|||| d}dd| |  dd| |   }|	|| }|| |t d| | ||  d|    |
 t |k}t 
|}|| |||| < ||7 }qt|||}t dt d|d  |}t j|d |gdd}|dur|||f }n
t |}|S )a$  
        Generate samples from a n-dimensional von Mises-Fisher distribution
        with mu = [1, 0, ..., 0] and kappa via rejection sampling.
        Samples then have to be rotated towards the desired mean direction mu.
        Reference: https://doi.org/10.1080/03610919408813161
        r   Nr  ry  r)   r   r   g      r  @   r  r   r   r   z...,...i->...irz  rg   )r8   r   r  r  rX   r]   log1pr   betar  r\   r  r   r   r   r+   )r`   r   r	  r   r{   Zdim_minus_oneZ	n_samplesrX   Zenvelop_paramnodeZ
correctionZ
n_acceptedrC   r  Zsym_betaZcoord_xZ
accept_tol	criterionZaccepted_iterZ
coord_restr  r*   r*   r/   _rejection_sampling  sl    





z'vonmises_fisher_gen._rejection_samplingc           	      C   s   t |f}d|d< t |dddf t |d |fg}t jt |\}}t t ||dddf dddf |rd}nd}t d||| }|S )a  A QR decomposition is used to find the rotation that maps the
        north pole (1, 0,...,0) to the vector mu. This rotation is then
        applied to all samples.

        Parameters
        ----------
        samples: array_like, shape = [..., n]
        mu : array-like, shape=[n, ]
            Point to parametrise the rotation.

        Returns
        -------
        samples : rotated samples

        r   r   Nr   r1   zij,...j->...i)	r8   r   r   rR   r  r   r
  r{  r   )	r`   r  r  r   Z
base_pointZembeddedZ	rotmatrixr   Zrotsignr*   r*   r/   _rotate_samplesA  s    (,z#vonmises_fisher_gen._rotate_samplesc                 C   s\   |dkr|  ||||}n(|dkr2| |||}n| ||||}|dkrX| |||}|S )Nr)   r  )r  r  r  r  )r`   r   r  r	  r   r{   r  r*   r*   r/   rB  ^  s    
zvonmises_fisher_gen._rvsc                 C   s2   |  ||\}}}| |}| |||||}|S )a(  Draw random samples from a von Mises-Fisher distribution.

        Parameters
        ----------
        mu : array_like
            Mean direction of the distribution. Must be a one-dimensional unit
            vector of norm 1.
        kappa : float
            Concentration parameter. Must be positive.
        size : int or tuple of ints, optional
            Given a shape of, for example, (m,n,k), m*n*k samples are
            generated, and packed in an m-by-n-by-k arrangement.
            Because each sample is N-dimensional, the output shape
            is (m,n,k,N). If no shape is specified, a single (N-D)
            sample is returned.
        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`.

        Returns
        -------
        rvs : ndarray
            Random variates of shape (`size`, `N`), where `N` is the
            dimension of the distribution.

        )r   r~   rB  )r`   r  r	  r   r{   r   r  r*   r*   r/   r   k  s    !
zvonmises_fisher_gen.rvsc                 C   s2   d| }|  || |t|| t|d |  S r   )r  r	   r  r*   r*   r/   r     s    zvonmises_fisher_gen._entropyc                 C   s   |  ||\}}}| ||S )a  Compute the differential entropy of the von Mises-Fisher
        distribution.

        Parameters
        ----------
        mu : array_like, default: None
            Mean direction of the distribution. Must be a one-dimensional unit
            vector of norm 1.
        kappa : float, default: 1
            Concentration parameter. Must be positive.

        Returns
        -------
        h : scalar
            Entropy of the von Mises-Fisher distribution.

        r  )r`   r  r	  r   r   r*   r*   r/   r     s    zvonmises_fisher_gen.entropyc           	         s   t |}|jdkrtdt t jj|ddds@d}t||jd }t|}|j	}|j
d|   fdd	}t|d
dd}|j}||fS )a  Fit the von Mises-Fisher distribution to data.

        Parameters
        ----------
        x : array-like
            Data the distribution is fitted to. Must be two dimensional.
            The second axis of `x` must be unit vectors of norm 1 and
            determine the dimensionality of the fitted
            von Mises-Fisher distribution.

        Returns
        -------
        mu : ndarray
            Estimated mean direction.
        kappa : float
            Estimated concentration parameter.

        r)   z'x' must be two dimensional.r1   rg   r   r  r   c                    s&   t   d g| }|d |d   S )Nr   r   )r	   )r	  Zbessel_valsr  r  r*   r/   solve_for_kappa  s    z0vonmises_fisher_gen.fit.<locals>.solve_for_kappaZbrentq)g:0yE>g    eA)r  Zbracket)r8   rO   r,   rU   r
  rR   r   r   r   Zmean_directionZmean_resultant_lengthr   root)	r`   rC   re   r   Zdirstatsr  r   Zroot_resr	  r*   r  r/   r     s"    


zvonmises_fisher_gen.fit)N)Nr   N)Nr   )Nr   )Nr   r   N)Nr   )ro   rp   rq   rr   rf   r   r   r  r  r   r   r   r  r  r  r  rB  r   r   r   r   r   r*   r*   ry   r/   r    s&    S
	

H
&
r  c                   @   s8   e Zd ZdddZdd Zdd Zdd	d
Zdd ZdS )r  Nr   c                 C   s(   t || _| j||\| _| _| _dS )a  Create a frozen von Mises-Fisher distribution.

        Parameters
        ----------
        mu : array_like, default: None
            Mean direction of the distribution.
        kappa : float, default: 1
            Concentration parameter. Must be positive.
        seed : {None, int, `numpy.random.Generator`,
                `numpy.random.RandomState`}, optional
            If `seed` is None (or `np.random`), the `numpy.random.RandomState`
            singleton is used.
            If `seed` is an int, a new ``RandomState`` instance is used,
            seeded with `seed`.
            If `seed` is already a ``Generator`` or ``RandomState`` instance
            then that instance is used.

        N)r  r   r   r   r  r	  r  r*   r*   r/   rf     s    
zvonmises_fisher_frozen.__init__c                 C   s   | j || j| j| jS )a  
        Parameters
        ----------
        x : array_like
            Points at which to evaluate the log of the probability
            density function. The last axis of `x` must correspond
            to unit vectors of the same dimensionality as the distribution.

        Returns
        -------
        logpdf : ndarray or scalar
            Log of probability density function evaluated at `x`.

        )r   r   r   r  r	  r   r*   r*   r/   r     s    zvonmises_fisher_frozen.logpdfc                 C   s   t | |S )a  
        Parameters
        ----------
        x : array_like
            Points at which to evaluate the log of the probability
            density function. The last axis of `x` must correspond
            to unit vectors of the same dimensionality as the distribution.

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

        r   r   r*   r*   r/   r   
  s    zvonmises_fisher_frozen.pdfc                 C   s&   | j |}| j | j| j| j||S )a?  Draw random variates from the Von Mises-Fisher distribution.

        Parameters
        ----------
        size : int or tuple of ints, optional
            Given a shape of, for example, (m,n,k), m*n*k samples are
            generated, and packed in an m-by-n-by-k arrangement.
            Because each sample is N-dimensional, the output shape
            is (m,n,k,N). If no shape is specified, a single (N-D)
            sample is returned.
        random_state : {None, int, `numpy.random.Generator`,
                        `numpy.random.RandomState`}, optional
            If `seed` is None (or `np.random`), the `numpy.random.RandomState`
            singleton is used.
            If `seed` is an int, a new ``RandomState`` instance is used,
            seeded with `seed`.
            If `seed` is already a ``Generator`` or ``RandomState`` instance
            then that instance is used.

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

        )r   r~   rB  r   r  r	  r   r*   r*   r/   r     s    zvonmises_fisher_frozen.rvsc                 C   s   | j | j| jS )z
        Calculate the differential entropy of the von Mises-Fisher
        distribution.

        Returns
        -------
        h: float
            Entropy of the Von Mises-Fisher distribution.

        )r   r   r   r	  rm   r*   r*   r/   r   :  s    zvonmises_fisher_frozen.entropy)Nr   N)r   N)ro   rp   rq   rf   r   r   r   r   r*   r*   r*   r/   r    s
   

r  )NN)rA   )N)N)r  numpyr8   Zscipy.linalgrQ   Z
scipy._libr   Zscipy.specialr   r   r   r   r   r   r	   r
   Zscipy._lib._utilr   r   Zscipy.linalg.blasr   r   Z_continuous_distnsr   Z_discrete_distnsr   r   r   r   r   Z_qmvntr   Z
_morestatsr   Zscipy.optimizer   __all__r]   r  r   r  Z_LOG_PIr   r0   r@   rK   rL   rt   r   r   r   Z_mvn_doc_frozen_callparamsZ_mvn_doc_frozen_callparams_noter   Zmvn_docdict_noparamsr   r   r   name__dict__r  Zmethod_frozenr   rr   r   r   Z_matnorm_doc_frozen_callparamsZ#_matnorm_doc_frozen_callparams_noter   Zmatnorm_docdict_noparamsr   r   r   r   Z _dirichlet_doc_frozen_callparamsZ%_dirichlet_doc_frozen_callparams_noter  Zdirichlet_docdict_noparamsr   r  r  r  r   r  Z_wishart_doc_default_callparamsZ_wishart_doc_callparams_noteZ_wishart_doc_frozen_callparamsZ#_wishart_doc_frozen_callparams_noter  Zwishart_docdict_noparamsr  r   r  rP  r   rQ  Z#_multinomial_doc_default_callparamsZ _multinomial_doc_callparams_noteZ"_multinomial_doc_frozen_callparamsZ'_multinomial_doc_frozen_callparams_noter[  Zmultinomial_docdict_noparamsrZ  r   r\  rq  r    rs  r  r!   r  r  r"   r  r  r#   r  r  r  Z_mvt_doc_frozen_callparams_noter  Zmvt_docdict_noparamsr  r  r$   Z_mhg_doc_default_callparamsZ_mhg_doc_callparams_noteZ_mhg_doc_frozen_callparamsZ_mhg_doc_frozen_callparams_noter  Zmhg_docdict_noparamsr  r%   r  r  r&   r  Z_ctab_doc_row_colZ_ctab_doc_xZ_ctab_doc_row_col_noteZ_ctab_doc_mean_paramsZ_ctab_doc_row_col_note_frozenZ_ctab_docdictr   Z_ctab_docdict_frozenupdater  r  r'   r  r  r  Z#_dirichlet_mn_doc_frozen_callparamsZ(_dirichlet_mn_doc_frozen_callparams_noter   Zdirichlet_mn_docdict_noparamsr  r  r   r  r  r(   r  r*   r*   r*   r/   <module>   sH  (

"
X"
    9g

	  e;


,  

    i:

   c>

  L0


 "x ],q   X7

	
   %


  b



 	
! \


    \