Skip to content

Commit

Permalink
Fix marginal_counts on memory with non-zero indices
Browse files Browse the repository at this point in the history
The marginalisation could previously return the empty string instead of
`"0"` if the given indices were too high for a given memory slot,
causing a later error in binary-to-hex conversion.
  • Loading branch information
jakelishman committed May 11, 2022
1 parent c8ad6cf commit 194138f
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 1 deletion.
2 changes: 1 addition & 1 deletion qiskit/result/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ def marginal_counts(
) # same convention as for the counts
bit_strings = [_hex_to_bin(s) for s in experiment_result.data.memory]
marginal_bit_strings = [
"".join([s[-idx - 1] for idx in sorted_indices if idx < len(s)])
"".join([s[-idx - 1] for idx in sorted_indices if idx < len(s)]) or "0"
for s in bit_strings
]
experiment_result.data.memory = [_bin_to_hex(s) for s in marginal_bit_strings]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
fixes:
- |
:func:`.marginal_counts` will now succeed when asked to marginalise memory
with an ``indices`` parameter containing non-zero elements. Previously,
shots whose hexadecimal result representation was sufficiently small could
raise a ``ValueError``. See `#8044 <https://github.com/Qiskit/qiskit-terra/issues/8044>`__.
10 changes: 10 additions & 0 deletions test/python/result/test_result.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,16 @@ def test_marginal_counts_result_memory(self):
marginal_memory = marginal_result.results[0].data.memory
self.assertEqual(marginal_memory, [hex(ii % 2) for ii in range(8)])

def test_marginal_counts_result_memory_nonzero_indices(self):
"""Test that a Result object containing memory marginalizes correctly."""
result = self.generate_qiskit_result()
index = 2
marginal_result = marginal_counts(result, indices=[index])
marginal_memory = marginal_result.results[0].data.memory
mask = 1 << index
expected = [hex((ii & mask) >> index) for ii in range(8)]
self.assertEqual(marginal_memory, expected)

def test_marginal_counts_result_memory_indices_None(self):
"""Test that a Result object containing memory marginalizes correctly."""
result = self.generate_qiskit_result()
Expand Down

0 comments on commit 194138f

Please sign in to comment.