a
    BCCfW                     @   s   d dl mZ d dlZd dlmZ d dlmZ dgZG dd dZ	G dd de	Z
d	d
 ZG dd de	ZG dd de	ZG dd de	ZG dd de	ZdS )    )cached_propertyN)linalg)_multivariate
Covariancec                   @   s   e Zd ZdZdd Zedd ZedddZed	d
 Zedd Z	dd Z
dd Zedd Zedd Zedd Zedd Zdd Zdd ZdS )r   aL  
    Representation of a covariance matrix

    Calculations involving covariance matrices (e.g. data whitening,
    multivariate normal function evaluation) are often performed more
    efficiently using a decomposition of the covariance matrix instead of the
    covariance matrix itself. This class allows the user to construct an
    object representing a covariance matrix using any of several
    decompositions and perform calculations using a common interface.

    .. note::

        The `Covariance` class cannot be instantiated directly. Instead, use
        one of the factory methods (e.g. `Covariance.from_diagonal`).

    Examples
    --------
    The `Covariance` class is is used by calling one of its
    factory methods to create a `Covariance` object, then pass that
    representation of the `Covariance` matrix as a shape parameter of a
    multivariate distribution.

    For instance, the multivariate normal distribution can accept an array
    representing a covariance matrix:

    >>> from scipy import stats
    >>> import numpy as np
    >>> d = [1, 2, 3]
    >>> A = np.diag(d)  # a diagonal covariance matrix
    >>> x = [4, -2, 5]  # a point of interest
    >>> dist = stats.multivariate_normal(mean=[0, 0, 0], cov=A)
    >>> dist.pdf(x)
    4.9595685102808205e-08

    but the calculations are performed in a very generic way that does not
    take advantage of any special properties of the covariance matrix. Because
    our covariance matrix is diagonal, we can use ``Covariance.from_diagonal``
    to create an object representing the covariance matrix, and
    `multivariate_normal` can use this to compute the probability density
    function more efficiently.

    >>> cov = stats.Covariance.from_diagonal(d)
    >>> dist = stats.multivariate_normal(mean=[0, 0, 0], cov=cov)
    >>> dist.pdf(x)
    4.9595685102808205e-08

    c                 C   s   d}t |d S )NzThe `Covariance` class cannot be instantiated directly. Please use one of the factory methods (e.g. `Covariance.from_diagonal`).)NotImplementedError)selfmessage r	   S/var/www/html/django/DPS/env/lib/python3.9/site-packages/scipy/stats/_covariance.py__init__;   s    zCovariance.__init__c                 C   s   t | S )a  
        Return a representation of a covariance matrix from its diagonal.

        Parameters
        ----------
        diagonal : array_like
            The diagonal elements of a diagonal matrix.

        Notes
        -----
        Let the diagonal elements of a diagonal covariance matrix :math:`D` be
        stored in the vector :math:`d`.

        When all elements of :math:`d` are strictly positive, whitening of a
        data point :math:`x` is performed by computing
        :math:`x \cdot d^{-1/2}`, where the inverse square root can be taken
        element-wise.
        :math:`\log\det{D}` is calculated as :math:`-2 \sum(\log{d})`,
        where the :math:`\log` operation is performed element-wise.

        This `Covariance` class supports singular covariance matrices. When
        computing ``_log_pdet``, non-positive elements of :math:`d` are
        ignored. Whitening is not well defined when the point to be whitened
        does not lie in the span of the columns of the covariance matrix. The
        convention taken here is to treat the inverse square root of
        non-positive elements of :math:`d` as zeros.

        Examples
        --------
        Prepare a symmetric positive definite covariance matrix ``A`` and a
        data point ``x``.

        >>> import numpy as np
        >>> from scipy import stats
        >>> rng = np.random.default_rng()
        >>> n = 5
        >>> A = np.diag(rng.random(n))
        >>> x = rng.random(size=n)

        Extract the diagonal from ``A`` and create the `Covariance` object.

        >>> d = np.diag(A)
        >>> cov = stats.Covariance.from_diagonal(d)

        Compare the functionality of the `Covariance` object against a
        reference implementations.

        >>> res = cov.whiten(x)
        >>> ref = np.diag(d**-0.5) @ x
        >>> np.allclose(res, ref)
        True
        >>> res = cov.log_pdet
        >>> ref = np.linalg.slogdet(A)[-1]
        >>> np.allclose(res, ref)
        True

        )CovViaDiagonal)diagonalr	   r	   r
   from_diagonalA   s    ;zCovariance.from_diagonalNc                 C   s
   t | |S )a  
        Return a representation of a covariance from its precision matrix.

        Parameters
        ----------
        precision : array_like
            The precision matrix; that is, the inverse of a square, symmetric,
            positive definite covariance matrix.
        covariance : array_like, optional
            The square, symmetric, positive definite covariance matrix. If not
            provided, this may need to be calculated (e.g. to evaluate the
            cumulative distribution function of
            `scipy.stats.multivariate_normal`) by inverting `precision`.

        Notes
        -----
        Let the covariance matrix be :math:`A`, its precision matrix be
        :math:`P = A^{-1}`, and :math:`L` be the lower Cholesky factor such
        that :math:`L L^T = P`.
        Whitening of a data point :math:`x` is performed by computing
        :math:`x^T L`. :math:`\log\det{A}` is calculated as
        :math:`-2tr(\log{L})`, where the :math:`\log` operation is performed
        element-wise.

        This `Covariance` class does not support singular covariance matrices
        because the precision matrix does not exist for a singular covariance
        matrix.

        Examples
        --------
        Prepare a symmetric positive definite precision matrix ``P`` and a
        data point ``x``. (If the precision matrix is not already available,
        consider the other factory methods of the `Covariance` class.)

        >>> import numpy as np
        >>> from scipy import stats
        >>> rng = np.random.default_rng()
        >>> n = 5
        >>> P = rng.random(size=(n, n))
        >>> P = P @ P.T  # a precision matrix must be positive definite
        >>> x = rng.random(size=n)

        Create the `Covariance` object.

        >>> cov = stats.Covariance.from_precision(P)

        Compare the functionality of the `Covariance` object against
        reference implementations.

        >>> res = cov.whiten(x)
        >>> ref = x @ np.linalg.cholesky(P)
        >>> np.allclose(res, ref)
        True
        >>> res = cov.log_pdet
        >>> ref = -np.linalg.slogdet(P)[-1]
        >>> np.allclose(res, ref)
        True

        )CovViaPrecision)	precision
