-
Notifications
You must be signed in to change notification settings - Fork 171
parameterize random_psd_operator with wishart option #1390
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 2 commits
1543fc3
0a76570
4386100
033ebac
6582e49
69dc08e
2e0f4c7
04ee607
b178239
68371dc
d9f6407
2b1e616
3190b3e
3821e99
c43e400
a11999f
789b245
3e1cb51
4d40650
0914f38
378bb08
d4dfbeb
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -7,6 +7,7 @@ def random_psd_operator( | |||||||||
| dim: int, | ||||||||||
| is_real: bool = False, | ||||||||||
| seed: int | None = None, | ||||||||||
| distribution: str = "uniform", | ||||||||||
| ) -> np.ndarray: | ||||||||||
| r"""Generate a random positive semidefinite operator. | ||||||||||
|
|
||||||||||
|
|
@@ -77,21 +78,38 @@ def random_psd_operator( | |||||||||
| :param is_real: Boolean denoting whether the returned matrix will have all real entries or not. | ||||||||||
| Default is :code:`False`. | ||||||||||
| :param seed: A seed used to instantiate numpy's random number generator. | ||||||||||
| :param distribution: Distribution used to generate the PSD operator. | ||||||||||
| Options are `"uniform"` (default) and `"wishart"`. | ||||||||||
| :return: A :code:`dim` x :code:`dim` random positive semidefinite matrix. | ||||||||||
|
|
||||||||||
| """ | ||||||||||
| # Generate a random matrix of dimension dim x dim. | ||||||||||
| gen = np.random.default_rng(seed=seed) | ||||||||||
| rand_mat = gen.random((dim, dim)) | ||||||||||
|
|
||||||||||
| # If is_real is False, add an imaginary component to the matrix. | ||||||||||
| if not is_real: | ||||||||||
| rand_mat = rand_mat + 1j * gen.random((dim, dim)) | ||||||||||
| if not isinstance(dim, int) or dim <= 0: | ||||||||||
| raise ValueError("`dim` must be a positive integer.") | ||||||||||
|
|
||||||||||
| # Constructing a Hermitian matrix. | ||||||||||
| rand_mat = (rand_mat.conj().T + rand_mat) / 2 | ||||||||||
| eigenvals, eigenvecs = np.linalg.eigh(rand_mat) | ||||||||||
| if distribution == "uniform": | ||||||||||
| rand_mat = gen.random((dim, dim)) | ||||||||||
|
|
||||||||||
| Q, R = np.linalg.qr(eigenvecs) | ||||||||||
| if not is_real: | ||||||||||
| rand_mat = rand_mat + 1j * gen.random((dim, dim)) | ||||||||||
|
|
||||||||||
| return Q @ np.diag(np.abs(eigenvals)) @ Q.conj().T | ||||||||||
| rand_mat = (rand_mat.conj().T + rand_mat) / 2 | ||||||||||
| eigenvals, eigenvecs = np.linalg.eigh(rand_mat) | ||||||||||
| Q, _ = np.linalg.qr(eigenvecs) | ||||||||||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Upper case letters are not appropriate for variable names according to PEP-8 |
||||||||||
|
|
||||||||||
| return Q @ np.diag(np.abs(eigenvals)) @ Q.conj().T | ||||||||||
|
|
||||||||||
| elif distribution == "wishart": | ||||||||||
| if is_real: | ||||||||||
| X = gen.standard_normal((dim, dim)) | ||||||||||
| else: | ||||||||||
| X = gen.standard_normal((dim, dim)) + 1j * gen.standard_normal((dim, dim)) | ||||||||||
|
|
||||||||||
| return X @ X.conj().T | ||||||||||
|
|
||||||||||
| else: | ||||||||||
| raise ValueError( | ||||||||||
| "Invalid distribution. Supported options are 'uniform' and 'wishart'." | ||||||||||
| ) | ||||||||||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Linter is set for 120 char-width:
Suggested change
|
||||||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -79,3 +79,34 @@ def test_random_psd_operator_with_seed(dim, is_real, seed, expected_mat): | |
| """Test that random_psd_operator function returns the expected output when seeded.""" | ||
| matrix = random_psd_operator(dim, is_real, seed) | ||
| assert_allclose(matrix, expected_mat) | ||
|
|
||
| def test_random_psd_operator_wishart(): | ||
| """Test Wishart distribution generates PSD matrix.""" | ||
| mat = random_psd_operator(4, distribution="wishart") | ||
| assert mat.shape == (4, 4) | ||
| assert is_positive_semidefinite(mat) | ||
|
|
||
|
|
||
| def test_random_psd_operator_invalid_distribution(): | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
with pytest.raises(ValueError, match="Supported options"):
random_psd_operator(4, distribution="invalid") |
||
| """Test invalid distribution raises ValueError.""" | ||
| with pytest.raises(ValueError): | ||
| random_psd_operator(4, distribution="invalid") | ||
|
|
||
| def test_random_psd_operator_invalid_dim_type(): | ||
| """Test invalid dim type raises ValueError.""" | ||
| with pytest.raises(ValueError): | ||
| random_psd_operator("4") | ||
|
|
||
|
|
||
| def test_random_psd_operator_invalid_dim_negative(): | ||
| """Test negative dim raises ValueError.""" | ||
| with pytest.raises(ValueError): | ||
| random_psd_operator(-2) | ||
|
|
||
|
|
||
| def test_random_psd_operator_wishart_real_branch(): | ||
| """Test Wishart distribution with real sampling branch.""" | ||
| mat = random_psd_operator(4, is_real=True, distribution="wishart") | ||
| assert mat.shape == (4, 4) | ||
| assert is_positive_semidefinite(mat) | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There should be a way to use the
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. sure @vprusso i will check and update shortly! |
||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The docstring still uses the old Sphinx/RST format (.. jupyter-execute::, :param:, :return:,
Examples\n========). The rest of the codebase — including the closest precedent random_density_matrix.py —
has been migrated to Google-style with markdown-exec blocks. Compare:
PR (outdated):
Examples
========
.. jupyter-execute::
from toqito.rand import random_psd_operator
:param dim: ...
:return: ...
Expected (matches random_density_matrix.py):
Examples:
python exec="1" source="above" session="psd_operator" from toqito.rand import random_psd_operator ...Args:
dim: ...
Returns:
...
The current master version of this file already uses the modern format. This PR would revert the docstring to
the old format, which would break the docs build.