|
| 1 | +import numpy as np |
| 2 | +import pytest |
| 3 | +from hidimstat.statistical_tools.gaussian_distribution import ( |
| 4 | + _s_equi, |
| 5 | + GaussianDistribution, |
| 6 | +) |
| 7 | +from hidimstat._utils.scenario import multivariate_simulation |
| 8 | +from sklearn.covariance import LedoitWolf |
| 9 | + |
| 10 | + |
| 11 | +def test_gaussian_equi(): |
| 12 | + """test function of gaussian""" |
| 13 | + seed = 42 |
| 14 | + n = 100 |
| 15 | + p = 50 |
| 16 | + X, y, beta, noise = multivariate_simulation(n, p, seed=seed) |
| 17 | + generator = GaussianDistribution( |
| 18 | + cov_estimator=LedoitWolf(assume_centered=True), |
| 19 | + random_state=seed * 2, |
| 20 | + centered=False, |
| 21 | + ) |
| 22 | + generator.fit(X=X) |
| 23 | + X_tilde = generator.sample() |
| 24 | + assert X_tilde.shape == (n, p) |
| 25 | + |
| 26 | + |
| 27 | +def test_gaussian_center(): |
| 28 | + """test function of gaussian""" |
| 29 | + seed = 42 |
| 30 | + n = 100 |
| 31 | + p = 50 |
| 32 | + X, y, beta, noise = multivariate_simulation(n, p, seed=seed) |
| 33 | + generator = GaussianDistribution( |
| 34 | + cov_estimator=LedoitWolf(assume_centered=True), |
| 35 | + random_state=seed * 2, |
| 36 | + centered=True, |
| 37 | + ) |
| 38 | + generator.fit(X=X) |
| 39 | + X_tilde = generator.sample() |
| 40 | + assert X_tilde.shape == (n, p) |
| 41 | + |
| 42 | + |
| 43 | +def test_gaussian_error(): |
| 44 | + """test function error""" |
| 45 | + seed = 42 |
| 46 | + n = 100 |
| 47 | + p = 50 |
| 48 | + X, y, beta, noise = multivariate_simulation(n, p, seed=seed) |
| 49 | + generator = GaussianDistribution( |
| 50 | + cov_estimator=LedoitWolf(assume_centered=True), |
| 51 | + random_state=seed * 2, |
| 52 | + centered=True, |
| 53 | + ) |
| 54 | + with pytest.raises( |
| 55 | + ValueError, match="The GaussianGenerator requires to be fit before simulate" |
| 56 | + ): |
| 57 | + generator.sample() |
| 58 | + |
| 59 | + |
| 60 | +def test_s_equi_not_define_positive(): |
| 61 | + """test the warning and error of s_equi function""" |
| 62 | + n = 10 |
| 63 | + tol = 1e-7 |
| 64 | + seed = 42 |
| 65 | + |
| 66 | + # random positive matrix |
| 67 | + rgn = np.random.RandomState(seed) |
| 68 | + a = rgn.randn(n, n) |
| 69 | + a -= np.min(a) |
| 70 | + with pytest.raises( |
| 71 | + Exception, match="The covariance matrix is not positive-definite." |
| 72 | + ): |
| 73 | + _s_equi(a) |
| 74 | + |
| 75 | + # matrix with positive eigenvalues, positive diagonal |
| 76 | + while not np.all(np.linalg.eigvalsh(a) > tol): |
| 77 | + a += 0.1 * np.eye(n) |
| 78 | + with pytest.warns(UserWarning, match="The equi-correlated matrix"): |
| 79 | + _s_equi(a) |
| 80 | + |
| 81 | + # positive definite matrix |
| 82 | + u, s, vh = np.linalg.svd(a) |
| 83 | + d = np.eye(n) |
| 84 | + sigma = u * d * u.T |
| 85 | + _s_equi(sigma) |
0 commit comments