403Webshell
Server IP : 35.80.110.71  /  Your IP : 216.73.216.221
Web Server : Apache/2.4.58 (Ubuntu)
System : Linux ip-172-31-21-44 6.17.0-1019-aws #19~24.04.1-Ubuntu SMP Tue Jun 23 18:53:06 UTC 2026 x86_64
User : ubuntu ( 1000)
PHP Version : 8.3.31
Disable Function : NONE
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : OFF  |  Sudo : ON  |  Pkexec : OFF
Directory :  /lib/python3/dist-packages/scipy/stats/__pycache__/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /lib/python3/dist-packages/scipy/stats/__pycache__/_multivariate.cpython-312.pyc
�

x�f���D�ddlZddlZddlmZmZddlmZddlZddl	m
Z
ddlmZm
Z
mZmZmZmZmZmZddlmZddlmZddlmZdd	lmZd
dlmZd
dlmZm Z m!Z!d
d
l"m#Z#d
dl$m%Z%ddl&m'Z'gd�Z(ejRdejTz�Z+ejRd�Z,ejRejT�Z-dZ.d�Z/d�d�Z0d�d�Z1Gd�d�Z2Gd�d�Z3Gd�d�Z4dZ5dZ6dZ7dZ8e5e6e.d �Z9e7e8e.d �Z:Gd!�d"e3�Z;e;�Z<Gd#�d$e4�Z=d%D]dZ>e;j~e>Z@e=j~e>ZAe
j�e@j�e:�eA_Ce
j�e@j�e9�e@_C�fd&ZDd'ZEdZFdZGeDeEe.d(�ZHeFeGe.d(�ZIGd)�d*e3�ZJeJ�ZKGd+�d,e4�ZLd-D]dZ>eJj~e>Z@eLj~e>ZAe
j�e@j�eI�eA_Ce
j�e@j�eH�e@_C�fd.ZMdZNdZOeMe.d/�ZPeNe.d/�ZQd0�ZRd1�ZSd2�ZTGd3�d4e3�ZUeU�ZVGd5�d6e4�ZWd7D]dZ>eUj~e>Z@eWj~e>ZAe
j�e@j�eQ�eA_Ce
j�e@j�eP�e@_C�fd8ZXdZYdZZdZ[eXeYe.d9�Z\eZe[e.d9�Z]Gd:�d;e3�Z^e^�Z_Gd<�d=e4�Z`d>D]dZ>e^j~e>Z@e`j~e>ZAe
j�e@j�e]�eA_Ce
j�e@j�e\�e@_C�fd�d?�ZaGd@�dAe^�Zbeb�ZcGdB�dCe4�ZddDD]dZ>ebj~e>Z@e`j~e>ZAe
j�e@j�e]�eA_Ce
j�e@j�e\�e@_C�fdEZedFZfdZgdZheeefe.d9�Ziegehe.d9�ZjGdG�dHe3�Zkek�ZlGdI�dJe4�ZmdKD]dZ>ekj~e>Z@emj~e>ZAe
j�e@j�ej�eA_Ce
j�e@j�ei�e@_C�fGdL�dMe3�Znen�ZoGdN�dOe4�ZpGdP�dQe3�Zqeq�ZrGdR�dSe4�ZsGdT�dUe3�Ztet�ZuGdV�dWe4�ZvGdX�dYe3�Zwew�ZxGdZ�d[e4�Zyd\Zzd]Z{dZ|eze{e.d^�Z}de|e.d^�Z~Gd_�d`e3�ZGda�dbe4�Z�e�Z�dcD]dZ>ej~e>Z@e�j~e>ZAe
j�e@j�e~�eA_Ce
j�e@j�e}�e@_C�fddZ�deZ�dZ�dZ�e�e�e.d9�Z�e�e�e.d9�Z�Gdf�dge3�Z�e��Z�Gdh�die4�Z�djD]dZ>e�j~e>Z@e�j~e>ZAe
j�e@j�e��eA_Ce
j�e@j�e��e@_C�fGdk�dle3�Z�e��Z�Gdm�dne4�Z�doZ�dpZ�dqZ�dre���Z�dZ�e.e�e�e�e�ds�Z�e��j)�Z�e��j-dde�dt��d�du�Z�e�e�e��dvD]=Z>e�j~e>Z@e�j~e>ZAe�eAe�e@j��e�e@e���?Gdw�dxe3�Z�e��Z�Gdy�dze4�Z�d{�Z�d|Z�dZ�dZ�e�e.d}�Z�e�e.d}�Z�d�d~�Z�Gd�d�e3�Z�e��Z�Gd��d�e4�Z�d�D]dZ>e�j~e>Z@e�j~e>ZAe
j�e@j�e��eA_Ce
j�e@j�e��e@_C�fGd��d�e3�Z�e��Z�Gd��d�e4�Z�y)��N)�asarray_chkfinite�asarray)�NumpyVersion)�doccer)�gammaln�psi�multigammaln�xlogy�entr�betaln�ive�loggamma)�check_random_state)�drot)�LinAlgError)�get_lapack_funcs�)�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�N�|j�}|jdk(r|d}|S)z_
    Remove single-dimensional entries from array and convert to scalar,
    if necessary.
    r�)�squeeze�ndim��outs �;/usr/lib/python3/dist-packages/scipy/stats/_multivariate.py�_squeeze_outputr48s(��
�+�+�-�C�
�x�x�1�}��"�g���J�c���|�|}|dvrN|jjj�}ddd�}||tj|�j
z}|tjt|��z}|S)a�Determine which eigenvalues are "small" given the spectrum.

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

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

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

    )N����@�@g��.A)�f�d)�dtype�char�lower�np�finfo�eps�max�abs)�spectrum�cond�rcond�t�factorr@s      r3�_eigvalsh_to_epsrHCso��0
�����z���N�N���%�%�'����%���a�y�2�8�8�A�;�?�?�*��
�����H�
�&�
&�C��Jr5c��tj|D�cgc]}t|�|krdnd|z��c}t��Scc}w)a�A helper function for computing the pseudoinverse.

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

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

    rr�r;)r>�arrayrB�float)�vr@�xs   r3�_pinv_1drOes6�� �8�8�!�<�Q�#�a�&�C�-�Q�Q�q�S�0�<�E�J�J��<s�=c�2�eZdZdZ		dd�Zd�Zed��Zy)�_PSDaN
    Compute coordinated functions of a symmetric positive semidefinite matrix.

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

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

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

    Nc��tj|�|_tjj|||��\}}t
|||�}	tj|�|	kr
d}
t|
��|||	kD}t|�t|�kr#|s!d}
tjj|
��t||	�}tj|tj|��}
d|	z|_|dd�||	kf|_t|�|_|
|_tj$tj&|��|_d|_y)N)r=�check_finitez9The input matrix must be symmetric positive semidefinite.zUWhen `allow_singular is False`, the input matrix must be symmetric positive definite.r8)r>r�_M�scipy�linalg�eighrH�min�
ValueError�lenrrO�multiply�sqrtr@�V�rank�U�sum�log�log_pdet�_pinv)�self�MrDrEr=rS�allow_singular�s�ur@�msgr:�s_pinvr_s              r3�__init__z
_PSD.__init__�s���*�*�Q�-���
�|�|� � ��%�l� �K���1��q�$��.��
�6�6�!�9��t��M�C��S�/�!�
�a�#�g�J���q�6�C��F�?�>�2�C��)�)�'�'��,�,��!�S�!���K�K��2�7�7�6�?�+���s�7����1�a�3�h�;������F��	�������r�v�v�a�y�)��
���
r5c��tjj||jzd��}||jk}|S)zJ
        Check whether x lies in the support of the distribution.
        r7��axis)r>rV�normr]r@)rdrN�residual�
in_supports    r3�
_support_maskz_PSD._support_mask�s6���9�9�>�>�!�d�f�f�*�2�>�6������(�
��r5c��|j�9tj|j|jj�|_|jS�N)rcr>�dotr_�T�rds r3�pinvz	_PSD.pinv�s4���:�:�������������1�D�J��z�z�r5)NNTTT)�__name__�
__module__�__qualname__�__doc__rkrr�propertyrxr.r5r3rQrQxs/��%�N8<�37��B����r5rQc�^��eZdZdZd�fd�	Zed��Zejd��Zd�Z�xZ	S)�multi_rv_genericzc
    Class which encapsulates common functionality between all multivariate
    distributions.
    c�B��t�|��t|�|_yrt)�superrkr�
_random_state�rd�seed�	__class__s  �r3rkzmulti_rv_generic.__init__�s���
����/��5��r5c��|jS)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.

        )r�rws r3�random_statezmulti_rv_generic.random_state�s���!�!�!r5c�$�t|�|_yrt�rr��rdr�s  r3r�zmulti_rv_generic.random_state�s��/��5��r5c�4�|�t|�S|jSrtr��rdr�s  r3�_get_random_statez"multi_rv_generic._get_random_state�s���#�%�l�3�3��%�%�%r5rt)
ryrzr{r|rkr}r��setterr��
__classcell__�r�s@r3rr�s@����6��"��"����6��6�&r5rc�D�eZdZdZed��Zejd��Zy)�multi_rv_frozenzj
    Class which encapsulates common functionality between all frozen
    multivariate distributions.
    c�.�|jjSrt)�_distr�rws r3r�zmulti_rv_frozen.random_state�s���z�z�'�'�'r5c�8�t|�|j_yrt)rr�r�r�s  r3r�zmulti_rv_frozen.random_state�s��#5�d�#;��
�
� r5N)ryrzr{r|r}r�r�r.r5r3r�r��s5����(��(����<��<r5r�aVmean : 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.
a5Setting 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���eZdZdZd�fd�	Zdd�Zdd�Zd�Zd�Zd�Z	d	�Z
dd
�Zdd�Zd�Z
		ddd
�d�Z		ddd
�d�Zdd�Zdd�Z�xZS)�multivariate_normal_genaA 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)  # noqa
        Cumulative distribution function.
    logcdf(x, mean=None, cov=1, allow_singular=False, maxpts=1000000*dim, abseps=1e-5, releps=1e-5)
        Log of the cumulative distribution function.
    rvs(mean=None, cov=1, size=1, random_state=None)
        Draw random samples from a multivariate normal distribution.
    entropy()
        Compute the differential entropy of the multivariate normal.

    Parameters
    ----------
    %(_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�v��t�|�|�tj|jt
�|_yrt)r�rkr�	docformatr|�mvn_docdict_paramsr�s  �r3rkz multivariate_normal_gen.__init__��)���
������'�'����6H�I��r5c� �t||||��S)zzCreate a frozen multivariate normal distribution.

        See `multivariate_normal_frozen` for more information.
        )rfr�)�multivariate_normal_frozen)rd�mean�covrfr�s     r3�__call__z multivariate_normal_gen.__call__�s��
*�$��9G�/3�5�	5r5c���t|tj�r|j||�S|j	d||�\}}}t||��}tj|�}|||fS)z�
        Infer dimensionality from mean or covariance matrix, ensure that
        mean and covariance are full vector resp. matrix.
        N�rf)�
isinstancer�
Covariance�_process_parameters_Covariance�_process_parameters_psdrQ�	CovViaPSD)rdr�r�rf�dim�psd�
cov_objects       r3�_process_parametersz+multivariate_normal_gen._process_parameters�sn��
�c�;�1�1�2��6�6�t�S�A�A�"�9�9�$��c�J�N�C��s��s�>�:�C�$�.�.�s�3�J���j�(�(r5c���|jd}|�tjdg�n|}d|�d|f��}	tj||�}|||fS#t$r}t	|�|�d}~wwxYw)Nr7�z(`cov` represents a covariance matrix in z9 dimensions,and so `mean` must be broadcastable to shape )�shaper>rK�broadcast_torY)rdr�r�r��message�es      r3r�z6multivariate_normal_gen._process_parameters_Covariance�s����i�i��m��!%��r�x�x���~�4��=�c�U�CC�DG�6�(�L��	-��?�?�4��-�D��D�#�~����	-��W�%�1�,��	-�s�A�	A)�A$�$A)c�n�|�l|�B|�d}n�tj|t��}|jdkrd}nX|jd}nHtj|t��}|j
}n tj|�std��|�tj|�}tj|t��}|�d}tj|t��}|dk(r#|jd�}|jdd�}|jdk7s|jd|k7rtd|z��|jdk(r|tj|�z}n�|jdk(rtj|�}n�|jdk(rx|j||fk7rg|j\}}||k7r#dt|j�z}t|��d	}|t|j�t|�fz}t|��|jdkDrtd
|jz��|||fS)NrrJr,rz.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)r>rrLr0r��size�isscalarrY�zeros�reshape�eye�diag�strrZ)rdr�r�r��rows�colsris       r3r�z/multivariate_normal_gen._process_parameters_psd�s����;��|��;��C��*�*�S��6�C��x�x�!�|���!�i�i��l���z�z�$�e�4���i�i���;�;�s�#� �"-�.�.�
�<��8�8�C�=�D��z�z�$�e�,���;��C��j�j��E�*���!�8��<�<��?�D��+�+�a��#�C��9�9��>�T�Z�Z��]�c�1��J� �!�"�
"��8�8�q�=�����s��#�C�
�X�X��]��'�'�#�,�C�
�X�X��]�s�y�y�S�#�J�6����J�D�$��t�|�.�03�C�I�I��?���S�/�!�?���S����^�S��Y�7�7���S�/�!�
�X�X��\��2�47�H�H�=�>�
>��D�#�~�r5c��tj|t��}|jdk(r|tj}|S|jdk(r5|dk(r|dd�tjf}|S|tjdd�f}|S��l
        Adjust quantiles array so that last axis labels the components of
        each data point.
        rJrrN�r>rrLr0�newaxis�rdrNr�s   r3�_process_quantilesz*multivariate_normal_gen._process_quantiles�sy��

