Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix marginal_counts on memory with non-zero indices #8047

Merged
merged 2 commits into from
May 11, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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"
mtreinish marked this conversation as resolved.
Show resolved Hide resolved
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