covariancer	   r	   r
   from_precision~   s    =zCovariance.from_precisionc                 C   s   t | S )a  
        Representation of a covariance provided via the (lower) Cholesky factor

        Parameters
        ----------
        cholesky : array_like
            The lower triangular Cholesky factor of the covariance matrix.

        Notes
        -----
        Let the covariance matrix be :math:`A` and :math:`L` be the lower
        Cholesky factor such that :math:`L L^T = A`.
        Whitening of a data point :math:`x` is performed by computing
        :math:`L^{-1} x`. :math:`\log\det{A}` is calculated as
        :math:`2tr(\log{L})`, where the :math:`\log` operation is performed
        element-wise.

        This `Covariance` class does not support singular covariance matrices
        because the Cholesky decomposition does not exist for a singular
        covariance matrix.

        Examples
        --------
        Prepare a symmetric positive definite covariance matrix ``A`` and a
        data point ``x``.

        >>> import numpy as np
        >>> from scipy import stats
        >>> rng = np.random.default_rng()
        >>> n = 5
        >>> A = rng.random(size=(n, n))
        >>> A = A @ A.T  # make the covariance symmetric positive definite
        >>> x = rng.random(size=n)

        Perform the Cholesky decomposition of ``A`` and create the
        `Covariance` object.

        >>> L = np.linalg.cholesky(A)
        >>> cov = stats.Covariance.from_cholesky(L)

        Compare the functionality of the `Covariance` object against
        reference implementation.

        >>> from scipy.linalg import solve_triangular
        >>> res = cov.whiten(x)
        >>> ref = solve_triangular(L, x, lower=True)
        >>> np.allclose(res, ref)
        True
        >>> res = cov.log_pdet
        >>> ref = np.linalg.slogdet(A)[-1]
        >>> np.allclose(res, ref)
        True

        )CovViaCholesky)choleskyr	   r	   r
   from_cholesky   s    8zCovariance.from_choleskyc                 C   s   t | S )a  
        Representation of a covariance provided via eigendecomposition

        Parameters
        ----------
        eigendecomposition : sequence
            A sequence (nominally a tuple) containing the eigenvalue and
            eigenvector arrays as computed by `scipy.linalg.eigh` or
            `numpy.linalg.eigh`.

        Notes
        -----
        Let the covariance matrix be :math:`A`, let :math:`V` be matrix of
        eigenvectors, and let :math:`W` be the diagonal matrix of eigenvalues
        such that `V W V^T = A`.

        When all of the eigenvalues are strictly positive, whitening of a
        data point :math:`x` is performed by computing
        :math:`x^T (V W^{-1/2})`, where the inverse square root can be taken
        element-wise.
        :math:`\log\det{A}` is calculated as  :math:`tr(\log{W})`,
        where the :math:`\log` operation is performed element-wise.

        This `Covariance` class supports singular covariance matrices. When
        computing ``_log_pdet``, non-positive eigenvalues are ignored.
        Whitening is not well defined when the point to be whitened
        does not lie in the span of the columns of the covariance matrix. The
        convention taken here is to treat the inverse square root of
        non-positive eigenvalues as zeros.

        Examples
        --------
        Prepare a symmetric positive definite covariance matrix ``A`` and a
        data point ``x``.

        >>> import numpy as np
        >>> from scipy import stats
        >>> rng = np.random.default_rng()
        >>> n = 5
        >>> A = rng.random(size=(n, n))
        >>> A = A @ A.T  # make the covariance symmetric positive definite
        >>> x = rng.random(size=n)

        Perform the eigendecomposition of ``A`` and create the `Covariance`
        object.

        >>> w, v = np.linalg.eigh(A)
        >>> cov = stats.Covariance.from_eigendecomposition((w, v))

        Compare the functionality of the `Covariance` object against
        reference implementations.

        >>> res = cov.whiten(x)
        >>> ref = x @ (v @ np.diag(w**-0.5))
        >>> np.allclose(res, ref)
        True
        >>> res = cov.log_pdet
        >>> ref = np.linalg.slogdet(A)[-1]
        >>> np.allclose(res, ref)
        True

        )CovViaEigendecomposition)eigendecompositionr	   r	   r
   from_eigendecomposition   s    @z"Covariance.from_eigendecompositionc                 C   s   |  t|S )a  
        Perform a whitening transformation on data.

        "Whitening" ("white" as in "white noise", in which each frequency has
        equal magnitude) transforms a set of random variables into a new set of
        random variables with unit-diagonal covariance. When a whitening
        transform is applied to a sample of points distributed according to
        a multivariate normal distribution with zero mean, the covariance of
        the transformed sample is approximately the identity matrix.

        Parameters
        ----------
        x : array_like
            An array of points. The last dimension must correspond with the
            dimensionality of the space, i.e., the number of columns in the
            covariance matrix.

        Returns
        -------
        x_ : array_like
            The transformed array of points.

        References
        ----------
        .. [1] "Whitening Transformation". Wikipedia.
               https://en.wikipedia.org/wiki/Whitening_transformation
        .. [2] Novak, Lukas, and Miroslav Vorechovsky. "Generalization of
               coloring linear transformation". Transactions of VSB 18.2
               (2018): 31-35. :doi:`10.31490/tces-2018-0013`

        Examples
        --------
        >>> import numpy as np
        >>> from scipy import stats
        >>> rng = np.random.default_rng()
        >>> n = 3
        >>> A = rng.random(size=(n, n))
        >>> cov_array = A @ A.T  # make matrix symmetric positive definite
        >>> precision = np.linalg.inv(cov_array)
        >>> cov_object = stats.Covariance.from_precision(precision)
        >>> x = rng.multivariate_normal(np.zeros(n), cov_array, size=(10000))
        >>> x_ = cov_object.whiten(x)
        >>> np.cov(x_, rowvar=False)  # near-identity covariance
        array([[0.97862122, 0.00893147, 0.02430451],
               [0.00893147, 0.96719062, 0.02201312],
               [0.02430451, 0.02201312, 0.99206881]])

        )_whitennpasarrayr   xr	   r	   r
   whiten9  s    1zCovariance.whitenc                 C   s   |  t|S )a  
        Perform a colorizing transformation on data.

        "Colorizing" ("color" as in "colored noise", in which different
        frequencies may have different magnitudes) transforms a set of
        uncorrelated random variables into a new set of random variables with
        the desired covariance. When a coloring transform is applied to a
        sample of points distributed according to a multivariate normal
        distribution with identity covariance and zero mean, the covariance of
        the transformed sample is approximately the covariance matrix used
        in the coloring transform.

        Parameters
        ----------
        x : array_like
            An array of points. The last dimension must correspond with the
            dimensionality of the space, i.e., the number of columns in the
            covariance matrix.

        Returns
        -------
        x_ : array_like
            The transformed array of points.

        References
        ----------
        .. [1] "Whitening Transformation". Wikipedia.
               https://en.wikipedia.org/wiki/Whitening_transformation
        .. [2] Novak, Lukas, and Miroslav Vorechovsky. "Generalization of
               coloring linear transformation". Transactions of VSB 18.2
               (2018): 31-35. :doi:`10.31490/tces-2018-0013`

        Examples
        --------
        >>> import numpy as np
        >>> from scipy import stats
        >>> rng = np.random.default_rng(1638083107694713882823079058616272161)
        >>> n = 3
        >>> A = rng.random(size=(n, n))
        >>> cov_array = A @ A.T  # make matrix symmetric positive definite
        >>> cholesky = np.linalg.cholesky(cov_array)
        >>> cov_object = stats.Covariance.from_cholesky(cholesky)
        >>> x = rng.multivariate_normal(np.zeros(n), np.eye(n), size=(10000))
        >>> x_ = cov_object.colorize(x)
        >>> cov_data = np.cov(x_, rowvar=False)
        >>> np.allclose(cov_data, cov_array, rtol=3e-2)
        True
        )	_colorizer   r   r   r	   r	   r
   colorizel  s    1zCovariance.colorizec                 C   s   t j| jtdd S )zH
        Log of the pseudo-determinant of the covariance matrix
        dtyper	   )r   array	_log_pdetfloatr   r	   r	   r
   log_pdet  s    zCovariance.log_pdetc                 C   s   t j| jtdd S )z/
        Rank of the covariance matrix
        r!   r	   )r   r#   _rankintr&   r	   r	   r
   rank  s    zCovariance.rankc                 C   s   | j S )zB
        Explicit representation of the covariance matrix
        )_covariancer&   r	   r	   r
   r     s    zCovariance.covariancec                 C   s   | j S )z/
        Shape of the covariance array
        )_shaper&   r	   r	   r
   shape  s    zCovariance.shapec                 C   sf   t |}|jdd  \}}||ksN|jdksNt |jt jsbt |jt jsbd| d}t||S )N   The input `z:` must be a square, two-dimensional array of real numbers.)	r   Z
