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,467 @@
1
+ """QuantumCircuit: an ordered list of instructions on qubits and classical bits."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import copy as _copy
6
+ import math
7
+ from dataclasses import dataclass, field
8
+ from typing import Iterable, Mapping, Sequence
9
+
10
+ from ..exceptions import CircuitError
11
+ from .gates import GATE_SPECS, INVERSES, NON_UNITARY
12
+ from .parameter import Parameter, ParameterExpression, param_sort_key
13
+
14
+
15
+ class _Register:
16
+ prefix = "r"
17
+
18
+ def __init__(self, size: int, name: str | None = None):
19
+ if int(size) < 0:
20
+ raise CircuitError("Register size must be zero or more.")
21
+ self.size = int(size)
22
+ self.name = name or self.prefix
23
+ self._offset: int | None = None
24
+
25
+ def __len__(self):
26
+ return self.size
27
+
28
+ def __getitem__(self, i):
29
+ if self._offset is None:
30
+ raise CircuitError(f"Register '{self.name}' is not in a circuit yet.", "Pass it to QuantumCircuit(...) first.")
31
+ if isinstance(i, slice):
32
+ return [self._offset + k for k in range(self.size)[i]]
33
+ if not -self.size <= i < self.size:
34
+ raise CircuitError(f"Index {i} is out of range for register '{self.name}' of size {self.size}.")
35
+ return self._offset + (i % self.size)
36
+
37
+ def __iter__(self):
38
+ return iter(self[:])
39
+
40
+ def __repr__(self):
41
+ return f"{type(self).__name__}({self.size}, '{self.name}')"
42
+
43
+
44
+ class QuantumRegister(_Register):
45
+ prefix = "q"
46
+
47
+
48
+ class ClassicalRegister(_Register):
49
+ prefix = "c"
50
+
51
+
52
+ @dataclass
53
+ class Instruction:
54
+ name: str
55
+ qubits: tuple[int, ...]
56
+ clbits: tuple[int, ...] = ()
57
+ params: list = field(default_factory=list)
58
+ definition: "QuantumCircuit | None" = None
59
+ label: str | None = None
60
+
61
+ @property
62
+ def is_parameterized(self) -> bool:
63
+ return any(isinstance(p, ParameterExpression) and p.parameters for p in self.params)
64
+
65
+
66
+ class Gate:
67
+ """A reusable gate. Make one from a circuit with ``circuit.to_gate()`` and add it with ``qc.append(gate, qubits)``."""
68
+
69
+ def __init__(self, name: str, num_qubits: int, definition: "QuantumCircuit", label: str | None = None):
70
+ self.name = name
71
+ self.num_qubits = num_qubits
72
+ self.definition = definition
73
+ self.label = label or name
74
+
75
+ def inverse(self) -> "Gate":
76
+ return Gate(self.name + "_dg", self.num_qubits, self.definition.inverse(), (self.label or self.name) + "†")
77
+
78
+ def __repr__(self):
79
+ return f"Gate({self.name}, num_qubits={self.num_qubits})"
80
+
81
+
82
+ Qubits = int | Sequence[int] | range
83
+
84
+
85
+ def _as_list(q: Qubits) -> list[int]:
86
+ if isinstance(q, (list, tuple, range)):
87
+ return [int(x) for x in q]
88
+ return [int(q)]
89
+
90
+
91
+ class QuantumCircuit:
92
+ """A quantum circuit.
93
+
94
+ ``QuantumCircuit(2)`` — 2 qubits; ``QuantumCircuit(2, 2)`` — 2 qubits and a classical register ``c`` of 2 bits;
95
+ ``QuantumCircuit(QuantumRegister(3, "a"), ClassicalRegister(3, "m"))`` — named registers.
96
+ """
97
+
98
+ def __init__(self, *regs, name: str | None = None, global_phase: float = 0.0):
99
+ self.name = name or "circuit"
100
+ self.qregs: list[QuantumRegister] = []
101
+ self.cregs: list[ClassicalRegister] = []
102
+ self.data: list[Instruction] = []
103
+ self.global_phase = global_phase
104
+ self.metadata: dict = {}
105
+ if len(regs) and all(isinstance(r, (int, float)) for r in regs):
106
+ if len(regs) > 2:
107
+ raise CircuitError("Use QuantumCircuit(num_qubits) or QuantumCircuit(num_qubits, num_clbits).")
108
+ if int(regs[0]):
109
+ self.add_register(QuantumRegister(int(regs[0]), "q"))
110
+ if len(regs) == 2 and int(regs[1]):
111
+ self.add_register(ClassicalRegister(int(regs[1]), "c"))
112
+ else:
113
+ for r in regs:
114
+ self.add_register(r)
115
+
116
+ # ───────────── registers & sizes ─────────────
117
+ def add_register(self, reg: _Register) -> None:
118
+ if isinstance(reg, QuantumRegister):
119
+ reg._offset = self.num_qubits
120
+ self.qregs.append(reg)
121
+ elif isinstance(reg, ClassicalRegister):
122
+ if any(r.name == reg.name for r in self.cregs):
123
+ raise CircuitError(f"A classical register named '{reg.name}' already exists.")
124
+ reg._offset = self.num_clbits
125
+ self.cregs.append(reg)
126
+ else:
127
+ raise CircuitError(f"Expected a QuantumRegister or ClassicalRegister, got {reg!r}.")
128
+
129
+ @property
130
+ def num_qubits(self) -> int:
131
+ return sum(r.size for r in self.qregs)
132
+
133
+ @property
134
+ def num_clbits(self) -> int:
135
+ return sum(r.size for r in self.cregs)
136
+
137
+ def width(self) -> int:
138
+ return self.num_qubits + self.num_clbits
139
+
140
+ def __len__(self):
141
+ return len(self.data)
142
+
143
+ # ───────────── appending ─────────────
144
+ def _check_qubits(self, qs: list[int]) -> tuple[int, ...]:
145
+ n = self.num_qubits
146
+ for q in qs:
147
+ if not 0 <= q < n:
148
+ raise CircuitError(f"Qubit {q} does not exist; this circuit has {n} qubit(s) (0..{n - 1}).")
149
+ if len(set(qs)) != len(qs):
150
+ raise CircuitError(f"A gate can't use the same qubit twice: {qs}.")
151
+ return tuple(qs)
152
+
153
+ def _gate(self, name: str, params: list, *qargs: Qubits) -> "QuantumCircuit":
154
+ spec = GATE_SPECS[name]
155
+ if spec.num_qubits == 1 and len(qargs) == 1 and isinstance(qargs[0], (list, tuple, range)):
156
+ for q in _as_list(qargs[0]): # broadcast: qc.h([0, 1, 2])
157
+ self._gate(name, params, q)
158
+ return self
159
+ qs = [int(q) for q in qargs]
160
+ if len(qs) != spec.num_qubits:
161
+ raise CircuitError(f"{name} acts on {spec.num_qubits} qubit(s); got {len(qs)}.")
162
+ for p in params:
163
+ if not isinstance(p, (int, float, ParameterExpression)):
164
+ raise CircuitError(f"Gate parameter must be a number or Parameter, got {p!r}.")
165
+ self.data.append(Instruction(name, self._check_qubits(qs), (), [p if isinstance(p, ParameterExpression) else float(p) for p in params]))
166
+ return self
167
+
168
+ def append(self, gate: "Gate | QuantumCircuit | Instruction", qargs: Qubits, cargs: Qubits = ()) -> "QuantumCircuit":
169
+ """Append a custom gate (from ``to_gate()``), a circuit, or an instruction on the given qubits."""
170
+ qs = _as_list(qargs)
171
+ if isinstance(gate, QuantumCircuit):
172
+ gate = gate.to_gate()
173
+ if isinstance(gate, Gate):
174
+ if len(qs) != gate.num_qubits:
175
+ raise CircuitError(f"Gate '{gate.name}' acts on {gate.num_qubits} qubit(s); got {len(qs)}.")
176
+ self.data.append(Instruction(gate.name, self._check_qubits(qs), (), [], gate.definition, gate.label))
177
+ elif isinstance(gate, Instruction):
178
+ self.data.append(Instruction(gate.name, self._check_qubits(qs), tuple(_as_list(cargs)), list(gate.params), gate.definition, gate.label))
179
+ else:
180
+ raise CircuitError(f"Can't append {gate!r}.")
181
+ return self
182
+
183
+ # 1-qubit gates
184
+ def id(self, q): return self._gate("id", [], q)
185
+ def x(self, q): return self._gate("x", [], q)
186
+ def y(self, q): return self._gate("y", [], q)
187
+ def z(self, q): return self._gate("z", [], q)
188
+ def h(self, q): return self._gate("h", [], q)
189
+ def s(self, q): return self._gate("s", [], q)
190
+ def sdg(self, q): return self._gate("sdg", [], q)
191
+ def sx(self, q): return self._gate("sx", [], q)
192
+ def sxdg(self, q): return self._gate("sxdg", [], q)
193
+ def t(self, q): return self._gate("t", [], q)
194
+ def tdg(self, q): return self._gate("tdg", [], q)
195
+ def p(self, lam, q): return self._gate("p", [lam], q)
196
+ def rx(self, theta, q): return self._gate("rx", [theta], q)
197
+ def ry(self, theta, q): return self._gate("ry", [theta], q)
198
+ def rz(self, theta, q): return self._gate("rz", [theta], q)
199
+ def u(self, theta, phi, lam, q): return self._gate("u", [theta, phi, lam], q)
200
+ # 2-qubit gates
201
+ def cx(self, control, target): return self._gate("cx", [], control, target)
202
+ def cnot(self, control, target): return self.cx(control, target)
203
+ def cy(self, control, target): return self._gate("cy", [], control, target)
204
+ def cz(self, control, target): return self._gate("cz", [], control, target)
205
+ def ch(self, control, target): return self._gate("ch", [], control, target)
206
+ def cp(self, lam, control, target): return self._gate("cp", [lam], control, target)
207
+ def crx(self, theta, control, target): return self._gate("crx", [theta], control, target)
208
+ def cry(self, theta, control, target): return self._gate("cry", [theta], control, target)
209
+ def crz(self, theta, control, target): return self._gate("crz", [theta], control, target)
210
+ def swap(self, a, b): return self._gate("swap", [], a, b)
211
+ def iswap(self, a, b): return self._gate("iswap", [], a, b)
212
+ def rxx(self, theta, a, b): return self._gate("rxx", [theta], a, b)
213
+ def ryy(self, theta, a, b): return self._gate("ryy", [theta], a, b)
214
+ def rzz(self, theta, a, b): return self._gate("rzz", [theta], a, b)
215
+ # 3-qubit gates
216
+ def ccx(self, c1, c2, target): return self._gate("ccx", [], c1, c2, target)
217
+ def toffoli(self, c1, c2, target): return self.ccx(c1, c2, target)
218
+ def cswap(self, control, a, b): return self._gate("cswap", [], control, a, b)
219
+ def fredkin(self, control, a, b): return self.cswap(control, a, b)
220
+
221
+ def mcx(self, controls: Sequence[int], target: int) -> "QuantumCircuit":
222
+ """Multi-controlled X, built from Toffolis with no extra qubits needed for up to 2 controls."""
223
+ cs = _as_list(controls)
224
+ if len(cs) == 1:
225
+ return self.cx(cs[0], target)
226
+ if len(cs) == 2:
227
+ return self.ccx(cs[0], cs[1], target)
228
+ # Multi-controlled X via controlled phase ladder (exact, no ancillas): H · C^n(P(pi)) · H
229
+ self.h(target)
230
+ self._mcp(math.pi, cs, target)
231
+ self.h(target)
232
+ return self
233
+
234
+ def _mcp(self, lam: float, controls: list[int], target: int) -> None:
235
+ # Gray-code construction of a multi-controlled phase gate.
236
+ n = len(controls)
237
+ qs = controls + [target]
238
+ angle = lam / (2 ** n)
239
+ for i in range(1, 2 ** (n + 1)):
240
+ gray = i ^ (i >> 1)
241
+ prev = (i - 1) ^ ((i - 1) >> 1)
242
+ changed = (gray ^ prev).bit_length() - 1
243
+ ones = bin(gray).count("1")
244
+ # parity of all set bits onto the highest set bit
245
+ bits = [k for k in range(n + 1) if gray >> k & 1]
246
+ hi = bits[-1]
247
+ for k in bits[:-1]:
248
+ self.cx(qs[k], qs[hi])
249
+ self.p(angle if ones % 2 else -angle, qs[hi])
250
+ for k in reversed(bits[:-1]):
251
+ self.cx(qs[k], qs[hi])
252
+ _ = changed
253
+
254
+ # non-unitary
255
+ def measure(self, qubit: Qubits, clbit: Qubits) -> "QuantumCircuit":
256
+ qs, cs = _as_list(qubit), _as_list(clbit)
257
+ if len(qs) != len(cs):
258
+ raise CircuitError("measure() needs the same number of qubits and classical bits.")
259
+ if not self.cregs:
260
+ raise CircuitError("This circuit has no classical bits.", "Use QuantumCircuit(n, n), or call measure_all().")
261
+ for q, c in zip(qs, cs):
262
+ if not 0 <= c < self.num_clbits:
263
+ raise CircuitError(f"Classical bit {c} does not exist; this circuit has {self.num_clbits}.")
264
+ self.data.append(Instruction("measure", self._check_qubits([q]), (c,)))
265
+ return self
266
+
267
+ def measure_all(self, add_bits: bool = True) -> "QuantumCircuit":
268
+ """Measure every qubit into a new classical register named ``meas`` (after a barrier)."""
269
+ n = self.num_qubits
270
+ if add_bits:
271
+ reg = ClassicalRegister(n, "meas")
272
+ self.add_register(reg)
273
+ start = reg._offset
274
+ else:
275
+ if self.num_clbits < n:
276
+ raise CircuitError("Not enough classical bits for measure_all(add_bits=False).")
277
+ start = 0
278
+ self.barrier()
279
+ for q in range(n):
280
+ self.data.append(Instruction("measure", (q,), (start + q,)))
281
+ return self
282
+
283
+ def reset(self, qubit: Qubits) -> "QuantumCircuit":
284
+ for q in _as_list(qubit):
285
+ self.data.append(Instruction("reset", self._check_qubits([q])))
286
+ return self
287
+
288
+ def barrier(self, *qubits) -> "QuantumCircuit":
289
+ qs = [q for arg in qubits for q in _as_list(arg)] or list(range(self.num_qubits))
290
+ if qs:
291
+ self.data.append(Instruction("barrier", self._check_qubits(qs)))
292
+ return self
293
+
294
+ # ───────────── whole-circuit operations ─────────────
295
+ def copy(self, name: str | None = None) -> "QuantumCircuit":
296
+ c = _copy.deepcopy(self)
297
+ if name:
298
+ c.name = name
299
+ return c
300
+
301
+ def to_gate(self, label: str | None = None) -> Gate:
302
+ """Wrap this (unitary) circuit as a reusable gate."""
303
+ if any(i.name in ("measure", "reset") for i in self.data):
304
+ raise CircuitError("Only unitary circuits can become gates (remove measure/reset).")
305
+ return Gate(label or self.name, self.num_qubits, self.copy(), label or self.name)
306
+
307
+ to_instruction = to_gate
308
+
309
+ def inverse(self) -> "QuantumCircuit":
310
+ """The adjoint circuit: gates reversed and inverted."""
311
+ out = QuantumCircuit(*[_clone_reg(r) for r in self.qregs], *[_clone_reg(r) for r in self.cregs], name=self.name + "_dg")
312
+ out.global_phase = -self.global_phase
313
+ for ins in reversed(self.data):
314
+ if ins.name in ("measure", "reset"):
315
+ raise CircuitError("Can't invert a circuit with measurements or resets.", "Use remove_final_measurements() first.")
316
+ if ins.name == "barrier":
317
+ out.data.append(Instruction("barrier", ins.qubits))
318
+ elif ins.definition is not None:
319
+ out.data.append(Instruction(ins.name + "_dg", ins.qubits, (), [], ins.definition.inverse(), (ins.label or ins.name) + "†"))
320
+ elif ins.name == "iswap":
321
+ out.data.extend(Instruction("iswap", ins.qubits) for _ in range(3)) # iswap^4 = I
322
+ else:
323
+ name, rule = INVERSES[ins.name]
324
+ if rule == "neg":
325
+ params = [-p for p in ins.params]
326
+ elif rule == "u":
327
+ th, ph, la = ins.params
328
+ params = [-th, -la, -ph]
329
+ else:
330
+ params = list(ins.params)
331
+ out.data.append(Instruction(name, ins.qubits, (), params))
332
+ return out
333
+
334
+ def power(self, n: int) -> "QuantumCircuit":
335
+ """Repeat the circuit n times (n < 0 repeats the inverse)."""
336
+ base = self if n >= 0 else self.inverse()
337
+ out = QuantumCircuit(*[_clone_reg(r) for r in self.qregs], *[_clone_reg(r) for r in self.cregs], name=f"{self.name}^{n}")
338
+ for _ in range(abs(n)):
339
+ out.data.extend(_copy.deepcopy(base.data))
340
+ return out
341
+
342
+ def repeat(self, n: int) -> "QuantumCircuit":
343
+ return self.power(n)
344
+
345
+ def compose(self, other: "QuantumCircuit", qubits: Qubits | None = None, clbits: Qubits | None = None,
346
+ front: bool = False, inplace: bool = False) -> "QuantumCircuit | None":
347
+ """Append ``other`` onto these qubits (default: the first ``other.num_qubits``)."""
348
+ qmap = _as_list(qubits) if qubits is not None else list(range(other.num_qubits))
349
+ cmap = _as_list(clbits) if clbits is not None else list(range(other.num_clbits))
350
+ if len(qmap) != other.num_qubits or max(qmap, default=-1) >= self.num_qubits:
351
+ raise CircuitError(f"compose: need {other.num_qubits} qubit(s) within 0..{self.num_qubits - 1}.")
352
+ if len(cmap) != other.num_clbits or max(cmap, default=-1) >= self.num_clbits:
353
+ raise CircuitError(f"compose: need {other.num_clbits} classical bit(s) within this circuit.")
354
+ target = self if inplace else self.copy()
355
+ new = [Instruction(i.name, tuple(qmap[q] for q in i.qubits), tuple(cmap[c] for c in i.clbits), list(i.params), i.definition, i.label) for i in other.data]
356
+ target.data = new + target.data if front else target.data + new
357
+ target.global_phase += other.global_phase
358
+ return None if inplace else target
359
+
360
+ def tensor(self, other: "QuantumCircuit") -> "QuantumCircuit":
361
+ """``self ⊗ other``: ``other`` on the low qubits, ``self`` on the high qubits."""
362
+ out = QuantumCircuit(self.num_qubits + other.num_qubits, self.num_clbits + other.num_clbits)
363
+ out.compose(other, range(other.num_qubits), range(other.num_clbits), inplace=True)
364
+ out.compose(self, range(other.num_qubits, out.num_qubits), range(other.num_clbits, out.num_clbits), inplace=True)
365
+ return out
366
+
367
+ def remove_final_measurements(self, inplace: bool = True) -> "QuantumCircuit | None":
368
+ target = self if inplace else self.copy()
369
+ while target.data and target.data[-1].name in ("measure", "barrier"):
370
+ target.data.pop()
371
+ target.cregs = [r for r in target.cregs if r.name != "meas"]
372
+ return None if inplace else target
373
+
374
+ # ───────────── parameters ─────────────
375
+ @property
376
+ def parameters(self) -> list[Parameter]:
377
+ ps: set[Parameter] = set()
378
+ for ins in self.data:
379
+ for p in ins.params:
380
+ if isinstance(p, ParameterExpression):
381
+ ps |= p.parameters
382
+ if ins.definition is not None:
383
+ ps |= set(ins.definition.parameters)
384
+ return sorted(ps, key=param_sort_key)
385
+
386
+ @property
387
+ def num_parameters(self) -> int:
388
+ return len(self.parameters)
389
+
390
+ def assign_parameters(self, values: Mapping | Sequence[float], inplace: bool = False) -> "QuantumCircuit | None":
391
+ """Bind parameters, from a dict ``{param: value}`` or a list in ``circuit.parameters`` order."""
392
+ params = self.parameters
393
+ if isinstance(values, Mapping):
394
+ mapping = {}
395
+ for k, v in values.items():
396
+ if hasattr(k, "__iter__") and not isinstance(k, (str, Parameter)): # ParameterVector -> list
397
+ for kk, vv in zip(k, v):
398
+ mapping[kk] = vv
399
+ else:
400
+ mapping[k] = v
401
+ else:
402
+ vals = list(values)
403
+ if len(vals) != len(params):
404
+ raise CircuitError(f"Expected {len(params)} values (for {', '.join(p.name for p in params)}); got {len(vals)}.")
405
+ mapping = dict(zip(params, vals))
406
+ target = self if inplace else self.copy()
407
+ for ins in target.data:
408
+ ins.params = [p.bind(mapping) if isinstance(p, ParameterExpression) else p for p in ins.params]
409
+ if ins.definition is not None:
410
+ ins.definition.assign_parameters(mapping, inplace=True)
411
+ return None if inplace else target
412
+
413
+ # ───────────── properties ─────────────
414
+ def size(self) -> int:
415
+ return sum(1 for i in self.data if i.name != "barrier")
416
+
417
+ def depth(self) -> int:
418
+ level = [0] * (self.num_qubits + self.num_clbits)
419
+ for ins in self.data:
420
+ if ins.name == "barrier":
421
+ continue
422
+ wires = list(ins.qubits) + [self.num_qubits + c for c in ins.clbits]
423
+ d = max(level[w] for w in wires) + 1
424
+ for w in wires:
425
+ level[w] = d
426
+ return max(level, default=0)
427
+
428
+ def count_ops(self) -> dict[str, int]:
429
+ counts: dict[str, int] = {}
430
+ for ins in self.data:
431
+ counts[ins.name] = counts.get(ins.name, 0) + 1
432
+ return dict(sorted(counts.items(), key=lambda kv: -kv[1]))
433
+
434
+ def num_nonlocal_gates(self) -> int:
435
+ return sum(1 for i in self.data if len(i.qubits) > 1 and i.name not in NON_UNITARY)
436
+
437
+ # ───────────── output ─────────────
438
+ def draw(self, output: str = "text", ascii: bool | None = None) -> "str":
439
+ """Text diagram of the circuit (``print(qc.draw())``). ``output="mpl"`` needs matplotlib.
440
+
441
+ ``ascii=True`` forces plain ASCII; by default it is chosen automatically for consoles that can't show Unicode.
442
+ """
443
+ from .drawer import draw_text, draw_mpl
444
+ if output == "text":
445
+ return draw_text(self, ascii)
446
+ if output == "mpl":
447
+ return draw_mpl(self)
448
+ raise CircuitError(f"Unknown output '{output}'. Use 'text' or 'mpl'.")
449
+
450
+ def __str__(self) -> str:
451
+ from .drawer import draw_text
452
+ return draw_text(self)
453
+
454
+ def __repr__(self) -> str:
455
+ return f"<QuantumCircuit '{self.name}' qubits={self.num_qubits} clbits={self.num_clbits} ops={len(self.data)}>"
456
+
457
+ def __eq__(self, other) -> bool:
458
+ if not isinstance(other, QuantumCircuit):
459
+ return NotImplemented
460
+ from ..quantum_info import Operator
461
+ if self.num_qubits != other.num_qubits:
462
+ return False
463
+ return Operator(self).equiv(Operator(other))
464
+
465
+
466
+ def _clone_reg(r: _Register) -> _Register:
467
+ return type(r)(r.size, r.name)
@@ -0,0 +1,210 @@
1
+ """QuantaKit Cloud client (optional). Everything in the SDK also works offline with ``LocalSimulator``.
2
+
3
+ >>> from quantakit.cloud import CloudService
4
+ >>> service = CloudService(token="qk_...") # or set the QK_TOKEN environment variable
5
+ >>> backend = service.least_busy(min_qubits=2)
6
+ >>> job = Sampler(backend).run([transpile(qc, backend)], shots=4000)
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import os
13
+ import time
14
+ import urllib.error
15
+ import urllib.request
16
+ from typing import Any
17
+
18
+ import numpy as np
19
+
20
+ from ..circuit.quantumcircuit import QuantumCircuit
21
+ from ..exceptions import AuthError, BackendError, IsaError, JobError, QuantaKitError, QuotaError
22
+ from ..sim import BackendStatus
23
+ from ..sim.engine import flatten
24
+ from ..version import __version__
25
+
26
+ DEFAULT_URL = "https://quantakit.my"
27
+
28
+ #: Gates the cloud accepts directly. Anything else is translated automatically before submission.
29
+ CLOUD_GATES = ["id", "x", "y", "z", "h", "s", "sdg", "sx", "t", "tdg", "p", "rx", "ry", "rz", "u",
30
+ "cx", "cy", "cz", "ch", "cp", "crz", "swap", "rzz", "ccx", "cswap"]
31
+ CLOUD_MAX_QUBITS = 16
32
+
33
+
34
+ class CloudService:
35
+ def __init__(self, token: str | None = None, url: str | None = None, timeout: float = 30.0):
36
+ self.token = token or os.environ.get("QK_TOKEN")
37
+ if not self.token:
38
+ raise AuthError("No API token.", "Create one at https://quantakit.my/app/account/api-keys and pass token=... or set QK_TOKEN.")
39
+ self.url = (url or os.environ.get("QK_URL") or DEFAULT_URL).rstrip("/")
40
+ self.timeout = timeout
41
+
42
+ # ───────── HTTP ─────────
43
+ def _request(self, method: str, path: str, body: Any = None) -> Any:
44
+ data = json.dumps(body).encode() if body is not None else None
45
+ req = urllib.request.Request(f"{self.url}/v1{path}", data=data, method=method, headers={
46
+ "Authorization": f"Bearer {self.token}", "Content-Type": "application/json", "Accept": "application/json",
47
+ "User-Agent": f"quantakit-python/{__version__}",
48
+ })
49
+ try:
50
+ with urllib.request.urlopen(req, timeout=self.timeout) as r:
51
+ raw = r.read()
52
+ return json.loads(raw) if raw else None
53
+ except urllib.error.HTTPError as e:
54
+ try:
55
+ info = json.loads(e.read() or b"{}")
56
+ except ValueError:
57
+ info = {}
58
+ msg, code = info.get("message", e.reason), info.get("code")
59
+ cls = {401: AuthError, 403: AuthError, 429: QuotaError, 503: BackendError}.get(e.code, QuantaKitError)
60
+ raise cls(f"{msg} (HTTP {e.code})", info.get("hint"), code) from None
61
+ except urllib.error.URLError as e:
62
+ raise BackendError(f"Can't reach {self.url}: {e.reason}.", "Check your internet connection, or use LocalSimulator() offline.") from None
63
+
64
+ # ───────── backends ─────────
65
+ def backends(self, simulator: bool | None = None, min_qubits: int = 0, operational: bool | None = None) -> list["CloudBackend"]:
66
+ rows = self._request("GET", "/backends")
67
+ out = [CloudBackend(self, r) for r in rows]
68
+ return [b for b in out if (simulator is None or b.simulator == simulator) and b.num_qubits >= min_qubits
69
+ and (operational is None or (b._info["status"] == "online") == operational)]
70
+
71
+ def backend(self, name: str) -> "CloudBackend":
72
+ return CloudBackend(self, self._request("GET", f"/backends/{name}"))
73
+
74
+ def least_busy(self, min_qubits: int = 1, simulator: bool | None = None) -> "CloudBackend":
75
+ cands = self.backends(simulator=simulator, min_qubits=min_qubits, operational=True)
76
+ if not cands:
77
+ raise BackendError(f"No online backend with at least {min_qubits} qubits.")
78
+ return min(cands, key=lambda b: (b._info.get("queue_length", 0), not b.simulator))
79
+
80
+ def job(self, job_id: str):
81
+ return _CloudJob(self, [job_id], [None], None).as_primitive_job()
82
+
83
+ def me(self) -> dict:
84
+ return self._request("GET", "/me")
85
+
86
+
87
+ class CloudBackend:
88
+ is_local = False
89
+
90
+ def __init__(self, service: CloudService, info: dict):
91
+ self._service, self._info = service, info
92
+ self.name: str = info["name"]
93
+ self.provider: str = info.get("provider", "")
94
+ self.simulator: bool = info.get("type") == "simulator"
95
+ self.num_qubits: int = min(int(info.get("num_qubits", 0)), CLOUD_MAX_QUBITS) if self.simulator else int(info.get("num_qubits", 0))
96
+ gates = info.get("native_gates") or ["any"]
97
+ self.basis_gates: list[str] | None = None if "any" in gates else [g for g in gates if g in CLOUD_GATES] or None
98
+
99
+ def status(self) -> BackendStatus:
100
+ i = self._service._request("GET", f"/backends/{self.name}")
101
+ return BackendStatus(self.name, i["status"] == "online", int(i.get("queue_length", 0)), i["status"])
102
+
103
+ @property
104
+ def properties(self) -> dict:
105
+ return dict(self._info)
106
+
107
+ def _run_sampler(self, circuits: list[QuantumCircuit], shots: int, seed: int | None):
108
+ from ..transpiler import transpile
109
+ ids, maps = [], []
110
+ for k, circ in enumerate(circuits):
111
+ ops = list(flatten(circ))
112
+ measured: set[int] = set()
113
+ for ins in ops:
114
+ if ins.name == "reset" or (ins.name not in ("measure", "barrier") and measured & set(ins.qubits)):
115
+ raise IsaError("Mid-circuit measurement and reset run on the local simulator in this edition.", "Use Sampler(LocalSimulator()).")
116
+ if ins.name == "measure":
117
+ measured.add(ins.qubits[0])
118
+ if circ.num_qubits > self.num_qubits:
119
+ raise IsaError(f"Circuit uses {circ.num_qubits} qubits; {self.name} accepts {self.num_qubits}.", code="QK-1003")
120
+ safe = transpile(circ, basis_gates=CLOUD_GATES, optimization_level=0)
121
+ qasm = _cloud_qasm(safe)
122
+ res = self._service._request("POST", "/jobs", {
123
+ "backend": self.name, "primitive": "sampler",
124
+ "pubs": [{"circuit": {"format": "qasm3", "data": qasm}, "shots": shots}],
125
+ "options": {"seed": None if seed is None else seed + k, "name": circ.name, "sdk_version": __version__,
126
+ "optimization_level": (circ.metadata.get("transpile") or {}).get("optimization_level", 1)},
127
+ })
128
+ ids.append(res["job_id"])
129
+ maps.append(circ)
130
+ return _CloudJob(self._service, ids, maps, shots).as_primitive_job()
131
+
132
+ def __repr__(self):
133
+ return f"<CloudBackend '{self.name}' {'simulator' if self.simulator else 'QPU'} {self.num_qubits} qubits>"
134
+
135
+
136
+ def _cloud_qasm(qc: QuantumCircuit) -> str:
137
+ """Single register ``q`` and bits ``c`` with c[i] = measure q[i] — the cloud's accepted subset."""
138
+ from ..qasm import _angle
139
+ lines = ["OPENQASM 3.0;", 'include "stdgates.inc";', f"qubit[{qc.num_qubits}] q;", f"bit[{qc.num_qubits}] c;"]
140
+ for ins in flatten(qc):
141
+ qs = ", ".join(f"q[{q}]" for q in ins.qubits)
142
+ if ins.name == "measure":
143
+ lines.append(f"c[{ins.qubits[0]}] = measure q[{ins.qubits[0]}];")
144
+ elif ins.name == "barrier":
145
+ lines.append(f"barrier {qs};")
146
+ else:
147
+ params = f"({', '.join(_angle(p) for p in ins.params)})" if ins.params else ""
148
+ lines.append(f"{ins.name}{params} {qs};")
149
+ return "\n".join(lines) + "\n"
150
+
151
+
152
+ class _CloudJob:
153
+ def __init__(self, service: CloudService, ids: list[str], circuits: list, shots: int | None):
154
+ self.service, self.ids, self.circuits, self.shots = service, ids, circuits, shots
155
+
156
+ def status(self) -> str:
157
+ states = [self.service._request("GET", f"/jobs/{i}")["status"] for i in self.ids]
158
+ for s in ("ERROR", "CANCELLED", "RUNNING", "VALIDATING", "QUEUED"):
159
+ if s in states:
160
+ return s
161
+ return "DONE"
162
+
163
+ def cancel(self) -> bool:
164
+ return all(self.service._request("POST", f"/jobs/{i}/cancel").get("cancelled") for i in self.ids)
165
+
166
+ def fetch(self, timeout: float | None):
167
+ from ..primitives import PrimitiveResult, PubResult, _register_arrays, DataBin, BitArray
168
+ deadline = None if timeout is None else time.time() + timeout
169
+ pubs = []
170
+ for jid, circ in zip(self.ids, self.circuits):
171
+ delay = 0.5
172
+ while True:
173
+ info = self.service._request("GET", f"/jobs/{jid}")
174
+ if info["status"] == "DONE":
175
+ break
176
+ if info["status"] in ("ERROR", "CANCELLED"):
177
+ raise JobError(f"Job {jid} {info['status']}: {info.get('error_message') or ''}".strip(), code=info.get("error_code"))
178
+ if deadline and time.time() > deadline:
179
+ raise JobError(f"Timed out waiting for job {jid} (status {info['status']}).", "Call job.result() again later.")
180
+ time.sleep(delay)
181
+ delay = min(delay * 1.5, 5)
182
+ res = self.service._request("GET", f"/jobs/{jid}/results")
183
+ counts: dict[str, int] = res["pubs"][0]["counts"]
184
+ if circ is None:
185
+ n = len(next(iter(counts), ""))
186
+ vals = np.repeat([int(k, 2) for k in counts], list(counts.values())) if counts else np.zeros(0, dtype=np.int64)
187
+ pubs.append(PubResult(DataBin(c=BitArray(vals, n)), {"job_id": jid}))
188
+ continue
189
+ # Server keys: measured qubits in ascending order, highest first. Map back onto classical bits.
190
+ qmap: dict[int, int] = {}
191
+ for ins in flatten(circ):
192
+ if ins.name == "measure":
193
+ qmap[ins.qubits[0]] = ins.clbits[0]
194
+ mq = sorted(qmap)
195
+ values = []
196
+ for key, cnt in counts.items():
197
+ v = 0
198
+ for pos, q in enumerate(mq):
199
+ if key[len(key) - 1 - pos] == "1":
200
+ v |= 1 << qmap[q]
201
+ values.extend([v] * cnt)
202
+ pubs.append(PubResult(_register_arrays(circ, np.array(values, dtype=np.int64)), {"job_id": jid, "shots": self.shots, **res.get("metadata", {})}))
203
+ return PrimitiveResult(pubs, {"job_ids": self.ids})
204
+
205
+ def as_primitive_job(self):
206
+ from ..primitives import PrimitiveJob
207
+ return PrimitiveJob(None, ",".join(self.ids), fetch=self.fetch, status_fn=self.status, cancel_fn=self.cancel)
208
+
209
+
210
+ __all__ = ["CloudService", "CloudBackend", "CLOUD_GATES"]