Skip to content

Commit

Permalink
Deprecate dense Operator Estimator observables
Browse files Browse the repository at this point in the history
This deprecates passing Operator and other dense `BaseOperator` subclasses as observables in `Estimator.run`. These were implicitly converted to SparsePauliOps by the Estimator, so now should be explicitly converted to `SparsePauliOps` by the user instead.
  • Loading branch information
chriseclectic committed Jan 9, 2024
1 parent c70ece9 commit fd1fafc
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
8 changes: 8 additions & 0 deletions qiskit/primitives/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,14 @@ def init_observable(observable: BaseOperator | str) -> SparsePauliOp:
if isinstance(observable, SparsePauliOp):
return observable
elif isinstance(observable, BaseOperator) and not isinstance(observable, BasePauli):
warnings.warn(
"Implicit conversion from a BaseOperator to a SparsePauliOp in estimator"
" observable arguments is deprecated as of Qiskit 0.46 and will be"
" in Qiskit 1.0. You should explicitly convert to a SparsePauli op using"
" `SparsePauliOp.from_operator(op)` instead.",
DeprecationWarning,
stacklevel=2,
)
return SparsePauliOp.from_operator(observable)
else:
if isinstance(observable, PauliList):
Expand Down
20 changes: 19 additions & 1 deletion test/python/primitives/test_estimator.py
Original file line number Diff line number Diff line change
Expand Up @@ -266,11 +266,29 @@ def test_run_with_operator(self):
[0.1809312, 0.0, 0.0, -1.06365335],
]
)
obs = SparsePauliOp.from_operator(matrix)
est = Estimator()
result = est.run([circuit], [matrix]).result()
result = est.run([circuit], [obs]).result()
self.assertIsInstance(result, EstimatorResult)
np.testing.assert_allclose(result.values, [-1.284366511861733])

def test_run_with_operator_deprecated(self):
"""test for run with Operator as an observable"""
circuit = self.ansatz.assign_parameters([0, 1, 1, 2, 3, 5])
matrix = Operator(
[
[-1.06365335, 0.0, 0.0, 0.1809312],
[0.0, -1.83696799, 0.1809312, 0.0],
[0.0, 0.1809312, -0.24521829, 0.0],
[0.1809312, 0.0, 0.0, -1.06365335],
]
)
est = Estimator()
with self.assertRaises(DeprecationWarning):
result = est.run([circuit], [matrix]).result()
self.assertIsInstance(result, EstimatorResult)
np.testing.assert_allclose(result.values, [-1.284366511861733])

def test_run_with_shots_option(self):
"""test with shots option."""
est = Estimator()
Expand Down

0 comments on commit fd1fafc

Please sign in to comment.