atleast_2dr-   ndim
issubdtyper"   integerfloating
ValueError)r   Anamemnr   r	   r	   r
   _validate_matrix  s    
"zCovariance._validate_matrixc                 C   sL   t |}|jdks4t |jt jsHt |jt jsHd| d}t||S )N   r0   z2` must be a one-dimensional array of real numbers.)r   Z
atleast_1dr1   r2   r"   r3   r4   r5   )r   r6   r7   r   r	   r	   r
   _validate_vector  s    
zCovariance._validate_vector)N)__name__
__module____qualname____doc__r   staticmethodr   r   r   r   r   r    propertyr'   r*   r   r-   r:   r<   r	   r	   r	   r
   r      s,   /
<>
9
A33




c                   @   s2   e Zd Zd
ddZdd Zedd Zdd	 ZdS )r   Nc                 C   s   |  |d}|d ur8|  |d}d}|j|jkr8t|tj|| _dtt| jj	dd | _
|jd | _|| _|| _|j| _d| _d S )Nr   r   z0`precision.shape` must equal `covariance.shape`.r.   ZaxisF)r:   r-   r5   r   r   r   _chol_Plogdiagsumr$   r(   Z
_precision_cov_matrixr,   _allow_singular)r   r   r   r   r	   r	   r
   r     s     zCovViaPrecision.__init__c                 C   s
   || j  S N)rE   r   r	   r	   r
   r     s    zCovViaPrecision._whitenc                 C   s2   | j d }| jd u r,t| jdft|S | jS )NrC   T)r,   rI   r   Z	cho_solverE   r   eye)r   r9   r	   r	   r
   r+     s
    
zCovViaPrecision._covariancec                 C   s   t j| jj|jddjS )NFlower)r   solve_triangularrE   Tr   r	   r	   r
   r     s    zCovViaPrecision._colorize)N)r=   r>   r?   r   r   r   r+   r   r	   r	   r	   r
   r     s
   

r   c                 C   s"   | j dk r| | S | t|d S )Nr/   r.   )r1   r   expand_dims)r   dr	   r	   r
   	_dot_diag  s    rS   c                   @   s,   e Zd Zdd Zdd Zdd Zdd Zd	S )
r   c                 C   s   |  |d}|dk}tj|tjd}d||< tjt|dd| _dt| }d||< t|| _|| _	|j
d |jdd | _ttjd|| _|| _| jj
| _d| _d S )Nr   r   r!   r;   rC   rD   T)r<   r   r#   float64rH   rF   r$   sqrt_sqrt_diagonal_LPr-   r(   Zapply_along_axisrG   r+   _i_zeror,   rJ   )r   r   i_zeroZpositive_diagonalpsuedo_reciprocalsr	   r	   r
   r     s    
zCovViaDiagonal.__init__c                 C   s   t || jS rK   )rS   rW   r   r	   r	   r
   r     s    zCovViaDiagonal._whitenc                 C   s   t || jS rK   )rS   rV   r   r	   r	   r
   r     s    zCovViaDiagonal._colorizec                 C   s   t jt|| jdd S zJ
        Check whether x lies in the support of the distribution.
        rC   rD   )r   anyrS   rX   r   r	   r	   r
   _support_mask  s    zCovViaDiagonal._support_maskN)r=   r>   r?   r   r   r   r]   r	   r	   r	   r
   r     s   r   c                   @   s0   e Zd Zdd Zedd Zdd Zdd Zd	S )
