Skip to content
QuantaKit
Book Edition 1.0.0

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.

Runs offline. Exercises never use cloud minutes.
API frozen for the book: every 1.x release keeps 1.0 code working.
Pure Python + NumPy. Windows, macOS, Linux. Python 3.10–3.13.

Installation

Install the exact version the book uses (recommended for readers):

pip install quantakit==1.0.0

Newest 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.whl

Optional 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.py

Tip 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)).

MethodQubitsParametersFamilyDescriptionCloud
qc.id(q)1—PauliIdentitynative
qc.x(q)1—PauliPauli-X (bit flip, NOT)native
qc.y(q)1—PauliPauli-Ynative
qc.z(q)1—PauliPauli-Z (phase flip)native
qc.h(q)1—CliffordHadamard: equal superpositionnative
qc.s(q)1—CliffordS = √Z (phase i on |1⟩)native
qc.sdg(q)1—CliffordS†native
qc.sx(q)1—Clifford√Xnative
qc.sxdg(q)1—Clifford√X†auto-translated
qc.t(q)1—PhaseT = √S (phase e^{iπ/4})native
qc.tdg(q)1—PhaseT†native
qc.p(λ, q)1λPhasePhase P(λ): e^{iλ} on |1⟩native
qc.rx(θ, q)1θRotationRotation about Xnative
qc.ry(θ, q)1θRotationRotation about Ynative
qc.rz(θ, q)1θRotationRotation about Znative
qc.u(θ, φ, λ, q)1θ, φ, λRotationGeneral single-qubit gatenative
qc.cx(c, t)2—Two-qubitCNOT (alias qc.cnot)native
qc.cy(c, t)2—Two-qubitControlled-Ynative
qc.cz(c, t)2—Two-qubitControlled-Znative
qc.ch(c, t)2—Two-qubitControlled-Hadamardnative
qc.cp(λ, c, t)2λTwo-qubitControlled phasenative
qc.crx(θ, c, t)2θTwo-qubitControlled RXauto-translated
qc.cry(θ, c, t)2θTwo-qubitControlled RYauto-translated
qc.crz(θ, c, t)2θTwo-qubitControlled RZnative
qc.swap(a, b)2—Two-qubitSwap two qubitsnative
qc.iswap(a, b)2—Two-qubitiSWAPauto-translated
qc.rxx(θ, a, b)2θTwo-qubitXX interactionauto-translated
qc.ryy(θ, a, b)2θTwo-qubitYY interactionauto-translated
qc.rzz(θ, a, b)2θTwo-qubitZZ interactionnative
qc.ccx(c1, c2, t)3—Three-qubitToffoli (alias qc.toffoli)native
qc.cswap(c, a, b)3—Three-qubitFredkin (alias qc.fredkin)native
qc.mcx([c…], t)any—Multi-qubitMulti-controlled X (built from the gates above)native
qc.measure(q, c)1—Non-unitaryMeasure qubit(s) into classical bit(s)native
qc.measure_all()any—Non-unitaryBarrier, then measure every qubit into register measnative
qc.reset(q)1—Non-unitaryReset to |0⟩ (local simulator)auto-translated
qc.barrier(...)any—Non-unitaryStop optimisation across this pointnative

“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 ansatz

Transpiler

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/after

Levels: 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 matplotlib

QuantaKit 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 offline

Every 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": "…"}.

MethodPathScopePurpose
GET/v1/meanyProfile, plan, quota and usage this month
GET/v1/backendsanyList backends
GET/v1/backends/{name}anyOne backend
POST/v1/jobsjobs:writeSubmit a Sampler job (OpenQASM 3) → 202 + job_id
GET/v1/jobsjobs:readYour jobs, newest first (?limit=)
GET/v1/jobs/{id}jobs:readStatus: QUEUED, VALIDATING, RUNNING, DONE, ERROR, CANCELLED
GET/v1/jobs/{id}/resultsjobs:readCounts
POST/v1/jobs/{id}/canceljobs:writeCancel
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

CodePython exceptionMeaning
QK-1001CircuitErrorInvalid circuit (bad qubit index, unbound parameter, unreadable QASM)
QK-1002 / 1003IsaErrorNot supported by the backend, or too many qubits
QK-1004QuantaKitErrorShots (1–100,000) or noise settings out of range
QK-1005TranspilerErrorCan't translate to the requested basis
QK-2001 / 2002AuthErrorMissing/invalid token, or no access
QK-3001 / 3002QuotaErrorMonthly quota used, or rate limit
QK-4001BackendErrorBackend offline or unreachable
QK-5001JobErrorJob failed, was cancelled, or timed out

Every exception has .code, .message and a .hint suggesting the fix.

Book Edition & versioning

Troubleshooting