
    (phW                         S SK Jr  S SKrS SKJr  S SKJr  S/r " S S5      r	 " S S\	5      r
S	 r " S
 S\	5      r " S S\	5      r " S S\	5      r " S S\	5      rg)    )cached_propertyN)linalg)_multivariate
Covariancec                       \ rS rSrSrS r\S 5       r\SS j5       r\S 5       r	\S 5       r
S	 rS
 r\S 5       r\S 5       r\S 5       r\S 5       rS rS rSrg)r      a  
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 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                     Sn[        U5      e)NzThe `Covariance` class cannot be instantiated directly. Please use one of the factory methods (e.g. `Covariance.from_diagonal`).)NotImplementedError)selfmessages     J/var/www/html/venv/lib/python3.13/site-packages/scipy/stats/_covariance.py__init__Covariance.__init__;   s    8 "'**    c                     [        U 5      $ )ae  
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)diagonals    r   from_diagonalCovariance.from_diagonalA   s    v h''r   Nc                     [        X5      $ )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
covariances     r   from_precisionCovariance.from_precision~   s    z y55r   c                     [        U 5      $ )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)choleskys    r   from_choleskyCovariance.from_cholesky   s    p h''r   c                     [        U 5      $ )aZ  
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)eigendecompositions    r   from_eigendecomposition"Covariance.from_eigendecomposition   s    @ ((:;;r   c                 L    U R                  [        R                  " U5      5      $ )ai  
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   xs     r   whitenCovariance.whiten9  s    b ||BJJqM**r   c                 L    U R                  [        R                  " U5      5      $ )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*   s     r   colorizeCovariance.colorizel  s    b ~~bjjm,,r   c                 N    [         R                  " U R                  [        S9S   $ )z8
Log of the pseudo-determinant of the covariance matrix
dtype )r(   array	_log_pdetfloatr   s    r   log_pdetCovariance.log_pdet  s    
 xxe4R88r   c                 N    [         R                  " U R                  [        S9S   $ )z
Rank of the covariance matrix
r3   r5   )r(   r6   _rankintr9   s    r   rankCovariance.rank  s    
 xx

#.r22r   c                     U R                   $ )z2
Explicit representation of the covariance matrix
)_covariancer9   s    r   r   Covariance.covariance  s    
 r   c                     U R                   $ )z
Shape of the covariance array
)_shaper9   s    r   shapeCovariance.shape  s    
 {{r   c                 p   [         R                  " U5      nUR                  SS  u  p4X4:w  dx  UR                  S:w  dh  [         R                  " UR
                  [         R                  5      (       dE  [         R                  " UR
                  [         R                  5      (       d  SU S3n[        U5      eU$ )N   The input `z:` must be a square, two-dimensional array of real numbers.)	r(   
atleast_2drF   ndim
issubdtyper4   integerfloating
ValueError)r   Anamemnr   s         r   _validate_matrixCovariance._validate_matrix  s    MM!wwrs|6QVVq[qww

)K)K)+qww)L)L$TF +@ @GW%%r   c                 D   [         R                  " U5      nUR                  S:w  dh  [         R                  " UR                  [         R
                  5      (       dE  [         R                  " UR                  [         R                  5      (       d  SU S3n[        U5      eU$ )N   rK   z2` must be a one-dimensional array of real numbers.)r(   
atleast_1drM   rN   r4   rO   rP   rQ   )r   rR   rS   r   s       r   _validate_vectorCovariance._validate_vector  so    MM!66Q;r}}QWWbjjAA!}}QWWbkkBB$TF +* *GW%%r   r5   N)__name__
__module____qualname____firstlineno____doc__r   staticmethodr   r   r   r$   r,   r0   propertyr:   r?   r   rF   rV   r[   __static_attributes__r5   r   r   r   r      s    .^+ :( :(x <6 <6| 7( 7(r ?< ?<B1+f1-f 9 9 3 3      r   c                   :    \ rS rSrSS jrS r\S 5       rS rSr	g)	r   i  Nc                    U R                  US5      nUb9  U R                  US5      nSnUR                  UR                  :w  a  [        U5      e[        R                  R                  U5      U l        S[        R                  " [        R                  " U R                  5      5      R                  SS9-  U l
        UR                  S   U l        Xl        X l        UR                  U l        SU l        g )Nr   r   z0`precision.shape` must equal `covariance.shape`.rI   axisF)rV   rF   rQ   r(   r   r   _chol_Plogdiagsumr7   r=   
_precision_cov_matrixrE   _allow_singular)r   r   r   r   s       r   r   CovViaPrecision.__init__  s    )))[A	!..z<HJHG*"2"22 ))yy)))4BFF2774<<#89==2=FF__R(
#%oo$r   c                     XR                   -  $ r]   )rk   r*   s     r   r'   CovViaPrecision._whiten  s    <<r   c                     U R                   S   nU R                  c7  [        R                  " U R                  S4[
        R                  " U5      5      $ U R                  $ )Nrh   T)rE   rp   r   	cho_solverk   r(   eye)r   rU   s     r   rB   CovViaPrecision._covariance  sS    KKO##+   $,,!5rvvayA 	C151A1A	Cr   c                 ~    [         R                  " U R                  R                  UR                  SS9R                  $ )NFlower)r   solve_triangularrk   Tr*   s     r   r/   CovViaPrecision._colorize  s)    &&t||~~qss%HJJJr   )rq   rk   rp   r7   ro   r=   rE   r]   )