�J�J�q��&���6�6�Q�;��"�*�*�
�A���
�V�V�q�[��a�x��a����m�$�����b�j�j�!�m�$���r5c�D�|j|j}}||z
}|jdkDr*|dtjf}|dtjf}tj
tj|j|��d��}d|tz|z|zzS)aLog 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.r7rm��)	rbr^r0r>r�r`�square�whiten�_LOG_2PI)rdrNr�r��log_det_covr^�dev�mahas        r3�_logpdfzmultivariate_normal_gen._logpdf�s���&'�/�/����T���$�h���8�8�a�<�%�c�2�:�:�o�6�K���R�Z�Z��(�D��v�v�b�i�i�
� 1� 1�#� 6�7�b�A���t�h���4�t�;�<�<r5c�*�|j|||�}|\}}}|j||�}|j|||�}tj|j
|k�r)|j
||z
�}	tj||	<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�r>�anyr^rr�infr4�
rdrNr�r�rf�paramsr�r�r2�
out_of_boundss
          r3�logpdfzmultivariate_normal_gen.logpdfs���&�)�)�$��^�D�� &���T�:��#�#�A�s�+���l�l�1�d�J�/��
�6�6�*�/�/�C�'�(�'�5�5�a��f�=�=�M�"$�&�&��C�
���s�#�#r5c�2�|j|||�}|\}}}|j||�}tj|j	|||��}tj
|j|k�r|j||z
�}	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�r>�expr�r�r^rrr4r�s
          r3�pdfzmultivariate_normal_gen.pdf6s���&�)�)�$��^�D�� &���T�:��#�#�A�s�+���f�f�T�\�\�!�T�:�6�7��
�6�6�*�/�/�C�'�(�'�5�5�a��f�=�=�M�!$�C�
���s�#�#r5c���������|�/tj�jtj�n|}tj||�\}	}
|	|
k}d|jd��z}|
j
�|	j
�}	}
|	||
|c|
|<|	|<|jd�tj|
|	fd��}
������fd�}tj|d|
�|z}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

        r7rmc	�L��tj|d�|�d������dS�Nr)r�mvnun)�limits�absepsr��maxptsr��n�relepss ������r3�func1dz,multivariate_normal_gen._cdf.<locals>.func1ds7����:�:�f�R�a�j�&���*�d�C�$�f�f�6�67�9�
9r5)
r>�fullr�r��broadcast_arraysr`�copy�concatenate�apply_along_axisr4)rdrNr�r�r�r�r��lower_limitr=�b�a�i_swap�signsr�r�r2r�s  `````         @r3�_cdfzmultivariate_normal_gen._cdfRs����> �'�������b�f�f�W�-�-8�	��"�"�1�e�,���1��Q����v�z�z�r�z�*�+���v�v�x�����1�� ��y�!�F�)���&�	�1�V�9�
�G�G�B�K������A��R�0��	9�	9��!�!�&�"�f�5��=���s�#�#r5�r�c	��|j|||�}	|	\}
}}|j}|j||
�}|sd|
z}|j|||||||�}t	j
|dk�r|dzn|}t	j|�}
|
S)a�Log of the multivariate normal cumulative distribution function.

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

        �@Br�)r��
covariancer�r�r>r�ra)rdrNr�r�rfr�r�r�r�r�r�r��cdfr2s              r3�logcdfzmultivariate_normal_gen.logcdf�s���@�)�)�$��^�D�� &���T�:��#�#���#�#�A�s�+����s�]�F��i�i��4��f�f�f�k�J���&�&��q��/�c�B�h�s���f�f�S�k���
r5c	��|j|||�}	|	\}
}}|j}|j||
�}|sd|
z}|j|||||||�}|S)a�Multivariate normal cumulative distribution function.

        Parameters
        ----------
        x : array_like
            Quantiles, with the last axis of `x` denoting the components.
        %(_mvn_doc_default_callparams)s
        maxpts : integer, optional
            The maximum number of points to use for integration
            (default `1000000*dim`)
        abseps : float, optional
            Absolute error tolerance (default 1e-5)
        releps : float, optional
            Relative error tolerance (default 1e-5)
        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�)
rdrNr�r�rfr�r�r�r�r�r�r�r2s
             r3r�zmultivariate_normal_gen.cdf�sm��@�)�)�$��^�D�� &���T�:��#�#���#�#�A�s�+����s�]�F��i�i��4��f�f�f�k�J���
r5c��|j||�\}}}|j|�}t|tj�r,|j
}|j
|||�}t|�}|S|xs
t�}tj|�s|f}t|�|jdfz}|j|��}	||j|	�z}|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

        r7�r�)r�r�r�rr�r�rr4�tupler>�iterabler��normal�colorize)
rdr�r�r�r�r�r�r2r�rNs
          r3�rvszmultivariate_normal_gen.rvs�s���*!%� 8� 8��s� C���T�:��-�-�l�;���j�+�"7�"7�8��'�'�C��2�2�4��d�C�C�!�#�&�C��
�
�?�5�7�D��;�;�t�$��w���$�K�:�#3�#3�B�#7�"9�9�E��#�#��#�/�A���,�,�Q�/�/�C��
r5c�z�|j||�\}}}d|jtdzz|jzzS)aGCompute 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�r^r�rb)rdr�r�r�r�s     r3�entropyzmultivariate_normal_gen.entropys@��"!%� 8� 8��s� C���T�:��j�o�o��A��6��9L�9L�L�M�Mr5rt)NrFN�T)NrF)NrFN��h㈵��>r�NrrN�Nr)ryrzr{r|rkr�r�r�r�r�r�r�r�r�r�r�rrr�r�s@r3r�r�$s{���^�@J�5�)�0	�7�r�"=�6$�8$�82$�hHL�#'�+�8<�+�ZEI� $�'�59�'�R#�JNr5r�c�Z�eZdZ		dd�Zed��Zd�Zd�Zdd�d�Zdd�d�Z	dd	�Z
d
�Zy)
r�Nc��t|�|_|jj|||�\|_|_|_|xs|j
j|_|sd|jz}||_||_	||_
y)afCreate 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��_allow_singularrfr�r�r�)rdr�r�rfr�r�r�r�s        r3rkz#multivariate_normal_frozen.__init__su��V-�T�2��
��J�J�*�*�4��n�E�	-���$�)�T�_�,�O����0O�0O�����t�x�x�'�F���������r5c�.�|jjSrt)r�r�rws r3r�zmultivariate_normal_frozen.covOs�����)�)�)r5c��|jj||j�}|jj||j|j
�}t
j|j
j|jk�r=|j
j||jz
�}tj||<t|�Srt)r�r�r�r�r�r�r>r�r^rrr�r4)rdrNr2r�s    r3r�z!multivariate_normal_frozen.logpdfSs����J�J�)�)�!�T�X�X�6���j�j� � ��D�I�I�t���?��
�6�6�$�/�/�&�&����1�2�!�_�_�:�:�1�T�Y�Y�;�G�G�M�"$�&�&��C�
���s�#�#r5c�J�tj|j|��Srt�r>r�r��rdrNs  r3r�zmultivariate_normal_frozen.pdf[����v�v�d�k�k�!�n�%�%r5r�c��|j||��}tj|dk�r|dzn|}tj|�}|S)Nr�rr�)r�r>r�ra)rdrNr�r�r2s     r3r�z!multivariate_normal_frozen.logcdf^sA���h�h�q�k�h�2���&�&��q��/�c�B�h�s���f�f�S�k���
r5c	��|jj||j�}|jj||j|j
j|j|j|j|�}t|�Srt)r�r�r�r�r�r�r�r�r�r�r4)rdrNr�r2s    r3r�zmultivariate_normal_frozen.cdffse���J�J�)�)�!�T�X�X�6���j�j�o�o�a����D�O�O�,F�,F�"�k�k�4�;�;����)�+���s�#�#r5c�f�|jj|j|j||�Srt)r�rr�r��rdr�r�s   r3rzmultivariate_normal_frozen.rvsms#���z�z�~�~�d�i�i����$��M�Mr5c�~�|jj}|jj}d|tdzz|zzS)z�Computes the differential entropy of the multivariate normal.

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

        rr)r�rbr^r�)rdrbr^s   r3rz"multivariate_normal_frozen.entropyps;���?�?�+�+�����#�#���d�h��l�+�h�6�7�7r5)NrFNNrr�rN)ryrzr{rkr}r�r�r�r�r�rrr.r5r3r�r�sK��DH�26�3�j�*��*�$�&�(,��%)�$�N�8r5r�)r�r�r�r�ramean : 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�d��eZdZdZd�fd�	Zd
d�Zd�Zd�Zd�Zdd�Z	dd�Z
dd	�Zdd
�Zd�Z
�xZS)�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.

    c�v��t�|�|�tj|jt
�|_yrt)r�rkrr�r|�matnorm_docdict_paramsr�s  �r3rkzmatrix_normal_gen.__init__�)���
������'�'����6L�M��r5c� �t||||��S)zoCreate a frozen matrix normal distribution.

        See `matrix_normal_frozen` for more information.

        �r�)�matrix_normal_frozen�rdr��rowcov�colcovr�s     r3r�zmatrix_normal_gen.__call__s��$�D�&�&�t�D�Dr5c��|�ctj|t��}|j}t	|�dk7rtd��tj|dk(�rtd��tj|t��}|jdk(r7|�|tjd�z}n=|tjd�z}n$|jdk(rtj|�}|j}t	|�dk7rtd��|d|dk7rtd��|ddk(rtd	��|d}tj|t��}|jdk(r7|�|tjd�z}n=|tjd�z}n$|jdk(rtj|�}|j}t	|�dk7rtd
��|d|dk7rtd��|ddk(rtd��|d}|�&d|k7rtd
��|d|k7r"td��tj||f�}||f}	|	|||fS)z
        Infer dimensionality from mean or covariance matrices. Handle
        defaults. Ensure compatible dimensions.
        rJr,z%Array `mean` must be two dimensional.rzArray `mean` has invalid shape.rz(`rowcov` must be a scalar or a 2D array.zArray `rowcov` must be square.z!Array `rowcov` has invalid shape.z(`colcov` must be a scalar or a 2D array.zArray `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.)r>rrLr�rZrYr�r0�identityr�r�)
rdr�r"r#�	meanshape�rowshape�numrows�colshape�numcols�dimss
          r3r�z%matrix_normal_gen._process_parameterssQ�����:�:�d�%�0�D��
�
�I��9�~��"� �!H�I�I��v�v�i�1�n�%� �!B�C�C����F�%�0���;�;�!�����"�+�+�i��l�";�;���"�+�+�a�.�0��
�[�[�A�
��W�W�V�_�F��<�<���x�=�A���G�H�H��A�;�(�1�+�%��=�>�>��A�;�!���@�A�A��1�+�����F�%�0���;�;�!�����"�+�+�i��l�";�;���"�+�+�a�.�0��
�[�[�A�
��W�W�V�_�F��<�<���x�=�A���G�H�H��A�;�(�1�+�%��=�>�>��A�;�!���@�A�A��1�+������|�w�&� �"8�9�9���|�w�&� �";�<�<��8�8�W�g�.�/�D���!���T�6�6�)�)r5c���tj|t��}|jdk(r|tjdd�f}|j
dd|k7rt
d��|S)zp
        Adjust quantiles array so that last two axes labels the components of
        each data point.
        rJr,N���zJThe shape of array `X` is not compatible with the distribution parameters.)r>rrLr0r�r�rY)rd�Xr+s   r3r�z$matrix_normal_gen._process_quantilesas]��

�J�J�q��&���6�6�Q�;��"�*�*�a�-� �A��7�7�2�3�<�4���A�B�
B��r5c�d�|\}}	tj||z
dd�}
tj|jtj|
|�d�}tj
tj
tj|�d��d��}d||	ztz|	|zz||zz|zzS)aLog 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.

        r7rrrmr�)r>�moveaxis�	tensordotrvrur`r�r�)
rdr+r.r��row_prec_rt�log_det_rowcov�col_prec_rt�log_det_colcovr(r*�roll_dev�	scale_devr�s
             r3r�zmatrix_normal_gen._logpdfns���< �����;�;�q��v�r�1�-���L�L����!#����+�!>��C�	��v�v�b�f�f�R�Y�Y�y�1��;�!�D���w�w��x�/�'�.�2H�H� ��/�0�26�7�8�	8r5c	��|j|||�\}}}}|j||�}t|d��}t|d��}|j||||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�rQr�r_rbr4)	rdr.r�r"r#r+�rowpsd�colpsdr2s	         r3r�zmatrix_normal_gen.logpdf�s���&&*�%=�%=�d�F�>D�&F�"��d�F�F��#�#�A�t�,���f�U�3���f�U�3���l�l�4��D�&�(�(�F�O�O�V�X�X�!�?�?�,���s�#�#r5c�P�tj|j||||��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)rdr.r�r"r#s     r3r�zmatrix_normal_gen.pdf�s"��&�v�v�d�k�k�!�T�6�6�:�;�;r5c���t|�}|j|||�\}}}}tjj	|d��}tjj	|d��}|j|�}|j
|d||df��jddd�}	|tjd||	|d��z}
|dk(r|
j|j�}
|
S)	aDraw 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�r=rrr�r,zjp,ipq,kq->ijk)�optimize)�intr�rUrV�choleskyr��standard_normal�	transposer>�einsumr�r�)rdr�r"r#r�r�r+�rowchol�colchol�std_normr2s           r3rzmatrix_normal_gen.rvs�s���*�4�y��%)�%=�%=�d�F�>D�&F�"��d�F�F��,�,�'�'��d�'�;���,�,�'�'��d�'�;���-�-�l�;��
 �/�/��q�'�4��a��)�0�
�
�)�A�q�!�
�	��R�Y�Y�/�&��'�(,�.�.���1�9��+�+�d�j�j�)�C��
r5c��tj|jd|jdf�}|j|||�\}}}}t	|d��}t	|d��}|j||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

        rFr�)r>r�r�r�rQ�_entropyrb)rdr"r#�
dummy_meanr+�_r9r:s        r3rzmatrix_normal_gen.entropy�s~��(�X�X�v�|�|�A�����Q��@�A�
�"&�":�":�:�;A�;A�#C���a����f�U�3���f�U�3���}�}�T�6�?�?�F�O�O�D�Dr5c�T�|\}}d|z|zdtzzd|z|zzd|z|zzS�Nrr)r�)rdr+�row_cov_logdet�col_cov_logdetr��ps      r3rHzmatrix_normal_gen._entropysC�����1��a��!��q�8�|�,�s�Q�w��/G�G��a��.�(�)�	*r5rtr�Nrr�NrrrN�rr)ryrzr{r|rkr�r�r�r�r�r�rrrHr�r�s@r3rr�sC���b�HN�E�@*�D�$8�L$�8<�*'�RE�:*r5rc�2�eZdZdZdd�Zd�Zd�Zd	d�Zd�Zy)
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
    Nc��t|�|_|jj|||�\|_|_|_|_t|j
d��|_t|jd��|_	y)NFr�)
rr�r�r+r�r"r#rQr9r:r!s     r3rkzmatrix_normal_frozen.__init__3s]��&�t�,��
��J�J�*�*�4���@�	7��	�4�9�d�k�4�;��4�;�;�u�=����4�;�;�u�=��r5c	�n�|jj||j�}|jj|j||j|j
j|j
j|jj|jj�}t|�Srt)
r�r�r+r�r�r9r_rbr:r4)rdr.r2s   r3r�zmatrix_normal_frozen.logpdf:sy���J�J�)�)�!�T�Y�Y�7���j�j� � ����A�t�y�y�$�+�+�-�-�!%���!5�!5�t�{�{�}�}�!%���!5�!5�7���s�#�#r5c�J�tj|j|��Srtr)rdr.s  r3r�zmatrix_normal_frozen.pdfArr5c�|�|jj|j|j|j||�Srt)r�rr�r"r#rs   r3rzmatrix_normal_frozen.rvsDs.���z�z�~�~�d�i�i����d�k�k�4�*�,�	,r5c��|jj|j|jj|j
j�Srt)r�rHr+r9rbr:rws r3rzmatrix_normal_frozen.entropyHs8���z�z�"�"�4�9�9�d�k�k�.B�.B�#'�;�;�#7�#7�9�	9r5rr)	ryrzr{r|rkr�r�rrr.r5r3r r s ���<>�$�&�,�9r5r )r�r�rrz�alpha : array_like
    The concentration parameters. The number of entries determines the
    dimensionality of the distribution.
)�!_dirichlet_doc_default_callparamsr�c���tj|�}tj|�dkrtd��|jdk7r$tdj|j���|S)Nrz%All parameters must be greater than 0rz?Parameter vector 'a' must be one dimensional, but a.shape = {}.)r>rrXrYr0�formatr���alphas r3�_dirichlet_check_parametersr^ks^���J�J�u��E�	�v�v�e�}����@�A�A�	���q���-�-3�V�E�K�K�-@�B�	B��Lr5c���tj|�}|jddz|jdk7rN|jd|jdk7r/tdj	|j|j���|jd|jdk7r�tj
dtj|d�z
g�}|jdk(rtj||�}n2|jdk(rtj||f�}ntd��tj|�dkrtd��tj|�dkDrtd��|dk(}|dk}|j|jk7r>tj||jdd�	�j|j�}tj||�}tj|�rtd
��tjtj|d�dz
�dkDj!�r"td
tj|d�z��|S)Nrrz�Vector 'x' must have either the same number of entries as, or one entry fewer than, parameter vector 'a', but alpha.shape = {} and x.shape = {}.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.r7rmzJEach 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.)r>rr�rYr[rKr`r0�append�vstackrXrA�repeatr��logical_andrBr�)r]rN�xk�xeq0�alphalt1�chks      r3�_dirichlet_check_inputrhus��
�
�
�1�
�A��w�w�q�z�A�~����Q��'�A�G�G�A�J�%�+�+�a�.�,H��-�.4�V�E�K�K����-I�K�	K�
	�w�w�q�z�U�[�[��^�#�
�X�X�q�2�6�6�!�Q�<�'�(�
)��
�7�7�a�<��	�	�!�R� �A�
�W�W��\��	�	�1�b�'�"�A��J�K�
K�
�v�v�a�y�1�}��$�%�	%�
�v�v�a�y�1�}��J�K�K�
��F�D���	�H��w�w�%�+�+���9�9�X�q�w�w�r�{��<�D�D�Q�W�W�M��
�.�.��x�
(�C�	�v�v�c�{��3�4�	4�	���r�v�v�a��|�c�!�"�V�+�0�0�2��;�=?�V�V�A�q�\�J�K�	K�
�Hr5c�|�tjt|��ttj|��z
S)avInternal 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

    )r>r`rr\s r3�_lnBrj�s)��$�6�6�'�%�.�!�G�B�F�F�5�M�$:�:�:r5c�X��eZdZdZd�fd�	Zdd�Zd�Zd�Zd�Zd�Z	d�Z
d	�Zdd
�Z�xZ
S)
�
dirichlet_genan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
    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.

    c�v��t�|�|�tj|jt
�|_yrt)r�rkrr�r|�dirichlet_docdict_paramsr�s  �r3rkzdirichlet_gen.__init__ s)���
������'�'����6N�O��r5c��t||��S�Nr)�dirichlet_frozen�rdr]r�s   r3r�zdirichlet_gen.__call__$s����D�1�1r5c��t|�}|tjt|dz
|j�jd�zS)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.

        rr)rjr>r`r
rv)rdrNr]�lnBs    r3r�zdirichlet_gen._logpdf's:�� �5�k���u�r�v�v�u�U�Q�Y����4�7�7��;�;�;r5c�j�t|�}t||�}|j||�}t|�S)ayLog 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^rhr�r4�rdrNr]r2s    r3r�zdirichlet_gen.logpdf:s5��,�E�2��"�5�!�,���l�l�1�e�$���s�#�#r5c��t|�}t||�}tj|j	||��}t|�S)akThe 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^rhr>r�r�r4rvs    r3r�zdirichlet_gen.pdfOs>��,�E�2��"�5�!�,���f�f�T�\�\�!�U�+�,���s�#�#r5c�^�t|�}|tj|�z}t|�S)z�Mean of the Dirichlet distribution.

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

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

        �r^r>r`r4)rdr]r2s   r3r�zdirichlet_gen.meands+��,�E�2���r�v�v�e�}�%���s�#�#r5c��t|�}tj|�}|||z
z||z|dzzz}t|�S)z�Variance of the Dirichlet distribution.

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

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

        rry)rdr]�alpha0r2s    r3�varzdirichlet_gen.varvsF��,�E�2������������'�V�f�_��!��,L�M���s�#�#r5c�N�t|�}tj|�}t|�}|jd}|||z
t
jj|�zztj|dz
t
jj|�z�z
}t|�S)a
        Differential entropy of the Dirichlet distribution.

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

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

        rr)	r^r>r`rjr�rU�specialrr4)rdr]r{rt�Kr2s      r3rzdirichlet_gen.entropy�s���,�E�2���������5�k���K�K��N���V�a�Z�5�=�=�#4�#4�V�#<�<�<�r�v�v�
�Q�Y�%�-�-�+�+�E�2�2�@4�4���s�#�#r5c�`�t|�}|j|�}|j||��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)rdr]r�r�s    r3rzdirichlet_gen.rvs�s4��$,�E�2���-�-�l�;���%�%�e�$�%�7�7r5rtr)ryrzr{r|rkr�r�r�r�r�r|rrr�r�s@r3rlrl�s8���g�RP�2�<�&$�*$�*$�$$�($�28r5rlc�:�eZdZd	d�Zd�Zd�Zd�Zd�Zd�Zd
d�Z	y)rqNc�D�t|�|_t|�|_yrt)r^r]rlr�rrs   r3rkzdirichlet_frozen.__init__�s��0��7��
�"�4�(��
r5c�N�|jj||j�Srt)r�r�r]rs  r3r�zdirichlet_frozen.logpdf�s���z�z� � ��D�J�J�/�/r5c�N�|jj||j�Srt)r�r�r]rs  r3r�zdirichlet_frozen.pdf�s���z�z�~�~�a����,�,r5c�L�|jj|j�Srt)r�r�r]rws r3r�zdirichlet_frozen.mean�s���z�z���t�z�z�*�*r5c�L�|jj|j�Srt)r�r|r]rws r3r|zdirichlet_frozen.var�s���z�z�~�~�d�j�j�)�)r5c�L�|jj|j�Srt)r�rr]rws r3rzdirichlet_frozen.entropy�s���z�z�!�!�$�*�*�-�-r5c�P�|jj|j||�Srt)r�rr]rs   r3rzdirichlet_frozen.rvs�s���z�z�~�~�d�j�j�$��=�=r5rtr)
ryrzr{rkr�r�r�r|rrr.r5r3rqrq�s%��)�0�-�+�*�.�>r5rq)r�r�rr�r|rz�df : 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
)�_doc_default_callparams�_doc_callparams_noter�c���eZdZdZd�fd�	Zdd�Zd�Zd�Zd�Zd�Z	d�Z
d	�Zd
�Zd�Z
d�Zd
�Zd�Zd�Zd�Zd�Zdd�Zd�Zd�Zd�Z�xZS)�wishart_genaqA 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.

    c�v��t�|�|�tj|jt
