Skip to content

Commit 555899e

Browse files
Fix Observables.coerce() for 0-d inputs (#11868) (#11876)
* Fix Observables.coerce() for 0-d inputs * force build (cherry picked from commit c92752d) Co-authored-by: Ian Hincks <ian.hincks@ibm.com>
1 parent d4d3873 commit 555899e

File tree

3 files changed

+21
-3
lines changed

3 files changed

+21
-3
lines changed

qiskit/primitives/containers/observables_array.py

-2
Original file line numberDiff line numberDiff line change
@@ -230,8 +230,6 @@ def coerce(cls, observables: ObservablesArrayLike) -> ObservablesArray:
230230
"""
231231
if isinstance(observables, ObservablesArray):
232232
return observables
233-
if isinstance(observables, (str, SparsePauliOp, Pauli, _Mapping)):
234-
observables = [observables]
235233
return cls(observables)
236234

237235
def validate(self):
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
fixes:
3+
- |
4+
Fixed `qiskit.primitives.containers.observables_array.ObservablesArray.coerce()`
5+
so that it returns a 0-d array when the input is a single, unnested observable.
6+
Previously, it erroneously upgraded to a single dimension, with shape `(1,)`.

test/python/primitives/containers/test_observables_array.py

+15-1
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ def test_coerce_observable_str(self, num_qubits):
3434
self.assertEqual(obs, {label: 1})
3535

3636
def test_coerce_observable_custom_basis(self):
37-
"""Test coerce_observable for custom allowed basis"""
37+
"""Test coerce_observable for custom al flowed basis"""
3838

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

130+
def test_coerce_0d(self):
131+
"""Test the coerce() method with 0-d input."""
132+
obs = ObservablesArray.coerce("X")
133+
self.assertEqual(obs.shape, ())
134+
self.assertDictAlmostEqual(obs[()], {"X": 1})
135+
136+
obs = ObservablesArray.coerce({"I": 2})
137+
self.assertEqual(obs.shape, ())
138+
self.assertDictAlmostEqual(obs[()], {"I": 2})
139+
140+
obs = ObservablesArray.coerce(qi.SparsePauliOp(["X", "Y"], [1, 3]))
141+
self.assertEqual(obs.shape, ())
142+
self.assertDictAlmostEqual(obs[()], {"X": 1, "Y": 3})
143+
130144
def test_format_invalid_mapping_qubits(self):
131145
"""Test an error is raised when different qubits in mapping keys"""
132146
mapping = {"IX": 1, "XXX": 2}

0 commit comments

Comments
 (0)