QuantaKit SDK documentation
Build, simulate and run quantum circuits in Python. Everything works offline on the free local simulator — no account, token or quota. QuantaKit Cloud is optional. Prefer to watch? See the video walkthroughs.
Installation
Install the exact version the book uses (recommended for readers):
pip install quantakit==1.0.0Newest release: 1.1.0, which adds noise settings for cloud jobs (see below). Every 1.0 example runs unchanged on it: pip install quantakit==1.1.0.
If the package index isn't reachable, install the same release from GitHub or from this site:
pip install https://github.com/mustafaalobaedy/quantakit-sdk/releases/download/v1.0.0/quantakit-1.0.0-py3-none-any.whl
pip install https://quantakit.my/downloads/quantakit-1.0.0-py3-none-any.whlOptional plots (histograms, Bloch spheres, circuit figures) need matplotlib:
pip install "quantakit[visualization]==1.0.0"Check the installation and run the offline tour:
python -c "import quantakit; print(quantakit.__version__)" # 1.0.0
python run_all_offline.pyTip for classes: use a virtual environment per course — python -m venv qk && qk\Scripts\activate (Windows) or source qk/bin/activate (macOS/Linux).
Quickstart (offline)
from quantakit import QuantumCircuit, transpile, LocalSimulator
from quantakit.primitives import Sampler
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
print(qc.draw())
backend = LocalSimulator() # free, offline
job = Sampler(backend).run([transpile(qc, backend)], shots=4000, seed=7)
counts = job.result()[0].data.meas.get_counts()
print(counts) # {'00': ~2000, '11': ~2000}Sampler() with no argument also uses the local simulator. Passing seed= makes results identical on every run — useful for printed outputs.
Bit order
Qubit 0 is the rightmost character of a bit string: "01" means q0 = 1 and q1 = 0. This matches OpenQASM tools and most SDKs. In Statevector.data, amplitude index i has qubit k in bit k of i.
Gate reference
Angles are in radians; use math.pi or a Parameter. 1-qubit methods broadcast: qc.h([0, 1, 2]) or qc.h(range(3)).
| Method | Qubits | Parameters | Family | Description | Cloud |
|---|---|---|---|---|---|
| qc.id(q) | 1 | — | Pauli | Identity | native |
| qc.x(q) | 1 | — | Pauli | Pauli-X (bit flip, NOT) | native |
| qc.y(q) | 1 | — | Pauli | Pauli-Y | native |
| qc.z(q) | 1 | — | Pauli | Pauli-Z (phase flip) | native |
| qc.h(q) | 1 | — | Clifford | Hadamard: equal superposition | native |
| qc.s(q) | 1 | — | Clifford | S = √Z (phase i on |1⟩) | native |
| qc.sdg(q) | 1 | — | Clifford | S† | native |
| qc.sx(q) | 1 | — | Clifford | √X | native |
| qc.sxdg(q) | 1 | — | Clifford | √X† | auto-translated |
| qc.t(q) | 1 | — | Phase | T = √S (phase e^{iπ/4}) | native |
| qc.tdg(q) | 1 | — | Phase | T† | native |
| qc.p(λ, q) | 1 | λ | Phase | Phase P(λ): e^{iλ} on |1⟩ | native |
| qc.rx(θ, q) | 1 | θ | Rotation | Rotation about X | native |
| qc.ry(θ, q) | 1 | θ | Rotation | Rotation about Y | native |
| qc.rz(θ, q) | 1 | θ | Rotation | Rotation about Z | native |
| qc.u(θ, φ, λ, q) | 1 | θ, φ, λ | Rotation | General single-qubit gate | native |
| qc.cx(c, t) | 2 | — | Two-qubit | CNOT (alias qc.cnot) | native |
| qc.cy(c, t) | 2 | — | Two-qubit | Controlled-Y | native |
| qc.cz(c, t) | 2 | — | Two-qubit | Controlled-Z | native |
| qc.ch(c, t) | 2 | — | Two-qubit | Controlled-Hadamard | native |
| qc.cp(λ, c, t) | 2 | λ | Two-qubit | Controlled phase | native |
| qc.crx(θ, c, t) | 2 | θ | Two-qubit | Controlled RX | auto-translated |
| qc.cry(θ, c, t) | 2 | θ | Two-qubit | Controlled RY | auto-translated |
| qc.crz(θ, c, t) | 2 | θ | Two-qubit | Controlled RZ | native |
| qc.swap(a, b) | 2 | — | Two-qubit | Swap two qubits | native |
| qc.iswap(a, b) | 2 | — | Two-qubit | iSWAP | auto-translated |
| qc.rxx(θ, a, b) | 2 | θ | Two-qubit | XX interaction | auto-translated |
| qc.ryy(θ, a, b) | 2 | θ | Two-qubit | YY interaction | auto-translated |
| qc.rzz(θ, a, b) | 2 | θ | Two-qubit | ZZ interaction | native |
| qc.ccx(c1, c2, t) | 3 | — | Three-qubit | Toffoli (alias qc.toffoli) | native |
| qc.cswap(c, a, b) | 3 | — | Three-qubit | Fredkin (alias qc.fredkin) | native |
| qc.mcx([c…], t) | any | — | Multi-qubit | Multi-controlled X (built from the gates above) | native |
| qc.measure(q, c) | 1 | — | Non-unitary | Measure qubit(s) into classical bit(s) | native |
| qc.measure_all() | any | — | Non-unitary | Barrier, then measure every qubit into register meas | native |
| qc.reset(q) | 1 | — | Non-unitary | Reset to |0⟩ (local simulator) | auto-translated |
| qc.barrier(...) | any | — | Non-unitary | Stop optimisation across this point | native |
“Auto-translated” gates are rewritten into native ones when sent to the cloud; locally every gate runs as written. Mid-circuit measurement and reset run on the local simulator in this edition.
Circuits
from quantakit import QuantumCircuit, QuantumRegister, ClassicalRegister, Parameter
import math
qc = QuantumCircuit(3, 3) # 3 qubits, classical register "c" of 3 bits
qc.h(0); qc.cx(0, 1); qc.ccx(0, 1, 2)
qc.measure([0, 1, 2], [0, 1, 2])
qc.depth(), qc.size(), qc.count_ops(), qc.num_nonlocal_gates()
a, m = QuantumRegister(2, "a"), ClassicalRegister(2, "m") # named registers
named = QuantumCircuit(a, m); named.x(a[1]); named.measure(a[:], m[:])
theta = Parameter("θ") # symbolic parameters
ansatz = QuantumCircuit(1); ansatz.ry(2 * theta + math.pi / 4, 0)
bound = ansatz.assign_parameters({theta: 0.3})
bell = QuantumCircuit(2, name="bell"); bell.h(0); bell.cx(0, 1)
big = QuantumCircuit(4); big.append(bell.to_gate(), [2, 3]) # reusable gate
undo = bell.inverse(); twice = bell.power(2); joined = bell.compose(undo)Sampler & Estimator
from quantakit.primitives import Sampler, Estimator
from quantakit.quantum_info import SparsePauliOp
result = Sampler().run([qc], shots=1000, seed=1).result()
result[0].data.c.get_counts() # one BitArray per classical register (here "c")
result[0].data.c.get_bitstrings() # every shot, in order
obs = SparsePauliOp.from_list([("ZZ", 1.0), ("XX", 1.0)])
Estimator().run([(bell, obs)]).result()[0].data.evs # exact: 2.0
Estimator().run([(bell, obs)], precision=0.01).result()[0].data # shot-based: evs, stds
Estimator().run([(ansatz, SparsePauliOp("Z"), [0.3])]).result()[0].data.evs # with parameter values
from quantakit import LocalSimulator
Sampler(LocalSimulator(readout_error=0.02)) # simple noise: each measured bit flips with probability 2%data.c or data.meas? The name after data. is the name of the circuit's classical register. QuantumCircuit(2, 2) with qc.measure(...) creates a register called c, so you read data.c; this is also what the composer's Python tab exports. qc.measure_all() adds a register called meas, so you read data.meas. Using the wrong name raises an AttributeError. If you don't want to think about it, result[0].join_data().get_counts() works for both.
States & operators
from quantakit.quantum_info import Statevector, DensityMatrix, Operator, SparsePauliOp, partial_trace, state_fidelity, entropy
sv = Statevector(bell) # 0.707107|00> + 0.707107|11>
sv.probabilities_dict() # {'00': 0.5, '11': 0.5}
sv.data # NumPy array — connects to plain NumPy linear algebra
Statevector.from_label("+0") # labels: 0 1 + - r l
rho = partial_trace(sv, [1]); rho.purity(), entropy(rho) # 0.5, 1.0
Operator(bell).data # 4x4 unitary
Operator(bell).equiv(Operator(bell.inverse().inverse())) # True (up to global phase)Circuit library
from quantakit.circuit import library
library.bell_state(); library.ghz_state(5); library.qft(4); library.qft(4, inverse=True)
library.grover(3, ["101"]) # oracle + diffuser, optimal iterations, measured
library.phase_estimation(3, unitary_circuit)
library.real_amplitudes(4, reps=2) # parameterised ansatzTranspiler
from quantakit import transpile
hw = transpile(qc, basis_gates=["rz", "sx", "x", "cx"], optimization_level=2)
hw.count_ops(), hw.metadata["transpile"] # gate counts, depth before/afterLevels: 0 translate only · 1 cancel adjacent inverse gates · 2–3 also merge single-qubit runs. This edition assumes all-to-all connectivity (no SWAP routing).
OpenQASM
from quantakit import qasm3, qasm2
text = qasm3.dumps(qc) # OpenQASM 3.0
qc2 = qasm3.loads(text) # also reads OpenQASM 2.0 (qreg/creg, measure q -> c)
qasm2.dumps(qc)The composer at /app/composer shows and accepts the same OpenQASM 3, so circuits move freely between the book, the SDK and the browser.
Importing files into the composer. Use Import (or drop a .qasm file on the page), or paste into the OpenQASM tab. It reads OpenQASM 2.0 and 3.0 from other tools: any register names (several registers are joined into one, in order), whole-register operations such as h q; and measure q -> c;, custom gate definitions, const values, and the qelib1.inc / stdgates.inc gates. Gates the palette doesn't have (u2, crx, cry, cu, cu3, csx, ccz, rxx, ryy, rzx, iswap, ecr, …) are rewritten exactly with palette gates, and a note says what changed. Up to 16 qubits; classical control (if), loops and gate modifiers (ctrl @) aren't supported. Use the SDK for those (qasm3.loads).
Visualisation
print(qc.draw()) # text diagram (no extra packages)
from quantakit.visualization import text_histogram, plot_histogram, plot_bloch_multivector, bloch_vectors
print(text_histogram(counts)) # text bar chart (no extra packages)
plot_histogram([counts_a, counts_b], legend=["ideal", "noisy"]) # needs matplotlib
plot_bloch_multivector(Statevector(qc_without_measurements)) # needs matplotlib
qc.draw("mpl") # needs matplotlibQuantaKit Cloud (optional)
Create an API key under Account → API keys (scopes jobs:read and jobs:write), then change one line:
from quantakit.cloud import CloudService
service = CloudService(token="qk_...") # or set QK_TOKEN in the environment
service.backends() # simulators and (emulated) hardware
backend = service.least_busy(min_qubits=2)
job = Sampler(backend).run([transpile(qc, backend)], shots=4000)
job.job_id, job.status()
counts = job.result()[0].data.meas.get_counts() # same code as offlineEvery account gets the free Academic plan (20 h simulator + 30 min hardware per month). Cloud jobs count against that monthly quota and appear under Jobs in the console. Hardware backends are emulated until partner devices go live.
REST API
Base URL https://quantakit.my/v1. Authenticate with Authorization: Bearer qk_…. JSON in and out; errors return {"code": "QK-xxxx", "message": "…"}.
| Method | Path | Scope | Purpose |
|---|---|---|---|
| GET | /v1/me | any | Profile, plan, quota and usage this month |
| GET | /v1/backends | any | List backends |
| GET | /v1/backends/{name} | any | One backend |
| POST | /v1/jobs | jobs:write | Submit a Sampler job (OpenQASM 3) → 202 + job_id |
| GET | /v1/jobs | jobs:read | Your jobs, newest first (?limit=) |
| GET | /v1/jobs/{id} | jobs:read | Status: QUEUED, VALIDATING, RUNNING, DONE, ERROR, CANCELLED |
| GET | /v1/jobs/{id}/results | jobs:read | Counts |
| POST | /v1/jobs/{id}/cancel | jobs:write | Cancel |
curl -X POST https://quantakit.my/v1/jobs -H "Authorization: Bearer $QK_TOKEN" -H "Content-Type: application/json" -d '{
"backend": "qk-sim-statevector", "primitive": "sampler",
"pubs": [{"circuit": {"format": "qasm3", "data": "OPENQASM 3.0; qubit[2] q; bit[2] c; h q[0]; cx q[0], q[1]; c[0] = measure q[0]; c[1] = measure q[1];"}, "shots": 1000}],
"options": {"seed": 7}
}'Noise on qk-sim-density
qk-sim-density runs a density-matrix simulator (up to 10 qubits). After every gate it applies depolarizing noise (separate rates for 1-qubit and multi-qubit gates), amplitude damping (T1) and phase damping (T2) to the qubits the gate touches; measured bits then get readout error. The result holds the exact noisy probabilities, sampled counts, and in metadata the noise model, the purity Tr(ρ²), the fidelity against the ideal circuit and the ideal probabilities.
Without settings it uses the backend's calibration (1% after multi-qubit gates, 0.1% after 1-qubit gates, 0.1% amplitude and 0.2% phase damping, 2% readout). Override any of them (probabilities from 0 to 1; readout up to 0.5) in the composer's Run dialog, from Python with SDK 1.1.0, or with options.noise in the REST API:
from quantakit.cloud import CloudService, NoiseModel # SDK 1.1.0+
from quantakit.primitives import Sampler
backend = CloudService().backend("qk-sim-density")
backend.supports_noise, backend.default_noise
backend.set_options(noise=NoiseModel(depolarizing_2q=0.05, readout=0.02)) # unset values = backend default
result = Sampler(backend).run([qc], shots=1000, seed=7).result()[0]
result.metadata["fidelity"], result.metadata["purity"], result.metadata["noiseModel"]
backend.set_options(noise=NoiseModel.ideal()) # no noise
backend.set_options(noise=None) # back to the default"backend": "qk-sim-density",
"options": {"seed": 7, "noise": {"depolarizing1": 0.001, "depolarizing2": 0.05,
"amplitudeDamping": 0.002, "phaseDamping": 0.004, "readout": 0.02}}Jobs sent with SDK 1.0.0 use the default noise. Offline, the book builds the same channels by hand with DensityMatrix and Operator, and LocalSimulator(readout_error=…) adds readout error.
Errors
| Code | Python exception | Meaning |
|---|---|---|
| QK-1001 | CircuitError | Invalid circuit (bad qubit index, unbound parameter, unreadable QASM) |
| QK-1002 / 1003 | IsaError | Not supported by the backend, or too many qubits |
| QK-1004 | QuantaKitError | Shots (1–100,000) or noise settings out of range |
| QK-1005 | TranspilerError | Can't translate to the requested basis |
| QK-2001 / 2002 | AuthError | Missing/invalid token, or no access |
| QK-3001 / 3002 | QuotaError | Monthly quota used, or rate limit |
| QK-4001 | BackendError | Backend offline or unreachable |
| QK-5001 | JobError | Job failed, was cancelled, or timed out |
Every exception has .code, .message and a .hint suggesting the fix.
Book Edition & versioning
- SDK 1.0.0 is the Book Edition and is frozen: the file published today will never change. Readers should install
quantakit==1.0.0. - Every 1.x release keeps every API on this page working (semantic versioning). Deprecated features keep working for at least two minor releases.
- 1.1.0 adds
NoiseModel,backend.set_options(noise=…),supports_noiseanddefault_noisefor cloud backends. Nothing from 1.0 changed. - Breaking changes only arrive in 2.0, which will be announced; pinned installs are never affected.
- The SDK version is separate from the website's version shown in the footer (the website updates often; that never changes SDK behaviour).
- The REST API is versioned under
/v1; changes to it are additive only.
Troubleshooting
- Strange characters in circuit diagrams on Windows — the SDK switches to plain ASCII automatically when the console can't show Unicode. To force it:
set QK_ASCII=1; to enable Unicode:set PYTHONIOENCODING=utf-8. - ModuleNotFoundError: quantakit — install into the same Python you run:
python -m pip install quantakit==1.0.0. - plot_histogram needs matplotlib —
pip install "quantakit[visualization]", or usetext_histogram. - Questions: new.technology@hotmail.com