�|_yrt�r�rkrr�r|�wishart_docdict_paramsr�s  �r3rkzwishart_gen.__init__krr5c��t|||�S)zbCreate a frozen Wishart distribution.

        See `wishart_frozen` for more information.
        )�wishart_frozen�rd�df�scaler�s    r3r�zwishart_gen.__call__os��
�b�%��.�.r5c�t�|�d}tj|t��}|jdk(r$|tjtjf}n�|jdk(rtj
|�}nv|jdk(r@|jd|jdk(s!tdt|j�z��|jdkDrtd|jz��|jd}|�|}n3tj|�std��||dz
krtd	��|||fS)
Nr�rJrrr,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.)
r>rrLr0r�r�r�rYr�r�)rdr�r�r�s    r3r�zwishart_gen._process_parametersvs(���=��E��
�
�5��.���:�:��?��"�*�*�b�j�j�0�1�E�
�Z�Z�1�_��G�G�E�N�E�
�Z�Z�1�_�U�[�[��^�u�{�{�1�~�%E��C�"�5�;�;�/�0�1�
1��Z�Z�!�^��4�6;�j�j�A�B�
B��k�k�!�n��
�:��B����R���C�D�D�
�3��7�]��B�C�
C��B��~�r5c���tj|t��}|jdk(r0|tj|�dd�dd�tj
fz}|jdk(r[|dk(r(|tj
tj
dd�f}�ntj|�dd�dd�tj
f}n�|jdk(r[|jd|jdk(s!tdt|j�z��|dd�dd�tj
f}nv|jdk(r@|jd|jdk(sHtdt|j�z��|jdkDrtd	|jz��|jdd||fk(s*td
j||f|jdd���|S)r�rJrNrr,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 = %dz=Quantiles have incompatible dimensions: should be {}, got {}.)r>rrLr0r�r�r�r�rYr�r[r�s   r3r�zwishart_gen._process_quantiles�s���

�J�J�q��&���6�6�Q�;��B�F�F�3�K��1�b�j�j� 0�1�1�A��6�6�Q�;��a�x��b�j�j�"�*�*�a�/�0���G�G�A�J�q�!�R�Z�Z�/�0��
�V�V�q�[��7�7�1�:������+� �"C�#&�q�w�w�<�"0�1�1��!�Q��
�
�"�#�A�
�V�V�q�[��7�7�1�:������+� �"7�9<�Q�W�W��"F�G�G��V�V�a�Z��;�=>�V�V�D�E�
E�
�w�w�q��|��S�z�)��/�/5�v�s�C�j�!�'�'�!�A�,�/O�Q�
Q��r5c��tj|�}|jdk(r|tj}n/|jdkDr t	dtt
|��z��|j�}t
|�}||fS)Nrrz_Size must be an integer or tuple of integers; thus must have dimension <= 1. Got size.ndim = %s)r>rr0r�rYr�r��prod)rdr�r�r�s    r3�
_process_sizezwishart_gen._process_size�sy���z�z�$����9�9��>���
�
�#�D�
�Y�Y��]��3�58��t��5E�F�G�
G�
�I�I�K���d����%�x�r5c�h�tj|jd�}tj|j�}tj|jd�}	t|jd�D]v}
|j	|dd�dd�|
f�\}||
<t
jj|df|dd�dd�|
f�|dd�dd�|
f<|dd�dd�|
fj�|	|
<�xd||z
dz
z|zd|	zz
d|z|ztzd|z|zztd|z|�zz
}|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.

        r7NTrr)r>�emptyr��range�_cholesky_logdetrUrV�	cho_solve�trace�_LOG_2r	)
rdrNr�r�r��
log_det_scale�C�	log_det_x�scale_inv_x�tr_scale_inv_x�irJr2s
             r3r�zwishart_gen._logpdf�s-��>�H�H�Q�W�W�R�[�)�	��h�h�q�w�w�'�����!�'�'�"�+�.���q�w�w�r�{�#�	=�A�"�3�3�A�a��A�g�J�?�O�A�y��|�#(�<�<�#9�#9�1�d�)�Q�q�!�Q�w�Z�#P�K��1�a�� � +�A�q�!�G� 4� :� :� <�N�1��	=��r�C�x�!�|�$�y�0�3��3G�G��b��3���'�#��(�]�*B�B��S��V�S�)�*�+���
r5c��|j||�\}}}|j||�}|j|�\}}|j||||||�}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�r4)rdrNr�r�r�r�r�r2s        r3r�zwishart_gen.logpdf�sh��(�1�1�"�e�<���R���#�#�A�s�+�� �0�0��7���=��l�l�1�c�2�u�m�Q�?���s�#�#r5c�N�tj|j|||��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�rdrNr�r�s    r3r�zwishart_gen.pdf� ��(�v�v�d�k�k�!�R��/�0�0r5c��||zS)aAMean 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.�rdr�r�r�s    r3�_meanzwishart_gen._mean's���E�z�r5c�j�|j||�\}}}|j|||�}t|�S)z�Mean of the Wishart distribution.

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

        Returns
        -------
        mean : float
            The mean of the distribution
        �r�r�r4�rdr�r�r�r2s     r3r�zwishart_gen.mean8s9���1�1�"�e�<���R���j�j��b�%�(���s�#�#r5c�4�||dzk\r
||z
dz
|z}|Sd}|S)aAMode 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.

        rNr.�rdr�r�r�r2s     r3�_modezwishart_gen._modeHs4����q��=��c�6�!�8�u�$�C��
��C��
r5c�r�|j||�\}}}|j|||�}|�t|�S|S)aEMode 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
        �r�r�r4r�s     r3�modezwishart_gen.mode]sB���1�1�"�e�<���R���j�j��b�%�(��'*���s�#�?�C�?r5c�l�|dz}|j�}|tj||�z
}||z}|S)aDVariance 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,��diagonalr>�outer�rdr�r�r�r|r�s      r3�_varzwishart_gen._varps<���Q�h���~�~����r�x�x��d�#�#���r�	���
r5c�j�|j||�\}}}|j|||�}t|�S)z�Variance of the Wishart distribution.

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

        Returns
        -------
        var : float
            The variance of the distribution
        �r�r�r4r�s     r3r|zwishart_gen.var�s9���1�1�"�e�<���R���i�i��R��'���s�#�#r5c	�<�||dz
zdz}|j||z��j||fz�}tjt	|�D�cgc]!}|j||dzz
dz|��dz��#c}j|f|ddd�z�j}	tj|||fz�}
ttddd�gt|�z�}tj|d��}||
||z<tj|�}
|	|
||
z<|
Scc}w)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.

        rr,r�rNr7��k)
r�r�r>�r_r��	chisquarervr�r��slicerZ�tril_indices�diag_indices)rdr�r�r�r�r��n_tril�covariancesr��	variances�A�size_idx�tril_idx�diag_idxs              r3�
_standard_rvszwishart_gen._standard_rvs�s:��:��A���!�#��"�)�)��6��*��"�7�5�&��?�3�	��U�U�%*�3�Z�1� !�)�2�2�2�q��s�8�A�:�A�2�F��K�1�2�29�'�3�&�:?��"��+�;F�3G�GH�q�	�

�H�H�U�c�3�Z�'�(���%��d�D�1�2�3�u�:�=�>���?�?�3�"�-��!,��(�X�
���?�?�3�'��!*��(�X�
�����!1s�&Dc��|j|�}|j|||||�}tj|�D]>}tj|||�}	tj|	|	j
�||<�@|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�r>�ndindexrurv)
rdr�r�r�r�r�r�r��index�CAs
          r3�_rvszwishart_gen._rvs�s{��.�-�-�l�;��
���q�%��b�,�?���Z�Z��&�	(�E�����1�U�8�$�B��v�v�b�"�$�$�'�A�e�H�	(��r5c���|j|�\}}|j||�\}}}tjj	|d��}|j||||||�}	t
|	�S)aDraw 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�rUrVr@r�r4)
rdr�r�r�r�r�r�r�r�r2s
          r3rzwishart_gen.rvs�sn��*�%�%�d�+���5��1�1�"�e�<���R��
�L�L�!�!�%�t�!�4���i�i��5�#�r�1�l�;���s�#�#r5c
��d|dzz|zd|z|dzztzztd|z|�zd||z
dz
ztjt	|�D�cgc]}td|dz|dzz
z���c}�zz
d|z|zzScc}w)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.

        rr)r�r	r>r`r�r)rdr�r�r�r�s     r3rHzwishart_gen._entropy	s���&
�3�q�5�M�M�)��#�I��Q���&�(�
)���R���%�
&�
�2��8�a�<� �2�6�6�49�#�J�?�q��S�"�q�&�A�a�C�.�)�*�?�$�
�
�
�"�H�s�N�

�	
��
@s�Bc�|�|j||�\}}}|j|�\}}|j|||�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�rH�rdr�r�r�rJr�s      r3rzwishart_gen.entropy1	sD��"�1�1�"�e�<���R���0�0��7���=��}�}�S�"�m�4�4r5c��tjj|d��}dtjtj
|j
���z}||fS)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,)rUrVr@r>r`rar�)rdr��c_decomp�logdets    r3r�zwishart_gen._cholesky_logdetF	sM��*�<�<�(�(��d�(�;���R�V�V�B�F�F�8�#4�#4�#6�7�8�8�����r5rt�NNNr)ryrzr{r|rkr�r�r�r�r�r�r�r�r�r�r�r�r|r�r�rrHrr�r�r�s@r3r�r��st���m�^N�/��:#�J�,�\$�:1�,�"$� �*@�&�*$� 2�h+�Z$�>
�85�* r5r�c�D�eZdZdZdd�Zd�Zd�Zd�Zd�Zd�Z	dd	�Z
d
�Zy)
r�aXCreate 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���t|�|_|jj||�\|_|_|_|jj
|j
�\|_|_yrt)	r�r�r�r�r�r�r�r�r�r�s    r3rkzwishart_frozen.__init__u	sV�� ��&��
�(,�
�
�(F�(F���)�%���$�'�4�:�%)�Z�Z�%@�%@����%L�"����"r5c��|jj||j�}|jj||j|j|j
|j|j�}t|�Srt)	r�r�r�r�r�r�r�r�r4�rdrNr2s   r3r�zwishart_frozen.logpdf{	s^���J�J�)�)�!�T�X�X�6���j�j� � ��D�H�H�d�g�g�t�z�z�!%�!3�!3�T�V�V�=���s�#�#r5c�J�tj|j|��Srtrrs  r3r�zwishart_frozen.pdf�	rr5c��|jj|j|j|j�}t|�Srt�r�r�r�r�r�r4�rdr2s  r3r�zwishart_frozen.mean�	�1���j�j���t�x�x����$�*�*�=���s�#�#r5c��|jj|j|j|j�}|�t|�S|Srt�r�r�r�r�r�r4r�s  r3r�zwishart_frozen.mode�	�:���j�j���t�x�x����$�*�*�=��'*���s�#�?�C�?r5c��|jj|j|j|j�}t|�Srt�r�r�r�r�r�r4r�s  r3r|zwishart_frozen.var�	s/���j�j�o�o�d�h�h�������<���s�#�#r5c���|jj|�\}}|jj|||j|j|j
|�}t
|�Srt�r�r�r�r�r�r�r4�rdr�r�r�r�r2s      r3rzwishart_frozen.rvs�	sP���:�:�+�+�D�1���5��j�j�o�o�a�����$�'�'�"�f�f�l�4���s�#�#r5c�x�|jj|j|j|j�Srt�r�rHr�r�r�rws r3rzwishart_frozen.entropy�	�)���z�z�"�"�4�8�8�T�W�W�d�6H�6H�I�Ir5rtr)ryrzr{r|rkr�r�r�r�r|rrr.r5r3r�r�c	s2���"M�$�&�$�@�$�$�Jr5r�)r�r�r�r�r|rrc��|rt|�}nt|�}t|j�dks|jd|jdk7rt	d��td|f�\}}t
j|jdd��\}}t
j|jdd�D]�}|||d	d
d
��\||<}|dkDrtd
|z��|dkrt	d|z��|||d	d
��\||<}|dkDrtd��|dkrt	d|z��||||f||||f<��|S)a*
    Invert the matrices a_i, using a Cholesky factorization of A, where
    a_i resides in the last two dimensions of a and the other indices describe
    the index i.

    Overwrites the data in a.

    Parameters
    ----------
    a : array
        Array of matrices to invert, where the matrices themselves are stored
        in the last two dimensions.
    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.

    Returns
    -------
    x : array
        Array of inverses of the matrices ``a_i``.

    See Also
    --------
    scipy.linalg.cholesky : Cholesky factorization of a matrix

    r,r-r7z-expected square matrix in last two dimensions)�potrf�potrirr�NTF)r=�overwrite_a�cleanrz)%d-th leading minor not positive definitez1illegal value in %d-th argument of internal potrf)r=�overwrite_cz!the inverse could not be computed)
