Skip to content

Commit

Permalink
fix sampling bit array with zero shots (#326)
Browse files Browse the repository at this point in the history
  • Loading branch information
kevinsung authored Oct 9, 2024
1 parent d679dcb commit 72fe5c3
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
4 changes: 4 additions & 0 deletions python/ffsim/states/bitstring.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,8 @@ def convert_bitstring_type(
return [int(s, base=2) for s in strings]

if output_type is BitstringType.BIT_ARRAY:
if not strings:
return np.empty((0, length), dtype=bool)
return np.array([[b == "1" for b in s] for s in strings])

if input_type is BitstringType.INT:
Expand All @@ -166,6 +168,8 @@ def convert_bitstring_type(
return [f"{string:0{length}b}" for string in strings]

if output_type is BitstringType.BIT_ARRAY:
if not strings:
return np.empty((0, length), dtype=bool)
return np.array(
[[s >> i & 1 for i in range(length - 1, -1, -1)] for s in strings],
dtype=bool,
Expand Down
16 changes: 12 additions & 4 deletions tests/python/qiskit/sampler_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,8 +256,17 @@ def test_measure_subset_spinless(norb: int, nocc: int):
assert _fidelity(ffsim_probs, qiskit_probs) > 0.99


@pytest.mark.parametrize("norb, nelec", [(5, (3, 2))])
def test_global_depolarizing(norb: int, nelec: tuple[int, int]):
@pytest.mark.parametrize(
"norb, nelec, global_depolarizing",
[
(5, (3, 2), 0.0),
(5, (3, 2), 0.1),
(5, (3, 2), 1.0),
],
)
def test_global_depolarizing(
norb: int, nelec: tuple[int, int], global_depolarizing: float
):
"""Test sampler with global depolarizing noise."""
rng = np.random.default_rng(12285)

Expand All @@ -269,7 +278,6 @@ def test_global_depolarizing(norb: int, nelec: tuple[int, int]):
circuit.measure_all()

shots = 10_000
global_depolarizing = 0.1

sampler = ffsim.qiskit.FfsimSampler(
default_shots=shots, global_depolarizing=global_depolarizing, seed=rng
Expand Down Expand Up @@ -297,7 +305,7 @@ def test_global_depolarizing(norb: int, nelec: tuple[int, int]):

fidelity = np.sum(np.sqrt(exact_probs * empirical_probs))
expected_fidelity = np.sum(np.sqrt(exact_probs * expected_probs))
assert np.allclose(fidelity, expected_fidelity, rtol=1e-2)
assert np.allclose(fidelity, expected_fidelity, rtol=1e-2, atol=1e-3)


# TODO remove after removing UCJOperatorJW
Expand Down

0 comments on commit 72fe5c3

Please sign in to comment.