-
Notifications
You must be signed in to change notification settings - Fork 32
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
Add utility for dealing with multiple SparsePauliOp
s
#587
Draft
garrison
wants to merge
11
commits into
main
Choose a base branch
from
sparsepauliop-util
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.
+489
−0
Draft
Changes from 8 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
be5a6c9
Add utility for dealing with multiple `SparsePauliOp`s
garrison 1d66d74
Fix on python 3.9 and earlier
garrison d5cdcb2
An empty `PauliList` is okay, actually
garrison 2311aed
Use a relative import
garrison 7145041
Draft of how-to
garrison 406e225
Merge branch 'main' into sparsepauliop-util
garrison 01932bd
Black
garrison 4973020
Add comparison cell
garrison 77c8785
observables as `PauliList` should get secondary billing
garrison b7cb77b
Move tests of exceptions away from regular tests
garrison 1aa8105
Improve the tests
garrison 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
There are no files selected for viewing
This file contains 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 |
---|---|---|
@@ -0,0 +1,90 @@ | ||
# This code is a Qiskit project. | ||
|
||
# (C) Copyright IBM 2024. | ||
|
||
# This code is licensed under the Apache License, Version 2.0. You may | ||
# obtain a copy of this license in the LICENSE.txt file in the root directory | ||
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. | ||
# Any modifications or derivative works of this code must retain this | ||
# copyright notice, and modified files need to carry a notice indicating | ||
# that they have been altered from the originals. | ||
|
||
r"""Utilities for working with the unique terms of a collection of :class:`~qiskit.quantum_info.SparsePauliOp`\ s.""" | ||
|
||
from __future__ import annotations | ||
|
||
from typing import Sequence, Iterable, Mapping | ||
|
||
from qiskit.quantum_info import Pauli, PauliList, SparsePauliOp | ||
from .iteration import strict_zip | ||
|
||
|
||
def gather_unique_observable_terms( | ||
observables: PauliList | Sequence[Pauli | SparsePauliOp], | ||
) -> PauliList: | ||
"""Inspect the contents of each observable to find and return the unique Pauli terms.""" | ||
if not observables: | ||
if isinstance(observables, PauliList): | ||
return observables.copy() | ||
raise ValueError("observables list cannot be empty") | ||
|
||
pauli_list: list[Pauli] = [] | ||
pauli_set: set[Pauli] = set() | ||
for observable in observables: | ||
if isinstance(observable, Pauli): | ||
observable = SparsePauliOp(observable) | ||
for pauli, coeff in strict_zip(observable.paulis, observable.coeffs): | ||
assert pauli.phase == 0 # SparsePauliOp should do this for us | ||
if coeff == 0: | ||
continue | ||
if pauli not in pauli_set: | ||
pauli_list.append(pauli) | ||
pauli_set.add(pauli) | ||
|
||
if not pauli_list: | ||
# Handle this special case, which can happen if all coeffs are zero. | ||
# We create an empty PauliList with the correct number of qubits. See | ||
# https://github.com/Qiskit/qiskit/pull/9770 for a proposal to make | ||
# this simpler in Qiskit. | ||
return PauliList(["I" * observables[0].num_qubits])[:0] | ||
|
||
try: | ||
return PauliList(pauli_list) | ||
except ValueError as ex: | ||
raise ValueError( | ||
"Cannot construct PauliList. Do provided observables all have " | ||
"the same number of qubits?" | ||
) from ex | ||
|
||
|
||
def _reconstruct_observable_expval_from_terms( | ||
observable: Pauli | SparsePauliOp, | ||
term_expvals: Mapping[Pauli, float | complex], | ||
) -> complex: | ||
if isinstance(observable, Pauli): | ||
observable = SparsePauliOp(observable) | ||
rv = 0.0j | ||
for pauli, coeff in strict_zip(observable.paulis, observable.coeffs): | ||
assert pauli.phase == 0 # SparsePauliOp should do this for us | ||
if coeff == 0: | ||
continue | ||
try: | ||
term_expval = term_expvals[pauli] | ||
except KeyError as ex: | ||
raise ValueError( | ||
"An observable contains a Pauli term whose expectation value " | ||
"was not provided." | ||
) from ex | ||
rv += coeff * term_expval | ||
return rv | ||
|
||
|
||
def reconstruct_observable_expvals_from_terms( | ||
observables: PauliList | Iterable[Pauli | SparsePauliOp], | ||
term_expvals: Mapping[Pauli, float | complex], | ||
) -> list[complex]: | ||
"""Reconstruct the expectation values given the expectation value of each unique term.""" | ||
return [ | ||
_reconstruct_observable_expval_from_terms(observable, term_expvals) | ||
for observable in observables | ||
] |
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 should swap the order here so
PauliList
gets secondary billing.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 didn't know that the order mattered. Could you clarify what you mean here?
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 was talking about the type hints. The order does not have any impact other than how things are presented in the API docs. Since
Sequence[Pauli | SparsePauliOp]
is the typical way users will use this function, I want that type to appear first in the documentation.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.
Okay, I now understand what you meant.