rrrZr�rYrr>�triu_indicesr�r)	r�rS�a1r�r��	triu_rows�	triu_colsr��infos	         r3�_cho_inv_batchr��	s���8�
�q�
!��
�Q�Z��
�2�8�8�}�q��B�H�H�R�L�B�H�H�R�L�8��H�I�I�#�$6���>�L�E�5��?�?�1�7�7�2�;�!�<��I�y����B�H�H�S�b�M�*�J�� ��5�	��5�&+�-���5�	�4��!�8��I� $�%�&�
&��!�8��&�)-��.�/�
/� ��5�	��5�I���5�	�4��!�8��A�B�B��!�8��&�)-��.�/�
/�+-�U�)�I�y�4H�*I��5�	�)�Y�&�'�)J�,�Ir5c���eZdZdZd�fd�	Zdd�Zd�Zd�Zd�Zd�Z	d�Z
d	�Zd
�Zd�Z
d�Z�fd
�Zdd�Zd�Zd�Z�xZS)�invwishart_genaAn 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}`.

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

    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.

    c�v��t�|�|�tj|jt
�|_yrtr�r�s  �r3rkzinvwishart_gen.__init__R
rr5c��t|||�S)znCreate a frozen inverse Wishart distribution.

        See `invwishart_frozen` for more information.

        )�invwishart_frozenr�s    r3r�zinvwishart_gen.__call__V
s��!��U�D�1�1r5c���tj|jd�}tj|�j}|dkDrt|�nd|z}tj|jd�}t
|jd�D]�}	tjj|dd�dd�|	fd��\}
}dtjtj|
j���z||	<tj|||	�j�||	<��d|z|zd|zz
d|z|ztzd||zdzz|zzz
t!d|z|�z
}|S)	agLog 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
        scale : ndarray
            Scale matrix
        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 'logpdf' instead.

        r7rr�NTr=r,r)r>r�r�r�rvr�r�rUrV�
cho_factorr`rar�rur�r�r	)
rdrNr�r�r�r�r��x_inv�tr_scale_x_invr�r�r=r2s
             r3r�zinvwishart_gen._logpdf^
sG��.�H�H�Q�W�W�R�[�)�	�����
������7��5�!��u�H�E����!�'�'�"�+�.���q�w�w�r�{�#�	@�A��|�|�.�.�q��A�q��z��.�F�H�A�u��r�v�v�b�f�f�Q�Z�Z�\�&:�;�;�I�a�L� "���u�e�A�h� 7� =� =� ?�N�1��	@��b��=�(�3��+?�?��b��3���'�#��c��A��*>��*J�J�L��C��F�C�(�)���
r5c��|j||�\}}}|j||�}|j|�\}}|j|||||�}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�)rdrNr�r�r�rJr�r2s        r3r�zinvwishart_gen.logpdf�
sd��(�1�1�"�e�<���R���#�#�A�s�+���0�0��7���=��l�l�1�c�2�u�m�<���s�#�#r5c�N�tj|j|||��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

        rr�s    r3r�zinvwishart_gen.pdf�
r�r5c�4�||dzkDr
|||z
dz
z}|Sd}|S)aIMean 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.

        rNr.r�s     r3r�zinvwishart_gen._mean�
s4����a��<��2��8�a�<�(�C��
��C��
r5c�r�|j||�\}}}|j|||�}|�t|�S|S)aXMean 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

        r�r�s     r3r�zinvwishart_gen.mean�
sB�� �1�1�"�e�<���R���j�j��b�%�(��'*���s�#�?�C�?r5c��|||zdzzS)aIMode 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.

        rr.r�s    r3r�zinvwishart_gen._mode�
s����S��1��%�%r5c�j�|j||�\}}}|j|||�}t|�S)z�Mode of the inverse Wishart distribution.

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

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

        r�r�s     r3r�zinvwishart_gen.mode�
s9���1�1�"�e�<���R���j�j��b�%�(���s�#�#r5c���||dzkDr_||z
dz|dzz}|j�}|||z
dz
tj||�zz
}|||z
||z
dz
dzz||z
dz
zz}|Sd}|S)aLVariance 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�rr,Nr�r�s      r3r�zinvwishart_gen._vars�����a��<���8�a�<�5�!�8�+�C��>�>�#�D��B��H�q�L�B�H�H�T�4�$8�8�8�C��B��H��c��A��� 1�1�R�#�X��\�B�B�C��
��C��
r5c�r�|j||�\}}}|j|||�}|�t|�S|S)aXVariance 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
        r�r�s     r3r|zinvwishart_gen.varsB���1�1�"�e�<���R���i�i��R��'��'*���s�#�?�C�?r5c����|j|�}t�
|�	|||||�}tj|�}td|f�}	tj|jdd�D]z}
tj|||
�}|dkDr2|	||d��\}}|dkDrtd��|dkrtd	|z��d
|z}tj|j|�||
<�||S)aeDraw 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.

        �trtrsNr-rTr=rzSingular matrix.z1Illegal value in %d-th argument of internal trtrsr�)r�r�r�r>r�rr�r�rurrYrv)rdr�r�r�r�r�r�r�r�rr�r�r�r�s             �r3r�zinvwishart_gen._rvs1s����.�-�-�l�;���G�!�!�U�C��\�B���f�f�S�k�� �'�Q�D�1���Z�Z�������-�	(�E�����1�U�8�$�B��Q�w� ��S��5���D��!�8�%�&8�9�9��!�8�$�&7�:>��&?�@�@��"�W���v�v�b�d�d�B�'�A�e�H�	(� �r5c��|j|�\}}|j||�\}}}tj|�}tj
j
|d��\}	}
tj
j|	|
f|�}tj
j|d��}|j||||||�}
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=)r�r�r>r�rUrVrr�r@r�r4)rdr�r�r�r�r�r�r�r��Lr=�	inv_scaler�r2s              r3rzinvwishart_gen.rvsbs���*�%�%�d�+���5��1�1�"�e�<���R���f�f�S�k���<�<�*�*�5��*�=���5��L�L�*�*�A�u�:�s�;�	��L�L�!�!�)�4�!�8���i�i��5�#�r�1�l�;���s�#�#r5c�&�td|dz�D�cgc]
}d||z
|zz��}}tj|�}td|z|�d|z|zzd|dzz|tz
zzd||zdzzt||��j
�zz
Scc}w)Nrrr1)r�r>rr	r�rr`)rdr�r�r�r��psi_eval_pointss      r3rHzinvwishart_gen._entropy�s���9>�q�#��'�9J�K�A�3�"�s�(�Q�,�/�K��K��*�*�_�5���C�"�H�c�*�S�3�Y��^�;��3��7�O�}�v�5�6�7��2��8�a�<� ���_�5�9�9�;�
<�<�	<��Ls�Bc�|�|j||�\}}}|j|�\}}|j|||�Srtr�r�s      r3rzinvwishart_gen.entropy�sB���1�1�"�e�<���R���0�0��7���=��}�}�S�"�m�4�4r5rtr�r)ryrzr{r|rkr�r�r�r�r�r�r�r�r�r|r�rrHrr�r�s@r3rr�	s[���k�ZN�2�+�Z$�41�,�*@�(&�"$�"�0@�&/�b!$�F<�5r5rc�@�eZdZd
d�Zd�Zd�Zd�Zd�Zd�Zdd�Z	d	�Z
y)rNc�F�t|�|_|jj||�\|_|_|_tjj|j
d��\}}dtjtj|j���z|_
tj|j�}tjj||f|�|_tjj#|j d��|_y)aGCreate 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)rr�r�r�r�r�rUrVrr>r`rar�r�r�r�rr@r�)rdr�r�r�r�r=r�s       r3rkzinvwishart_frozen.__init__�s���"$�D�)��
�(,�
�
�(F�(F���)
�%���$�'�4�:�
�<�<�*�*�4�:�:�T�*�B���5��������q�z�z�|�(<�!=�=����f�f�T�X�X������/�/��E�
�C�@������&�&�t�~�~�T�&�B��r5c���|jj||j�}|jj||j|j|j
|j�}t|�Srt)r�r�r�r�r�r�r�r4r�s   r3r�zinvwishart_frozen.logpdf�sX���J�J�)�)�!�T�X�X�6���j�j� � ��D�H�H�d�g�g�t�z�z�!%�!3�!3�5���s�#�#r5c�J�tj|j|��Srtrrs  r3r�zinvwishart_frozen.pdf�rr5c��|jj|j|j|j�}|�t|�S|Srtr�r�s  r3r�zinvwishart_frozen.mean�r�r5c��|jj|j|j|j�}t|�Srtr�r�s  r3r�zinvwishart_frozen.mode�r�r5c��|jj|j|j|j�}|�t|�S|Srtr�r�s  r3r|zinvwishart_frozen.var�s8���j�j�o�o�d�h�h�������<��'*���s�#�?�C�?r5c���|jj|�\}}|jj|||j|j|j
|�}t
|�Srtr�r�s      r3rzinvwishart_frozen.rvs�sR���:�:�+�+�D�1���5��j�j�o�o�a�����$�'�'�"�f�f�l�4���s�#�#r5c�x�|jj|j|j|j�Srtr�rws r3rzinvwishart_frozen.entropy�r�r5rtr)ryrzr{rkr�r�r�r�r|rrr.r5r3rr�s/��C�B$�&�@�$�@�$�Jr5r)r�r�r�r�r|rzsn : 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�l��eZdZdZd�fd�	Zdd�Zdd�Zd�Zd�Zd�Z	d�Z
d	�Zd
�Zd�Z
d�Zdd
�Z�xZS)�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.
    c�v��t�|�|�tj|jt
�|_yrt)r�rkrr�r|�multinomial_docdict_paramsr�s  �r3rkzmultinomial_gen.__init__ls,���
��������T�\�\�+E�F�	
�r5c��t|||�S)zjCreate a frozen multinomial distribution.

        See `multinomial_frozen` for more information.
        )�multinomial_frozen)rdr�rOr�s    r3r�zmultinomial_gen.__call__qs��
"�!�Q��-�-r5c��tj|tjd��}d|ddd�fjd��z
}tj|�|kD}||||df<tj
|dkd��}|tj
|d	kDd��z}tj|tjd��}|dk}||||zfS)
z�Returns: n_, p_, npcond.

        n_ and p_ are arrays of the correct shape; npcond is a boolean array
        flagging values out of the domain.
        T�r;r�r�.Nr7rmrr)r>rK�float64r`rBr��int_)rdr�rOr@�
p_adjusted�
i_adjusted�pcond�nconds        r3r�z#multinomial_gen._process_parametersxs���
�H�H�Q�b�j�j�t�4���!�C��"��H�+�/�/�r�/�2�2�
��V�V�J�'�#�-�
�&�z�2��*�b�.�����q�1�u�2�&��
�����A��B�'�'���H�H�Q�b�g�g�D�1���A����!�U�U�]�"�"r5c���tj|tj��}|jdk(rt	d��|j
dk7rI|jd|jdk(s*t	d|jd|jdfz��tj||k7d��}|tj|dkd��z}|tj|d��|k7z}||fS)z}Returns: x_, xcond.

        x_ is an int array; xcond is a boolean array flagging values out of the
        domain.
        rJrzx must be an array.r7zHSize of each quantile should be size of p: received %d, but expected %d.rm)	r>rr*r0rYr�r�r�r`)rdrNr�rO�xxrDs      r3r�z"multinomial_gen._process_quantiles�s����Z�Z�����
)��
�7�7�a�<��2�3�3�
�7�7�a�<����������� ;��=� �h�h�r�l�A�G�G�B�K�8�9�:�
:�
�v�v�b�A�g�B�'������r�A�v�B�'�'���r�v�v�b�r�*�a�/�0���4�x�r5c��tj|�}|jdk7r|||<|S|r|jdk(r|S||d<|S)Nr.�r>rr0�rd�resultrD�	bad_values    r3�_checkresultzmultinomial_gen._checkresult�sP�����F�#���9�9��>�$�F�4�L�
�
�	��{�{�a�� � �#�F�3�K��
r5c��t|dz�tjt||�t|dz�z
d��zS)Nrr7rm)rr>r`r
�rdrNr�rOs    r3�_logpmfzmultinomial_gen._logpmf�s3���q��s�|�b�f�f�U�1�a�[�7�1�Q�3�<�%?�b�I�I�Ir5c���|j||�\}}}|j|||�\}}|j|||�}|tj|j
tj��z}|j||tj�}|tj|j
tj��z}|j||tj�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
        rJ)
r�r�r9r>r�r��bool_r6r��nan)	rdrNr�rO�npcond�xcondr4�xcond_�npcond_s	         r3�logpmfzmultinomial_gen.logpmf�s���$�/�/��1�5���1�f��*�*�1�a��3���5����a��A�&������&�,�,�b�h�h�?�?���"�"�6�6�B�F�F�7�;���2�8�8�E�K�K�r�x�x�@�@��� � ���"�&�&�9�9r5c�N�tj|j|||��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
        �r>r�rAr8s    r3�pmfzmultinomial_gen.pmf�s ��$�v�v�d�k�k�!�Q��*�+�+r5c��|j||�\}}}|dtjf|z}|j||tj�S)z�Mean of the Multinomial distribution.

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

        Returns
        -------
        mean : float
            The mean of the distribution
        .)r�r>r�r6r<)rdr�rOr=r4s     r3r�zmultinomial_gen.mean�sL���/�/��1�5���1�f��3��
�
�?�#�A�%��� � ������8�8r5c�X�|j||�\}}}|dtjtjf}|tjd||�z}t	|j
d�D]}|d||fxx||d|fzz
cc<�|j
||tj�S)z�Covariance matrix of the multinomial distribution.

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

        Returns
        -------
        cov : ndarray
            The covariance matrix of the distribution
        .z...j,...k->...jkr7)r�r>r�rCr�r�r6r<)rdr�rOr=�nnr4r�s       r3r�zmultinomial_gen.cov�s����/�/��1�5���1�f�
�s�B�J�J��
�
�*�
+���b�i�i� 2�Q�B��:�:���q�w�w�r�{�#�	-�A��3��1�9���1�S�!�V�9��,��	-�� � ������8�8r5c�j�|j||�\}}}tjdtj|�dz}|tjt|�d��z}|t
|dz�z}|dtjf}t|j|j�|jz
dz}|xjd|zz
c_	tjtj|||�t
|dz�zdd|z
f��}|j||z|tj�S)aCompute 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
        rr7rm.)r)r�r>r�rAr`rrr�r0r�rrDr6r<)rdr�rOr=rN�term1�new_axes_needed�term2s        r3rzmultinomial_gen.entropy
s��.�/�/��1�5���1�f��E�E�!�B�F�F�1�I�a�K� ���"�&�&��a��r�*�*��
���1�����
�c�2�:�:�o����a�f�f�a�f�f�-����6��:��	���4��'�'�����u�y�y��A�q�)�'�!�A�#�,�6���O�!3�4�6��� � ��������?�?r5c�v�|j||�\}}}|j|�}|j|||�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")rdr�rOr�r�r=s      r3rzmultinomial_gen.rvs5
sA��&�/�/��1�5���1�f��-�-�l�;���'�'��1�d�3�3r5rt)gV瞯�<�NN)ryrzr{r|rkr�r�r�r6r9rArDr�r�rrr�r�s@r3r"r"sK���f�PG�
.�#�,�.	�J�:�@,�(9� 9�.%@�N4r5r"c�>�eZdZdZd
d�Zd�Zd�Zd�Zd�Zd�Z	dd	�Z
y)r&aZCreate 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���t|��_�jj||�\�_�_�_�fd�}|�j_y)Nc�J���j�j�jfSrt)r�rOr=)r�rOrds  �r3r�z8multinomial_frozen.__init__.<locals>._process_parametersf
s����6�6�4�6�6�4�;�;�.�.r5)r"r�r�r�rOr=)rdr�rOr�r�s`    r3rkzmultinomial_frozen.__init__a
sE���$�T�*��
�&*�j�j�&D�&D�Q��&J�#�������	/�*=��
�
�&r5c�d�|jj||j|j�Srt)r�rAr�rOrs  r3rAzmultinomial_frozen.logpmfk
�#���z�z� � ��D�F�F�D�F�F�3�3r5c�d�|jj||j|j�Srt)r�rDr�rOrs  r3rDzmultinomial_frozen.pmfn
�!���z�z�~�~�a�������0�0r5c�b�|jj|j|j�Srt)r�r�r�rOrws r3r�zmultinomial_frozen.meanq
����z�z���t�v�v�t�v�v�.�.r5c�b�|jj|j|j�Srt)r�r�r�rOrws r3r�zmultinomial_frozen.covt
����z�z�~�~�d�f�f�d�f�f�-�-r5c�b�|jj|j|j�Srt)r�rr�rOrws r3rzmultinomial_frozen.entropyw
s!���z�z�!�!�$�&�&�$�&�&�1�1r5c�f�|jj|j|j||�Srt)r�rr�rOrs   r3rzmultinomial_frozen.rvsz
s#���z�z�~�~�d�f�f�d�f�f�d�L�A�Ar5rtr)ryrzr{r|rkrArDr�r�rrr.r5r3r&r&P
s+��� =�4�1�/�.�2�Br5r&)rArDr�r�rc�:��eZdZdZd�fd�	Zdd�Zd�Zdd�Z�xZS)	�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

    c�l��t�|�|�tj|j�|_yrt�r�rkrr�r|r�s  �r3rkz special_ortho_group_gen.__init__�
