From 72fe5c3c457c2ba964f6ec7fd49896167347808b Mon Sep 17 00:00:00 2001 From: "Kevin J. Sung" Date: Wed, 9 Oct 2024 15:52:00 -0400 Subject: [PATCH] fix sampling bit array with zero shots (#326) --- python/ffsim/states/bitstring.py | 4 ++++ tests/python/qiskit/sampler_test.py | 16 ++++++++++++---- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/python/ffsim/states/bitstring.py b/python/ffsim/states/bitstring.py index 98cc3ae22..14b73e3b9 100644 --- a/python/ffsim/states/bitstring.py +++ b/python/ffsim/states/bitstring.py @@ -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: @@ -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, diff --git a/tests/python/qiskit/sampler_test.py b/tests/python/qiskit/sampler_test.py index c8ffcd358..180e08151 100644 --- a/tests/python/qiskit/sampler_test.py +++ b/tests/python/qiskit/sampler_test.py @@ -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) @@ -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 @@ -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