Skip to content

Commit

Permalink
Fix of eval_observables() when quantum_circuit is a StateFn. (#7863) (#…
Browse files Browse the repository at this point in the history
…7881)

* Fix the eval_observables() when quantum_state is StateFn.

StateFn(StateFn()) actually returns an OperatorStateFn.
This caused an issue that was not checked by the
test cases test_aux_ops_evaluator.py.

The associated test case was added.

* Add the associated releasenote

* Update releasenotes/notes/fix-aux-ops-evaluator-83ce1606d1ad19b3.yaml

Co-authored-by: Julien Gacon <[email protected]>

* Fix sphinx identifier

Co-authored-by: Julien Gacon <[email protected]>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
(cherry picked from commit a296ca0)

Co-authored-by: Anthony-Gandon <[email protected]>
  • Loading branch information
mergify[bot] and Anthony-Gandon authored Apr 4, 2022
1 parent 080950b commit 5306c95
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 3 deletions.
6 changes: 4 additions & 2 deletions qiskit/algorithms/aux_ops_evaluator.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,8 +122,10 @@ def _prepare_list_op(
if isinstance(observables, dict):
observables = list(observables.values())

state = StateFn(quantum_state)
return ListOp([StateFn(obs, is_measurement=True).compose(state) for obs in observables])
if not isinstance(quantum_state, StateFn):
quantum_state = StateFn(quantum_state)

return ListOp([StateFn(obs, is_measurement=True).compose(quantum_state) for obs in observables])


def _prepare_result(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
fixes:
- |
The :func:`~qiskit.algorithms.eval_observables` function raised an error when the
``quantum_state`` argument is a :class:`~qiskit.opflow.StateFn`.
This error was fixed and ``eval_observables`` now correctly supports all input types
specifying in the type hints.
22 changes: 21 additions & 1 deletion test/python/algorithms/test_aux_ops_evaluator.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,16 @@
from qiskit.algorithms import eval_observables
from qiskit import BasicAer, QuantumCircuit
from qiskit.circuit.library import EfficientSU2
from qiskit.opflow import PauliSumOp, X, Z, I, ExpectationFactory, OperatorBase, ExpectationBase
from qiskit.opflow import (
PauliSumOp,
X,
Z,
I,
ExpectationFactory,
OperatorBase,
ExpectationBase,
StateFn,
)
from qiskit.utils import QuantumInstance, algorithm_globals


Expand Down Expand Up @@ -155,6 +164,17 @@ def test_eval_observables(self, observables: ListOrDict[OperatorBase]):
quantum_instance,
)

with self.subTest(msg="Test StateFn."):
statefn = StateFn(bound_ansatz)
self._run_test(
expected_result,
statefn,
decimal,
expectation,
observables,
quantum_instance,
)


if __name__ == "__main__":
unittest.main()

0 comments on commit 5306c95

Please sign in to comment.