�&���
������'�'����5��r5c��t||��S)zlCreate a frozen SO(N) distribution.

        See `special_ortho_group_frozen` for more information.
        r)�special_ortho_group_frozen�rdr�r�s   r3r�z special_ortho_group_gen.__call__�
s��
*�#�D�9�9r5c�p�|�(tj|�r|dks|t|�k7rtd��|S)�5Dimension N must be specified; it cannot be inferred.rzmDimension of rotation must be specified,
                                and must be a scalar greater than 1.�r>r�r?rY�rdr�s  r3r�z+special_ortho_group_gen._process_parameters�
s>���;�b�k�k�#�.�#��(�c�S��X�o��H�I�
I��
r5c���|j|�}t|�}|dkDr|fnd}|j|�}tj|||fz�}tj
|�|ddd�dd�f<tj||fz�}t
|dz
�D�]$}|j|||z
fz��}|dddd�f}|ddd�df}	tj||	�jd�}
|dj�}tj|dk7tj|�d�|d|f<|dxx|d|ftj|
�zz
cc<|tj|
|d	zz
|dd	zzd
z�dz}|ddd�|d�fxxtj|ddd�|d�f|	�|zzcc<��'d|dz
z|ddd�fjd�
�z|d<||ddd�dfz}|S)asDraw 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)

        rr..Nr�)r-r7�.rrr,�@�.Nr7rm).r7)r�r?r�r>r�r�r�r��matmulr/r��where�signr\r�)rdr�r�r��H�Dr�rN�xrow�xcol�norm2�x0s            r3rzspecial_ortho_group_gen.rvs�
s�� �-�-�l�;���4�y����(��w����&�&�s�+��
�H�H�T�S�#�J�&�'���v�v�c�{��#�q�!�)���H�H�T�S�F�]�#���s�1�u��	C�A��#�#���Q����#�9�A��S�$��\�?�D��S�!�T�\�?�D�
�I�I�d�D�)�1�1�(�;�E��6����!�B�����q��"�'�'�"�+�q�9�A�c�1�f�I�
�f�I��3��6��2�7�7�5�>�1�1�I�
����%�"�a�%�-�!�F�)�Q�,�6�"�<�=�i�H�H�A�
�c�1�a�b�j�M�R�Y�Y�q��a����}�d�;�d�B�B�M�3	C�6�C��E�]�1�S�#�2�#�X�;�#3�#3��#3�#<�<��'�
�	
�Q�s�A�t�|�_����r5rtrMr�	ryrzr{r|rkr�r�rr�r�s@r3r\r\�
s���G�R6�:��Ar5r\c��eZdZdd�Zdd�Zy)raNc�d�t|�|_|jj|�|_y)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)r\r�r�r�rbs   r3rkz#special_ortho_group_frozen.__init__.s&��,-�T�2��
��:�:�1�1�#�6��r5c�P�|jj|j||�Srt�r�rr�rs   r3rzspecial_ortho_group_frozen.rvsG����z�z�~�~�d�h�h��l�;�;r5rMr�ryrzr{rkrr.r5r3rara-���7�2<r5rac�:��eZdZdZd�fd�	Zdd�Zd�Zdd�Z�xZS)	�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
    c�l��t�|�|�tj|j�|_yrtr^r�s  �r3rkzortho_group_gen.__init__�r_r5c��t||��S)zcCreate a frozen O(N) distribution.

        See `ortho_group_frozen` for more information.
        r)�ortho_group_frozenrbs   r3r�zortho_group_gen.__call__�s��
"�#�D�1�1r5c�p�|�(tj|�r|dks|t|�k7rtd��|S�rdrzLDimension of rotation must be specified,and must be a scalar greater than 1.rerfs  r3r�z#ortho_group_gen._process_parameters��>���;�b�k�k�#�.�#��(�c�S��X�o��D�E�
E��
r5c
�$�|j|�}t|�}|dkDrZttj�dkr>tj
t
|�D�cgc]}|j|d|����c}�S|j|�}|dkDr|fnd}|j|||fz��}tjj|�\}}|jddd�	�}||t|�zd
tjdd�fz}|Scc}w)arDraw 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�1.22.0�r�r�r.r�rr-r7��offset�axis1�axis2.N)r�r?rr>�__version__rKr�rr�r�rV�qrr�rBr��	rdr�r�r�r��z�q�rr:s	         r3rzortho_group_gen.rvs�s�� �-�-�l�;���4�y���!�8��R�^�^�4�x�?��8�8�&+�D�k�3�!"�"�X�X�c���X�M�3�4�
4��&�&�s�+����(��w������T�S�#�J�%6��7���y�y�|�|�A����1�
�J�J�a�r��J�4��	
�a��A��h��R�Z�Z��*�
+�+�����3s�D
rtrMrrtr�s@r3r}r}Ks���@�D6�2��"r5r}c��eZdZdd�Zdd�Zy)r�Nc�d�t|�|_|jj|�|_y)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�rbs   r3rkzortho_group_frozen.__init__�s&��,%�T�*��
��:�:�1�1�#�6��r5c�P�|jj|j||�Srtrxrs   r3rzortho_group_frozen.rvs�ryr5rMrrzr.r5r3r�r��r{r5r�c�F��eZdZdZd�fd�	Zd	d�Zd�Zd�Zd�Zd	d�Z	�xZ
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])

    c�l��t�|�|�tj|j�|_yrtr^r�s  �r3rkzrandom_correlation_gen.__init__3r_r5c� �t||||��S)zrCreate a frozen random correlation matrix.

        See `random_correlation_frozen` for more information.
        )r��tol�diag_tol)�random_correlation_frozen)rd�eigsr�r�r�s     r3r�zrandom_correlation_gen.__call__7s��
)��D�c�2:�<�	<r5c�\�tj|t��}|j}|jdk7s|j
d|k7s|dkrt
d��tjtj|�|z
�|kDrt
d��|D]}||ks�
t
d��||fS)NrJrrz7Array 'eigs' must be a vector of length greater than 1.z-Sum of eigenvalues must equal dimensionality.z%All eigenvalues must be non-negative.)	r>rrLr�r0r�rY�fabsr`)rdr�r�r�rNs     r3r�z*random_correlation_gen._process_parameters?s����z�z�$�e�,���i�i���9�9��>�T�Z�Z��]�c�1�S�A�X��/�0�
0��7�7�2�6�6�$�<�#�%�&��,��L�M�M��	J�A��C�4�x� �!H�I�I�	J��D�y�r5c��|dz
}|dz
}|dk(rytjt|dz||zz
d��}|tj||�z|z}dtjd||zz�z}|dk(rd}	||	fS||z}	||	fS)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,)�mathr\rA�copysign)
rd�aii�ajj�aij�aiid�ajjd�ddrF�crgs
          r3�_givens_to_1z#random_correlation_gen._givens_to_1Ps����R�x���R�x���1�9��
�Y�Y�s�3��6�D��I�-�q�1�
2���4�=�=��S�)�
)�T�1������2��!��8�$�$����6��A��!�t���!��A��!�t�r5c��|jjr<|jtjk(r|j
d|j
dk(s
t
��|j
d}t|dz
�D]�}|||fdk(r�|||fdkDr!t|dz|�D]}|||fdks�n"n t|dz|�D]}|||fdkDs�n|j|||f||f|||f�\}}|j�}t|||||||zd||zddd��t|||||||||dd����|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
        rrT)r��offx�incx�offy�incy�overwrite_x�overwrite_y)�flags�c_contiguousr;r>r)r�rYr�r��ravelr)rd�mr:r��jr�rg�mvs        r3�_to_corrzrandom_correlation_gen._to_corrqsq�����$�$����B�J�J�)>�����
�a�g�g�a�j�(��,��
�G�G�A�J���q��s��	5�A���A��w�!�|���1�a�4��1���q��s�A���A���A��w��{����q��s�A���A���A��w��{����$�$�Q�q�!�t�W�a��1��g�q��A��w�?�D�A�q�����B���R��Q�B�!���c���!��!�!�t�
5�
��R��Q�B�!��a�a�a�!�t�
5�/	5�6�r5c��|j||��\}}|j|�}tj||��}t	j
t	j
|t	j|��|j�}|j|�}t|j�dz
�j�|kDrtd��|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�rz-Failed to generate a valid correlation matrix)
r�r�r$rr>rur�rvr�rBr�rA�RuntimeError)rdr�r�r�r�r�r�s       r3rzrandom_correlation_gen.rvs�s���4�,�,�T�s�,�;�	��T��-�-�l�;���O�O�C�l�O�;���F�F�2�6�6�!�R�W�W�T�]�+�Q�S�S�1���M�M�!����q�z�z�|�a�� �$�$�&��1��N�O�O��r5rt�Ng�vIh�%<=gH�����z>)ryrzr{r|rkr�r�r�r�rr�r�s@r3r�r��s*���I�V6�<��"�B'�R&r5r�c��eZdZdd�Zdd�Zy)r�Nc��t|�|_||_||_|jj	||j��\}|_y)axCreate 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�)rdr�r�r�r�rJs      r3rkz"random_correlation_frozen.__init__�sB��B,�D�1��
���� ��
��z�z�5�5�d����5�I���4�9r5c�|�|jj|j||j|j��S)N)r�r�r�)r�rr�r�r�r�s  r3rzrandom_correlation_frozen.rvs�s3���z�z�~�~�d�i�i�l�"&�(�(�T�]�]��D�	Dr5r�rtrzr.r5r3r�r��s��$J�LDr5r�c�:��eZdZdZd�fd�	Zdd�Zd�Zdd�Z�xZS)	�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
    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

    c�l��t�|�|�tj|j�|_yrtr^r�s  �r3rkzunitary_group_gen.__init__-r_r5c��t||��S)z�Create a frozen (U(N)) n-dimensional unitary matrix distribution.

        See `unitary_group_frozen` for more information.
        r)�unitary_group_frozenrbs   r3r�zunitary_group_gen.__call__1s��
$�C�d�3�3r5c�p�|�(tj|�r|dks|t|�k7rtd��|Sr�rerfs  r3r�z%unitary_group_gen._process_parameters8r�r5c
��|j|�}t|�}|dkDrZttj�dkr>tj
t
|�D�cgc]}|j|d|����c}�S|j|�}|dkDr|fnd}dtjd�z|j|||fz��d|j|||fz��zzz}tjj|�\}}|jdd	d
��}||t|�zdtj d
d
�fz}|Scc}w)aiDraw 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)

        rr�r�r.r,r�y�?rr-r7r�.N)r�r?rr>r�rKr�rr�r�r\r�rVr�r�rBr�r�s	         r3rzunitary_group_gen.rvs@s=�� �-�-�l�;���4�y���!�8��R�^�^�4�x�?��8�8�&+�D�k�3�!"�"�X�X�c���X�M�3�4�
4��&�&�s�+����(��w���
�d�i�i��l�N�L�/�/�T�S�#�J�5F�/�G��|�2�2���S�z�8I�2�J�J�K�
L���y�y�|�|�A����1�
�J�J�a�r��J�4��	
�a��A��h��R�Z�Z��*�
+�+�����3s�ErtrMrrtr�s@r3r�r��s���8�t6�4��#r5r�c��eZdZdd�Zdd�Zy)r�Nc�d�t|�|_|jj|�|_y)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�rbs   r3rkzunitary_group_frozen.__init__js&��,'�t�,��
��:�:�1�1�#�6��r5c�P�|jj|j||�Srtrxrs   r3rzunitary_group_frozen.rvs�ryr5rMrrzr.r5r3r�r�ir{r5r�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``)
aSetting 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���eZdZdZd�fd�	Z		dd�Zdd�Zdd�Zd�Z		dd�Z	ddddd	�d
�Z
dd�Zdd�Zdd
�Z
d�Zd�Z�xZS)�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���t�|�|�tj|jt
�|_t
|�|_y)z�Initialize a multivariate t-distributed random variable.

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

        N)r�rkrr�r|�mvt_docdict_paramsrr�r�s  �r3rkzmultivariate_t_gen.__init__�s8���	������'�'����6H�I���/��5��r5c�f�|tjk(rt||||��St|||||��S)zjCreate a frozen multivariate t-distribution.

        See `multivariate_t_frozen` for parameters.
        )r�r�rfr�)�locr�r�rfr�)r>r�r��multivariate_t_frozen)rdr�r�r�rfr�s      r3r�zmultivariate_t_gen.__call__	sB������<�-�3�E�=K�37�9�
9�%��E�b�4B��O�	Or5c	��|j|||�\}}}}|j||�}t||��}|j|||j|j
|||j�}tj|�S)aZMultivariate 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�rQr�r_rbr^r>r�)	rdrNr�r�r�rfr��
shape_infor�s	         r3r�zmultivariate_t_gen.pdfsx��0#�6�6�s�E�2�F���S�%���#�#�A�s�+���%��?�
����a��j�l�l�J�4G�4G��!�:�?�?�4���v�v�f�~�r5c	���|j|||�\}}}}|j||�}t|�}|j|||j|j
|||j�S)a�Log of the multivariate t-distribution probability density function.

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

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

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

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

        )r�r�rQr�r_rbr^)rdrNr�r�r�r�r�s       r3r�zmultivariate_t_gen.logpdf5sj��:#�6�6�s�E�2�F���S�%���#�#�A�s�+���%�[�
��|�|�A�s�J�L�L�*�2E�2E�r�3�&�O�O�-�	-r5c���|tjk(rtj|||||�S||z
}tjtj
||��j
d��}	d||zz}
t|
�}td|z�}|dztj|tjz�z}
d|z}|
tjdd|z|	zz�z}t||z
|
z
|z
|z�S)aBUtility 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.

        r7rmrrirr�)r>r�rr�r�rur`rra�pir4)rdrNr��prec_Urbr�r�r^r�r�rFr��Br�ro�Es                r3r�zmultivariate_t_gen._logpdfXs���8����<�&�.�.�q�#�v�x��N�N��#�g���y�y�����V�,�-�1�1�r�1�:���2��8����A�J���C�"�H�����F�R�V�V�B����J�'�'���(�N��
