Skip to content

AI-assisted docs. Parts of this page were drafted or edited with AI assistance. The project creator reviews and maintains the final text; see the AI notice.

Standard Library

Quantar's standard library is split into a few deliberately boring-named boxes:

Import What it is
quantum Simulator, qubits, gates, backends, seeding, QASM export
stl.quantum_algs Shor, Grover, QFT/IQFT, factorization, variational tools
stl.physics_algs Units, dual numbers, vector fields, trajectories, kernels
quantar Lazy umbrella package that re-exports common names

In other words: quantum is the lab bench, stl is the recipe book, and quantar is the helpful friend who fetches both before you finish asking.

The simulator

import quantum
from quantum import QuantumComputer, h_MAT, set_seed, swap_MAT

set_seed(7)  # randomness, but with a save file

qc = QuantumComputer(2)

qc[0].apply_gate(h_MAT())          # superposition, otherwise known as "maybe"
qc.apply_gate(swap_MAT(), [0, 1])  # SWAP

print(qc.state_vector)
print(qc.to_openqasm3())


def circuit(qc):
    qc[0].apply_gate(h_MAT())
    qc.apply_gate(swap_MAT(), [0, 1])


print(qc.sample(circuit, 1000))  # resets, reruns, counts bitstrings

Qubit objects are handles, not containers. Passing one around does not clone the state vector, which is good news for both memory usage and your patience.

h_MAT() is a matrix factory. apply_gate(h_MAT()) is the explicit route; h qc[0] and qc[0] <-> qc[1] are the built-in operator forms. User-defined binary and unary operators can also be registered with the @operator decorators, but bracket-style user operators are not supported.

Backends

The default is the pure-Python simulator. The compiled Rust backend is available when quantum.quantar_kernels is present:

import quantum

print(quantum.get_backend())        # "python"
print(quantum.available_backends())

quantum.use_backend("rust")         # fails early if unavailable; no quiet fallback
qc = quantum.QuantumComputer(2)

quantum.use_backend("python")       # switch back

From the CLI, use the explicit flag:

qtr run --rust main.qtr
qtr compile --rust --compile-to binary

--rust validates the extension and refuses to silently fall back to NumPy. If the extension is missing or stale and cargo plus the Rust source tree are available, the loader can build it first.

Useful environment variables:

  • QUANTAR_BACKEND=rust — choose the backend before startup.
  • QUANTAR_RUST_AUTO_BUILD=0 — disable automatic local builds.
  • QUANTAR_RUST_SOURCE_DIR — point at the repo root or its rust/ directory.
  • QUANTAR_CARGO — select a specific cargo executable.
  • QUANTAR_RUST_BACKEND_PATH — load a specific .pyd/.so file.

Reproducible sampling

Both backends share one seed. Measurement, sample, sample_parallel, Pauli expectations, and the Rust per-computer RNG all follow it:

import quantum

quantum.set_seed(1234)
qc = quantum.QuantumComputer(3)
first = qc.sample(circuit, 1000)

quantum.set_seed(1234)
qc = quantum.QuantumComputer(3)
second = qc.sample(circuit, 1000)

assert first == second

quantum.get_seed() generates and remembers a seed from OS entropy on first use, so a run can always be reproduced after the fact. The seed affects new computers and samples; existing computer objects keep their own generator.

Quantum algorithms

Common algorithms are re-exported from stl.quantum_algs and stl:

from stl.quantum_algs import (
    qft_program, iqft_program, qft_gate, iqft_gate,
    grovers_alg, shors_alg, factor,
    Ansatz, Hamiltonian, QuantumOptimizer,
)

qc.apply(qft_gate(3), qc[0:3])  # QFT as a single reusable circuit gate

Shor and Grover implementations moved into shors_alg_lib.py and grovers_alg_lib.py in 1.2.1. Import the functions from stl.quantum_algs instead of hunting through the furniture arrangement.

factor(n) provides a convenience factorization entry point, while Ansatz, Hamiltonian, and QuantumOptimizer support variational workflows.

Physics helpers

The physics side exists to remove bookkeeping. Units carry dimensions, Dual propagates derivatives through ordinary arithmetic, and VectorField evaluates and differentiates fields on points.

import numpy as np
from stl.physics_algs import (
    Q, Dual, VectorField, gradient, hessian, laplacian,
    momentum, angular_momentum, velocity_verlet, SpaceMetric,
)

distance = Q(12, "km").to("m")     # 12000 m
speed = Q(36, "km/h").to("m/s")    # 10 m/s
travel_time = distance / speed     # 1200 s

x = Dual(3.0, [1.0])               # value 3, dx/dx = 1
y = x * x + 2 * x
print(y.real, y.dual.tolist())     # 15.0 [8.0]

field = VectorField(lambda p: [-p[1], p[0]])
print(field([1.0, 2.0]))           # [-2.  1.]
print(gradient(lambda p: p[0] ** 2 + p[1] ** 3, [2.0, 3.0]))  # [ 4. 27.]

orbit = velocity_verlet([1.0, 0.0], [0.0, 1.0], 0.01, 628, lambda p: -p)
print(round(float(orbit.speeds()[-1]), 4))      # 1.0

print(SpaceMetric("spherical").volume_element([2.0, np.pi / 2, 0.0]))
# 4.0

velocity_verlet returns a Trajectory with positions, velocities, and times, plus speeds(), momenta(), angular_momentum(), and energy(potential) for analysis.

Rust-backed physics kernels

Four numeric hot paths use compiled kernels in quantum.quantar_kernels: kinetic-energy sums, Lorentz forces, central-difference reductions, and the two velocity-Verlet half-steps. Large batches release the GIL and parallelise with rayon.

from stl.physics_algs import rust_available, use_rust_physics

if rust_available():
    print("compiled physics kernels active")

use_rust_physics(False)    # force NumPy implementations
print(use_rust_physics())  # False

Setting QUANTAR_PHYSICS_KERNELS=0 before import does the same thing without code changes. The physics loader checks the installed extension for the required functions and falls back silently if it is missing or older than 1.2.3; it does not trigger a Rust build for physics-only programs.

The physics kernels are polite guests: if the compiled extension is absent, they use NumPy and do not make a scene. qtr --rust is less polite—it checks your ticket at the door.

Import cheat sheet

# Umbrella: common names, loaded lazily
import quantar

qc = quantar.QuantumComputer(2)
quantar.set_seed(1234)

# Direct subpackages: implementation modules
import quantum
from stl.quantum_algs import shors_alg, grovers_alg
from stl.physics_algs import Quantity, Unit, SI

# Explicit modules: the source of truth
from quantum.seed_set import get_rng
from stl.physics_algs.units import Quantity as QuantityImpl
from lang_systems import parse_ast

To see everything a package currently exports:

import quantar
print(quantar.__all__)

For the full API map, see the repository's docs/API.md. For the .qtr file syntax, head to Syntax.