L iXddlmZddlZddlmZddlmZdgZGddZ Gdde Z d Z Gd d e Z Gd d e Z Gdde ZGdde Zy))cached_propertyN)linalg) _multivariate CovarianceceZdZdZdZedZeddZedZedZ dZ d Z e d Z e d Ze d Ze d ZdZdZy)raI 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 cd}t|)NzThe `Covariance` class cannot be instantiated directly. Please use one of the factory methods (e.g. `Covariance.from_diagonal`).)NotImplementedError)selfmessages ]/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/scipy/stats/_covariance.py__init__zCovariance.__init__;s8"'**ct|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)diagonals r from_diagonalzCovariance.from_diagonalAsvh''rNct||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 covariances r from_precisionzCovariance.from_precision~szy*55rct|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)choleskys r from_choleskyzCovariance.from_choleskysph''rct|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)eigendecompositions r from_eigendecompositionz"Covariance.from_eigendecompositions@((:;;rcJ|jtj|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]]) )_whitennpasarrayr xs r whitenzCovariance.whiten9sb||BJJqM**rcJ|jtj|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$s r colorizezCovariance.colorizelsb~~bjjm,,rcRtj|jtdS)zH Log of the pseudo-determinant of the covariance matrix dtype)r"array _log_pdetfloatr s r log_pdetzCovariance.log_pdets xxe4R88rcRtj|jtdS)z/ Rank of the covariance matrix r+r-)r"r._rankintr1s r rankzCovariance.ranks xx #.r22rc|jS)zB Explicit representation of the covariance matrix ) _covariancer1s r rzCovariance.covariances rc|jS)z/ Shape of the covariance array )_shaper1s r shapezCovariance.shapes {{rcVtj|}|jdd\}}||k7sk|jdk7s\tj|j tj s?tj|j tjsd|d}t||S)N The input `z:` must be a square, two-dimensional array of real numbers.) r" atleast_2dr;ndim issubdtyper,integerfloating ValueError)r Anamemnr s r _validate_matrixzCovariance._validate_matrixs MM! wwrs|1 6QVVq[qww )K)+qww )L$TF+@@GW% %rc(tj|}|jdk7s\tj|jtj s?tj|jtj sd|d}t||S)Nr?z2` must be a one-dimensional array of real numbers.)r" atleast_1drArBr,rCrDrE)r rFrGr s r _validate_vectorzCovariance._validate_vectorsi MM!  66Q;r}}QWWbjjA!}}QWWbkkB$TF+**GW% %rN)__name__ __module__ __qualname____doc__r staticmethodrrrrr&r)propertyr2r6rr;rJrNr-rr rr s.^+ :(:(x<6<6|7(7(r?<?r=)rAr" expand_dims)r%ds r _dot_diagrqs-FFQJ1q5=Aq"(=$==rc$eZdZdZdZdZdZy)rcT|j|d}|dk}tj|tj}d||<tjtj |d|_dtj|z }d||<tj||_||_ |jd|j dz |_ tjtjd||_||_|jj|_d|_y)Nrrr+rLrXrYT)rNr"r.float64r^r\r/sqrt_sqrt_diagonal_LPr;r4apply_along_axisr]r8_i_zeror:ra)r ri_zeropositive_diagonalpsuedo_reciprocalss r r zCovViaDiagonal.__init__s((:>QHHXRZZ@$%&!'8 9C):!;;%&6" ggh/%&,,R06::2:3FF ..rwwHE &&,, #rc.t||jSrO)rqrwr$s r r!zCovViaDiagonal._whiten sDHH%%rc.t||jSrO)rqrvr$s r r(zCovViaDiagonal._colorizesD//00rcZtjt||jdSzJ Check whether x lies in the support of the distribution. rXrY)r"anyrqryr$s r _support_maskzCovViaDiagonal._support_masks#yDLL1;;;rN)rPrQrRr r!r(rr-rr rrs$(&1rXrYF) rJ_factorr"r\r]r^r/r;r4r:ra)r rLs r r zCovViaCholesky.__init__sm  ! !(J 7 266"''$,,"78<<"<EEWWR[ gg $rcH|j|jjzSrOrrir1s r r8zCovViaCholesky._covariance%s||dllnn,,rc |jjd}tj|j|jj |dd}|j |jjjS)NrrXTrg)rir;rrjrrkrls r r!zCovViaCholesky._whiten)sW CCIIaL%%dllACCKK24FdS{{13399%'''rc4||jjzSrOrr$s r r(zCovViaCholesky._colorize.s4<<>>!!rN)rPrQrRr rr8r!r(r-rr rrs%%--( "rrc4eZdZdZdZdZedZdZy)rc*|\}}|j|d}|j|d}d} tj|d}tj||\}}|ddddf}|dk}tj |tj}d||<tjtj|d |_ dtj|z }d||<||z|_ |tj|z|_ |jd |jd z |_||_||_|j|_||z|_t)j*|d z|_d |_y#t $r t |wxYw) N eigenvalues eigenvectorszBThe shapes of `eigenvalues` and `eigenvectors` must be compatible.r=.rr+rLrXrYiT)rNrJr"robroadcast_arraysrEr.rtr^r\r/rurw_LAr;r4_w_vr: _null_basisr_eigvalsh_to_eps_epsra)r rrrr rzpositive_eigenvaluesr|s r r z!CovViaEigendecomposition.__init__4s$6! \++KG ,,\>J ) &..b9K(*(;(;L>%&6""44"''+"66)//3fjjbj6II "(( '&0"22;?%G #- &W% % &s 9E==Fc ||jzSrOrwr$s r r!z CovViaEigendecomposition._whitenW488|rc4||jjzSrO)rrir$s r r(z"CovViaEigendecomposition._colorizeZs488::~rcb|j|jz|jjzSrO)rrrir1s r r8z$CovViaEigendecomposition._covariance]s"$''!TWWYY..rctjj||jzd}||jk}|Sr)r"rnormrr)r r%residual in_supports r rz&CovViaEigendecomposition._support_maskas999>>!d&6&6"6R>@ ) rN) rPrQrRr r!r(rr8rr-rr rr2s+!$F//rrc"eZdZdZdZdZdZy) CovViaPSDzI Representation of a covariance provided via an instance of _PSD c|j|_|j|_|j|_|j |_|j j|_ ||_ d|_ y)NF) Urwr2r/r6r4_Mr8r;r:_psdra)r psds r r zCovViaPSD.__init__osM55XX 66ffll  $rc ||jzSrOrr$s r r!zCovViaPSD._whitenxrrc8|jj|SrO)rrr$s r rzCovViaPSD._support_mask{syy&&q))rN)rPrQrRrSr r!rr-rr rrjs%*rr) functoolsrnumpyr"scipyr scipy.statsr__all__rrrqrrrrr-rr rsk%% .AAH(j(B>