diff --git a/qiskit/result/utils.py b/qiskit/result/utils.py index 498798bbe94b..d0fb018e8a58 100644 --- a/qiskit/result/utils.py +++ b/qiskit/result/utils.py @@ -14,7 +14,7 @@ """Utility functions for working with Results.""" -from typing import List, Union, Optional, Dict +from typing import Sequence, Union, Optional, Dict, List from collections import Counter from copy import deepcopy @@ -199,7 +199,9 @@ def marginal_memory( def marginal_distribution( - counts: dict, indices: Optional[List[int]] = None, format_marginal: bool = False + counts: dict, + indices: Optional[Sequence[int]] = None, + format_marginal: bool = False, ) -> Dict[str, int]: """Marginalize counts from an experiment over some indices of interest. @@ -222,7 +224,7 @@ def marginal_distribution( is invalid. """ num_clbits = len(max(counts.keys()).replace(" ", "")) - if indices is not None and (not indices or not set(indices).issubset(range(num_clbits))): + if indices is not None and (len(indices) == 0 or not set(indices).issubset(range(num_clbits))): raise QiskitError(f"indices must be in range [0, {num_clbits - 1}].") if isinstance(counts, Counts): diff --git a/releasenotes/notes/fix-numpy-indices-marginal-dist-45889e49ba337d84.yaml b/releasenotes/notes/fix-numpy-indices-marginal-dist-45889e49ba337d84.yaml new file mode 100644 index 000000000000..713a22b1f9ff --- /dev/null +++ b/releasenotes/notes/fix-numpy-indices-marginal-dist-45889e49ba337d84.yaml @@ -0,0 +1,7 @@ +--- +fixes: + - | + Fixed an issue with the :func:`~.marginal_distribution` function: when + a numpy array was passed in for the ``indices`` argument the function would + raise an error. + Fixed `#8283 `__ diff --git a/test/python/result/test_counts.py b/test/python/result/test_counts.py index 33d93c25e81d..6fa52b92917a 100644 --- a/test/python/result/test_counts.py +++ b/test/python/result/test_counts.py @@ -16,6 +16,8 @@ import unittest +import numpy as np + from qiskit.result import counts from qiskit import exceptions from qiskit.result import utils @@ -50,6 +52,14 @@ def test_marginal_distribution(self): result = utils.marginal_distribution(counts_obj, [0, 1]) self.assertEqual(expected, result) + def test_marginal_distribution_numpy_indices(self): + raw_counts = {"0x0": 4, "0x1": 7, "0x2": 10, "0x6": 5, "0x9": 11, "0xD": 9, "0xE": 8} + expected = {"00": 4, "01": 27, "10": 23} + indices = np.asarray([0, 1]) + counts_obj = counts.Counts(raw_counts, creg_sizes=[["c0", 4]], memory_slots=4) + result = utils.marginal_distribution(counts_obj, indices) + self.assertEqual(expected, result) + def test_int_outcomes(self): raw_counts = {"0x0": 21, "0x2": 12, "0x3": 5, "0x2E": 265} expected = {0: 21, 2: 12, 3: 5, 46: 265}