Skip to content
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

Efficiently check PauliSumOps for diagonality in CVaRMeasurement #7574

Merged
merged 4 commits into from
Feb 1, 2022
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 11 additions & 13 deletions qiskit/opflow/state_fns/cvar_measurement.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
from qiskit.opflow.exceptions import OpflowError
from qiskit.opflow.list_ops import ListOp, SummedOp, TensoredOp
from qiskit.opflow.operator_base import OperatorBase
from qiskit.opflow.primitive_ops import PauliOp
from qiskit.opflow.primitive_ops import PauliOp, PauliSumOp
from qiskit.opflow.state_fns.circuit_state_fn import CircuitStateFn
from qiskit.opflow.state_fns.dict_state_fn import DictStateFn
from qiskit.opflow.state_fns.operator_state_fn import OperatorStateFn
Expand Down Expand Up @@ -360,24 +360,22 @@ def _check_is_diagonal(operator: OperatorBase) -> bool:
"""
if isinstance(operator, PauliOp):
# every X component must be False
if not np.any(operator.primitive.x):
return True
return False
return not np.any(operator.primitive.x)

if isinstance(operator, SummedOp):
# cover the case of sums of diagonal paulis, but don't raise since there might be summands
# canceling the non-diagonal parts
# For sums (PauliSumOp and SummedOp), we cover the case of sums of diagonal paulis, but don't
# raise since there might be summand canceling the non-diagonal parts. That case is checked
# in the inefficient matrix check at the bottom.
if isinstance(operator, PauliSumOp):
if not np.any(operator.primitive.paulis.x):
return True

# ignoring mypy since we know that all operators are PauliOps
elif isinstance(operator, SummedOp):
if all(isinstance(op, PauliOp) and not np.any(op.primitive.x) for op in operator.oplist):
return True

if isinstance(operator, ListOp):
elif isinstance(operator, ListOp):
return all(operator.traverse(_check_is_diagonal))

# cannot efficiently check if a operator is diagonal, converting to matrix
matrix = operator.to_matrix()

if np.all(matrix == np.diag(np.diagonal(matrix))):
return True
return False
return np.all(matrix == np.diag(np.diagonal(matrix)))
7 changes: 7 additions & 0 deletions releasenotes/notes/cvar-paulisumop-fe48698236b77f9b.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
fixes:
- |
Fixed a bug, where the :class:`~qiskit.opflow.CVaRMeasurement` attempted to convert a
:class:`~qiskit.opflow.PauliSumOp` to a dense matrix to check whether it is diagonal.
For large operators (> 16 qubits) this computation is extremely expensive and raised
an error if not explicitly enabled using ``qiskit.utils.algorithm_globals.massive = True``.
26 changes: 26 additions & 0 deletions test/python/opflow/test_cvar.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from ddt import ddt, data

from qiskit import QuantumCircuit
from qiskit.utils import algorithm_globals
from qiskit.opflow import (
CVaRMeasurement,
StateFn,
Expand All @@ -26,6 +27,7 @@
X,
Y,
Plus,
PauliSumOp,
PauliExpectation,
MatrixExpectation,
CVaRExpectation,
Expand Down Expand Up @@ -70,6 +72,10 @@ def expected_cvar(self, statevector, operator, alpha):

return result / alpha

def cleanup_algorithm_globals(self, massive):
"""Method used to reset the values of algorithm_globals."""
algorithm_globals.massive = massive

def test_cvar_simple(self):
"""Test a simple case with a single Pauli."""
theta = 1.2
Expand Down Expand Up @@ -161,6 +167,26 @@ def test_unsupported_operations(self):
with self.assertRaises(OpflowError):
cvar.adjoint()

def test_cvar_on_paulisumop(self):
"""Test a large PauliSumOp is checked for diagonality efficiently.

Regression test for Qiskit/qiskit-terra#7573.
"""
op = PauliSumOp.from_list([("Z" * 30, 1)])
# assert global algorithm settings do not have massive calculations turned on
# -- which is the default, but better to be sure in the test!
# also add a cleanup so we're sure to reset to the original value after the test, even if
# the test would fail
self.addCleanup(self.cleanup_algorithm_globals, algorithm_globals.massive)
algorithm_globals.massive = False

cvar = CVaRMeasurement(op, alpha=0.1)
fake_probabilities = [0.2, 0.8]
fake_energies = [1, 2]

expectation = cvar.compute_cvar(fake_energies, fake_probabilities)
self.assertEqual(expectation, 1)


@ddt
class TestCVaRExpectation(QiskitOpflowTestCase):
Expand Down