Skip to content

Commit

Permalink
Fix Observables.coerce() for 0-d inputs (#11868)
Browse files Browse the repository at this point in the history
* Fix Observables.coerce() for 0-d inputs

* force build
  • Loading branch information
ihincks committed Feb 23, 2024
1 parent 3e6b646 commit c92752d
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 3 deletions.
2 changes: 0 additions & 2 deletions qiskit/primitives/containers/observables_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,8 +230,6 @@ def coerce(cls, observables: ObservablesArrayLike) -> ObservablesArray:
"""
if isinstance(observables, ObservablesArray):
return observables
if isinstance(observables, (str, SparsePauliOp, Pauli, _Mapping)):
observables = [observables]
return cls(observables)

def validate(self):
Expand Down
6 changes: 6 additions & 0 deletions releasenotes/notes/obs-array-coerce-0d-28b192fb3d004d4a.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
fixes:
- |
Fixed `qiskit.primitives.containers.observables_array.ObservablesArray.coerce()`
so that it returns a 0-d array when the input is a single, unnested observable.
Previously, it erroneously upgraded to a single dimension, with shape `(1,)`.
16 changes: 15 additions & 1 deletion test/python/primitives/containers/test_observables_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def test_coerce_observable_str(self, num_qubits):
self.assertEqual(obs, {label: 1})

def test_coerce_observable_custom_basis(self):
"""Test coerce_observable for custom allowed basis"""
"""Test coerce_observable for custom al flowed basis"""

class PauliArray(ObservablesArray):
"""Custom array allowing only Paulis, not projectors"""
Expand Down Expand Up @@ -127,6 +127,20 @@ def test_coerce_observable_pauli_mapping(self):
target = {key.to_label(): val for key, val in mapping.items()}
self.assertEqual(obs, target)

def test_coerce_0d(self):
"""Test the coerce() method with 0-d input."""
obs = ObservablesArray.coerce("X")
self.assertEqual(obs.shape, ())
self.assertDictAlmostEqual(obs[()], {"X": 1})

obs = ObservablesArray.coerce({"I": 2})
self.assertEqual(obs.shape, ())
self.assertDictAlmostEqual(obs[()], {"I": 2})

obs = ObservablesArray.coerce(qi.SparsePauliOp(["X", "Y"], [1, 3]))
self.assertEqual(obs.shape, ())
self.assertDictAlmostEqual(obs[()], {"X": 1, "Y": 3})

def test_format_invalid_mapping_qubits(self):
"""Test an error is raised when different qubits in mapping keys"""
mapping = {"IX": 1, "XXX": 2}
Expand Down

0 comments on commit c92752d

Please sign in to comment.