fuqit 0.1.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.
fuqit/__init__.py ADDED
@@ -0,0 +1,9 @@
1
+ """FUQIT: an educational quantum circuit simulator."""
2
+
3
+ from . import gates
4
+ from .circuit import Circuit
5
+ from .states import QubitState
6
+
7
+ __version__ = "0.1.0"
8
+
9
+ __all__ = ["Circuit", "QubitState", "__version__", "gates"]
fuqit/circuit.py ADDED
@@ -0,0 +1,273 @@
1
+ """
2
+ circuit.py — an ordered sequence of gates that can be run on an n-qubit state.
3
+
4
+ Each gate returns a new QubitState (states are immutable -- see states.py),
5
+ so the state you pass in is never changed.
6
+
7
+ Examples
8
+ --------
9
+ >>> from fuqit.circuit import Circuit
10
+ >>> from fuqit.states import QubitState
11
+ >>> bell = Circuit(2).h(0).cnot(0, 1)
12
+ >>> bell.run() == QubitState.bell("phi+")
13
+ True
14
+ >>> bell.run("00") # a label string works as a shortcut too
15
+ QubitState(0.707|00> + 0.707|11>)
16
+ >>> Circuit(3).h(0).cnot(0, 1).cnot(1, 2).run() == QubitState.ghz(3)
17
+ True
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import numpy as np
23
+ from numpy.typing import ArrayLike
24
+
25
+ from . import gates
26
+ from .gates import Gate
27
+ from .states import QubitState
28
+
29
+
30
+ class Circuit:
31
+ """An ordered list of gates acting on a register of ``num_qubits`` qubits.
32
+
33
+ Gates are applied in the order they are added (left to right on a
34
+ circuit diagram). Methods like ``h`` and ``cnot`` return the circuit
35
+ itself, so calls can be chained: ``Circuit(2).h(0).cnot(0, 1)``.
36
+
37
+ Parameters
38
+ ----------
39
+ num_qubits : int
40
+ Size of the register. Every gate added must act on this many qubits.
41
+ gate_list : list of Gate, optional
42
+ Gates to start the circuit with.
43
+
44
+ Raises
45
+ ------
46
+ ValueError
47
+ If ``num_qubits`` is not a positive integer, or a gate in
48
+ ``gate_list`` acts on a different number of qubits.
49
+ TypeError
50
+ If an item in ``gate_list`` is not a Gate.
51
+ """
52
+
53
+ def __init__(self, num_qubits: int = 2, gate_list: list[Gate] | None = None):
54
+ if not isinstance(num_qubits, (int, np.integer)) or num_qubits < 1:
55
+ raise ValueError(f"num_qubits must be a positive integer, got {num_qubits!r}.")
56
+ self.num_qubits = int(num_qubits)
57
+ self.gates: list[Gate] = []
58
+ for g in gate_list or []:
59
+ self.add(g)
60
+
61
+ # --- building ---------------------------------------------------------
62
+ def add(self, gate: Gate) -> Circuit:
63
+ """Append any Gate object to the end of the circuit.
64
+
65
+ Parameters
66
+ ----------
67
+ gate : Gate
68
+ The gate to append. It must act on ``num_qubits`` qubits.
69
+
70
+ Returns
71
+ -------
72
+ Circuit
73
+ This circuit, so calls can be chained.
74
+
75
+ Raises
76
+ ------
77
+ TypeError
78
+ If ``gate`` is not a Gate.
79
+ ValueError
80
+ If ``gate`` acts on a different number of qubits than the circuit.
81
+ """
82
+ if not isinstance(gate, Gate):
83
+ raise TypeError(f"Expected a Gate, got {type(gate).__name__}.")
84
+ if gate.num_qubits != self.num_qubits:
85
+ raise ValueError(
86
+ f"Gate '{gate.name}' acts on {gate.num_qubits} qubits but this "
87
+ f"circuit has {self.num_qubits}. Build the gate with "
88
+ f"num_qubits={self.num_qubits}, or use the circuit's shortcut "
89
+ f"methods (e.g. circuit.h(0)), which do this for you."
90
+ )
91
+ self.gates.append(gate)
92
+ return self
93
+
94
+ # Shortcuts for common gates (each builds the gate at the right size)
95
+ def x(self, target: int) -> Circuit:
96
+ """Add a Pauli-X (NOT) gate on qubit ``target``."""
97
+ return self.add(gates.X(target, self.num_qubits))
98
+
99
+ def y(self, target: int) -> Circuit:
100
+ """Add a Pauli-Y gate on qubit ``target``."""
101
+ return self.add(gates.Y(target, self.num_qubits))
102
+
103
+ def z(self, target: int) -> Circuit:
104
+ """Add a Pauli-Z gate on qubit ``target``."""
105
+ return self.add(gates.Z(target, self.num_qubits))
106
+
107
+ def h(self, target: int) -> Circuit:
108
+ """Add a Hadamard gate on qubit ``target``."""
109
+ return self.add(gates.H(target, self.num_qubits))
110
+
111
+ def s(self, target: int) -> Circuit:
112
+ """Add an S (phase, sqrt(Z)) gate on qubit ``target``."""
113
+ return self.add(gates.S(target, self.num_qubits))
114
+
115
+ def t(self, target: int) -> Circuit:
116
+ """Add a T (pi/8, sqrt(S)) gate on qubit ``target``."""
117
+ return self.add(gates.T(target, self.num_qubits))
118
+
119
+ def rx(self, theta: float, target: int) -> Circuit:
120
+ """Add a rotation by ``theta`` radians about the X axis on qubit ``target``."""
121
+ return self.add(gates.Rx(theta, target, self.num_qubits))
122
+
123
+ def ry(self, theta: float, target: int) -> Circuit:
124
+ """Add a rotation by ``theta`` radians about the Y axis on qubit ``target``."""
125
+ return self.add(gates.Ry(theta, target, self.num_qubits))
126
+
127
+ def rz(self, theta: float, target: int) -> Circuit:
128
+ """Add a rotation by ``theta`` radians about the Z axis on qubit ``target``."""
129
+ return self.add(gates.Rz(theta, target, self.num_qubits))
130
+
131
+ def cnot(self, control: int = 0, target: int = 1) -> Circuit:
132
+ """Add a CNOT gate: flips ``target`` when ``control`` is 1."""
133
+ return self.add(gates.CNOT(control, target, self.num_qubits))
134
+
135
+ def cz(self, q_a: int = 0, q_b: int = 1) -> Circuit:
136
+ """Add a controlled-Z gate between ``q_a`` and ``q_b`` (symmetric)."""
137
+ return self.add(gates.CZ(q_a, q_b, self.num_qubits))
138
+
139
+ def swap(self, q_a: int = 0, q_b: int = 1) -> Circuit:
140
+ """Add a SWAP gate exchanging qubits ``q_a`` and ``q_b``."""
141
+ return self.add(gates.SWAP(q_a, q_b, self.num_qubits))
142
+
143
+ # --- using ------------------------------------------------------------
144
+ def _as_state(self, state) -> QubitState:
145
+ """Accept None (meaning |00..0>), a QubitState, a label, or amplitudes."""
146
+ if state is None:
147
+ state = QubitState.from_label("0" * self.num_qubits)
148
+ elif isinstance(state, str):
149
+ state = QubitState.from_label(state)
150
+ elif not isinstance(state, QubitState):
151
+ state = QubitState(state)
152
+ if state.num_qubits != self.num_qubits:
153
+ raise ValueError(
154
+ f"This circuit has {self.num_qubits} qubits but the state has "
155
+ f"{state.num_qubits}."
156
+ )
157
+ return state
158
+
159
+ def unitary(self) -> np.ndarray:
160
+ """The overall 2^n x 2^n unitary of the circuit.
161
+
162
+ If gates G1, G2, ..., Gk are applied in that order, the total is
163
+ U = Gk ... G2 G1 (later gates multiply on the left).
164
+
165
+ Returns
166
+ -------
167
+ numpy.ndarray
168
+ Complex array of shape ``(2**num_qubits, 2**num_qubits)``.
169
+ The identity if the circuit is empty.
170
+ """
171
+ U = np.eye(2 ** self.num_qubits, dtype=complex)
172
+ for g in self.gates:
173
+ U = g.matrix @ U
174
+ return U
175
+
176
+ def run(
177
+ self,
178
+ state: QubitState | str | ArrayLike | None = None,
179
+ return_history: bool = False,
180
+ ) -> QubitState | tuple[QubitState, list[QubitState]]:
181
+ """Apply every gate in turn and return the final QubitState.
182
+
183
+ Parameters
184
+ ----------
185
+ state : QubitState, str, array_like or None
186
+ The initial state. None (the default) means |00...0>. A string is
187
+ passed to ``QubitState.from_label`` (e.g. ``"00"``, ``"+1"``); a
188
+ list or array of amplitudes is passed to ``QubitState(...)``.
189
+ return_history : bool
190
+ If True, also return a list of QubitStates: the initial state
191
+ followed by the state after each gate. Handy for notebooks.
192
+
193
+ Returns
194
+ -------
195
+ QubitState or tuple of (QubitState, list of QubitState)
196
+ The final state. If ``return_history`` is True, a tuple of the
197
+ final state and the history list (length ``len(self) + 1``).
198
+
199
+ Raises
200
+ ------
201
+ ValueError
202
+ If ``state`` has a different number of qubits than the circuit.
203
+ """
204
+ current = self._as_state(state)
205
+ history = [current]
206
+ for g in self.gates:
207
+ current = g.apply(current)
208
+ history.append(current)
209
+
210
+ if return_history:
211
+ return current, history
212
+ return current
213
+
214
+ def measure(
215
+ self,
216
+ shots: int = 1000,
217
+ state: QubitState | str | ArrayLike | None = None,
218
+ rng: np.random.Generator | None = None,
219
+ ) -> dict[str, int]:
220
+ """Run the circuit and simulate measuring every qubit ``shots`` times.
221
+
222
+ Parameters
223
+ ----------
224
+ shots : int
225
+ Number of repetitions.
226
+ state : QubitState, str, array_like or None
227
+ The initial state, as for ``run`` (default |00...0>).
228
+ rng : numpy.random.Generator, optional
229
+ Random number generator; pass one with a fixed seed for
230
+ reproducible results, e.g. ``np.random.default_rng(42)``.
231
+
232
+ Returns
233
+ -------
234
+ dict
235
+ Counts for every basis label, e.g. ``{'00': 503, '01': 0, ...}``.
236
+
237
+ Raises
238
+ ------
239
+ ValueError
240
+ If ``shots`` is not a positive integer, or ``state`` has a
241
+ different number of qubits than the circuit.
242
+ """
243
+ if not isinstance(shots, (int, np.integer)) or shots < 1:
244
+ raise ValueError(f"shots must be a positive integer, got {shots!r}.")
245
+ rng = np.random.default_rng() if rng is None else rng
246
+ probs = self.run(state).probabilities()
247
+ labels = list(probs)
248
+ p = np.array(list(probs.values()))
249
+ outcomes = rng.choice(len(labels), size=shots, p=p / p.sum())
250
+ counts = np.bincount(outcomes, minlength=len(labels))
251
+ return {label: int(c) for label, c in zip(labels, counts)}
252
+
253
+ def inverse(self) -> Circuit:
254
+ """A circuit that undoes this one (reversed order, each gate daggered)."""
255
+ return Circuit(self.num_qubits, [g.dagger() for g in reversed(self.gates)])
256
+
257
+ # --- nice-to-haves ----------------------------------------------------
258
+ def __len__(self) -> int:
259
+ """Number of gates in the circuit."""
260
+ return len(self.gates)
261
+
262
+ def __add__(self, other: Circuit) -> Circuit:
263
+ """``c1 + c2`` runs c1 then c2 (both must have the same number of qubits)."""
264
+ if not isinstance(other, Circuit):
265
+ return NotImplemented
266
+ if other.num_qubits != self.num_qubits:
267
+ raise ValueError("Can only join circuits with the same number of qubits.")
268
+ return Circuit(self.num_qubits, self.gates + other.gates)
269
+
270
+ def __repr__(self) -> str:
271
+ if not self.gates:
272
+ return f"Circuit({self.num_qubits} qubits, empty)"
273
+ return f"Circuit({self.num_qubits} qubits): " + " → ".join(g.name for g in self.gates)