r   c                 C   sP   |  |d}|| _dtt| jjdd | _|jd | _|j| _	d| _
d S )Nr   r/   rC   rD   F)r:   _factorr   rF   rG   rH   r$   r-   r(   r,   rJ   )r   r   Lr	   r	   r
   r     s     zCovViaCholesky.__init__c                 C   s   | j | j j S rK   r^   rP   r&   r	   r	   r
   r+   #  s    zCovViaCholesky._covariancec                 C   s   t j| j|jddj}|S )NTrM   )r   rO   r^   rP   )r   r   resr	   r	   r
   r   '  s    zCovViaCholesky._whitenc                 C   s   || j j S rK   r`   r   r	   r	   r
   r   +  s    zCovViaCholesky._colorizeN)r=   r>   r?   r   r   r+   r   r   r	   r	   r	   r
   r     s
   	
r   c                   @   s8   e Zd Zdd Zdd Zdd Zedd Zd	d
 ZdS )r   c                 C   s(  |\}}|  |d}| |d}d}z2t|d}t||\}}|ddd d f }W n typ   t|Y n0 |dk}tj|tjd}d||< tjt	|d	d
| _
dt| }d||< || | _|t| | _|jd	 |jd	d
 | _|| _|| _|j| _|| | _t|d | _d| _d S )NeigenvalueseigenvectorszBThe shapes of `eigenvalues` and `eigenvectors` must be compatible.r.   .r   r!   r;   rC   rD   i  T)r<   r:   r   rQ   Zbroadcast_arraysr5   r#   rT   rH   rF   r$   rU   rW   _LAr-   r(   _w_vr,   _null_basisr   Z_eigvalsh_to_eps_epsrJ   )r   r   rb   rc   r   rY   Zpositive_eigenvaluesrZ   r	   r	   r
   r   1  s6    

z!CovViaEigendecomposition.__init__c                 C   s
   || j  S rK   rW   r   r	   r	   r
   r   T  s    z CovViaEigendecomposition._whitenc                 C   s   || j j S rK   )rd   rP   r   r	   r	   r
   r   W  s    z"CovViaEigendecomposition._colorizec                 C   s   | j | j | j j S rK   )rf   re   rP   r&   r	   r	   r
   r+   Z  s    z$CovViaEigendecomposition._covariancec                 C   s$   t jj|| j dd}|| jk }|S r[   )r   r   Znormrg   rh   )r   r   ZresidualZ
in_supportr	   r	   r
   r]   ^  s    
z&CovViaEigendecomposition._support_maskN)	r=   r>   r?   r   r   r   r   r+   r]   r	   r	   r	   r
   r   /  s   #
r   c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )		CovViaPSDzI
    Representation of a covariance provided via an instance of _PSD
    c                 C   s:   |j | _|j| _|j| _|j| _|jj| _	|| _
d| _d S )NF)UrW   r'   r$   r*   r(   Z_Mr+   r-   r,   _psdrJ   )r   Zpsdr	   r	   r
   r   l  s    
zCovViaPSD.__init__c                 C   s
   || j  S rK   ri   r   r	   r	   r
   r   u  s    zCovViaPSD._whitenc                 C   s   | j |S rK   )rl   r]   r   r	   r	   r
   r]   x  s    zCovViaPSD._support_maskN)r=   r>   r?   r@   r   r   r]   r	   r	   r	   r
   rj   g  s   	rj   )	functoolsr   numpyr   Zscipyr   Zscipy.statsr   __all__r   r   rS   r   r   r   rj   r	   r	   r	   r
   <module>   s      G#8