-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Add sparse_matrix() to PauliString and PauliSum #8127
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
base: main
Are you sure you want to change the base?
Changes from all commits
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 |
|---|---|---|
|
|
@@ -1078,6 +1078,37 @@ def test_pauli_sum_matrix() -> None: | |
| assert np.allclose(H3, paulisum.matrix([q[1], q[2], q[0]])) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| 'paulisum, qubits', | ||
| ( | ||
| # Single term. | ||
| (cirq.X(q0), None), | ||
| # Two terms, default ordering. | ||
| (cirq.X(q0) * cirq.X(q1) + cirq.Z(q0), None), | ||
| # Three terms. | ||
| (cirq.X(q0) + cirq.Y(q1) + cirq.Z(q2), None), | ||
| # Reversed qubit ordering. | ||
| (cirq.X(q0) * cirq.X(q1) + cirq.Z(q0), [q1, q0]), | ||
| # Shuffled ordering with an idle qubit. | ||
| (cirq.X(q0) * cirq.X(q1) + cirq.Z(q0), [q1, q2, q0]), | ||
| # Complex coefficients. | ||
| ((1 + 2j) * cirq.X(q0) * cirq.Y(q1) - 0.5 * cirq.Z(q0), None), | ||
| # Identity factors included. | ||
| (cirq.X(q0) * cirq.I(q1) + cirq.Z(q1), None), | ||
| ), | ||
| ) | ||
| def test_pauli_sum_sparse_matrix(paulisum, qubits) -> None: | ||
| actual = paulisum.sparse_matrix(qubits).toarray() | ||
| expected = paulisum.matrix(qubits) | ||
| assert np.allclose(actual, expected) | ||
|
Collaborator
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. Nit - we should use |
||
|
|
||
|
|
||
| def test_pauli_sum_sparse_matrix_empty() -> None: | ||
| q = cirq.LineQubit.range(2) | ||
| empty = cirq.PauliSum.from_pauli_strings([]) | ||
| assert np.allclose(empty.sparse_matrix(q).toarray(), np.zeros((4, 4))) | ||
|
Collaborator
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. We should use assert np.array_equal(empty.sparse_matrix().toarray(), np.zeros((1, 1)))
assert np.array_equal(empty.sparse_matrix(q).toarray(), np.zeros((4, 4))) |
||
|
|
||
|
|
||
| def test_pauli_sum_repr() -> None: | ||
| q = cirq.LineQubit.range(2) | ||
| pstr1 = cirq.X(q[0]) * cirq.X(q[1]) | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -33,6 +33,7 @@ | |
|
|
||
| import numpy as np | ||
| import sympy | ||
| from scipy import sparse | ||
|
|
||
| from cirq import _compat, linalg, protocols, qis, value | ||
| from cirq._compat import deprecated | ||
|
|
@@ -451,7 +452,7 @@ def __str__(self) -> str: | |
| return prefix + '*'.join(factors) | ||
|
|
||
| def matrix(self, qubits: Iterable[TKey] | None = None) -> np.ndarray: | ||
| """Returns the matrix of self in computational basis of qubits. | ||
| """Returns the matrix of self in the computational basis of the qubits. | ||
|
|
||
| Args: | ||
| qubits: Ordered collection of qubits that determine the subspace | ||
|
|
@@ -460,15 +461,71 @@ def matrix(self, qubits: Iterable[TKey] | None = None) -> np.ndarray: | |
| the identity. Defaults to `self.qubits`. | ||
|
|
||
| Raises: | ||
| NotImplementedError: If this PauliString is parameterized. | ||
| NotImplementedError: If this `PauliString` is parameterized. | ||
| """ | ||
| qubits = self.qubits if qubits is None else qubits | ||
| factors = [self.get(q, default=identity.I) for q in qubits] | ||
| if protocols.is_parameterized(self): | ||
| raise NotImplementedError('Cannot express as matrix when parameterized') | ||
| raise NotImplementedError('Cannot express a parameterized PauliString as a matrix.') | ||
| assert isinstance(self.coefficient, complex) | ||
| return linalg.kron(self.coefficient, *[protocols.unitary(f) for f in factors]) | ||
|
|
||
| def sparse_matrix(self, qubits: Iterable[TKey] | None = None) -> sparse.csr_matrix: | ||
| """Returns the sparse matrix of self in the computational basis of the qubits. | ||
|
|
||
| Uses a direct bit-manipulation algorithm that avoids Kronecker products | ||
| by computing row/col indices and phases for each basis state directly. | ||
|
|
||
| Args: | ||
| qubits: Ordered collection of qubits that determine the subspace | ||
| in which the matrix representation of the Pauli string is to | ||
| be computed. Qubits absent from `self.qubits` are acted on by | ||
| the identity. Defaults to `self.qubits`. | ||
|
|
||
| Returns: | ||
| A `scipy.sparse.csr_matrix` representing the Pauli string. | ||
|
|
||
| Raises: | ||
| NotImplementedError: If this `PauliString` is parameterized. | ||
| AssertionError: If an unexpected Pauli gate instance is encountered. | ||
|
Collaborator
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. Nit - perhaps we should leave |
||
| """ | ||
| qubits = self.qubits if qubits is None else tuple(qubits) | ||
| if protocols.is_parameterized(self): | ||
| raise NotImplementedError('Cannot express a parameterized PauliString as a matrix.') | ||
| assert isinstance(self.coefficient, complex) | ||
|
|
||
| n = len(qubits) | ||
| dim = 1 << n | ||
| qubit_to_idx = {q: i for i, q in enumerate(qubits)} | ||
|
|
||
| x_mask = y_mask = z_mask = 0 | ||
| for q, pauli in self.items(): | ||
| if q not in qubit_to_idx: | ||
| continue | ||
| idx = qubit_to_idx[q] | ||
| bit = 1 << (n - 1 - idx) | ||
| if pauli is pauli_gates.X: | ||
| x_mask |= bit | ||
| elif pauli is pauli_gates.Y: | ||
| y_mask |= bit | ||
| elif pauli is pauli_gates.Z: | ||
| z_mask |= bit | ||
|
pavoljuhas marked this conversation as resolved.
|
||
| else: # pragma: no cover | ||
| raise AssertionError( | ||
| "Unhandled instance of Pauli gate. " | ||
| "Expected one of (cirq.X, cirq.Y, cirq.Z) identically." | ||
| ) | ||
|
|
||
| cols = np.arange(dim, dtype=np.int32) | ||
| rows = cols ^ x_mask ^ y_mask | ||
|
|
||
| num_y = y_mask.bit_count() | ||
| y_phase = (1j**num_y) * np.where(np.bitwise_count(cols & y_mask) & 1, -1.0, 1.0) | ||
| z_phase = np.where(np.bitwise_count(cols & z_mask) & 1, -1.0, 1.0) | ||
| data = self.coefficient * y_phase * z_phase | ||
|
|
||
| return sparse.coo_matrix((data, (rows, cols)), shape=(dim, dim)).tocsr() | ||
|
|
||
| def _has_unitary_(self) -> bool: | ||
| if self._is_parameterized_(): | ||
| return False | ||
|
|
||
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.
Nit - let us annotate the argument types here: