Browse code

Add tests for the measurement module

Joseph Weston authored on 01/11/2023 04:35:35
Showing 1 changed files
1 1
new file mode 100644
... ...
@@ -0,0 +1,45 @@
1
+from functools import reduce
2
+
3
+from hypothesis import given
4
+import hypothesis.strategies as st
5
+import numpy as np
6
+import pytest
7
+
8
+import qsim.gate
9
+import qsim.state
10
+from qsim.measurement import measure
11
+
12
+from .common import (
13
+    classical_bitstrings,
14
+    n_qubits,
15
+    rng,
16
+    valid_states,
17
+)
18
+
19
+classical_states = classical_bitstrings.map(qsim.state.from_classical)
20
+arbitrary_qubit = n_qubits.flatmap(lambda n: st.integers(0, n - 1))
21
+
22
+
23
+@given(rng, arbitrary_qubit, classical_bitstrings)
24
+def test_classical_measurement(rng, qubit, bitstring):
25
+    """Test measurements on "classical" states.
26
+
27
+    The outcome of a measurement on qubit 'n' of a classical state (i.e. a state
28
+    constructed from a classical bitstring) is the value of the n-th bit of
29
+    the bitstring.
30
+    """
31
+    classical_state = qsim.state.from_classical(bitstring)
32
+    # [::-1] because qubits are indexed from the least-significant,
33
+    # but bitstring are written most-significant bit first.
34
+    expected_outcome = bool(int(bitstring[::-1][qubit]))
35
+    outcome, _ = measure(rng, qubit, classical_state)
36
+    assert outcome == expected_outcome
37
+
38
+
39
+@given(rng, arbitrary_qubit, valid_states)
40
+def test_subsequent_measurement(rng, qubit, ket):
41
+    """Test that subsequent measurements of the same qubit yield the same outcome."""
42
+    outcome, measured_ket = measure(rng, qubit, ket)
43
+    outcome2, measured_ket2 = measure(rng, qubit, measured_ket)
44
+    assert np.allclose(measured_ket, measured_ket2)
45
+    assert outcome == outcome2