r^   r_   r`   ra   r   r'   r   rB   r/   re   r5   r   r   r   r     s(    %   C C
Kr   r   c                 ^    U R                   S:  a  X-  $ U [        R                  " US5      -  $ )NrJ   rI   )rM   r(   expand_dims)r+   ds     r   	_dot_diagr     s+     FFQJ15=Aq"(=$==r   c                   ,    \ rS rSrS rS rS rS rSrg)r   i  c                 F   U R                  US5      nUS:*  n[        R                  " U[        R                  S9nSX2'   [        R                  " [        R
                  " U5      SS9U l        S[        R                  " U5      -  nSXB'   [        R                  " U5      U l        X@l	        UR                  S   UR	                  SS9-
  U l        [        R                  " [        R                  SU5      U l        X l        U R                  R                  U l        SU l        g )Nr   r   r3   rY   rh   ri   T)r[   r(   r6   float64rn   rl   r7   sqrt_sqrt_diagonal_LPrF   r=   apply_along_axisrm   rB   _i_zerorE   rq   )r   r   i_zeropositive_diagonalpsuedo_reciprocalss        r   r   CovViaDiagonal.__init__  s    ((:>QHHXRZZ@$%!'8 9C):!;;%&" ggh/%&,,R06::2:3FF
..rwwHE&&,,#r   c                 ,    [        XR                  5      $ r]   )r   r   r*   s     r   r'   CovViaDiagonal._whiten  s    HH%%r   c                 ,    [        XR                  5      $ r]   )r   r   r*   s     r   r/   CovViaDiagonal._colorize  s    //00r   c                 T    [         R                  " [        XR                  5      SS9) $ z:
Check whether x lies in the support of the distribution.
rh   ri   )r(   anyr   r   r*   s     r   _support_maskCovViaDiagonal._support_mask  s!     yLL1;;;r   )r   rq   rB   r   r7   r=   rE   r   N)	r^   r_   r`   ra   r   r'   r/   r   re   r5   r   r   r   r     s    $(&1<r   r   c                   6    \ rS rSrS r\S 5       rS rS rSr	g)r   i  c                    U R                  US5      nX l        S[        R                  " [        R                  " U R                  5      5      R                  SS9-  U l        UR                  S   U l        UR                  U l	        SU l
        g )Nr   rJ   rh   ri   F)rV   _factorr(   rl   rm   rn   r7   rF   r=   rE   rq   )r   r   Ls      r   r   CovViaCholesky.__init__  sk    !!(J7266"''$,,"78<<"<EEWWR[
gg$r   c                 H    U R                   U R                   R                  -  $ r]   r   r}   r9   s    r   rB   CovViaCholesky._covariance#  s    ||dllnn,,r   c                 n    [         R                  " U R                  UR                  SS9R                  nU$ )NTrz   )r   r|   r   r}   )r   r+   ress      r   r'   CovViaCholesky._whiten'  s)    %%dllACCtDFF
r   c                 2    XR                   R                  -  $ r]   r   r*   s     r   r/   CovViaCholesky._colorize+  s    <<>>!!r   )rq   r   r7   r=   rE   N)
r^   r_   r`   ra   r   r   rB   r'   r/   re   r5   r   r   r   r     s%    % - -"r   r   c                   <    \ rS rSrS rS rS r\S 5       rS r	Sr
g)	r"   i/  c                    Uu  p#U R                  US5      nU R                  US5      nSn [        R                  " US5      n[        R                  " UU5      u  p2USSS S 24   nUS:*  n[        R                  " U[        R                  S9nSXe'   [        R                  " [        R                  " U5      S	S
9U l
        S[        R                  " U5      -  nSXu'   X7-  U l        U[        R                  " U5      -  U l        UR                  S	   UR                  S	S
9-
  U l        X l        X0l        UR                  U l        X5-  U l        [(        R*                  " U5      S-  U l        SU l        g ! [
         a    [        U5      ef = f)NeigenvalueseigenvectorszBThe shapes of `eigenvalues` and `eigenvectors` must be compatible.rI   .r   r3   rY   rh   ri   i  T)r[   rV   r(   r   broadcast_arraysrQ   r6   r   rn   rl   r7   r   r   _LArF   r=   _w_vrE   _null_basisr   _eigvalsh_to_eps_epsrq   )r   r#   r   r   r   r   positive_eigenvaluesr   s           r   r   !CovViaEigendecomposition.__init__1  sw   $6!++KG,,\>J)	&..b9K(*(;(;L<G)I%L%c1ai0K !!xx2::F'($'; <2F)=!>>%&"4"''+"66)//3fjjbj6II
"(('0 "22;?%G	#-  	&W%%	&s   :E4 4F
c                     XR                   -  $ r]   r   r*   s     r   r'    CovViaEigendecomposition._whitenT      88|r   c                 2    XR                   R                  -  $ r]   )r   r}   r*   s     r   r/   "CovViaEigendecomposition._colorizeW  s    88::~r   c                 b    U R                   U R                  -  U R                   R                  -  $ r]   )r   r   r}   r9   s    r   rB   $CovViaEigendecomposition._covarianceZ  s"    $''!TWWYY..r   c                 v    [         R                  R                  XR                  -  SS9nX R                  :  nU$ r   )r(   r   normr   r   )r   r+   residual
in_supports       r   r   &CovViaEigendecomposition._support_mask^  s5     99>>!&6&6"6R>@		)
r   )
r   r   rq   r   r7   r   r=   rE   r   r   N)r^   r_   r`   ra   r   r'   r/   r   rB   r   re   r5   r   r   r"   r"   /  s+    !$F / /r   r"   c                   *    \ rS rSrSrS rS rS rSrg)	CovViaPSDig  zA
Representation of a covariance provided via an instance of _PSD
c                     UR                   U l        UR                  U l        UR                  U l        UR                  U l        UR                  R                  U l	        Xl
        SU l        g )NF)Ur   r:   r7   r?   r=   _MrB   rF   rE   _psdrq   )r   psds     r   r   CovViaPSD.__init__l  sK    55XX
66ffll	$r   c                     XR                   -  $ r]   r   r*   s     r   r'   CovViaPSD._whitenu  r   r   c                 8    U R                   R                  U5      $ r]   )r   r   r*   s     r   r   CovViaPSD._support_maskx  s    yy&&q))r   )r   rq   rB   r7   r   r=   rE   N)	r^   r_   r`   ra   rb   r   r'   r   re   r5   r   r   r   r   g  s    %*r   r   )	functoolsr   numpyr(   scipyr   scipy.statsr   __all__r   r   r   r   r   r"   r   r5   r   r   <module>r      sl    %   % .A AHKj K>> <Z  <F"Z ".5z 5p*
 *r   