-
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
Open
ToastCheng
wants to merge
3
commits into
quantumlib:main
Choose a base branch
from
ToastCheng:i3057-sparse2
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+150
−8
Open
Changes from 2 commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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,65 @@ 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. | ||
| """ | ||
| 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 | ||
|
Comment on lines
+507
to
+508
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. I just realized the identity check would fail for a deep copy of PauliString or for an pickled/unpickled object, for example, ps = pickle.loads(pickle.dumps(cirq.PauliString(cirq.X(cirq.q(0)))))
ps.sparse_matrix()
---------------------------------------------------------------------------
AssertionErrorPlease rewrite with equality instead of identity comparison (consider using the match-case statement). |
||
| elif pauli is pauli_gates.Y: | ||
| y_mask |= bit | ||
| elif pauli is pauli_gates.Z: | ||
| z_mask |= bit | ||
|
pavoljuhas marked this conversation as resolved.
|
||
|
|
||
| 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 | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
I would recommend parameterizing this test case and passing in a variety of pauli sums.
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.
Updated
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.
@dstrain115 when you get a chance, would you review & approve the PR if it's ready?