Skip to content

Commit

Permalink
Fix bitstring padding in the BackendSampler (Qiskit#9744)
Browse files Browse the repository at this point in the history
* fix padding

* add reno
  • Loading branch information
Cryoris authored Mar 7, 2023
1 parent 5c49d14 commit 2553376
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
2 changes: 1 addition & 1 deletion qiskit/primitives/backend_sampler.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ def _postprocessing(self, result: Result, circuits: list[QuantumCircuit]) -> Sam
probabilities = []
metadata: list[dict[str, Any]] = [{} for _ in range(len(circuits))]
for count in counts:
prob_dist = {k: v / shots for k, v in count.int_outcomes().items()}
prob_dist = {k: v / shots for k, v in count.items()}
probabilities.append(
QuasiDistribution(prob_dist, shots=shots, stddev_upper_bound=math.sqrt(1 / shots))
)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
fixes:
- |
Fixed a bug in the :class:`.BackendSampler` where the binary probability bitstrings
were truncated to the minimal number of bits required to represent the largest outcome
as integer. That means that if e.g. ``{"0001": 1.0}`` was measured, the result was truncated
to ``{"1": 1.0}``.
21 changes: 21 additions & 0 deletions test/python/primitives/test_backend_sampler.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
from qiskit.primitives import BackendSampler, SamplerResult
from qiskit.providers import JobStatus, JobV1
from qiskit.providers.fake_provider import FakeNairobi, FakeNairobiV2
from qiskit.providers.basicaer import QasmSimulatorPy
from qiskit.test import QiskitTestCase
from qiskit.transpiler import PassManager
from qiskit.utils import optionals
Expand Down Expand Up @@ -361,6 +362,26 @@ def test_sequential_run(self):
self.assertDictAlmostEqual(result3.quasi_dists[0], {0: 1}, 0.1)
self.assertDictAlmostEqual(result3.quasi_dists[1], {1: 1}, 0.1)

def test_outcome_bitstring_size(self):
"""Test that the result bitstrings are properly padded.
E.g. measuring '0001' should not get truncated to '1'.
"""
qc = QuantumCircuit(4)
qc.x(0)
qc.measure_all()

# We need a noise-free backend here (shot noise is fine) to ensure that
# the only bit string measured is "0001". With device noise, it could happen that
# strings with a leading 1 are measured and then the truncation cannot be tested.
sampler = BackendSampler(backend=QasmSimulatorPy())

result = sampler.run(qc).result()
probs = result.quasi_dists[0].binary_probabilities()

self.assertIn("0001", probs.keys())
self.assertEqual(len(probs), 1)

def test_bound_pass_manager(self):
"""Test bound pass manager."""

Expand Down

0 comments on commit 2553376

Please sign in to comment.