�B�����R��U�d�N�*�+�+���q�1�u�q�y�1�}�q�0�1�1r5c	�`������|�t|��n|j��sd|z�|j||�}|�/tj|j
tj�n|}||z
||z
}}tj||�\}	}
|	|
k}d|jd��z}|
j�|	j�}	}
|	||
|c|
|<|	|<|j
d�tj|
|	fd��}
�����fd�}tj|d|
�|z}t|�S)Ni�r7rmc�>��|d�|�d}}t���||��dSr�r)r�r�r�r�r�r��rngr�s   �����r3r�z'multivariate_t_gen._cdf.<locals>.func1d�s2����"�1�:�v�a�b�z�q�A����U�A�q�#�6�q�9�9r5)
rr�r�r>r�r�r�r�r`r�r�r�r4)rdrNr�r�r�r�r�r�r�r�r�r�r�r�r��resr�r�s   `` `         @@r3r�zmultivariate_t_gen._cdf�s2����#�$�\�2�C��$�$�C���C�Z�F��#�#�A�s�+��%�-��w�w�s�y�y�2�6�6�'�2�3>�	��S��+��"3�;���"�"�1�k�2���1��Q����v�z�z�r�z�*�+���v�v�x�����1�� ��y�!�F�)���&�	�1�V�9�
�G�G�B�K������A��R�0��	:�	:��!�!�&�"�f�5��=���s�#�#r5�r�r�r�c
��|j|||�\}	}}}t||��j}|j|||||	|||�S)aMultivariate 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�rQrTr�)
rdrNr�r�r�rfr�r�r�r�s
          r3r�zmultivariate_t_gen.cdf�sV��B#�6�6�s�E�2�F���S�%���U�>�:�=�=���y�y��C���C��$�l�4�	4r5c�n�|tjk(rtd|��j�St	|�}d||zz}d|z}t|�t|�zd|ztj|tjz�zz|t|�t|�z
zzd|jzzS)N)r�r)
r>r�rrrQrrar�rrb)rdr�r�r�r��halfsum�half_dfs       r3rHzmultivariate_t_gen._entropy�s���
����<�&�t��7�?�?�A�A��%�[�
���r��"����(����!�!�G�G�$4�4���)�b�f�f�R�"�%�%�Z�0�0�1�3:��w�<�#�g�,�.�40�0��
�+�+�+�,�	-r5c�X�|jd||�\}}}}|j|||�S)z�Calculate the differential entropy of a multivariate
        t-distribution.

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

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

        N�r�rH)rdr�r�r�r�s     r3rzmultivariate_t_gen.entropy�s4��#�6�6�t�U�B�G���S�%���}�}�S�"�e�,�,r5c��|j|||�\}}}}|�t|�}n|j}tj|�rtj
|�}n|j
||��|z}|jtj|�||��}	||	tj|�dzz}
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]])

        r�rj)r�rr�r>�isinf�onesr�rr�r\r4)rdr�r�r�r�r�r�r�rNr��sampless           r3rzmultivariate_t_gen.rvs�s���@#�6�6�s�E�2�F���S�%���#�$�\�2�C��$�$�C�
�8�8�B�<�����
�A��
�
�b�t�
�,�r�1�A��#�#�B�H�H�S�M�5�t�#�D����B�G�G�A�J�y�1�1�1���w�'�'r5c��tj|t��}|jdk(r|tj}|S|jdk(r5|dk(r|dd�tjf}|S|tjdd�f}|Sr�r�r�s   r3r�z%multivariate_t_gen._process_quantilessy��

�J�J�q��&���6�6�Q�;��"�*�*�
�A����V�V�q�[��a�x��a����m�$�����b�j�j�!�m�$���r5c�@�|�;|�9tjdt��}tjdt��}d}n�|�Rtj|t��}|jdkrd}n|jd}tj
|�}n�|�=tj|t��}|j}tj|�}nBtj|t��}tj|t��}|j}|dk(r#|jd�}|jdd�}|jdk7s|jd|k7rtd|z��|jdk(r|tj|�z}n�|jdk(rtj|�}n�|jdk(rx|j||fk7rg|j\}}||k7r#dt|j�z}t|��d}|t|j�t|�fz}t|��|jdkDrtd|jz��|�d}n0|dkrtd	��tj|�rtd
��||||fS)z�
        Infer dimensionality from location array and shape matrix, handle
        defaults, and ensure compatible dimensions.
        rrJrr,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'.)r>rrLr0r�r�r�r�r�rYr�r�rZ�isnan)rdr�r�r�r�r�r�ris        r3r�z&multivariate_t_gen._process_parameters,s@��
�;�5�=��*�*�Q�e�,�C��J�J�q��.�E��C�
�[��J�J�u�E�2�E��z�z�A�~����k�k�!�n���(�(�3�-�C�
�]��*�*�S��.�C��(�(�C��F�F�3�K�E��J�J�u�E�2�E��*�*�S��.�C��(�(�C��!�8��+�+�a�.�C��M�M�!�Q�'�E��8�8�q�=�C�I�I�a�L�C�/��I� �!�"�
"��:�:��?��B�F�F�3�K�'�E�
�Z�Z�1�_��G�G�E�N�E�
�Z�Z�1�_�����c�
�!:����J�D�$��t�|�.�03�E�K�K�0@�A���S�/�!�>���S����-�s�3�x�8�8���S�/�!�
�Z�Z�!�^��2�49�J�J�?�@�
@��:��B�
�1�W��>�?�?�
�X�X�b�\��W�X�X��C���"�"r5rt�NrrFN)NrrFrPr�rRrQ)ryrzr{r|rkr�r�r�r�r�r�rHrrr�r�r�r�s@r3r�r��sl���P�d
6�@E��O��>!-�F)2�VEI��%$�N%4��T��%4�N
-�-�"-(�^
�:#r5r�c�B�eZdZ		d	d�Zd�Zdddd�d�Zd�Zd
d�Zd�Zy)r�Nc���t|�|_|jj|||�\}}}}||||f\|_|_|_|_t||��|_y)a�Create a frozen multivariate t distribution.

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

        Examples
        --------
        >>> import numpy as np
        >>> 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�rQr�)rdr�r�r�rfr�r�s       r3rkzmultivariate_t_frozen.__init__ks^��*(��-��
�"�j�j�<�<�S�%��L���S�%��25�s�E�2�2E�/���$�(�D�J����u�^�D��r5c	�L�|jj||j�}|jj}|jj
}|jj
||j|||j|j|jj�Srt)
r�r�r�r�r_rbr�r�r�r^)rdrNr_rbs    r3r�zmultivariate_t_frozen.logpdf�sv���J�J�)�)�!�T�X�X�6���O�O�����?�?�+�+���z�z�!�!�!�T�X�X�q�(�D�G�G�T�X�X�"&�/�/�"6�"6�8�	8r5r�c
���|jj||j�}|jj||j|j
|j|j|||�Srt)r�r�r�r�r�r�r�)rdrNr�r�r�s     r3r�zmultivariate_t_frozen.cdf�sT���J�J�)�)�!�T�X�X�6���z�z���q�$�(�(�D�J�J�������%�{�L�B�	Br5c�J�tj|j|��Srtrrs  r3r�zmultivariate_t_frozen.pdf�rr5c�~�|jj|j|j|j||��S)N)r�r�r�r�r�)r�rr�r�r�rs   r3rzmultivariate_t_frozen.rvs�s6���z�z�~�~�$�(�(�$(�J�J�!%���#'�+7�	�9�	9r5c�x�|jj|j|j|j�Srt)r�rHr�r�r�rws r3rzmultivariate_t_frozen.entropy�s'���z�z�"�"�4�8�8�T�W�W�d�j�j�A�Ar5r�r)	ryrzr{rkr�r�r�rrr.r5r3r�r�is2��?D��E�48� $��D�B�
&�9�Br5r�)r�r�rr�rz�m : 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�j��eZdZdZd�fd�	Zdd�Zd�Zd�Zd�Zd�Z	d�Z
d	�Zd
�Zd�Z
d�Zdd
�Z�xZS)�multivariate_hypergeom_genaA 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/_downloads/pdf/multi_hyper.pdf
    c�v��t�|�|�tj|jt
�|_yrt)r�rkrr�r|�mhg_docdict_paramsr�s  �r3rkz#multivariate_hypergeom_gen.__init__Br�r5c��t|||��S)z�Create a frozen multivariate_hypergeom distribution.

        See `multivariate_hypergeom_frozen` for more information.
        r)�multivariate_hypergeom_frozen)rdr�r�r�s    r3r�z#multivariate_hypergeom_gen.__call__Fs��
-�Q���=�=r5c	�$�tj|�}tj|�}|jdk(r|jt�}|jdk(r|jt�}tj
|jtj�std��tj
|jtj�std��|jdk(rtd��|jdk7r|dtjf}tj||�\}}|jdk7r|d}|dk}|jd��}|dk||kDz}|||||tj|d��|zfS)	Nrz'm' must an array of integers.z'n' must an array of integers.z1'm' must be an array with at least one dimension..rhr7rm)r>rr��astyper?�
issubdtyper;�integer�	TypeErrorr0rYr�r�r`r�)rdr�r��mcondrer.s      r3r�z.multivariate_hypergeom_gen._process_parametersMsE���J�J�q�M���J�J�q�M���6�6�Q�;�����
�A��6�6�Q�;�����
�A��}�}�Q�W�W�b�j�j�1��<�=�=��}�}�Q�W�W�b�j�j�1��<�=�=��6�6�Q�;��8�9�
9�
�6�6�Q�;��#�r�z�z�/�"�A��"�"�1�a�(���1�
�6�6�Q�;��&�	�A��A���
�E�E�r�E�N���Q��1�q�5�!���!�Q��u�b�f�f�U��&<�u�&D�D�Dr5c	���tj|�}tj|jtj�std��|jdk(rtd��|jd|jdk(s,td|jd�d|jd�d���|jdk7r*|dtjf}|dtjf}tj||||�\}}}}|jdk7r
|d	|d	}}|dk||kDz}|||||tj|d�
�|jd�
�|k7zfS)Nz'x' must an array of integers.rz1'x' must be an array with at least one dimension.r7z4Size of each quantile must be size of 'm': received z, but expected �..rhrm)r>rr�r;r�r�r0rYr�r�r�r�r�r`)rdrNrer�r�r>s      r3r�z-multivariate_hypergeom_gen._process_quantilesmsV���J�J�q�M���}�}�Q�W�W�b�j�j�1��<�=�=��6�6�Q�;��8�9�
9��w�w�r�{�a�g�g�b�k�)�� )�)*�����
�6-�-.�W�W�R�[�M��<�=�
=�

�6�6�Q�;��#�r�z�z�/�"�A��#�r�z�z�/�"�A��(�(��A�q�!�4�
��1�a��
�6�6�Q�;��V�9�a��i�q�A��Q��1�q�5�!���1�a��E����u�2�&�!�%�%�R�%�.�A�*=�>�@�	@r5c��tj|�}|jdk7r|||<n|r|S|jdk(r|dS|S)Nrr.r2r3s    r3r6z'multivariate_hypergeom_gen._checkresult�sH�����F�#���9�9��>�$�F�4�L�
����;�;�!���"�:���
r5c���tj|tj��}tj|tj��}||||}}||||}}t|dzd�t|dz||z
dz�z
||<t|dzd�t|dz||z
dz�z
||<tj||<tj||<|jd��}||z
S)NrJrr7rm)r>�
zeros_like�float_rr<r`)	rdrNrer�r��mxcondr.�num�dens	         r3r9z"multivariate_hypergeom_gen._logpmf�s����m�m�A�R�Y�Y�/���m�m�A�R�Y�Y�/���&��z�1�f�W�:�1���%��y�!�U�F�)�1���q��s�A����!��Q�q�S��U�);�;��V�G���a��c�1�~��q��s�A�a�C��E�(:�:��U�F���f�f��F���V�V��E�
��g�g�2�g����S�y�r5c�R�|j||�\}}}}}}|j||||�\}}}}}}	||z}
|tj|jtj
��z}|j
|||||
|�}|	tj|jtj
��z}|j||tj�}|tj|	jtj
��z}
|j||
tj�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
        rJ)
r�r�r>r�r�r;r9r6r�r<)rdrNr�r�rer�r.�mncondr>�
xcond_reducedrr4r?�mncond_s              r3rAz!multivariate_hypergeom_gen.logpmf�s���$)-�(@�(@��A�(F�%��1�a���v��1�1�!�Q��1�=�	��A�q�!�U�	���������������9�9�����a��A�q�&�%�8������&�,�,�b�h�h�!G�G���"�"�6�6�B�F�F�7�;���2�8�8�M�$7�$7�r�x�x�H�H��� � ���"�&�&�9�9r5c�R�tj|j|||��}|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
        rC)rdrNr�r�r2s     r3rDzmultivariate_hypergeom_gen.pmf�s$��$�f�f�T�[�[��A�q�)�*���
r5c���|j||�\}}}}}}|jdk7r*|dtjf|dtjf}}|dk(}tjj||��}|||zz}|jdk7rE|dtjftj|jtj��z}|j||tj�S)z�Mean of the multivariate hypergeometric distribution.

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

        Returns
        -------
        mean : array_like or scalar
            The mean of the distribution
        r.��maskrJ�r�r�r>r��ma�masked_arrayr�r�r;r6r<)rdr�r�rerJr	rD�mus        r3r�zmultivariate_hypergeom_gen.mean�s���!%� 8� 8��A� >���1�a��A�v��6�6�Q�;��S�"�*�*�_�%�q��b�j�j��'9�q�A��Q����E�E���q�t��,��
��!��W���6�6�Q�;��S�"�*�*�_�-��h�h�r�x�x�r�x�x�8�9�F�� � ��V�R�V�V�4�4r5c�(�|j||�\}}}}}}|jdk7r*|dtjf|dtjf}}|dk(|dz
dk(z}tjj||��}||z|z||z
z|z||z
z|dz
z}|jdk7rE|dtjftj|jtj��z}|j||tj�S)aQVariance 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.rrrJr)rdr�r�rerJr	rD�outputs        r3r|zmultivariate_hypergeom_gen.var�s���!%� 8� 8��A� >���1�a��A�v��6�6�Q�;��S�"�*�*�_�%�q��b�j�j��'9�q�A��Q��1�Q�3�!�8�$���E�E���q�t��,���Q��q��A�a�C���"�a��c�*�A�a�C�0���6�6�Q�;��S�"�*�*�_�-��h�h�v�|�|�2�8�8�<�=�F�� � ������8�8r5c��|j||�\}}}}}}|jdk7rH|dtjtjf}|dtjtjf}|dk(|dz
dk(z}tjj||��}|||z
z|dz
ztjd||�z|dzz}|jdk7r|d|d}}|d}|jd}t|�D]K}	|||z
z|d|	fz||d|	fz
z|d|	|	f<|d|	|	f|dz
z|d|	|	f<|d|	|	f|dzz|d|	|	f<�M|jdk7rT|dtjtjftj|jtj�	�z}|j||tj�S)
aCovariance matrix of the multivariate hypergeometric distribution.

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

        Returns
        -------
        cov : array_like
            The covariance matrix of the distribution
        r.rrz...i,...j->...ijr,).rrr7rJ)
r�r�r>r�rrrCr�r�r�r;r6r<)
rdr�r�rerJr	rDrr�r�s
          r3r�zmultivariate_hypergeom_gen.cov
s���!%� 8� 8��A� >���1�a��A�v��6�6�Q�;��#�r�z�z�2�:�:�-�.�A��#�r�z�z�2�:�:�-�.�A��Q��1�Q�3�!�8�$���E�E���q�t��,���"��!��*�a��c�"��)�)�.��1�5�6�9:�A��?��
�6�6�Q�;��Y�<��9��q�A��	�?�D��g�g�b�k���s��	;�A�!"�a��c��Q�s�A�v�Y�!6��!�C��F�)��!D�F�3��1�9�� &�s�A�q�y� 1�Q�q�S� 9�F�3��1�9�� &�s�A�q�y� 1�Q��T� :�F�3��1�9��	;�
�6�6�Q�;��S�"�*�*�b�j�j�8�9��h�h�v�|�|�2�8�8�<�=�F�� � ������8�8r5c�:�|j||�\}}}}}}|j|�}|�t|t�r|f}|�,t	j
|j|j��}n2t	j
||jdfz|j��}|}t|jddz
�D]D}	||d|	fz
}|dk(}
|
|j|d|	f||
z||
z|��z|d|	f<||d|	fz
}�F||d|jddz
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.
        rJr7r.rr�)
