quantakit 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,319 @@
1
+ """States, operators and observables, backed by NumPy arrays."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from typing import Iterable, Sequence
7
+
8
+ import numpy as np
9
+
10
+ from ..circuit.quantumcircuit import QuantumCircuit
11
+ from ..exceptions import CircuitError
12
+ from ..sim import engine
13
+
14
+ _PAULI = {
15
+ "I": np.eye(2, dtype=complex),
16
+ "X": np.array([[0, 1], [1, 0]], dtype=complex),
17
+ "Y": np.array([[0, -1j], [1j, 0]], dtype=complex),
18
+ "Z": np.array([[1, 0], [0, -1]], dtype=complex),
19
+ }
20
+
21
+
22
+ def _bits(i: int, n: int) -> str:
23
+ return format(i, f"0{n}b") if n else ""
24
+
25
+
26
+ def _fmt_c(z: complex) -> str:
27
+ re, im = round(z.real, 6) + 0.0, round(z.imag, 6) + 0.0
28
+ if im == 0:
29
+ return f"{re:g}"
30
+ if re == 0:
31
+ return f"{im:g}j"
32
+ return f"({re:g}{im:+g}j)"
33
+
34
+
35
+ class Statevector:
36
+ """A pure quantum state. ``Statevector.from_label("01")``, ``Statevector(circuit)``, or from an array.
37
+
38
+ ``data[i]`` is the amplitude of basis state ``i`` where bit k of i is qubit k (so ``"01"`` means q0 = 1).
39
+ """
40
+
41
+ def __init__(self, data: "Sequence[complex] | np.ndarray | QuantumCircuit"):
42
+ if isinstance(data, QuantumCircuit):
43
+ vec = engine.to_vector(engine.evolve(engine.zero_state(data.num_qubits), data, data.num_qubits))
44
+ else:
45
+ vec = np.asarray(data, dtype=complex).reshape(-1)
46
+ n = int(round(math.log2(len(vec)))) if len(vec) else 0
47
+ if 2 ** n != len(vec):
48
+ raise CircuitError("A statevector's length must be a power of 2.")
49
+ self._data = vec
50
+ self.num_qubits = n
51
+
52
+ @classmethod
53
+ def from_label(cls, label: str) -> "Statevector":
54
+ """Labels use 0, 1, +, -, r (|+i>), l (|-i>); the leftmost character is the highest qubit."""
55
+ single = {"0": [1, 0], "1": [0, 1], "+": [1, 1], "-": [1, -1], "r": [1, 1j], "l": [1, -1j]}
56
+ vec = np.array([1], dtype=complex)
57
+ for ch in label:
58
+ if ch not in single:
59
+ raise CircuitError(f"Unknown label character '{ch}'. Use 0 1 + - r l.")
60
+ v = np.array(single[ch], dtype=complex)
61
+ vec = np.kron(vec, v / np.linalg.norm(v))
62
+ return cls(vec)
63
+
64
+ @classmethod
65
+ def from_instruction(cls, circuit: QuantumCircuit) -> "Statevector":
66
+ return cls(circuit)
67
+
68
+ @property
69
+ def data(self) -> np.ndarray:
70
+ return self._data
71
+
72
+ def evolve(self, other: "QuantumCircuit | Operator") -> "Statevector":
73
+ if isinstance(other, Operator):
74
+ return Statevector(other.data @ self._data)
75
+ st = self._data.reshape((2,) * self.num_qubits) if self.num_qubits else self._data
76
+ return Statevector(engine.to_vector(engine.evolve(st, other, self.num_qubits)))
77
+
78
+ def probabilities(self, qargs: Sequence[int] | None = None) -> np.ndarray:
79
+ p = np.abs(self._data) ** 2
80
+ if qargs is None:
81
+ return p
82
+ out = np.zeros(2 ** len(qargs))
83
+ for i, pi in enumerate(p):
84
+ j = 0
85
+ for k, q in enumerate(qargs):
86
+ j |= ((i >> q) & 1) << k
87
+ out[j] += pi
88
+ return out
89
+
90
+ def probabilities_dict(self, qargs: Sequence[int] | None = None, decimals: int | None = None) -> dict[str, float]:
91
+ n = len(qargs) if qargs is not None else self.num_qubits
92
+ p = self.probabilities(qargs)
93
+ out = {}
94
+ for i, v in enumerate(p):
95
+ if v > 1e-12:
96
+ out[_bits(i, n)] = round(float(v), decimals) if decimals is not None else float(v)
97
+ return out
98
+
99
+ def sample_counts(self, shots: int, seed: int | None = None, qargs: Sequence[int] | None = None) -> dict[str, int]:
100
+ rng = np.random.default_rng(seed)
101
+ p = self.probabilities(qargs)
102
+ n = len(qargs) if qargs is not None else self.num_qubits
103
+ draws = rng.choice(len(p), size=shots, p=p / p.sum())
104
+ vals, cnt = np.unique(draws, return_counts=True)
105
+ return {_bits(int(v), n): int(c) for v, c in sorted(zip(vals, cnt), key=lambda t: -t[1])}
106
+
107
+ def expectation_value(self, oper: "SparsePauliOp | Operator | np.ndarray") -> complex:
108
+ mat = oper.to_matrix() if isinstance(oper, SparsePauliOp) else oper.data if isinstance(oper, Operator) else np.asarray(oper)
109
+ val = np.vdot(self._data, mat @ self._data)
110
+ return complex(val) if abs(val.imag) > 1e-12 else float(val.real)
111
+
112
+ def inner(self, other: "Statevector") -> complex:
113
+ return complex(np.vdot(self._data, other._data))
114
+
115
+ def equiv(self, other: "Statevector", atol: float = 1e-8) -> bool:
116
+ """Equal up to a global phase."""
117
+ return self.num_qubits == other.num_qubits and abs(abs(self.inner(other)) - 1) < atol
118
+
119
+ def to_dict(self, decimals: int = 6) -> dict[str, complex]:
120
+ return {_bits(i, self.num_qubits): complex(round(a.real, decimals), round(a.imag, decimals)) for i, a in enumerate(self._data) if abs(a) > 1e-10}
121
+
122
+ def __eq__(self, other):
123
+ return isinstance(other, Statevector) and np.allclose(self._data, other._data)
124
+
125
+ def __str__(self):
126
+ terms = [f"{_fmt_c(a)}|{_bits(i, self.num_qubits)}>" for i, a in enumerate(self._data) if abs(a) > 1e-10]
127
+ return " + ".join(terms) or "0"
128
+
129
+ def __repr__(self):
130
+ return f"Statevector({self})"
131
+
132
+ def draw(self, output: str = "text") -> str:
133
+ if output != "text":
134
+ raise CircuitError("Statevector.draw supports output='text' in this edition.")
135
+ return str(self)
136
+
137
+
138
+ class DensityMatrix:
139
+ """A (possibly mixed) state. Build from a Statevector or a circuit; use ``partial_trace`` to discard qubits."""
140
+
141
+ def __init__(self, data: "np.ndarray | Statevector | QuantumCircuit"):
142
+ if isinstance(data, QuantumCircuit):
143
+ data = Statevector(data)
144
+ if isinstance(data, Statevector):
145
+ data = np.outer(data.data, data.data.conj())
146
+ self._data = np.asarray(data, dtype=complex)
147
+ self.num_qubits = int(round(math.log2(self._data.shape[0])))
148
+
149
+ @property
150
+ def data(self) -> np.ndarray:
151
+ return self._data
152
+
153
+ def probabilities(self) -> np.ndarray:
154
+ return np.real(np.diag(self._data)).copy()
155
+
156
+ def probabilities_dict(self) -> dict[str, float]:
157
+ return {_bits(i, self.num_qubits): float(p) for i, p in enumerate(self.probabilities()) if p > 1e-12}
158
+
159
+ def purity(self) -> float:
160
+ return float(np.real(np.trace(self._data @ self._data)))
161
+
162
+ def expectation_value(self, oper) -> float:
163
+ mat = oper.to_matrix() if isinstance(oper, SparsePauliOp) else oper.data if isinstance(oper, Operator) else np.asarray(oper)
164
+ return float(np.real(np.trace(self._data @ mat)))
165
+
166
+
167
+ def partial_trace(state: "Statevector | DensityMatrix", qargs: Iterable[int]) -> DensityMatrix:
168
+ """Trace out the qubits in ``qargs``; returns the reduced density matrix of the rest."""
169
+ rho = state if isinstance(state, DensityMatrix) else DensityMatrix(state)
170
+ n = rho.num_qubits
171
+ trace_out = sorted(set(qargs))
172
+ t = rho.data.reshape((2,) * (2 * n))
173
+ # tensor axes: 0..n-1 rows (axis 0 = highest qubit), n..2n-1 columns
174
+ for count, q in enumerate(sorted(trace_out, reverse=True)):
175
+ m = n - count
176
+ ax = m - 1 - q
177
+ t = np.trace(t, axis1=ax, axis2=ax + m)
178
+ keep = n - len(trace_out)
179
+ return DensityMatrix(t.reshape(2 ** keep, 2 ** keep))
180
+
181
+
182
+ def state_fidelity(a: "Statevector | DensityMatrix", b: "Statevector | DensityMatrix") -> float:
183
+ if isinstance(a, Statevector) and isinstance(b, Statevector):
184
+ return float(abs(a.inner(b)) ** 2)
185
+ if isinstance(a, Statevector):
186
+ a, b = b, a
187
+ if isinstance(b, Statevector):
188
+ return float(np.real(np.vdot(b.data, a.data @ b.data)))
189
+ from numpy.linalg import eigh
190
+ w, v = eigh(a.data)
191
+ sq = v @ np.diag(np.sqrt(np.clip(w, 0, None))) @ v.conj().T
192
+ ev = np.linalg.eigvalsh(sq @ b.data @ sq)
193
+ return float(np.sum(np.sqrt(np.clip(ev, 0, None))) ** 2)
194
+
195
+
196
+ def entropy(state: "Statevector | DensityMatrix", base: float = 2) -> float:
197
+ """Von Neumann entropy."""
198
+ rho = state if isinstance(state, DensityMatrix) else DensityMatrix(state)
199
+ ev = np.linalg.eigvalsh(rho.data)
200
+ ev = ev[ev > 1e-12]
201
+ return float(-np.sum(ev * np.log(ev)) / np.log(base))
202
+
203
+
204
+ class Operator:
205
+ """A unitary (or general) matrix. ``Operator(circuit)`` gives the circuit's unitary (up to ~12 qubits)."""
206
+
207
+ def __init__(self, data: "np.ndarray | QuantumCircuit"):
208
+ if isinstance(data, QuantumCircuit):
209
+ n = data.num_qubits
210
+ if n > 12:
211
+ raise CircuitError("Operator(circuit) is limited to 12 qubits.")
212
+ cols = []
213
+ for i in range(2 ** n):
214
+ basis = np.zeros(2 ** n, dtype=complex)
215
+ basis[i] = 1
216
+ st = basis.reshape((2,) * n) if n else basis
217
+ cols.append(engine.to_vector(engine.evolve(st, data, n, allow_final_measure=False)))
218
+ data = np.array(cols).T
219
+ self._data = np.asarray(data, dtype=complex)
220
+ self.num_qubits = int(round(math.log2(self._data.shape[0])))
221
+
222
+ @classmethod
223
+ def from_label(cls, label: str) -> "Operator":
224
+ m = np.array([[1]], dtype=complex)
225
+ for ch in label:
226
+ m = np.kron(m, _PAULI[ch])
227
+ return cls(m)
228
+
229
+ @property
230
+ def data(self) -> np.ndarray:
231
+ return self._data
232
+
233
+ def adjoint(self) -> "Operator":
234
+ return Operator(self._data.conj().T)
235
+
236
+ def compose(self, other: "Operator") -> "Operator":
237
+ """Apply self, then other."""
238
+ return Operator(other.data @ self._data)
239
+
240
+ def tensor(self, other: "Operator") -> "Operator":
241
+ return Operator(np.kron(self._data, other.data))
242
+
243
+ def is_unitary(self, atol: float = 1e-8) -> bool:
244
+ return np.allclose(self._data @ self._data.conj().T, np.eye(len(self._data)), atol=atol)
245
+
246
+ def equiv(self, other: "Operator | QuantumCircuit", atol: float = 1e-8) -> bool:
247
+ """Equal up to a global phase."""
248
+ o = other if isinstance(other, Operator) else Operator(other)
249
+ if o.data.shape != self._data.shape:
250
+ return False
251
+ idx = np.unravel_index(np.argmax(np.abs(self._data)), self._data.shape)
252
+ if abs(o.data[idx]) < atol:
253
+ return False
254
+ phase = self._data[idx] / o.data[idx]
255
+ return abs(abs(phase) - 1) < atol and np.allclose(self._data, phase * o.data, atol=atol)
256
+
257
+ def __eq__(self, other):
258
+ return isinstance(other, Operator) and np.allclose(self._data, other.data)
259
+
260
+ def __repr__(self):
261
+ return f"Operator({self.num_qubits} qubits)\n{np.round(self._data, 4)}"
262
+
263
+
264
+ class SparsePauliOp:
265
+ """A weighted sum of Pauli strings, e.g. ``SparsePauliOp.from_list([("ZZ", 1.0), ("XI", 0.5)])``.
266
+
267
+ The rightmost character acts on qubit 0.
268
+ """
269
+
270
+ def __init__(self, paulis: "str | Sequence[str]", coeffs: Sequence[complex] | None = None):
271
+ paulis = [paulis] if isinstance(paulis, str) else list(paulis)
272
+ if not paulis:
273
+ raise CircuitError("SparsePauliOp needs at least one Pauli string.")
274
+ n = len(paulis[0])
275
+ for p in paulis:
276
+ if len(p) != n or any(ch not in "IXYZ" for ch in p):
277
+ raise CircuitError(f"Invalid Pauli string '{p}': use I, X, Y, Z with equal lengths.")
278
+ self.paulis = paulis
279
+ self.coeffs = np.array(coeffs if coeffs is not None else [1.0] * len(paulis), dtype=complex)
280
+ self.num_qubits = n
281
+
282
+ @classmethod
283
+ def from_list(cls, pairs: Sequence[tuple[str, complex]]) -> "SparsePauliOp":
284
+ return cls([p for p, _ in pairs], [c for _, c in pairs])
285
+
286
+ def to_list(self) -> list[tuple[str, complex]]:
287
+ return list(zip(self.paulis, self.coeffs.tolist()))
288
+
289
+ def to_matrix(self) -> np.ndarray:
290
+ dim = 2 ** self.num_qubits
291
+ m = np.zeros((dim, dim), dtype=complex)
292
+ for p, c in zip(self.paulis, self.coeffs):
293
+ m += c * Operator.from_label(p).data
294
+ return m
295
+
296
+ def simplify(self, atol: float = 1e-12) -> "SparsePauliOp":
297
+ acc: dict[str, complex] = {}
298
+ for p, c in zip(self.paulis, self.coeffs):
299
+ acc[p] = acc.get(p, 0) + c
300
+ kept = [(p, c) for p, c in acc.items() if abs(c) > atol] or [("I" * self.num_qubits, 0)]
301
+ return SparsePauliOp.from_list(kept)
302
+
303
+ def __add__(self, other: "SparsePauliOp") -> "SparsePauliOp":
304
+ return SparsePauliOp(self.paulis + other.paulis, list(self.coeffs) + list(other.coeffs))
305
+
306
+ def __mul__(self, k: complex) -> "SparsePauliOp":
307
+ return SparsePauliOp(self.paulis, self.coeffs * k)
308
+
309
+ __rmul__ = __mul__
310
+
311
+ def __len__(self):
312
+ return len(self.paulis)
313
+
314
+ def __repr__(self):
315
+ terms = ", ".join(f"('{p}', {_fmt_c(c)})" for p, c in zip(self.paulis, self.coeffs))
316
+ return f"SparsePauliOp([{terms}])"
317
+
318
+
319
+ __all__ = ["Statevector", "DensityMatrix", "Operator", "SparsePauliOp", "partial_trace", "state_fidelity", "entropy"]
@@ -0,0 +1,52 @@
1
+ """Local simulators. Free, offline, no account or token needed."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+ from ..exceptions import BackendError
8
+ from .engine import MAX_QUBITS
9
+
10
+
11
+ @dataclass
12
+ class BackendStatus:
13
+ name: str
14
+ operational: bool
15
+ pending_jobs: int
16
+ status_msg: str = "online"
17
+
18
+
19
+ class LocalSimulator:
20
+ """Exact statevector simulator running on your computer.
21
+
22
+ >>> from quantakit import LocalSimulator
23
+ >>> backend = LocalSimulator() # ideal
24
+ >>> noisy = LocalSimulator(readout_error=0.02) # 2% chance each measured bit flips
25
+
26
+ Use it with ``Sampler(backend)`` / ``Estimator(backend)``. Supports every gate in the library, mid-circuit
27
+ measurement and reset, up to 26 qubits (memory permitting).
28
+ """
29
+
30
+ is_local = True
31
+
32
+ def __init__(self, readout_error: float = 0.0, name: str = "local_statevector"):
33
+ if not 0 <= readout_error < 0.5:
34
+ raise BackendError("readout_error must be between 0 and 0.5.")
35
+ self.name = name
36
+ self.readout_error = float(readout_error)
37
+ self.num_qubits = MAX_QUBITS
38
+ self.basis_gates: list[str] | None = None # any gate
39
+
40
+ def status(self) -> BackendStatus:
41
+ return BackendStatus(self.name, True, 0)
42
+
43
+ def run(self, circuits, shots: int = 1024, seed: int | None = None):
44
+ """Shortcut for ``Sampler(self).run(circuits, shots=shots, seed=seed)``."""
45
+ from ..primitives import Sampler
46
+ return Sampler(self).run(circuits if isinstance(circuits, list) else [circuits], shots=shots, seed=seed)
47
+
48
+ def __repr__(self):
49
+ return f"<LocalSimulator '{self.name}'{f' readout_error={self.readout_error}' if self.readout_error else ''}>"
50
+
51
+
52
+ __all__ = ["LocalSimulator", "BackendStatus"]
@@ -0,0 +1,149 @@
1
+ """NumPy statevector engine. Qubit 0 is the least-significant bit of every basis index (little-endian)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import cmath
6
+ from typing import Iterator
7
+
8
+ import numpy as np
9
+
10
+ from ..circuit.gates import gate_matrix
11
+ from ..circuit.quantumcircuit import QuantumCircuit, Instruction
12
+ from ..circuit.parameter import ParameterExpression
13
+ from ..exceptions import CircuitError
14
+
15
+ MAX_QUBITS = 26
16
+
17
+
18
+ def flatten(qc: QuantumCircuit, qmap: tuple[int, ...] | None = None) -> Iterator[Instruction]:
19
+ """Yield primitive instructions, expanding custom gates (``to_gate``) recursively."""
20
+ for ins in qc.data:
21
+ qs = tuple(qmap[q] for q in ins.qubits) if qmap else ins.qubits
22
+ if ins.definition is not None:
23
+ yield from flatten(ins.definition, qs)
24
+ else:
25
+ yield Instruction(ins.name, qs, ins.clbits, ins.params)
26
+
27
+
28
+ def total_phase(qc: QuantumCircuit) -> float:
29
+ ph = float(qc.global_phase)
30
+ for ins in qc.data:
31
+ if ins.definition is not None:
32
+ ph += total_phase(ins.definition)
33
+ return ph
34
+
35
+
36
+ def numeric(params) -> list[float]:
37
+ out = []
38
+ for p in params:
39
+ if isinstance(p, ParameterExpression):
40
+ out.append(float(p)) # raises a helpful CircuitError if unbound
41
+ else:
42
+ out.append(float(p))
43
+ return out
44
+
45
+
46
+ def zero_state(n: int) -> np.ndarray:
47
+ if n > MAX_QUBITS:
48
+ raise CircuitError(f"The local simulator handles up to {MAX_QUBITS} qubits; this circuit has {n}.")
49
+ st = np.zeros((2,) * n if n else (1,), dtype=complex)
50
+ st.flat[0] = 1.0
51
+ return st
52
+
53
+
54
+ def apply_matrix(state: np.ndarray, u: np.ndarray, qubits: tuple[int, ...], n: int) -> np.ndarray:
55
+ """Apply a k-qubit matrix (first listed qubit = most significant) to an n-qubit state tensor."""
56
+ k = len(qubits)
57
+ axes = [n - 1 - q for q in qubits] # tensor axis 0 is the highest qubit
58
+ ut = u.reshape((2,) * (2 * k))
59
+ out = np.tensordot(ut, state, axes=(list(range(k, 2 * k)), axes))
60
+ return np.moveaxis(out, list(range(k)), axes)
61
+
62
+
63
+ def evolve(state: np.ndarray, qc: QuantumCircuit, n: int, allow_final_measure: bool = True) -> np.ndarray:
64
+ measured: set[int] = set()
65
+ for ins in flatten(qc):
66
+ if ins.name == "barrier":
67
+ continue
68
+ if ins.name == "measure":
69
+ if not allow_final_measure:
70
+ raise CircuitError("This operation needs a circuit without measurements.")
71
+ measured.add(ins.qubits[0])
72
+ continue
73
+ if ins.name == "reset":
74
+ raise CircuitError("reset() can't be represented in a statevector.", "Run the circuit with Sampler instead.")
75
+ if measured & set(ins.qubits):
76
+ raise CircuitError("A gate acts on a qubit after it was measured.", "Run mid-circuit measurements with Sampler.")
77
+ state = apply_matrix(state, gate_matrix(ins.name, numeric(ins.params)), ins.qubits, n)
78
+ ph = total_phase(qc)
79
+ return state * cmath.exp(1j * ph) if ph else state
80
+
81
+
82
+ def to_vector(state: np.ndarray) -> np.ndarray:
83
+ return state.reshape(-1)
84
+
85
+
86
+ def _is_terminal(qc_flat: list[Instruction]) -> bool:
87
+ """True if no gate or reset touches a qubit after it was measured (fast sampling path)."""
88
+ measured: set[int] = set()
89
+ for ins in qc_flat:
90
+ if ins.name == "measure":
91
+ measured.add(ins.qubits[0])
92
+ elif ins.name == "barrier":
93
+ continue
94
+ elif ins.name == "reset" or measured & set(ins.qubits):
95
+ return False
96
+ return True
97
+
98
+
99
+ def sample_clbits(qc: QuantumCircuit, shots: int, seed: int | None = None, readout_error: float = 0.0) -> np.ndarray:
100
+ """Run ``shots`` shots and return an int array of classical-register values (bit c = classical bit c)."""
101
+ n = qc.num_qubits
102
+ rng = np.random.default_rng(seed)
103
+ ops = list(flatten(qc))
104
+ clbits = np.zeros(shots, dtype=np.int64)
105
+ if _is_terminal(ops):
106
+ state = zero_state(n)
107
+ for ins in ops:
108
+ if ins.name in ("measure", "barrier"):
109
+ continue
110
+ state = apply_matrix(state, gate_matrix(ins.name, numeric(ins.params)), ins.qubits, n)
111
+ probs = np.abs(to_vector(state)) ** 2
112
+ probs = probs / probs.sum()
113
+ outcomes = rng.choice(len(probs), size=shots, p=probs)
114
+ for ins in ops:
115
+ if ins.name == "measure":
116
+ q, c = ins.qubits[0], ins.clbits[0]
117
+ bit = (outcomes >> q) & 1
118
+ if readout_error:
119
+ flip = rng.random(shots) < readout_error
120
+ bit = bit ^ flip
121
+ clbits = (clbits & ~(1 << c)) | (bit.astype(np.int64) << c)
122
+ return clbits
123
+ # Trajectory path: mid-circuit measurement and reset, one shot at a time.
124
+ for s in range(shots):
125
+ state = zero_state(n)
126
+ reg = 0
127
+ for ins in ops:
128
+ if ins.name == "barrier":
129
+ continue
130
+ if ins.name in ("measure", "reset"):
131
+ q = ins.qubits[0]
132
+ ax = n - 1 - q
133
+ p1 = float(np.sum(np.abs(np.take(state, 1, axis=ax)) ** 2))
134
+ bit = int(rng.random() < p1)
135
+ keep = np.take(state, bit, axis=ax)
136
+ norm = np.sqrt(p1 if bit else 1 - p1) or 1.0
137
+ state = np.zeros_like(state)
138
+ idx = [slice(None)] * n
139
+ target_bit = 0 if ins.name == "reset" else bit
140
+ idx[ax] = target_bit
141
+ state[tuple(idx)] = keep / norm
142
+ if ins.name == "measure":
143
+ rb = bit ^ int(readout_error and rng.random() < readout_error)
144
+ c = ins.clbits[0]
145
+ reg = (reg & ~(1 << c)) | (rb << c)
146
+ continue
147
+ state = apply_matrix(state, gate_matrix(ins.name, numeric(ins.params)), ins.qubits, n)
148
+ clbits[s] = reg
149
+ return clbits