python-synthetica 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
synthetica/stats.py ADDED
@@ -0,0 +1,92 @@
1
+ import numpy as np
2
+
3
+
4
+ def _is_positive_definite(symmetric_matrix: np.array) -> bool:
5
+ """Returns true when input is positive-definite, via Cholesky"""
6
+ try:
7
+ _ = np.linalg.cholesky(symmetric_matrix)
8
+ return True
9
+
10
+ except np.linalg.LinAlgError:
11
+ return False
12
+
13
+
14
+ def nearest_positive_definite(matrix: np.array) -> np.ndarray:
15
+ """Find the nearest positive-definite matrix to input.
16
+
17
+ A Python/Numpy port of John D'Errico's `nearestSPD` MATLAB code [1],
18
+ which credits [2]:
19
+ * [1] [Matlab](https://www.mathworks.com/matlabcentral/fileexchange/42885-nearestspd)
20
+ * [2] N.J. Higham, "Computing a nearest symmetric positive semidefinite
21
+ matrix" (1988): [Source](https://doi.org/10.1016/0024-3795(88)90223-6)
22
+
23
+ Notes
24
+ -----
25
+ Other sources:
26
+ * [Stackoverflow](https://stackoverflow.com/.../python-convert-matrix-to-positive-semi-definite)
27
+ * [Gist](https://gist.github.com/fasiha/fdb5cec2054e6f1c6ae35476045a0bbd)
28
+
29
+ Parameters
30
+ ----------
31
+ matrix : np.array
32
+ The input matrix.
33
+
34
+ Returns
35
+ -------
36
+ np.ndarray
37
+ The nearest positive-definite matrix.
38
+ """
39
+ # Computes the symmetric component of a covariance matrix.
40
+ # It does this by adding the covariance matrix with its transpose and
41
+ # dividing the result by 2, which produces a new matrix that is symmetric
42
+ # about its main diagonal. This operation ensures that the resulting matrix
43
+ # can be used in further mathematical operations that require a symmetric
44
+ # matrix.
45
+ symmetric_matrix = (matrix + matrix.T) / 2
46
+ # Performs a Singular Value Decomposition (SVD) on a symmetric matrix.
47
+ # Decomposes a matrix into three matrices: left singular vectors, singular
48
+ # values, and right singular vectors.
49
+ # Returns principal components and their corresponding variances
50
+ _, variance, eigenvectors = np.linalg.svd(symmetric_matrix)
51
+ # Computes the covariance matrix of the data in a new coordinate system
52
+ # defined by the eigenvectors of the original covariance matrix
53
+ transformed_matrix = np.dot(
54
+ eigenvectors.T, np.dot(np.diag(variance), eigenvectors))
55
+ # Symmetric matrix that blends the original symmetric matrix of the data
56
+ # with the covariance matrix of the data in the transformed coordinate
57
+ # system
58
+ weighted_matrix = (symmetric_matrix + transformed_matrix) / 2
59
+ weighted_symetric_matrix = (weighted_matrix + weighted_matrix.T) / 2
60
+ if _is_positive_definite(weighted_symetric_matrix):
61
+ return weighted_symetric_matrix
62
+ # The above is different from [1]. It appears that MATLAB's `chol` Cholesky
63
+ # decomposition will accept matrixes with exactly 0-eigenvalue, whereas
64
+ # Numpy's will not. So where [1] uses `eps(mineig)` (where `eps` is Matlab
65
+ # for `np.spacing`), we use the above definition. CAVEAT: our `spacing`
66
+ # will be much larger than [1]'s `eps(min_eigenvalues)`, since
67
+ # `min_eigenvalues` is usually on the order of 1e-16, and `eps(1e-16)` is
68
+ # on the order of 1e-34, whereas `spacing` will, for Gaussian random matrixes
69
+ # of small dimension, be on other order of 1e-16. In practice, both ways
70
+ # converge, as the unit test below suggests.
71
+ spacing = np.spacing(np.linalg.norm(matrix))
72
+ # Process known as "shrinking" a matrix towards the identity matrix to
73
+ # ensure that it is positive definite
74
+ identity_matrix = np.eye(matrix.shape[0])
75
+ k = 1 # shrinkage parameter
76
+ # Loop until the weighted symmetric matrix is positive definite, which is
77
+ # determined by the is_positive_definite() function. This function likely
78
+ # checks that all eigenvalues of the matrix are positive.
79
+ while not _is_positive_definite(weighted_symetric_matrix):
80
+ # Find the minimum eigenvalue of the matrix using linalg.eigvals().
81
+ # The np.real() function is used to discard any imaginary components
82
+ # that may be returned due to numerical errors.
83
+ min_eigenvalues = np.min(
84
+ np.real(np.linalg.eigvals(weighted_symetric_matrix)))
85
+ # Shrink the matrix towards the identity matrix by adding a multiple of
86
+ # the identity matrix to the matrix. The multiple is calculated using a
87
+ # formula involving the minimum eigenvalue, the shrinkage parameter k,
88
+ # and a constant spacing.
89
+ weighted_symetric_matrix += identity_matrix * \
90
+ (- min_eigenvalues * k**2 + spacing)
91
+ k += 1 # Increment the shrinkage parameter k.
92
+ return weighted_symetric_matrix