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.
- quantakit/__init__.py +25 -0
- quantakit/circuit/__init__.py +7 -0
- quantakit/circuit/drawer.py +167 -0
- quantakit/circuit/gates.py +144 -0
- quantakit/circuit/library.py +143 -0
- quantakit/circuit/parameter.py +143 -0
- quantakit/circuit/quantumcircuit.py +467 -0
- quantakit/cloud/__init__.py +210 -0
- quantakit/exceptions.py +40 -0
- quantakit/primitives/__init__.py +238 -0
- quantakit/qasm.py +189 -0
- quantakit/qasm2.py +11 -0
- quantakit/qasm3.py +11 -0
- quantakit/quantum_info/__init__.py +319 -0
- quantakit/sim/__init__.py +52 -0
- quantakit/sim/engine.py +149 -0
- quantakit/transpiler/__init__.py +257 -0
- quantakit/version.py +4 -0
- quantakit/visualization/__init__.py +112 -0
- quantakit-1.0.0.dist-info/METADATA +74 -0
- quantakit-1.0.0.dist-info/RECORD +23 -0
- quantakit-1.0.0.dist-info/WHEEL +4 -0
- quantakit-1.0.0.dist-info/licenses/LICENSE +202 -0
quantakit/exceptions.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Exceptions. Each carries a code (matching the QuantaKit Cloud error codes), a message and a hint."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class QuantaKitError(Exception):
|
|
5
|
+
code = "QK-0000"
|
|
6
|
+
|
|
7
|
+
def __init__(self, message: str, hint: str | None = None, code: str | None = None):
|
|
8
|
+
self.message = message
|
|
9
|
+
self.hint = hint
|
|
10
|
+
if code:
|
|
11
|
+
self.code = code
|
|
12
|
+
super().__init__(f"{message}" + (f" Hint: {hint}" if hint else ""))
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class CircuitError(QuantaKitError):
|
|
16
|
+
code = "QK-1001"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class IsaError(QuantaKitError):
|
|
20
|
+
code = "QK-1002"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class TranspilerError(QuantaKitError):
|
|
24
|
+
code = "QK-1005"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class AuthError(QuantaKitError):
|
|
28
|
+
code = "QK-2001"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class QuotaError(QuantaKitError):
|
|
32
|
+
code = "QK-3001"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class BackendError(QuantaKitError):
|
|
36
|
+
code = "QK-4001"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class JobError(QuantaKitError):
|
|
40
|
+
code = "QK-5001"
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
"""Primitives: Sampler (measurement counts) and Estimator (expectation values).
|
|
2
|
+
|
|
3
|
+
The same code runs on the local simulator and on QuantaKit Cloud — only the backend object changes:
|
|
4
|
+
|
|
5
|
+
>>> Sampler() # local, offline (default)
|
|
6
|
+
>>> Sampler(LocalSimulator(readout_error=0.02))
|
|
7
|
+
>>> Sampler(CloudService().least_busy())
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import math
|
|
13
|
+
import uuid
|
|
14
|
+
from typing import Any, Mapping, Sequence
|
|
15
|
+
|
|
16
|
+
import numpy as np
|
|
17
|
+
|
|
18
|
+
from ..circuit.quantumcircuit import QuantumCircuit
|
|
19
|
+
from ..exceptions import CircuitError, JobError
|
|
20
|
+
from ..quantum_info import SparsePauliOp, Statevector
|
|
21
|
+
from ..sim import LocalSimulator
|
|
22
|
+
from ..sim import engine
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class BitArray:
|
|
26
|
+
"""Measurement outcomes of one classical register over all shots."""
|
|
27
|
+
|
|
28
|
+
def __init__(self, values: np.ndarray, num_bits: int):
|
|
29
|
+
self._values = np.asarray(values, dtype=np.int64)
|
|
30
|
+
self.num_bits = num_bits
|
|
31
|
+
|
|
32
|
+
@property
|
|
33
|
+
def num_shots(self) -> int:
|
|
34
|
+
return len(self._values)
|
|
35
|
+
|
|
36
|
+
def get_bitstrings(self) -> list[str]:
|
|
37
|
+
return [format(int(v), f"0{self.num_bits}b") for v in self._values]
|
|
38
|
+
|
|
39
|
+
def get_int_counts(self) -> dict[int, int]:
|
|
40
|
+
vals, cnt = np.unique(self._values, return_counts=True)
|
|
41
|
+
return {int(v): int(c) for v, c in sorted(zip(vals, cnt), key=lambda t: -t[1])}
|
|
42
|
+
|
|
43
|
+
def get_counts(self) -> dict[str, int]:
|
|
44
|
+
"""Counts keyed by bit string; the leftmost bit is the highest classical bit."""
|
|
45
|
+
return {format(k, f"0{self.num_bits}b"): v for k, v in self.get_int_counts().items()}
|
|
46
|
+
|
|
47
|
+
def get_probabilities(self) -> dict[str, float]:
|
|
48
|
+
return {k: v / self.num_shots for k, v in self.get_counts().items()}
|
|
49
|
+
|
|
50
|
+
def __repr__(self):
|
|
51
|
+
return f"BitArray(num_shots={self.num_shots}, num_bits={self.num_bits})"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class DataBin:
|
|
55
|
+
"""Attribute access to results, e.g. ``data.meas`` or ``data.c`` (named after the classical registers)."""
|
|
56
|
+
|
|
57
|
+
def __init__(self, **fields):
|
|
58
|
+
self.__dict__.update(fields)
|
|
59
|
+
|
|
60
|
+
def keys(self):
|
|
61
|
+
return list(self.__dict__)
|
|
62
|
+
|
|
63
|
+
def __getitem__(self, k):
|
|
64
|
+
return self.__dict__[k]
|
|
65
|
+
|
|
66
|
+
def __repr__(self):
|
|
67
|
+
return f"DataBin({', '.join(f'{k}={v!r}' for k, v in self.__dict__.items())})"
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class PubResult:
|
|
71
|
+
def __init__(self, data: DataBin, metadata: dict | None = None):
|
|
72
|
+
self.data = data
|
|
73
|
+
self.metadata = metadata or {}
|
|
74
|
+
|
|
75
|
+
def join_data(self) -> BitArray:
|
|
76
|
+
"""All classical registers joined into one BitArray (Sampler results)."""
|
|
77
|
+
regs = [v for v in self.data.__dict__.values() if isinstance(v, BitArray)]
|
|
78
|
+
if len(regs) == 1:
|
|
79
|
+
return regs[0]
|
|
80
|
+
vals = np.zeros(regs[0].num_shots, dtype=np.int64)
|
|
81
|
+
shift = 0
|
|
82
|
+
for r in regs:
|
|
83
|
+
vals |= r._values << shift
|
|
84
|
+
shift += r.num_bits
|
|
85
|
+
return BitArray(vals, shift)
|
|
86
|
+
|
|
87
|
+
def __repr__(self):
|
|
88
|
+
return f"PubResult(data={self.data!r})"
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class PrimitiveResult(list):
|
|
92
|
+
def __init__(self, pubs: list[PubResult], metadata: dict | None = None):
|
|
93
|
+
super().__init__(pubs)
|
|
94
|
+
self.metadata = metadata or {}
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class PrimitiveJob:
|
|
98
|
+
"""Result of ``Sampler.run``/``Estimator.run``. Local jobs finish immediately."""
|
|
99
|
+
|
|
100
|
+
def __init__(self, result: PrimitiveResult | None = None, job_id: str | None = None, fetch=None, status_fn=None, cancel_fn=None):
|
|
101
|
+
self._result, self._fetch, self._status_fn, self._cancel_fn = result, fetch, status_fn, cancel_fn
|
|
102
|
+
self.job_id = job_id or f"local-{uuid.uuid4().hex[:12]}"
|
|
103
|
+
|
|
104
|
+
def status(self) -> str:
|
|
105
|
+
return self._status_fn() if self._status_fn else "DONE"
|
|
106
|
+
|
|
107
|
+
def done(self) -> bool:
|
|
108
|
+
return self.status() in ("DONE", "ERROR", "CANCELLED")
|
|
109
|
+
|
|
110
|
+
def result(self, timeout: float | None = None) -> PrimitiveResult:
|
|
111
|
+
if self._result is None:
|
|
112
|
+
self._result = self._fetch(timeout)
|
|
113
|
+
return self._result
|
|
114
|
+
|
|
115
|
+
def cancel(self) -> bool:
|
|
116
|
+
return bool(self._cancel_fn and self._cancel_fn())
|
|
117
|
+
|
|
118
|
+
def __repr__(self):
|
|
119
|
+
return f"<PrimitiveJob {self.job_id}>"
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _normalize_pub(pub) -> tuple[QuantumCircuit, Any]:
|
|
123
|
+
if isinstance(pub, QuantumCircuit):
|
|
124
|
+
return pub, None
|
|
125
|
+
if isinstance(pub, (tuple, list)) and pub and isinstance(pub[0], QuantumCircuit):
|
|
126
|
+
return pub[0], (pub[1] if len(pub) > 1 else None)
|
|
127
|
+
raise CircuitError("Each PUB must be a circuit or (circuit, parameter_values).")
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _bind(circ: QuantumCircuit, values) -> QuantumCircuit:
|
|
131
|
+
if values is None:
|
|
132
|
+
if circ.parameters:
|
|
133
|
+
raise CircuitError(f"Circuit has unbound parameters: {', '.join(p.name for p in circ.parameters)}.", "Pass (circuit, values) as the PUB.")
|
|
134
|
+
return circ
|
|
135
|
+
return circ.assign_parameters(values if isinstance(values, Mapping) else list(np.asarray(values, dtype=float).ravel()))
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _register_arrays(circ: QuantumCircuit, clbit_values: np.ndarray) -> DataBin:
|
|
139
|
+
fields = {}
|
|
140
|
+
for reg in circ.cregs:
|
|
141
|
+
off = reg._offset or 0
|
|
142
|
+
fields[reg.name] = BitArray((clbit_values >> off) & ((1 << reg.size) - 1), reg.size)
|
|
143
|
+
return DataBin(**fields)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
class Sampler:
|
|
147
|
+
"""Samples measurement outcomes. ``Sampler(backend=None)`` uses the local simulator."""
|
|
148
|
+
|
|
149
|
+
def __init__(self, backend=None, mode=None):
|
|
150
|
+
self.backend = backend or LocalSimulator()
|
|
151
|
+
|
|
152
|
+
def run(self, pubs: Sequence, shots: int = 1024, seed: int | None = None) -> PrimitiveJob:
|
|
153
|
+
if isinstance(pubs, QuantumCircuit):
|
|
154
|
+
pubs = [pubs]
|
|
155
|
+
shots = int(shots)
|
|
156
|
+
if shots < 1:
|
|
157
|
+
raise CircuitError("shots must be at least 1.")
|
|
158
|
+
circuits = []
|
|
159
|
+
for pub in pubs:
|
|
160
|
+
circ, vals = _normalize_pub(pub)
|
|
161
|
+
circ = _bind(circ, vals)
|
|
162
|
+
if not circ.cregs or not any(i.name == "measure" for i in circ.data):
|
|
163
|
+
raise CircuitError("This circuit has no measurements, so the Sampler has nothing to count.", "Add qc.measure_all().")
|
|
164
|
+
circuits.append(circ)
|
|
165
|
+
if getattr(self.backend, "is_local", False):
|
|
166
|
+
results = []
|
|
167
|
+
for k, circ in enumerate(circuits):
|
|
168
|
+
s = None if seed is None else seed + k
|
|
169
|
+
values = engine.sample_clbits(circ, shots, s, getattr(self.backend, "readout_error", 0.0))
|
|
170
|
+
results.append(PubResult(_register_arrays(circ, values), {"shots": shots, "circuit_metadata": circ.metadata}))
|
|
171
|
+
return PrimitiveJob(PrimitiveResult(results, {"backend": self.backend.name, "seed": seed}))
|
|
172
|
+
return self.backend._run_sampler(circuits, shots, seed)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
class Estimator:
|
|
176
|
+
"""Expectation values of observables. PUB = ``(circuit, observable)`` or ``(circuit, observable, values)``.
|
|
177
|
+
|
|
178
|
+
Locally, ``precision=None`` (default) gives exact values from the statevector. With a ``precision``
|
|
179
|
+
(target standard error) or a cloud backend, values are estimated from measurement shots.
|
|
180
|
+
"""
|
|
181
|
+
|
|
182
|
+
def __init__(self, backend=None, mode=None):
|
|
183
|
+
self.backend = backend or LocalSimulator()
|
|
184
|
+
|
|
185
|
+
def run(self, pubs: Sequence, precision: float | None = None, seed: int | None = None) -> PrimitiveJob:
|
|
186
|
+
results = []
|
|
187
|
+
for k, pub in enumerate(pubs):
|
|
188
|
+
if not isinstance(pub, (tuple, list)) or len(pub) < 2:
|
|
189
|
+
raise CircuitError("Estimator PUBs are (circuit, observable) or (circuit, observable, parameter_values).")
|
|
190
|
+
circ = _bind(pub[0], pub[2] if len(pub) > 2 else None).remove_final_measurements(inplace=False)
|
|
191
|
+
obs_list = pub[1] if isinstance(pub[1], (list, tuple)) else [pub[1]]
|
|
192
|
+
obs_list = [o if isinstance(o, SparsePauliOp) else SparsePauliOp(o) for o in obs_list]
|
|
193
|
+
evs, stds = [], []
|
|
194
|
+
for obs in obs_list:
|
|
195
|
+
if obs.num_qubits != circ.num_qubits:
|
|
196
|
+
raise CircuitError(f"Observable has {obs.num_qubits} qubits; circuit has {circ.num_qubits}.")
|
|
197
|
+
if getattr(self.backend, "is_local", False) and precision is None and not getattr(self.backend, "readout_error", 0):
|
|
198
|
+
evs.append(float(np.real(Statevector(circ).expectation_value(obs))))
|
|
199
|
+
stds.append(0.0)
|
|
200
|
+
else:
|
|
201
|
+
ev, sd = self._sampled(circ, obs, precision or 0.015625, None if seed is None else seed + 1000 * k)
|
|
202
|
+
evs.append(ev)
|
|
203
|
+
stds.append(sd)
|
|
204
|
+
data = DataBin(evs=np.array(evs) if len(evs) > 1 else np.float64(evs[0]), stds=np.array(stds) if len(stds) > 1 else np.float64(stds[0]))
|
|
205
|
+
results.append(PubResult(data, {"precision": precision}))
|
|
206
|
+
return PrimitiveJob(PrimitiveResult(results, {"backend": getattr(self.backend, "name", "?")}))
|
|
207
|
+
|
|
208
|
+
def _sampled(self, circ: QuantumCircuit, obs: SparsePauliOp, precision: float, seed: int | None) -> tuple[float, float]:
|
|
209
|
+
shots = max(1, math.ceil(1 / precision ** 2))
|
|
210
|
+
total, var = 0.0, 0.0
|
|
211
|
+
sampler = Sampler(self.backend)
|
|
212
|
+
for term, coeff in zip(obs.paulis, obs.coeffs):
|
|
213
|
+
if set(term) == {"I"}:
|
|
214
|
+
total += float(np.real(coeff))
|
|
215
|
+
continue
|
|
216
|
+
qc = circ.copy()
|
|
217
|
+
qubits = []
|
|
218
|
+
for pos, ch in enumerate(reversed(term)): # rightmost char = qubit 0
|
|
219
|
+
if ch == "X":
|
|
220
|
+
qc.h(pos)
|
|
221
|
+
elif ch == "Y":
|
|
222
|
+
qc.sdg(pos)
|
|
223
|
+
qc.h(pos)
|
|
224
|
+
if ch != "I":
|
|
225
|
+
qubits.append(pos)
|
|
226
|
+
qc.measure_all()
|
|
227
|
+
counts = sampler.run([qc], shots=shots, seed=seed).result()[0].data.meas.get_int_counts()
|
|
228
|
+
ev = 0.0
|
|
229
|
+
for outcome, c in counts.items():
|
|
230
|
+
parity = sum((outcome >> q) & 1 for q in qubits) % 2
|
|
231
|
+
ev += (-1 if parity else 1) * c
|
|
232
|
+
ev /= shots
|
|
233
|
+
total += float(np.real(coeff)) * ev
|
|
234
|
+
var += abs(coeff) ** 2 * (1 - ev ** 2) / shots
|
|
235
|
+
return total, math.sqrt(var)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
__all__ = ["Sampler", "Estimator", "BitArray", "DataBin", "PubResult", "PrimitiveResult", "PrimitiveJob"]
|
quantakit/qasm.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
"""OpenQASM 2.0 / 3.0 import and export for the standard gate library."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import ast
|
|
6
|
+
import math
|
|
7
|
+
import operator
|
|
8
|
+
import re
|
|
9
|
+
|
|
10
|
+
from .circuit.quantumcircuit import QuantumCircuit, QuantumRegister, ClassicalRegister
|
|
11
|
+
from .circuit.parameter import ParameterExpression
|
|
12
|
+
from .circuit.gates import GATE_SPECS
|
|
13
|
+
from .exceptions import CircuitError
|
|
14
|
+
from .sim.engine import flatten
|
|
15
|
+
|
|
16
|
+
_QASM3_NAME = {"sxdg": "sxdg", "iswap": "iswap", "id": "id"}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _angle(p) -> str:
|
|
20
|
+
if isinstance(p, ParameterExpression) and p.parameters:
|
|
21
|
+
raise CircuitError("Bind all parameters before exporting to OpenQASM.", "Use circuit.assign_parameters(...).")
|
|
22
|
+
v = float(p)
|
|
23
|
+
for k, s in [(1, "pi"), (0.5, "pi/2"), (0.25, "pi/4"), (0.125, "pi/8"), (-1, "-pi"), (-0.5, "-pi/2"), (-0.25, "-pi/4"), (2, "2*pi"), (0.75, "3*pi/4"), (1.5, "3*pi/2")]:
|
|
24
|
+
if abs(v - k * math.pi) < 1e-12:
|
|
25
|
+
return s
|
|
26
|
+
return repr(v)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _reg_names(qc: QuantumCircuit):
|
|
30
|
+
qnames = []
|
|
31
|
+
for r in qc.qregs:
|
|
32
|
+
qnames += [f"{r.name}[{i}]" for i in range(r.size)]
|
|
33
|
+
cnames = []
|
|
34
|
+
for r in qc.cregs:
|
|
35
|
+
cnames += [f"{r.name}[{i}]" for i in range(r.size)]
|
|
36
|
+
return qnames, cnames
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _dumps(qc: QuantumCircuit, version: int) -> str:
|
|
40
|
+
qn, cn = _reg_names(qc)
|
|
41
|
+
lines = ["OPENQASM 3.0;", 'include "stdgates.inc";'] if version == 3 else ["OPENQASM 2.0;", 'include "qelib1.inc";']
|
|
42
|
+
for r in qc.qregs:
|
|
43
|
+
lines.append(f"qubit[{r.size}] {r.name};" if version == 3 else f"qreg {r.name}[{r.size}];")
|
|
44
|
+
for r in qc.cregs:
|
|
45
|
+
lines.append(f"bit[{r.size}] {r.name};" if version == 3 else f"creg {r.name}[{r.size}];")
|
|
46
|
+
for ins in flatten(qc):
|
|
47
|
+
qs = ", ".join(qn[q] for q in ins.qubits)
|
|
48
|
+
if ins.name == "measure":
|
|
49
|
+
c = cn[ins.clbits[0]]
|
|
50
|
+
lines.append(f"{c} = measure {qs};" if version == 3 else f"measure {qs} -> {c};")
|
|
51
|
+
elif ins.name in ("barrier", "reset"):
|
|
52
|
+
lines.append(f"{ins.name} {qs};")
|
|
53
|
+
else:
|
|
54
|
+
name = ins.name
|
|
55
|
+
if version == 2 and name == "p":
|
|
56
|
+
name = "u1"
|
|
57
|
+
if version == 2 and name == "u":
|
|
58
|
+
name = "u3"
|
|
59
|
+
params = f"({', '.join(_angle(p) for p in ins.params)})" if ins.params else ""
|
|
60
|
+
lines.append(f"{name}{params} {qs};")
|
|
61
|
+
return "\n".join(lines) + "\n"
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
_ALLOWED_BIN = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.truediv, ast.Pow: operator.pow}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _eval_angle(expr: str) -> float:
|
|
68
|
+
expr = expr.replace("π", "pi").strip()
|
|
69
|
+
|
|
70
|
+
def ev(node):
|
|
71
|
+
if isinstance(node, ast.Expression):
|
|
72
|
+
return ev(node.body)
|
|
73
|
+
if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
|
|
74
|
+
return float(node.value)
|
|
75
|
+
if isinstance(node, ast.Name) and node.id in ("pi", "tau", "e"):
|
|
76
|
+
return {"pi": math.pi, "tau": 2 * math.pi, "e": math.e}[node.id]
|
|
77
|
+
if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.USub, ast.UAdd)):
|
|
78
|
+
v = ev(node.operand)
|
|
79
|
+
return -v if isinstance(node.op, ast.USub) else v
|
|
80
|
+
if isinstance(node, ast.BinOp) and type(node.op) in _ALLOWED_BIN:
|
|
81
|
+
return _ALLOWED_BIN[type(node.op)](ev(node.left), ev(node.right))
|
|
82
|
+
raise ValueError(expr)
|
|
83
|
+
|
|
84
|
+
try:
|
|
85
|
+
return ev(ast.parse(expr, mode="eval"))
|
|
86
|
+
except Exception as e:
|
|
87
|
+
raise CircuitError(f"Can't read the angle '{expr}'.") from e
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def loads(text: str) -> QuantumCircuit:
|
|
91
|
+
"""Parse OpenQASM 2.0 or 3.0 (standard gates, measure, reset, barrier)."""
|
|
92
|
+
qregs: dict[str, QuantumRegister] = {}
|
|
93
|
+
cregs: dict[str, ClassicalRegister] = {}
|
|
94
|
+
qc: QuantumCircuit | None = None
|
|
95
|
+
body = re.sub(r"//.*", "", text)
|
|
96
|
+
stmts = [s.strip() for s in body.split(";") if s.strip()]
|
|
97
|
+
|
|
98
|
+
def circuit() -> QuantumCircuit:
|
|
99
|
+
nonlocal qc
|
|
100
|
+
if qc is None:
|
|
101
|
+
qc = QuantumCircuit(*qregs.values(), *cregs.values())
|
|
102
|
+
return qc
|
|
103
|
+
|
|
104
|
+
def ref(token: str, regs: dict) -> list[int]:
|
|
105
|
+
token = token.strip()
|
|
106
|
+
m = re.fullmatch(r"(\w+)\[(\d+)\]", token)
|
|
107
|
+
if m:
|
|
108
|
+
if m.group(1) not in regs:
|
|
109
|
+
raise CircuitError(f"Unknown register '{m.group(1)}'.")
|
|
110
|
+
return [regs[m.group(1)][int(m.group(2))]]
|
|
111
|
+
if token in regs:
|
|
112
|
+
return list(regs[token])
|
|
113
|
+
raise CircuitError(f"Can't read operand '{token}'.")
|
|
114
|
+
|
|
115
|
+
for line_no, st in enumerate(stmts, 1):
|
|
116
|
+
if re.match(r"^OPENQASM\s+[23]", st) or st.startswith("include"):
|
|
117
|
+
continue
|
|
118
|
+
m = re.fullmatch(r"qubit\[(\d+)\]\s+(\w+)|qreg\s+(\w+)\[(\d+)\]", st)
|
|
119
|
+
if m:
|
|
120
|
+
size, name = (m.group(1), m.group(2)) if m.group(1) else (m.group(4), m.group(3))
|
|
121
|
+
if qc is not None:
|
|
122
|
+
raise CircuitError("Declare all registers before the first operation.")
|
|
123
|
+
qregs[name] = QuantumRegister(int(size), name)
|
|
124
|
+
continue
|
|
125
|
+
m = re.fullmatch(r"bit\[(\d+)\]\s+(\w+)|creg\s+(\w+)\[(\d+)\]", st)
|
|
126
|
+
if m:
|
|
127
|
+
size, name = (m.group(1), m.group(2)) if m.group(1) else (m.group(4), m.group(3))
|
|
128
|
+
if qc is not None:
|
|
129
|
+
raise CircuitError("Declare all registers before the first operation.")
|
|
130
|
+
cregs[name] = ClassicalRegister(int(size), name)
|
|
131
|
+
continue
|
|
132
|
+
c = circuit()
|
|
133
|
+
m = re.fullmatch(r"(\S+)\s*=\s*measure\s+(\S+)", st) or re.fullmatch(r"measure\s+(\S+)\s*->\s*(\S+)", st)
|
|
134
|
+
if m:
|
|
135
|
+
if st.startswith("measure"):
|
|
136
|
+
qs, cs = ref(m.group(1), qregs), ref(m.group(2), cregs)
|
|
137
|
+
else:
|
|
138
|
+
cs, qs = ref(m.group(1), cregs), ref(m.group(2), qregs)
|
|
139
|
+
c.measure(qs, cs)
|
|
140
|
+
continue
|
|
141
|
+
m = re.fullmatch(r"(barrier|reset)\s+(.+)", st)
|
|
142
|
+
if m:
|
|
143
|
+
qs = [q for t in m.group(2).split(",") for q in ref(t, qregs)]
|
|
144
|
+
c.barrier(qs) if m.group(1) == "barrier" else c.reset(qs)
|
|
145
|
+
continue
|
|
146
|
+
m = re.fullmatch(r"(\w+)\s*(?:\(([^)]*)\))?\s+(.+)", st)
|
|
147
|
+
if not m:
|
|
148
|
+
raise CircuitError(f"Statement {line_no}: can't read '{st}'.")
|
|
149
|
+
name = {"cnot": "cx", "u1": "p", "u3": "u", "phase": "p", "cphase": "cp"}.get(m.group(1).lower(), m.group(1).lower())
|
|
150
|
+
if name == "u2":
|
|
151
|
+
phi, lam = (_eval_angle(x) for x in m.group(2).split(","))
|
|
152
|
+
name, params = "u", [math.pi / 2, phi, lam]
|
|
153
|
+
else:
|
|
154
|
+
params = [_eval_angle(x) for x in m.group(2).split(",")] if m.group(2) else []
|
|
155
|
+
if name not in GATE_SPECS:
|
|
156
|
+
raise CircuitError(f"Statement {line_no}: unknown gate '{m.group(1)}'.")
|
|
157
|
+
operands = [ref(t, qregs) for t in m.group(3).split(",")]
|
|
158
|
+
width = max(len(o) for o in operands)
|
|
159
|
+
for k in range(width): # broadcast over whole registers
|
|
160
|
+
qs = [o[k] if len(o) > 1 else o[0] for o in operands]
|
|
161
|
+
c._gate(name, params, *qs)
|
|
162
|
+
return circuit()
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def dumps(circuit: QuantumCircuit) -> str:
|
|
166
|
+
"""OpenQASM 3.0 text."""
|
|
167
|
+
return _dumps(circuit, 3)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def dumps2(circuit: QuantumCircuit) -> str:
|
|
171
|
+
"""OpenQASM 2.0 text (gates outside qelib1 may not load in older tools)."""
|
|
172
|
+
return _dumps(circuit, 2)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
class _Namespace:
|
|
176
|
+
def __init__(self, version: int):
|
|
177
|
+
self.version = version
|
|
178
|
+
|
|
179
|
+
def dumps(self, circuit: QuantumCircuit) -> str:
|
|
180
|
+
return _dumps(circuit, self.version)
|
|
181
|
+
|
|
182
|
+
def loads(self, text: str) -> QuantumCircuit:
|
|
183
|
+
return loads(text)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
qasm3 = _Namespace(3)
|
|
187
|
+
qasm2 = _Namespace(2)
|
|
188
|
+
|
|
189
|
+
__all__ = ["dumps", "dumps2", "loads", "qasm2", "qasm3"]
|
quantakit/qasm2.py
ADDED
quantakit/qasm3.py
ADDED