... | ... |
@@ -1,3 +1,34 @@ |
1 | 1 |
"""Quantum measurements""" |
2 | 2 |
|
3 |
-__all__ = [] # type: ignore |
|
3 |
+from typing import Tuple |
|
4 |
+ |
|
5 |
+import numpy as np |
|
6 |
+ |
|
7 |
+from . import operator |
|
8 |
+from .state import normalize, num_qubits |
|
9 |
+ |
|
10 |
+__all__ = ["measure"] # type: ignore |
|
11 |
+ |
|
12 |
+ |
|
13 |
+def measure( |
|
14 |
+ rng: np.random.RandomState, qubit: int, state: np.ndarray |
|
15 |
+) -> Tuple[bool, np.ndarray]: |
|
16 |
+ """Measure the given qubit in the computational basis.""" |
|
17 |
+ nqs = num_qubits(state) |
|
18 |
+ if qubit >= nqs: |
|
19 |
+ raise ValueError("Cannot measure qubit {qubit} of an {nqs}-qubit state.") |
|
20 |
+ |
|
21 |
+ proj_1 = operator.apply(m_1, [qubit], state) |
|
22 |
+ |
|
23 |
+ p_1 = state.conj() @ proj_1 |
|
24 |
+ |
|
25 |
+ if rng.random() < p_1: |
|
26 |
+ return (True, normalize(proj_1)) |
|
27 |
+ else: |
|
28 |
+ proj_0 = operator.apply(m_0, [qubit], state) |
|
29 |
+ p_0 = 1 - p_1 |
|
30 |
+ return (False, normalize(proj_0)) |
|
31 |
+ |
|
32 |
+ |
|
33 |
+m_1 = np.array([[0, 0], [0, 1]], complex) |
|
34 |
+m_0 = np.array([[1, 0], [0, 0]], complex) |