Coverage for src / cvx / linalg / rand_cov.py: 100%
6 statements
« prev ^ index » next coverage.py v7.14.0, created at 2026-05-19 05:40 +0000
« prev ^ index » next coverage.py v7.14.0, created at 2026-05-19 05:40 +0000
1"""Random covariance matrix generation utilities.
3This module provides functions for generating random positive semi-definite
4covariance matrices. These are useful for testing and simulation purposes.
6Example:
7 Generate a random covariance matrix:
9 >>> import numpy as np
10 >>> from cvx.linalg import rand_cov
11 >>> # Generate a 5x5 random covariance matrix
12 >>> cov = rand_cov(5, seed=42)
13 >>> cov.shape
14 (5, 5)
15 >>> # Verify it's symmetric
16 >>> bool(np.allclose(cov, cov.T))
17 True
18 >>> # Verify it's positive semi-definite
19 >>> bool(np.all(np.linalg.eigvals(cov) >= -1e-10))
20 True
22"""
24from __future__ import annotations
26import numpy as np
29def rand_cov(n: int, seed: int | None = None) -> np.ndarray:
30 """Construct a random positive semi-definite covariance matrix of size n x n.
32 The matrix is constructed as A^T @ A where A is a random n x n matrix with
33 elements drawn from a standard normal distribution. This ensures the result
34 is symmetric and positive semi-definite.
36 Args:
37 n: Size of the covariance matrix (n x n).
38 seed: Random seed for reproducibility. If None, uses the current
39 random state.
41 Returns:
42 A random positive semi-definite n x n covariance matrix.
44 Example:
45 Generate a reproducible random covariance matrix:
47 >>> import numpy as np
48 >>> from cvx.linalg import rand_cov
49 >>> cov1 = rand_cov(3, seed=42)
50 >>> cov2 = rand_cov(3, seed=42)
51 >>> np.allclose(cov1, cov2)
52 True
54 Verify positive definiteness via Cholesky decomposition:
56 >>> cov = rand_cov(5, seed=123)
57 >>> # If Cholesky succeeds without error, matrix is positive definite
58 >>> L = np.linalg.cholesky(cov)
59 >>> bool(np.allclose(L @ L.T, cov))
60 True
62 Eigenvalue verification:
64 >>> cov = rand_cov(3, seed=99)
65 >>> eigenvalues = np.linalg.eigvalsh(cov)
66 >>> # All eigenvalues should be positive for PD matrix
67 >>> bool(np.all(eigenvalues > 0))
68 True
70 Different seeds produce different matrices:
72 >>> cov1 = rand_cov(3, seed=1)
73 >>> cov2 = rand_cov(3, seed=2)
74 >>> bool(not np.allclose(cov1, cov2))
75 True
77 Without seed, consecutive calls may differ (random state):
79 >>> # These may or may not be equal depending on random state
80 >>> cov_a = rand_cov(2, seed=None)
81 >>> cov_b = rand_cov(2, seed=None)
82 >>> cov_a.shape == cov_b.shape == (2, 2)
83 True
85 Note:
86 The generated matrix is guaranteed to be positive semi-definite because
87 it is constructed as A^T @ A. In practice, it will typically be positive
88 definite (all eigenvalues strictly positive) unless n is very large.
90 """
91 rng = np.random.default_rng(seed)
92 a = rng.standard_normal((n, n))
93 return np.transpose(a) @ a