r�r�r�r?r>r�r�r;r��hypergeometric)rdr�r�r�r�rerJr�remr��n0masks           r3rzmultivariate_hypergeom_gen.rvs0sC��0 �3�3�A�q�9���1�a��A�q��-�-�l�;����
�4�� 5��8�D��<��(�(�1�7�7�!�'�'�2�C��(�(�4�1�7�7�2�;�/�1����A�C����q�w�w�r�{�Q��'�	 �A���#�q�&�	�/�C��!�V�F�"�7�'�6�6�q��a��y�7:�V�|�78�6�z�<@�7�B�B�C��Q��K�
�C��Q��K��A�	 �%&��C������q�� �!��
r5rtrM)ryrzr{r|rkr�r�r�r6r9rArDr�r|r�rr�r�s@r3r�r��sL���o�`J�>�E�@@�6��":�H�*5�09�2$9�L2r5r�c�:�eZdZd	d�Zd�Zd�Zd�Zd�Zd�Zd
d�Z	y)r�Nc����t|��_�jj||�\�_�_�_�_�_�_�fd�}|�j_y)Nc����j�j�j�j�j�j
fSrt)rer�r�r�r.r	)r�r�rds  �r3r�zCmultivariate_hypergeom_frozen.__init__.<locals>._process_parametersps4����F�F�D�F�F�D�F�F��J�J��
�
��K�K�!�
!r5)	r�r�r�rer�r�r�r.r	)rdr�r�r�r�s`    r3rkz&multivariate_hypergeom_frozen.__init__isW���/��5��
��
�
�6�6�q�!�<�	�������	
��T�Z�	
��	!�*=��
�
�&r5c�d�|jj||j|j�Srt)r�rAr�r�rs  r3rAz$multivariate_hypergeom_frozen.logpmfvrRr5c�d�|jj||j|j�Srt)r�rDr�r�rs  r3rDz!multivariate_hypergeom_frozen.pmfyrTr5c�b�|jj|j|j�Srt)r�r�r�r�rws r3r�z"multivariate_hypergeom_frozen.mean|rVr5c�b�|jj|j|j�Srt)r�r|r�r�rws r3r|z!multivariate_hypergeom_frozen.varrXr5c�b�|jj|j|j�Srt)r�r�r�r�rws r3r�z!multivariate_hypergeom_frozen.cov�rXr5c�h�|jj|j|j||��S)Nr�)r�rr�r�rs   r3rz!multivariate_hypergeom_frozen.rvs�s.���z�z�~�~�d�f�f�d�f�f�#'�+7��9�	9r5rtr)
ryrzr{rkrArDr�r|r�rr.r5r3r�r�hs%��=�4�1�/�.�.�9r5r�)rArDr�r|r�rc���eZdZdZd�fd�	Zdd�d�Zd�Zd�Zd�Zdddd	�d
�Z	e
d��Ze
d��Ze
d
��Ze
d��Ze
d��Ze
d��Z�xZS)�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�$��t�|�|�yrt�r�rkr�s  �r3rkzrandom_table_gen.__init__�����
����r5rc��t|||��S)z~Create a frozen distribution of tables with given marginals.

        See `random_table_frozen` for more information.
        r)�random_table_frozen)rd�row�colr�s    r3r�zrandom_table_gen.__call__�s��
#�3��$�7�7r5c��|j||�\}}}tj|�}|jdkrt	d��tj
|jtj�}tjd��5|s6tj|jt�|k(�st	d��ddd�tj|dk�rt	d��tj|d	�
�}tj|d�
�}	|jd	t|�k7rt	d��|	jd	t|�k7rt	d
��tj |jdd�}
tj||k(d	�
�tj|	|k(d	�
�z}d�}tj||�d	�
�tj||�d	�
�z||�z
tj|||�d�
�z
|
|<tj"|
|<|
dS#1swY���xYw)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 valuesNrz)`x` must contain only non-negative valuesr7rmr-z"shape of `x` must agree with `row`z"shape of `x` must agree with `col`c��t|dz�Sr)r)rNs r3�lnfacz&random_table_gen.logpmf.<locals>.lnfac%s���1�q�5�>�!r5)r7r-r.)r�r>rr0rYr�r;r��errstate�allr�r?r�r`r�rZr�r�)
rdrNr+r,r�r�r��dtype_is_int�r2�c2r�rr1s
             r3rAzrandom_table_gen.logpmf�s���L�*�*�3��4���1�a��J�J�q�M���6�6�A�:��C�D�D��}�}�Q�W�W�b�j�j�9��
�[�[��
*�	J�����q�x�x��}��/A�(B� �!H�I�I�	J�
�6�6�!�a�%�=��H�I�I�
�V�V�A�B�
��
�V�V�A�B�
��
�8�8�B�<�3�q�6�!��A�B�B�
�8�8�B�<�3�q�6�!��A�B�B��h�h�q�w�w�s��|�$���v�v�b�A�g�B�'�"�&�&��q��r�*B�B��	"��V�V�E�!�H�2�.�����a��r�1J�J��Q�x� �"$�&�&��q��w��h�"G�H��D�	��f�f�W��T�E�
��2�w��9	J�	J�s�
9I�Ic�N�tj|j|||��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
        rC)rdrNr+r,s    r3rDzrandom_table_gen.pmf.s!��L�v�v�d�k�k�!�S�#�.�/�/r5c�`�|j||�\}}}tj||�|zS)aAMean 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�r>r�)rdr+r,r�r�r�s      r3r�zrandom_table_gen.meanVs1��>�*�*�3��4���1�a��x�x��1�~��!�!r5�r��methodr�c���|j||�\}}}|j|||�\}}	|j|�}|j||||�}
|
|||||�j	|	�S)agDraw 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�)rdr+r,r�r:r�r�r�r�r��meths           r3rzrandom_table_gen.rvsxsy��P�*�*�3��4���1�a��.�.�t�Q��:���e��-�-�l�;���'�'���1�a�8���A�q�!�T�<�0�8�8��?�?r5c��tj|tjd��}tj|tjd��}tj|�dk7rt	d��tj|�dk7rt	d��tj
|dk�rt	d��tj
|dk�rt	d��tj|�}|tj|�k7rt	d	��tj|tj|�k(�st	d
��tj|tj|�k(�st	d��|||fS)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(rz`row` must be one-dimensionalz`col` must be one-dimensionalrz*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)	r>rK�int64r0rYr�r`r3r)r+r,r�r�r�s     r3r�z$random_table_gen._process_parameters�s��
�H�H�S����t�4���H�H�S����t�4��
�7�7�1�:��?��<�=�=�
�7�7�1�:��?��<�=�=�
�6�6�!�a�%�=��I�J�J�
�6�6�!�a�%�=��I�J�J��F�F�1�I������q�	�>��F�G�G��v�v�a�2�:�:�c�?�*�+��G�H�H��v�v�a�2�:�:�c�?�*�+��G�H�H��!�Q�w�r5c�L�t|�t|�f}|�d|fStj|�}tj|jtj
�rtj|dk�rtd��tj|�t|�|zfS)zW
        Compute the number of samples to be drawn and the shape of the output
        rrz/`size` must be a non-negative integer or `None`)
rZr>�
atleast_1dr�r;r�r�rYr�r�)r�r�r�r�s    r3r<z$random_table_gen._process_size_shape�s��
�Q���Q�� ���<��e�8�O��}�}�T�"���}�}�T�Z�Z����4����t�a�x�8H��N�O�O��w�w�t�}�e�D�k�E�1�1�1r5c	��|j|||�|j|jd�}	||S#t$rt	d|�dt|�����wxYw)N)N�boyett�	patefield�'z!' not recognized, must be one of )�_rvs_select�_rvs_boyett�_rvs_patefield�KeyErrorrY�set)�clsr:r�r�r��
known_methodss      r3r=z$random_table_gen._process_rvs_method�sx���/�/�!�Q��*��o�o��+�+�
�
�
	E� ��(�(���	E��q���)/�/2�=�/A�.B�D�E�
E�	E�s	�2�$Ac��d}t|�t|�z}||tj|dz�z|zkDr|jS|jS)Nr�r)rZr>rarIrH)rLr�r�r��facr�s      r3rGzrandom_table_gen._rvs_select�sL������F�S��V�O���s�R�V�V�A��E�]�"�Q�&�&��%�%�%����r5c�4�tj|||||�Srt)r�
rvs_rcont1�r+r,�ntotr�r�s     r3rHzrandom_table_gen._rvs_boyett����� � ��c�4��|�D�Dr5c�4�tj|||||�Srt)r�
rvs_rcont2rRs     r3rIzrandom_table_gen._rvs_patefield�rTr5rt)ryrzr{r|rkr�rArDr�r�staticmethodr�r<�classmethodr=rGrHrIr�r�s@r3r%r%�s����@�D�*.�8�I�V&0�P "�D%)��D�.@�`����<�
2��
2��
E��
E������E��E��E��Er5r%c�2�eZdZdd�d�Zd�Zd�Zd�Zdd�Zy)	r*Nrc���t|��_�jj||��_�fd�}|�j_y)Nc����jSrt)�_params)r�r�rds  �r3r�z9random_table_frozen.__init__.<locals>._process_parameters�s
����<�<�r5)r%r�r�r\)rdr+r,r�r�s`    r3rkzrandom_table_frozen.__init__�s8���%�d�+��
��z�z�5�5�c�3�?���	 �)<��
�
�&r5c�<�|jj|dd�Srt)r�rArs  r3rAzrandom_table_frozen.logpmfs���z�z� � ��D�$�/�/r5c�<�|jj|dd�Srt)r�rDrs  r3rDzrandom_table_frozen.pmfs���z�z�~�~�a��t�,�,r5c�:�|jjdd�Srt)r�r�rws r3r�zrandom_table_frozen.mean	s���z�z���t�T�*�*r5c�B�|jjdd|||��S)Nr9)r�r)rdr�r:r�s    r3rzrandom_table_frozen.rvss'���z�z�~�~�d�D�t�F�+7��9�	9r5r�)ryrzr{rkrArDr�rr.r5r3r*r*�s��)-�=�0�-�+�9r5r*zprow : array_like
    Sum of table entries in each row.
col : array_like
    Sum of table entries in each column.z�x : array-like
   Two-dimensional table of non-negative integers, or a
   multi-dimensional array with the last two dimensions
   corresponding with the tables.z�The 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_col�_doc_x�_doc_mean_params�_doc_row_col_note)rarcrdc�V�tj|xs|j|�|_yrt)rr�r|)�obj�docdict�templates   r3�_docfillri;s���"�"�8�#:�s�{�{�G�D�C�Kr5)rArDr�rc�:��eZdZdZd�fd�	Zdd�Zd�Zdd�Z�xZS)�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]])
    c�l��t�|�|�tj|j�|_yrtr^r�s  �r3rkzuniform_direction_gen.__init__�r_r5c��t||��S)z}Create a frozen n-dimensional uniform direction distribution.

        See `uniform_direction` for more information.
        r)�uniform_direction_frozenrbs   r3r�zuniform_direction_gen.__call__�s��
(��$�7�7r5c��|�(tj|�r|dks|t|�k7rtd��t|�S)rdrzMDimension of vector must be specified, and must be an integer greater than 0.rerfs  r3r�z)uniform_direction_gen._process_parameters�sB���;�b�k�k�#�.�#��'�S�C��H�_��F�G�
G��3�x�r5c���|j|�}|�tjgt��}tj|�}|j|�}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

        rJ)r�r>rKr?rBr��_sample_uniform_direction)rdr�r�r�r�s     r3rzuniform_direction_gen.rvs�sZ��>�-�-�l�;���<��8�8�B�c�*�D��}�}�T�"���&�&�s�+��+�C��|�D���r5rtrMrtr�s@r3rkrkIs���?�B6�8��'r5rkc��eZdZdd�Zdd�Zy)rnNc�d�t|�|_|jj|�|_y)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)rkr�r�r�rbs   r3rkz!uniform_direction_frozen.__init__�s&��0+�4�0��
��:�:�1�1�#�6��r5c�P�|jj|j||�Srtrxrs   r3rzuniform_direction_frozen.rvs�ryr5rMrzr.r5r3rnrn�s��7�6<r5rnc��tj||�}|j|�}|tjj	|dd��z}|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.
    r7T)rn�keepdims)r>r`rArVro)r�r�r��
samples_shaper�s     r3rqrq�sF���I�I�d�C�(�M��*�*�=�9�G��r�y�y�~�~�g�B��~�>�>�G��Nr5a"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���tj|�}tj|�}|�l	tj||�\}}tj|�}tj
|dk�stj
||k7�rtd��|}tj
|dk�rtd��tj|�}tj
|dk�stj
||k7�rtd��|}tj|d��}tj||�\}}|�|||fS||||fS#t$r}d}t|�|�d}~wwxYw)Nz&`x` and `alpha` must be broadcastable.rz,`x` must contain only non-negative integers.z*`alpha` must contain only positive values.z`n` must be a positive integer.r7rm)r>rr�rY�floorr�r`)r]r�rNr�ri�x_int�n_int�	sum_alphas        r3�'_dirichlet_multinomial_check_parametersr~s;���J�J�u��E�
�
�
�1�
�A��}�	)��*�*�1�e�4�H�A�u�
������
�6�6�!�a�%�=�B�F�F�1��:�.��K�L�L���	�v�v�e�q�j���E�F�F��H�H�Q�K�E�	�v�v�a�1�f�~�����U�
�+��:�;�;�
�A����u�2�&�I��&�&�y�!�4�L�I�q�$%�I�E�9�a� �K�E�9�a��3K�K��)�	)�:�C��S�/�q�(��	)�s�E�	E'�E"�"E'c�J��eZdZdZd	�fd�	Zd	d�Zd�Zd�Zd�Zd�Z	d�Z
�xZS)
�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)

    c�v��t�|�|�tj|jt
�|_yrt)r�rkrr�r|�dirichlet_mn_docdict_paramsr�s  �r3rkz"dirichlet_multinomial_gen.__init__�s,���
������'�'����(C�E��r5c��t|||��Srp)�dirichlet_multinomial_frozen)rdr]r�r�s    r3r�z"dirichlet_multinomial_gen.__call__�s��+�E�1�4�@�@r5c��t|||�\}}}}tjt|�t|dz�zt||z�z
�}|t||z�t|�t|dz�zz
j	d��z
}tj
|||j	d��k7tj�|dS)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.

        rr7rmr.)r~r>rrr`�placer�)rdrNr]r�r��Sar2s       r3rAz dirichlet_multinomial_gen.logpmf�s���$>�e�Q��J���2�q�!��j�j��"����Q���7�(�1�r�6�:J�J�K�����Q���8�A�;��!�a�%��#@�A�F�F�B�F�O�O��
����a�1�5�5�b�5�>�)�B�F�F�7�3��2�w�r5c�N�tj|j|||��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.

        rC)rdrNr]r�s    r3rDzdirichlet_multinomial_gen.pmf�s ��"�v�v�d�k�k�!�U�A�.�/�/r5c��t||�\}}}|dtjf|dtjf}}||z|zS)z�Mean of a Dirichlet multinomial distribution.

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

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

        .�r~r>r��rdr]r�r�r�s     r3r�zdirichlet_multinomial_gen.mean�sG��;�5�!�D���2�q��#�r�z�z�/�"�B�s�B�J�J��$7�2���1�u�r�z�r5c��t||�\}}}|dtjf|dtjf}}||z|zd||zz
z||zzd|zzS)abThe 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.

        .rr�r�s     r3r|zdirichlet_multinomial_gen.var�sf��;�5�!�D���2�q��#�r�z�z�/�"�B�s�B�J�J��$7�2���1�u�r�z�Q��2��X�&�!�b�&�1�Q��V�<�<r5c���t||�\}}}tj||�}|dtjtjf|dtjtjf}}|ddd�tjf|dtjdd�fz}||z|dzz||zzd|zz}tj
|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,rr7)r~rr|r>r��aranger�)	rdr]r�r�r�r|�aiajr��iis	         r3r�zdirichlet_multinomial_gen.cov�s���;�5�!�D���2�q�#�'�'��1�-���#�r�z�z�2�:�:�-�.��3��
�
�B�J�J�3N�0O�2����a����#�$�q��b�j�j�!�);�'<�<���b�4�i�"��'�!�Q��V�,��B��7��
�Y�Y�s�y�y��}�
%����C��R�K���
r5rt)ryrzr{r|rkr�rArDr�r|r�r�r�s@r3r�r�1s/���i�TE�
A��20�&�"=�$r5r�c�2�eZdZdd�Zd�Zd�Zd�Zd�Zd�Zy)	r�Nc�`�t||�\}}}||_||_t|�|_yrt)r~r]r�r�r�)rdr]r�r�r�s     r3rkz%dirichlet_multinomial_frozen.__init__s.��>�u�a�H���r�1���
����.�t�4��
r5c�d�|jj||j|j�Srt)r�rAr]r�rs  r3rAz#dirichlet_multinomial_frozen.logpmfs#���z�z� � ��D�J�J����7�7r5c�d�|jj||j|j�Srt)r�rDr]r�rs  r3rDz dirichlet_multinomial_frozen.pmfs!���z�z�~�~�a����T�V�V�4�4r5c�b�|jj|j|j�Srt)r�r�r]r�rws r3r�z!dirichlet_multinomial_frozen.means���z�z���t�z�z�4�6�6�2�2r5c�b�|jj|j|j�Srt)r�r|r]r�rws r3r|z dirichlet_multinomial_frozen.var����z�z�~�~�d�j�j�$�&�&�1�1r5c�b�|jj|j|j�Srt)r�r�r]r�rws r3r�z dirichlet_multinomial_frozen.cov"r�r5rt)	ryrzr{rkrArDr�r|r�r.r5r3r�r�s ��5�8�5�3�2�2r5r�)rArDr�r|r�c���eZdZdZd�fd�	Zdd�Zd�Zd�Zd�Zd�Z	dd�Z
dd	�Zd
�Zd�Z
d�Zd
�Zd�Zdd�Zd�Zdd�Zd�Z�xZS)�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 dimenions 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.

    c�$��t�|�|�yrtr'r�s  �r3rkzvonmises_fisher_gen.__init__r(r5c��t|||��S)zsCreate a frozen von Mises-Fisher distribution.

        See `vonmises_fisher_frozen` for more information.
        r)�vonmises_fisher_frozen�rdr�kappar�s    r3r�zvonmises_fisher_gen.__call__s��
