Skip to content

Commit ed3276e

Browse files
authored
Fix memory handling in result formatting to include only measured bits (#245)
Fix memory handling in result formatting to include only measured bits
1 parent 0e805b3 commit ed3276e

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

qiskit_aqt_provider/aqt_job.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -523,7 +523,22 @@ def _partial_qiskit_result_dict(
523523
data: dict[str, Any] = {"counts": _format_counts(samples, meas_map)}
524524

525525
if memory:
526-
data["memory"] = ["".join(str(x) for x in reversed(states)) for states in samples]
526+
# build per-shot classical memory strings using the measurement mapping
527+
mem_slots = circuit.num_clbits
528+
memory_list: list[str] = []
529+
for states in samples:
530+
# initialize classical register (all 0)
531+
creg = ["0"] * mem_slots
532+
for src_index, dest_indices in meas_map.items():
533+
if src_index < len(states):
534+
src_bit = str(states[src_index])
535+
for dest_index in dest_indices:
536+
# place measured bit into the classical register position(s)
537+
if 0 <= dest_index < mem_slots:
538+
creg[dest_index] = src_bit
539+
# Qiskit orders memory strings with bit 0 as least-significant (rightmost)
540+
memory_list.append("".join(reversed(creg)))
541+
data["memory"] = memory_list
527542

528543
return {
529544
"shots": shots,

test/test_execution.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,39 @@ def test_get_memory_ancilla_qubits(
239239
assert len(memory) == shots
240240

241241

242+
@pytest.mark.parametrize(
243+
("clbits", "flip", "measure", "expected"),
244+
[
245+
(5, [1], [0, 1, 2, 3, 4], "00010"),
246+
(3, [1], [0, 1, 2], "010"),
247+
(2, [2, 4], [3, 4], "10"),
248+
(3, [2, 3], [1, 2, 3], "110"),
249+
(3, [2, 4], [0, 2, 4], "110"),
250+
],
251+
)
252+
def test_memory_ignores_unmeasured_qubits(
253+
clbits: int,
254+
flip: list[int],
255+
measure: list[int],
256+
expected: str,
257+
any_offline_simulator_no_noise: AnyAQTResource,
258+
) -> None:
259+
"""Regression test: memory should only contain measured classical bits."""
260+
qc = QuantumCircuit(5, clbits)
261+
for i in flip:
262+
qc.x(i)
263+
qc.measure(measure, range(clbits))
264+
265+
job = any_offline_simulator_no_noise.run(
266+
qiskit.transpile(qc, any_offline_simulator_no_noise), shots=2, memory=True
267+
)
268+
269+
memory = job.result().get_memory()
270+
271+
assert set(memory) == {expected}
272+
assert len(memory) == 2
273+
274+
242275
@pytest.mark.parametrize("shots", [123])
243276
def test_get_memory_bit_ordering(
244277
shots: int, any_offline_simulator_no_noise: AnyAQTResource

0 commit comments

Comments
 (0)