&�b�%�d�;�;r5c��tj|�}|jdkDrtd��tjtj
j
|�d�std��|jdkDstd��d}tj|�r|dkrt|��t|�dk(rtd	��|j}|||fS)
z~
        Infer dimensionality from mu and ensure that mu is a one-dimensional
        unit vector and kappa positive.
        rz%'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.rr�z�For 'kappa=0' the von Mises-Fisher distribution becomes the uniform distribution on the sphere surface. Consider using 'scipy.stats.uniform_direction' instead.)
r>rr0rY�allcloserVror�r�rL)rdrr��kappa_error_msgr�s     r3r�z'vonmises_fisher_gen._process_parameterss���
�Z�Z��^��
�7�7�Q�;��D�E�E��{�{�2�9�9�>�>�"�-�r�2��D�E�E��w�w��{��C�D�D�>���{�{�5�!�U�Q�Y��_�-�-���<�2���H�I�
I��g�g���B��~�r5c���|jd|k7rtd��tjtjj|d��d�s
d}t|��y)Nr7znThe dimensionality of the last axis of 'x' must match the dimensionality of the von Mises Fisher distribution.rmr��8'x' must be unit vectors of norm 1 along last dimension.)r�rYr>r�rVro)rdrNr�ris    r3�_check_data_vs_distz'vonmises_fisher_gen._check_data_vs_dist&sY���7�7�2�;�#���>�?�
?��{�{�2�9�9�>�>�!�"�>�5�r�:�L�C��S�/�!�;r5c��d|z}d|dz
ztj|�z|tzz
tjt|dz
|��z
|z
S)Nrr,r)r>rar�r
�rdr�r��halfdims    r3�_log_norm_factorz$vonmises_fisher_gen._log_norm_factor/sX����)���s�Q�w�����u�
�-��(�0B�B����s�7�Q�;��.�/�0�27�8�	9r5c��tj|�}|j||�tjd||�}|j	||�||zzS)z�Log of the von Mises-Fisher probability density function.

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

        zi,...i->...)r>rr�rCr�)rdrNr�rr��dotproductss      r3r�zvonmises_fisher_gen._logpdf=sP��
�J�J�q�M��� � ��C�(��i�i�
�r�1�5���$�$�S�%�0�5�;�3F�F�Fr5c�V�|j||�\}}}|j||||�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��rdrNrr�r�s     r3r�zvonmises_fisher_gen.logpdfIs1��*�1�1�"�e�<���R���|�|�A�s�B��.�.r5c�|�|j||�\}}}tj|j||||��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�r>r�r�r�s     r3r�zvonmises_fisher_gen.pdfas:��*�1�1�"�e�<���R���v�v�d�l�l�1�c�2�u�5�6�6r5c���tj|d|d�}|j|||��}tjtj|�tj
|�gd��}|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.

        rrr�r7rm)r>�arctan2�vonmises�stack�cos�sin)rdrr�r�r��
mean_angle�
angle_samplesr�s        r3�_rvs_2dzvonmises_fisher_gen._rvs_2dysb���Z�Z��1��r�!�u�-�
�$�-�-�j�%�d�-�K�
��(�(�B�F�F�=�1�2�6�6�-�3H�I� "�$���r5c	��|�d}n|}|j|�}dtj|d|z
tjd|z�zz�|zz}tjdtj
|�z
�}t
d||�}tj|||dz||dzgd��}|�tj|�}|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

        rr�r-r,rh).rr7rm)	�randomr>rar�r\r�rqr�r/)	rdr�r�r��sample_sizerN�temp�
uniformcircler�s	         r3�_rvs_3dzvonmises_fisher_gen._rvs_3d�s����<��K��K�
����,�������R�!�V�r�v�v�b�5�j�'9�9�9�:�5�@�@���w�w�r�B�I�I�a�L�(�)��1�!�[�,�O�
��(�(�A�t�m�F�&;�;� �=��#8�8�:� "�$���<��j�j��)�G��r5c�x�|dz
}|�.tj|�s|f}tj|�}nd}tjd|dzz|dzz�}d|z|z|z}|dk(r|dz|dzz|dzd	z|d
zzz
}d|z
d|zz}	||	z|tj
d�tj
|�zdtj|�zz
zz}
d}tj|f�}d|z}
||kr�|j|
|
||z
�
�}dd|z|zz
dd|z
|zz
z}|j||z
�}||z|tj
d|z|z
||zzd|zz�zz|
z
tj
|�kD}tj|�}||||||z||z
}||kr��t|||�}tjdtjd|dzz
�|�}tj|d|gd��}|�|j||fz�}|Stj|�}|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�rir,r-rg�r��@g�r�rr�z...,...i->...irjrm)r>r�r�r�r\ra�log1pr��betar�r`rqrCr�r�r/)rdr�r�r�r��
dim_minus_one�	n_samplesr\�
envelop_param�node�
correction�
n_acceptedrNr��sym_beta�coord_x�
accept_tol�	criterion�
accepted_iter�
coord_restr�s                     r3�_rejection_samplingz'vonmises_fisher_gen._rejection_sampling�s����a��
����;�;�t�$��x���	�	�$��I��I��w�w�q�5�B�;���!�);�;�<���e��d�*�m�;�
��A��+�1�_�u�c�z�9�,�a�/��2�U�C�Z�?�@�M��]�"�r�M�'9�:���d�l�]������R�V�V�M�%:�:��B�H�H�]�3�3�4�&5�5�
��
��H�H�i�]�#���
�%���9�$�#�(�(��'�.7�*�.D�)�F�H��A�
�-��9�9��Q��&�(�2�2�4�G�&�,�,�Y��-C�D�J�����2�6�6�1�}�+<�w�+F��M�)�,*�./�-�.?�+A�$B�C�C���!#���z� 2�	3�I�
�F�F�9�-�M�7>�y�7I�A�j��m�3�4��-�'�J�%�9�$�(/�}�j�/;�=�
��Y�Y��b�g�g�a�!�q�&�j�1�:�?�
��.�.�!�I�,�
�!;�!�D�����o�o�d�c�W�n�5�G����j�j��)�G��r5c��tj|f�}d|d<tj|ddd�ftj|dz
|f�g�}tjj	tj
|��\}}tjtj||dd�df�dd�df|�rd}nd}tjd||�|z}|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�rNrr7z
ij,...j->...i)	r>r�r�rVr�rBr�rkrC)	rdr�rr��
base_point�embedded�	rotmatrixrJ�rotsigns	         r3�_rotate_samplesz#vonmises_fisher_gen._rotate_samples�s��� �X�X�s�g�&�
��
�1�
��>�>�2�d�A�g�;����#��'�3��0H�"I�J���y�y�|�|�B�L�L��$:�;��	�1�
�;�;�r�y�y��J�q�$�w�,?�@��A��F��K��G��G��)�)�O�Y��@�7�J���r5c���|dk(r|j||||�}n-|dk(r|j|||�}n|j||||�}|dk7r|j|||�}|S)Nr,r�)r�r�r�r�)rdr�rr�r�r�r�s       r3r�zvonmises_fisher_gen._rvs
sq���!�8��l�l�2�u�d�L�A�G�
�A�X��l�l�5�$��=�G��.�.�s�E�4�/;�=�G��!�8��*�*�7�B��<�G��r5c�~�|j||�\}}}|j|�}|j|||||�}|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�r�)rdrr�r�r�r�r�s       r3rzvonmises_fisher_gen.rvssH��B�1�1�"�e�<���R���-�-�l�;���)�)�C��U�D�,�?���r5c�r�d|z}|j||�|t||�zt|dz
|�zz
SrL)r�r
r�s    r3rHzvonmises_fisher_gen._entropy=sL����)���&�&�s�E�2�2�U��G�U�#�6$�&)�'�A�+�u�&=�6>�>�	?r5c�R�|j||�\}}}|j||�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�)rdrr�r�rJs     r3rzvonmises_fisher_gen.entropyBs-��$�0�0��U�;�
��Q���}�}�S�%�(�(r5c��	�
�tj|�}|jdk7rtd��tjtj
j
|d��d�s
d}t|��|jd}t|�}|j}|j�
d|z�	�	�
fd�}t|d	d
��}|j}||fS)aFit 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.r7rmr�r�rc�B��t��dz
g|�}|d|dz�z
S)Nrr)r
)r��bessel_valsr�r�s  ��r3�solve_for_kappaz0vonmises_fisher_gen.fit.<locals>.solve_for_kappas0����w��!��4�e�<�K��q�>�+�a�.�0�1�4�4r5�brentq)g:�0�yE>ge��A)r:�bracket)
r>rr0rYr�rVror�r�mean_direction�mean_resultant_lengthr�root)rdrNrir��dirstatsrr��root_resr�r�r�s         @@r3�fitzvonmises_fisher_gen.fitWs����(
�J�J�q�M���6�6�Q�;��;�<�<��{�{�2�9�9�>�>�!�"�>�5�r�:�L�C��S�/�!��g�g�b�k��%�Q�'��
�
$�
$���*�*����)��	5���x�'2�4���
�
���5�y�r5rt�NrNrr)ryrzr{r|rkr�r�r�r�r�r�r�r�r�r�r�r�rrHrr�r�r�s@r3r�r�1sc���Q�d�<��0"�9�
G�/�07�0��<F�P�:�$�L?�
)�*/r5r�c�.�eZdZdd�Zd�Zd�Zdd�Zd�Zy)	r�Nc��t|�|_|jj||�\|_|_|_y)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�rr�r�s    r3rkzvonmises_fisher_frozen.__init__�s5��&)��.��
��J�J�*�*�2�u�5�	&���$�'�4�:r5c�z�|jj||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�rr�rs  r3r�zvonmises_fisher_frozen.logpdf�s+���z�z�!�!�!�T�X�X�t�w�w��
�
�C�Cr5c�J�tj|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
        -------
        pdf : ndarray or scalar
            Probability density function evaluated at `x`.

        rrs  r3r�zvonmises_fisher_frozen.pdf�s���v�v�d�k�k�!�n�%�%r5c��|jj|�}|jj|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�r�r�rr�rs   r3rzvonmises_fisher_frozen.rvs�sD��6�z�z�3�3�L�A���z�z���t�x�x����$�*�*�d�+�-�	-r5c�b�|jj|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�rHr�r�rws r3rzvonmises_fisher_frozen.entropy�s#���z�z�"�"�4�8�8�T�Z�Z�8�8r5r�r)ryrzr{rkr�r�rrr.r5r3r�r��s��
�0D�"&�"-�>9r5r�rM)rrrt)�r��numpyr>rr�	numpy.libr�scipy.linalgrU�
scipy._libr�
scipy.specialrrr	r
rrr
r�scipy._lib._utilr�scipy.linalg.blasr�scipy.linalg._miscr�scipy.linalg.lapackr�_discrete_distnsrr�rrr�_qmvntr�
_morestatsr�scipy.optimizer�__all__rar�r�r��_LOG_PIr�r4rHrOrQrr�r�r��_mvn_doc_frozen_callparams�_mvn_doc_frozen_callparams_noter��mvn_docdict_noparamsr�rr��name�__dict__r:�
method_frozenr�r|rr�_matnorm_doc_frozen_callparams�#_matnorm_doc_frozen_callparams_noter�matnorm_docdict_noparamsrrr rY� _dirichlet_doc_frozen_callparams�%_dirichlet_doc_frozen_callparams_notern�dirichlet_docdict_noparamsr^rhrjrlrrq�_wishart_doc_default_callparams�_wishart_doc_callparams_note�_wishart_doc_frozen_callparams�#_wishart_doc_frozen_callparams_noter��wishart_docdict_noparamsr�r r�r�rr!r�#_multinomial_doc_default_callparams� _multinomial_doc_callparams_note�"_multinomial_doc_frozen_callparams�'_multinomial_doc_frozen_callparams_noter$�multinomial_docdict_noparamsr"r"r&r\r#rar}r$r�r�r%r�r�r&r�r�r��_mvt_doc_frozen_callparams_noter��mvt_docdict_noparamsr�r�r'�_mhg_doc_default_callparams�_mhg_doc_callparams_note�_mhg_doc_frozen_callparams�_mhg_doc_frozen_callparams_noter��mhg_docdict_noparamsr�r(r�r%r)r*�_ctab_doc_row_col�_ctab_doc_x�_ctab_doc_row_col_note�_ctab_doc_mean_params�_ctab_doc_row_col_note_frozen�
_ctab_docdictr��_ctab_docdict_frozen�updaterirkr*rnrqrx�#_dirichlet_mn_doc_frozen_callparams�(_dirichlet_mn_doc_frozen_callparams_noter��dirichlet_mn_docdict_noparamsr~r�rr�r�r+r�r.r5r3�<module>r$s3
����,�"���*�*�*�/�"�*�0�#�'�'��)�&���"�2�6�6�!�b�e�e�)���	�������
�"�&�&����-��	����DK�&U�U�p&�&�D<�<����� ��#B��$?� 8�*���$>� ?�*���oN�.�oN�d.�/��b8��b8�N
6�J�D�
$�
-�
-�d�
3�F�.�7�7��=�M�,�F�,�,�V�^�^�-A�C�M��%�V�%�%�f�n�n�6H�I�F�N�J�#��
 ��"$��'B�#�(G�$@�*���(F�$G�*���`*�(�`*�F"�#�
�69�?�69�v
0�N�D�
�
'�
'��
-�F�(�1�1�$�7�M�,�F�,�,�V�^�^�-E�G�M��%�V�%�%�f�n�n�6L�M�F�N�N�%�!�
$&� �)B�%�*K�*���*J�*����)
�X;�*A8�$�A8�H
�O�	�>��>�4
?�P�D�
�
#�
#�D�
)�F�$�-�-�d�3�M�,�F�,�,����2�4�M��%�V�%�%�f�n�n�6N�O�F�N�P�#�� "��!#��'B�#� ?�8�*��� >�?�*���b	 �"�b	 �J�-��5J�_�5J�t
G�N�D�
�
!�
!�$�
'�F�"�+�+�D�1�M�,�F�,�,����0�2�M��%�V�%�%�f�n�n�6L�M�F�N�N�<�~m5�[�m5�`
�
�
�@J��@J�J
<�N�D�
�
$�
$�T�
*�F�"�+�+�D�1�M�,�F�,�,����0�2�M��%�V�%�%�f�n�n�6L�M�F�N�N�'�#�$� �&(�"�+B�'� C�<�*��� B�C�*� ��G4�&�G4�T
���+B��+B�`
4�B�D�
�
%�
%�d�
+�F�&�/�/��5�M�,�F�,�,����4�6�M��%�V�%�%�f�n�n�&@�B�F�N�B�^�.�^�B.�/��<��<�<x�&�x�v���<��<�<Y�-�Y�x,�-��)D��)D�Xq�(�q�h"�#�
�<�?�<�<
����#B��$?� 8�*���$&� ?�*���|#�)�|#�~
3B�O�3B�l$�%��

7�J�D�
�
(�
(��
.�F�)�2�2�4�8�M�,�F�,�,�V�^�^�-A�C�M��%�V�%�%�f�n�n�6H�I�F�N�J����� ��#B�� ;�4�*��� :�;�*���Q�!1�Q�h4�5�� 9�O� 9�J
;�:�D�
'�
0�
0��
6�F�1�:�:�4�@�M�,�F�,�,����,�.�M��%�V�%�%�f�n�n�&8�:�F�N�:�]E�'�]E�@ �!��9�/�9�2,��%����
�����
!B��+�%��-�/��
�%�)�)�+�������6���E�	�	�=�)�,�$�D�
�
&�
&�t�
,�F�'�0�0��6�M��]�0�&�.�.�A��V�]�#�	$�|�,�|�~*�+��<��<�@	�(�$�')�#�,B�(�-Q�*���-P�*�!��L�BX� 0�X�v2�3��2�?�2�2
4�C�D�
&�
/�
/��
5�F�0�9�9�$�?�M�,�F�,�,����5�7�M��%�V�%�%�f�n�n�&A�C�F�N�C�U	�*�U	�p&�'��e9�_�e9r5

Youez - 2016 - github.com/yon3zu
LinuXploit