No description
Find a file
2026-11-22 18:46:33 -05:00
doc date 2026-07-23 20:33:07 -04:00
docs Update docs/QPOS_DESIGN.md 2026-11-22 18:46:33 -05:00
include date 2026-07-23 20:33:07 -04:00
shaders date 2026-07-23 20:33:07 -04:00
src Mon Nov 9 09:38:38 AM EST 2026 2026-11-09 09:38:38 -05:00
tests date 2026-07-23 20:33:07 -04:00
tools Mon Nov 9 09:38:38 AM EST 2026 2026-11-09 09:38:38 -05:00
web Web playhead: hide per-gate circles in row playback, keep them for instruction mode 2026-11-16 13:41:16 -05:00
.gitignore Feature-detect touch for mobile UI; drag-to-move reposition; ignore agent HANDOFF.txt 2026-07-24 12:24:44 -04:00
benchmark_device_comparison.py date 2026-07-23 20:33:07 -04:00
Makefile Mon Oct 5 01:43:07 PM EDT 2026 2026-10-05 13:43:07 -04:00
README.md readme 2026-11-17 21:31:27 -05:00

QAnsel

A quantum-circuit workbench built around a quantum VM with ontic states.

QAnsel is a desktop app and browser UI for drawing OpenQASM 2.0 circuits, compiling them, and watching them execute instruction by instruction. The backend is a small C toolchain: qas assembles OpenQASM into .qbin bytecode, and qvm runs that bytecode on the CPU or a Vulkan GPU.

What makes qvm different from a conventional state-vector simulator is the model it implements. Every qubit has a definite 0/1 value at all times; the configuration of those values is the system's ontic state. qvm stores that configuration as one bit per qubit, and the q register in a trace shows it at every step. At each gate the ontic state moves through a stochastic transition matrix while the complex amplitudes evolve unitarily alongside. That matrix is fitted to the gate's outcome probabilities (the Born rule) with iterative proportional fitting. Measurement is a passive reveal in the computational basis: it copies the value that was already there. Over many shots the measured distribution matches quantum mechanics, but each individual run is a definite trajectory you can step through and watch.

That makes QAnsel useful both as a circuit workbench and as a way to inspect the ontic state at every step: each run follows a definite configuration, while the statistics match standard quantum predictions.

Interfaces Qt6 desktop shell, or any modern browser
Circuit language OpenQASM 2.0 (custom gates, if conditionals, reset, barrier)
Backends CPU (pthreads), Vulkan GPU at native f16/f32/f64
State model Definite ontic state at every step, with complex amplitudes evolved alongside
Qubits Up to 30 (memory-bound); 256 classical bits
Randomness Quantis QRNG, TrueRNG, Intel RDSEED, or /dev/urandom
Runtime C libraries only; the optional desktop shell adds Qt6 WebEngine

Contents


Quick start

From a checkout:

make
./build/qansel

make builds qas, qvm, qpos, and the Qt6 desktop shell qansel. Launching qansel starts a local server, waits for it, and opens the workbench in a Chromium window.

If Qt6 is not installed, build the headless toolchain and open the same UI in a browser:

make USE_GUI=0
./build/qvm -port 8090 -webroot web -qas build/qas -inc include

Then open http://127.0.0.1:8090/.

Build dependencies, optional features, installation, and test targets are covered in Compiling from source at the end.


The names

A few similarly named pieces show up throughout the docs and command line:

Name What it is
QAnsel The project and the workbench UI
qansel The Qt6 WebEngine desktop shell (the window)
qas The OpenQASM 2.0 assembler: .qasm → .qbin
qvm The ontic-state quantum virtual machine: executes .qbin
qvm-server qvm invoked in HTTP server mode
qpos Companion 2D position-space simulator (separate experiment; see its design doc)

The desktop shell is only a UI. All compilation and simulation happens in qas and qvm, which work perfectly well on their own.


How the pieces fit together

┌──────────────────┐   spawns   ┌────────────────────────────────────┐
│ qansel           │───────────▶│ qvm-server  (qvm -port P)          │
│ Qt6 WebEngine    │            │  GET  /             → web/ UI      │
│ desktop window   │            │  POST /api/compile  → qas          │
└──────────────────┘            │  POST /api/run      → NDJSON ⤵     │
        │                       └────────────────────────────────────┘
        │ loads http://127.0.0.1:P/            ▲
        └──────────────────────────────────────┘
                                      any browser on the LAN can load
                                      the page and use the same API

Browsers cannot open raw TCP sockets, so the transport is HTTP with a streaming (chunked NDJSON) response that the page reads live with fetch(). The UI host and the compute host do not have to be the same machine; see Serving the UI and the HTTP API.


Your first circuit

This builds a Bell state and runs it 1,024 times.

  1. Start the workbench with ./build/qansel, or open the browser URL from the quick start.
  2. Clear the example and set the register size. Click Clear in the Circuit header, then use the Qubits − control to go from 3 qubits to 2.
  3. Add a Hadamard. Drag H from the Gates palette onto the wire q[0] in the first empty column.
  4. Add a CNOT. Drag CX onto q[0] in the next column. QAnsel uses the clicked wire as the control and fills the remaining wires with the nearest free qubits, so you should get control q[0], target q[1]. Drag an endpoint if it picked the wrong wire.
  5. Measure both qubits. Drag M (the meter symbol) onto q[0], then onto q[1]. Measurements default to c[0] and c[1] respectively; the destination is printed under the meter. Right-click a measurement (or tap it on touch) to retarget it to another classical register.
  6. Run in Shots mode. Click Shots, set Shots to 1024, and press Run. The histogram should show roughly 50% 00 and 50% 11; the register table shows the last traced shot.

In the circuit, a highlighted playhead marks the active column while a paced run plays. The code editor below the circuit starts as a rendering of the circuit; once you hand-edit it, your text is what Run compiles.

On a phone or tablet the fixed Gates palette is not shown. Tap an empty cell to open the gate picker, tap a placed gate for its menu, and drag a gate to reposition it. Dragging a gate off the grid deletes it.


Using the workbench

Building circuits

The palette is grouped into:

Group Gates
Single qubit H X Y Z S S† T T† I
Rotations RX RY RZ (angle prompt; expressions like pi/2 are accepted)
Controlled CX CZ CY CH SWAP CCX
Operations M (measure), reset, barrier
  • Desktop placement: drag a gate from the palette onto a cell. Right-click an empty cell for a floating picker or a placed gate for its menu. Drag a placed gate to move it, and drag it off the grid to delete it.
  • Touch placement: tap an empty cell to open the picker, tap a placed gate for its menu, and drag a gate to move it.
  • Multi-qubit gates: dropping CX, CZ, CY, CH, SWAP, or CCX on a wire uses that wire as the first control and fills the remaining wires with the nearest free qubits. Adjust by dragging the endpoints.
  • Measurements: each M targets a classical bit. Defaults are c[0], c[1], … from the qubit index. Use the gate menu's Target register… to point a measurement at a different register or bit.
  • Classical conditions: the if row below the circuit has one cell per column. Click the + to guard every gate in that column behind if (creg == value). OpenQASM 2.0 only supports equality against a whole register; to test a single bit, give that qubit its own 1-bit register (retarget its measurement) and use if (c1 == 1) or if (c1 == 0).
  • Reset: |0⟩ prepares the qubit in state 0. Barrier is a scheduling marker; it spans the whole column.

The Qubits and Columns controls under the circuit add or remove qubit wires and time columns. Columns grow automatically when you place a gate at the right edge.

The code editor

The OpenQASM 2.0 pane is a real editor with syntax highlighting. It is regenerated from the circuit while you are working on the circuit; as soon as you type in the pane, your text becomes authoritative:

  • Circuit-first: draw gates and let QAnsel emit the OpenQASM.
  • Code-first: edit the text directly. Press Run and the text is used verbatim; the circuit view is not consulted.
  • Build circuit ↺: re-parses the code back into the circuit. This is best-effort and covers the palette's gate subset. If you use custom gate definitions or other OpenQASM constructs outside that subset, edit the code and press Run directly; Build circuit will reject the program rather than silently misrepresent it.

Opaque gates are parsed for interface compatibility but cannot be executed: the assembler has no matrix to expand them into.

Copy puts the whole program on the clipboard.

Run modes

Mode What it does
Single One shot. Streams the full per-instruction trace into the register table and animates the playhead.
Shots Runs N repetitions (up to 1,000,000) and builds a measurement histogram. Full traces stream for the first 32 shots; every shot still contributes to the histogram, and periodic progress updates keep the bar moving.

While a run is active the primary button becomes Pause / Resume, and Stop aborts it. Playback is client-side: the server streams at full speed, and the UI paces what you see.

Settings → Playback delay controls that pacing for each mode:

  • 250 ms is the default in Single mode, which is watchable but not slow.
  • Shots mode defaults to -1, so a large run goes straight to the histogram.
  • -1 skips the animation and jumps to the final result.
  • 0 shows every step as fast as the browser can paint.

Playback advance chooses what one step means:

  • Step (default): one whole circuit row at a time.
  • Instruction: one compiled instruction at a time. This is more granular, but a CCX is decomposed into several instructions by the compiler, so the playhead is approximate across a Toffoli.

Reading the results

The Results pane has three things to watch:

  • Register table: one row per register, with the current value in Int, Hex, and Binary. The values update live during a paced run.
  • Measurement distribution: a histogram of measured outcomes, shown in Shots mode. Its keys are the measured classical bit strings.
  • Run metadata: chips for shots, noise, qubits, classical bits, the active backend (CPU or GPU: <device>), and the RNG source when a hardware TRNG is driving the physics (TRNG: RDSEED, TRNG: Quantis, …).

The now playing strip shows the current shot, instruction index, and bytecode address while a traced run is in progress.

Saving, loading, exporting, printing

Action What it produces
Save (disk button) A self-contained circuit.qansel JSON snapshot: circuit layout, code, run mode, and the currently displayed register/histogram results. Reloading restores the whole screen without re-running.
Load (folder button) Opens a .qansel snapshot, or a plain OpenQASM program. A .qasm/.txt file is dropped into the editor and Build circuit is attempted; if it cannot be represented, the file is rejected rather than half-loaded.
CSV Measurement table for a completed Shots run: binary, decimal, hex, count, and percentage. Disabled until such a run exists.
Print A clean, always-light circuit printout. The on-screen theme does not matter.

Settings

Settings persist per browser (local storage) and apply to the next run:

Setting Meaning
Server URL Blank means same origin. On a named domain the UI defaults to qvm.<your-domain>; override it here to point at a specific machine. The ?qvm= URL parameter wins for the current page load.
Random seed -1 means random. A positive value seeds the fallback PRNG; see Randomness and reproducibility for the one caveat.
Playback delay: Single / Shots Per-mode pacing in milliseconds; -1 skips to the final state.
Playback advance Step (whole row) or instruction (one gate).
Noise (decoherence) 0 = exact dynamics, 1 = fully uniform. Applied at every gate.
Numeric precision 8, 16, 32, or 64-bit gate matrices. The default is 32-bit.
Bit order (endianness) Big (UI default; q[0] is the most-significant bit) or little (q[0] is the least-significant bit).
Hardware acceleration Enables the Vulkan backend, reveals a GPU-device dropdown populated from /api/devices, and offers an optional "only use GPU above N qubits" threshold (default 16).
Theme Auto, light, or dark.

If you choose a precision the selected GPU does not advertise, saving the settings warns you; the run may still be refused by qvm (see Precision and GPU).

On first launch the UI turns GPU acceleration on when any Vulkan device is present, including a software llvmpipe device. The qubit threshold keeps small circuits on the CPU; uncheck Hardware acceleration to force the CPU entirely.

Keyboard and touch

  • Ctrl+Enter / Cmd+Enter: start a run. (Use the Run/Pause button to pause or resume an active run.)
  • Esc: cancel an in-progress gate drag.
  • On touch devices, QAnsel switches to a feature-based touch layout rather than relying only on screen width, so a landscape phone still gets large hit targets and the floating gate picker.
  • The UI ships a web app manifest, so supporting browsers can add it to the home screen or install it as an app when it is served from localhost or over HTTPS.

Command-line usage

The CLI is the same engine the UI uses, and is the easiest way to script circuits, generate bytecode, or benchmark hardware.

qas: assemble OpenQASM

qas [options] input.qasm [output.qbin]
qas -port N
# Compile a circuit, with debug symbols for named registers.
./build/qas -I include -g bell.qasm bell.qbin

# Compile at 64-bit precision, big-endian bytecode.
./build/qas -I include -f64 -be -g bell.qasm bell.qbin
Flag Default Meaning
-g off Write a .dbg symbol sidecar next to the .qbin. qvm auto-loads it and reports named registers instead of flat qbits/cbits. The UI uses it to drive the playhead.
-f8 -f16 -f32 -f64 -f32 Width used to store gate matrices. -f8 is a compact non-IEEE format and is CPU-only; -f16/-f32/-f64 are IEEE half/single/double and can run natively on the GPU where the device supports it. The width is baked into the bytecode.
-le / -be -le Bytecode endianness. This also chooses bit significance: little-endian means q[0]/c[0] is the least-significant bit; big-endian means q[0] is the most-significant bit.
-I path n/a Add an include search path for include "…";. Repeatable. Needed for qelib1.inc: qas has no built-in library path. Use -I include in the source tree or -I /usr/local/lib/oq2 after installation.
-port N n/a Run the compile microservice on port N (GET /api/health, POST /api/compile) instead of compiling a file.
--help, --version n/a Print help / version and exit.

If output.qbin is omitted, the output is written beside the input with a .qbin extension. Source files are limited to 4 MiB.

qvm: run bytecode

qvm [options] bytecode.qbin
qvm -list-gpus
qvm -port N [-webroot DIR -qas PATH -inc DIR]
# Run on the CPU and stream the full trace as JSON lines.
./build/qvm bell.qbin

# Run at the bytecode's native width on the GPU.
./build/qvm -gpu bell.qbin

# Add noise and seed the fallback PRNG.
./build/qvm -seed 42 -noise 0.05 bell.qbin

With debug symbols, output looks like this (the initial state, then one object per instruction, on stdout):

{"address":0,"index":0,"data":{"q":{"type":"quantum","value":"00"},"c":{"type":"classical","value":"00"}}}
{"address":44,"index":1,"data":{"q":{"type":"quantum","value":"10"},"c":{"type":"classical","value":"00"}}}
{"address":188,"index":2,"data":{"q":{"type":"quantum","value":"11"},"c":{"type":"classical","value":"00"}}}
{"address":206,"index":3,"data":{"q":{"type":"quantum","value":"11"},"c":{"type":"classical","value":"11"}}}
…

Without a .dbg sidecar the same stream uses flat buffers: {"cbits":"00","qbits":"11"}. Diagnostics (RNG selection, Vulkan enumeration) go to stderr, so stdout stays machine-readable.

Compute and precision

Flag Default Meaning
-gpu off Use the Vulkan backend at the bytecode's exact compiled float width. If the device cannot run that width natively, the run is refused; it is never silently converted or downgraded.
--cpu-only (default) Force the CPU backend.
-device N auto Prefer Vulkan device N (index from -list-gpus). 0 means auto-select the first discrete GPU.
-vram N 9 GPU VRAM budget in GB, capping the resident state vector.
-list-gpus n/a Print detected Vulkan devices and their f16/f32/f64 support as JSON, then exit.

Physics and randomness

Flag Default Meaning
-noise X 0 Decoherence in [0,1], mixed into every gate's transition. 0 is exact, 1 is fully uniform.
-seed Z -1 Seed for the libc fallback PRNG. -1 uses hardware entropy. See the reproducibility caveat below.
-chunk off Force 4 KB chunked reads from the hardware RNG (the broken-Quantis workaround).
-collapse n/a Accepted and ignored; measurement always collapses. Kept for compatibility.

Server

Flag Meaning
-port N Run the HTTP/JSON server on port N (default 8090). Invoking the binary as qvm-server also enables server mode.
-webroot DIR Directory of static UI files to serve at /.
-qas PATH The qas binary that POST /api/compile will spawn. Without it, the server looks for qas on PATH.
-inc DIR Include directory containing qelib1.inc, passed to the spawned qas.

qansel: desktop shell

qansel [--gui HOST:PORT] [--qvm HOST:PORT] [--port N] \
       [--webroot DIR] [--qas PATH] [--inc DIR]

With no arguments, qansel picks a free local port, spawns qvm-server, waits for it, and opens the UI. Closing the window terminates the server.

Flag Meaning
--gui HOST:PORT Load the UI from this host and do not spawn a local server. Accepts HOST:PORT or a full http://… URL.
--qvm HOST:PORT Send /api requests here instead of the UI's own origin. Handed to the page as ?qvm=.
--server HOST:PORT Deprecated alias for --gui.
--port N Port for the spawned local server (default: auto-picked free port).
--webroot DIR UI directory to serve. Default: auto-detected relative to the binary (../share/qansel/web, then ../web, then ./web).
--qas PATH qas binary for the spawned server. Default: qas next to the shell, else qas on PATH.
--inc DIR Directory containing qelib1.inc. Default: ../include or ../lib/oq2 relative to the binary.

Common splits:

Command UI from Compute on
qansel spawned local server same local server
qansel --qvm 192.168.1.20:8090 local remote 192.168.1.20:8090
qansel --gui 192.168.1.7:8090 remote (must be started with -webroot) same remote host
qansel --gui 192.168.1.7:8090 --qvm 192.168.1.20:8090 remote A remote B

Typical CLI workflow

# 1. Write a circuit.
cat > bell.qasm <<'QASM'
OPENQASM 2.0;
include "qelib1.inc";

qreg q[2];
creg c[2];

h q[0];
cx q[0],q[1];
measure q -> c;
QASM

# 2. Assemble with debug symbols.
./build/qas -I include -g bell.qasm bell.qbin

# 3. Run once and inspect the trace.
./build/qvm bell.qbin

For statistics, run it repeatedly and count the final c values, or just use Shots mode in the UI, which is what it is for.

qpos: companion position-space simulator

qpos is a separate experiment: a 2D tight-binding particle evolved by exact unitary dynamics, with definite stochastic trajectories fitted to the evolution. It writes JSON and is covered in detail in docs/QPOS_DESIGN.md.

./build/qpos -mode double -walkers 20000 -o double.json
./build/qpos -quiet -mode single -walkers 5000 -o single.json

Its key knobs are -mode none|single|double|slitA|slitB, grid sizes -nx/-ny, wavelength -lam (should be ≥ 8 cells; shorter wavelengths break the lattice dispersion), slit geometry -slitw/-slitd, time -dt/-steps, and trajectory count -walkers. -noipf runs the bare |U|² control. The regression suite is make test-qpos.


Serving the UI and the HTTP API

A headless server

On the machine with the GPU/TRNG:

qvm-server -port 8090 \
  -webroot /usr/local/share/qansel/web \
  -qas /usr/local/bin/qas \
  -inc /usr/local/lib/oq2

From any device on the LAN, open http://<host>:8090/.

From the source tree, without installing:

./build/qvm -port 8090 -webroot web -qas build/qas -inc include

The server binds all interfaces and has no authentication or TLS. Run it on a trusted network, or put it behind a reverse proxy.

Pointing the UI at a different compute host

There are three equivalent ways:

  1. Settings → Server URL in the UI (persists in that browser).
  2. URL parameter ?qvm=http://host:port: handy for saved links and the desktop shell.
  3. qansel --qvm host:port: passes the same parameter to the page.

The UI host and the compute host can be different machines. For example, serve the static UI from a small box and run qvm on the machine with the Quantis card:

# UI + compute on the big machine:
qvm-server -port 8090 -webroot /usr/local/share/qansel/web \
           -qas /usr/local/bin/qas -inc /usr/local/lib/oq2

# On a laptop, without installing anything but qansel:
qansel --gui 192.168.1.7:8090 --qvm 192.168.1.20:8090

HTTP API

All endpoints send Access-Control-Allow-Origin: *.

Endpoint Served by Purpose
GET / qvm-server Static UI from -webroot
GET /api/health qvm-server, qas -port Liveness and limits
GET /api/devices qvm-server Vulkan device enumeration
POST /api/compile qvm-server, qas -port OpenQASM → base64 .qbin
POST /api/run qvm-server only Run and stream NDJSON

GET /api/health

{"ok":true,"service":"qvm","max_qubits":30}

qas -port reports {"ok":true,"service":"qas"} instead.

GET /api/devices

{
  "vulkan": true,
  "devices": [
    {"index":0,"name":"ZX C-1190","type":"discrete","f16":false,"f32":true,"f64":false},
    {"index":1,"name":"llvmpipe (LLVM 17.0.6, 256 bits)","type":"cpu","f16":true,"f32":true,"f64":true}
  ]
}

type is discrete, integrated, cpu, or other. f32 is reported true for any Vulkan compute device; f16/f64 reflect the device's advertised features.

POST /api/compile

Request:

{
  "source": "OPENQASM 2.0; include \"qelib1.inc\"; qreg q[1]; creg c[1]; h q[0]; measure q -> c;",
  "float_bits": 32,
  "endian": "little"
}

float_bits is 8, 16, 32, or 64 (default 32). endian is "little" or "big" (default little; the UI sends big).

Success:

{
  "ok": true,
  "qbin_b64": "<base64 bytecode>",
  "dbg": "name,type,offset,length\nq,quantum,0,1\nc,classical,0,1\n",
  "qubits": 1,
  "cbits": 1
}

Failure carries compiler diagnostics with line numbers:

{"ok":false,"error":"Error (line 3): expected token 25, got 'h'"}

A one-liner:

curl -s http://127.0.0.1:8090/api/compile \
  -H 'Content-Type: application/json' \
  -d '{"source":"OPENQASM 2.0; include \"qelib1.inc\"; qreg q[1]; creg c[1]; h q[0]; measure q -> c;","float_bits":32,"endian":"little"}'

POST /api/run

Request:

{
  "qbin_b64": "<base64 from /api/compile>",
  "dbg": "<dbg CSV from /api/compile>",
  "shots": 1024,
  "noise": 0.0,
  "seed": -1,
  "gpu": 0,
  "device": -1
}
Field Default Meaning
qbin_b64 required Bytecode to execute
dbg empty Debug symbols; makes the stream use named registers
shots 1 Repetitions, clamped to [1, 1000000]
noise 0 Decoherence in [0,1]
seed -1 Seed for the fallback PRNG
gpu 0 1 requests the GPU; if it cannot run the compiled width the server returns an error rather than falling back
device -1 -1 auto-selects; otherwise a device index

The response is application/x-ndjson: one JSON object per line, flushed as it is produced.

{"type":"meta","shots":1024,"noise":0,"qubits":2,"cbits":2,"backend":"cpu","device":"","trng":1,"rng":"RDSEED","endian":"big"}
{"type":"shot","shot":0}
{"type":"state","shot":0,"address":0,"index":0,"data":{"q":{"type":"quantum","value":"00"},"c":{"type":"classical","value":"00"}}}
{"type":"shot_end","shot":0,"measured":"00"}
…
{"type":"stats","histogram":{"00":512,"11":512}}
{"type":"done"}
Type Meaning
meta Shots, noise, qubits, cbits, actual backend/device, RNG provenance, endianness
shot Start of a traced shot
state One instruction's register state (only for traced shots)
shot_end Final measured classical bits for that shot
progress Periodic {"type":"progress","shot":N} for untraced shots
stats Final histogram over all shots
done End of stream
error The run could not start (e.g. GPU refusal); sent instead of a stream

Two details that matter when consuming the stream:

  • Full traces are sent for the first 32 shots (all shots when shots < 32). Every shot still counts toward stats.
  • Register value strings inside state are LSB-first. The UI reorders them for display according to the run's endianness.

A complete shell example using jq:

COMPILED=$(curl -s http://127.0.0.1:8090/api/compile \
  -H 'Content-Type: application/json' \
  -d '{"source":"OPENQASM 2.0; include \"qelib1.inc\"; qreg q[2]; creg c[2]; h q[0]; cx q[0],q[1]; measure q -> c;","float_bits":32,"endian":"little"}')

QUBIN=$(printf '%s' "$COMPILED" | jq -r .qbin_b64)
DBG_JSON=$(printf '%s' "$COMPILED" | jq -r .dbg | jq -Rs .)

curl -sN http://127.0.0.1:8090/api/run \
  -H 'Content-Type: application/json' \
  -d "{\"qbin_b64\":\"$QUBIN\",\"dbg\":$DBG_JSON,\"shots\":1024,\"noise\":0,\"seed\":-1}"

Behaviour worth knowing

Ontic states and passive measurement

At every gate, qvm:

  1. Evolves the complex state vector by the gate's unitary U.
  2. Forms S = |U|², the element-wise squared unitary.
  3. Uses iterative proportional fitting to find the column-stochastic matrix Γ closest to S (in KL divergence) that transports the old Born distribution to the new one: Γ · p_before = p_after.
  4. Samples the target qubits' new definite values from the current column of Γ.

Measurement is a passive reveal, but only in the computational basis. It copies the qubit's already-definite ontic value into the classical bit and collapses the amplitudes onto that value so later operations remain consistent. It does not resample from the Born rule and does not change the ontic state. To measure in another basis, apply the corresponding basis-change gate first; the VM has no other measurement basis. Consequently:

  • The measured qubit's q value and its classical bit agree in every trace.
  • Measuring a qubit does not change its definite value.
  • Across many shots the definite values are Born-distributed because of the gate dynamics, so the measured statistics still match quantum predictions.

Noise

-noise X (or the noise field, or the UI slider) mixes each gate's transition columns toward uniform:

column_i  ←  (1 − X) · column_i  +  X · (1/dim)

X = 0 is the exact ontic-state dynamics. X = 1 makes every hop land uniformly at random, giving a fully uniform outcome. Because noise acts per gate, its effect accumulates with circuit depth; more gates on a qubit means more opportunities for its value to be scrambled. This is deliberate and physically reasonable; it is not a constant added at the end.

Precision and GPU

qas bakes a float width into the bytecode, and qvm executes that width natively. The GPU path never converts gate matrices or the state vector to another width; if the device cannot run the compiled width, the run is refused with a clear error.

Width Storage GPU support
-f8 1-byte compact format Never: no Vulkan 8-bit float type; CPU only
-f16 IEEE half Device must expose shaderFloat16 + 16-bit storage
-f32 IEEE single Always available (the default)
-f64 IEEE double Device must expose shaderFloat64

The f32/f16/f64 SPIR-V headers are checked into src/, so a normal build has all three GPU paths compiled in; make shaders regenerates them if you edit the GLSL.

./build/qvm -list-gpus          # see what your machine reports
./build/qvm -gpu circuit.qbin   # run at the bytecode's width

The GPU is a real win only once the circuit is large enough to amortise upload and dispatch costs; on the hardware tested the crossover is around 16 qubits, which is why the UI's automatic GPU threshold defaults to 16. Below that, the CPU is often faster. -vram N caps the resident state-vector allocation.

For deep circuits or fine rotation angles, -f32 is a good default and still GPU-native almost everywhere. Use -f64 on the CPU when you need the extra precision. The ontic-state model is the same at every width, so measurement semantics do not change.

Endianness

The bytecode header's endianness flag governs two things at once:

  • the byte order of stored numbers, and
  • the bit significance of q[0]/c[0].
Mode q[0] / c[0] x q[0] on 2 qubits reads as
Little (qas default) Least-significant bit 01 = 1
Big (qas -be, UI default) Most-significant bit 10 = 2

This affects register int/hex values, if (creg == k) comparisons, and histogram labels. The per-qubit physics is identical either way. If a CLI run and a UI run disagree about the number in a register despite the same circuit, check the bit order first.

For the GPU, the resident state and uploaded gate matrices are kept in the host's native byte order. A little-endian build on a little-endian host is a zero-copy upload; a big-endian .qbin is byte-swapped into host order first (a lossless reordering, not a precision conversion).

Randomness and reproducibility

The sampler prefers, in order:

  1. Quantis QRNG (/dev/qrandom0)
  2. TrueRNG (/dev/TrueRNG0)
  3. Intel RDSEED (Secure Key)
  4. /dev/urandom

The UI reports the active source in the run metadata when it is a true hardware source.

There is one caveat to the seed setting: in the default build (USE_TRNG=1), the physics draws from the hardware RNG, so -seed does not make runs bit-reproducible. It only seeds the libc fallback used by non-TRNG builds. If you need deterministic runs for regression testing, build with USE_TRNG=0; qvm -seed Z then controls the sampler. This is also why the UI labels the seed field as a random seed rather than a reproducibility guarantee.


Limits

Limit Value
Qubits 30 hard cap (MAX_QUBITS)
Classical bits 256 (MAX_CBITS)
Shots per run 1,000,000
OpenQASM source size 4 MiB
Include depth 16
State-vector memory at 30 qubits CPU: 16 GiB (amplitudes are double complex). A GPU run adds f16 ≈ 4 GiB, f32 ≈ 8 GiB, or f64 ≈ 16 GiB of device state.

The 30-qubit cap is a compile-time bound, not a promise that 30 qubits fits your machine. The CPU path keeps amplitudes as double complex, so the state vector alone at 30 qubits needs 16 GiB; gate application allocates a second full-size work buffer, and a GPU run still allocates the host state plus the device-resident vector at the compiled width. In practice, available RAM (CPU) or VRAM (GPU) decides the largest circuit you can run. The UI lets you build up to 30 wires; qvm rejects anything larger at load time.

GPU runs are additionally limited by -vram (default 9 GB). The device must also natively support the bytecode's float width.


Troubleshooting

Symptom Likely cause and fix
UI says Cannot reach server No server is listening at the configured URL. Check curl http://HOST:PORT/api/health, then fix Settings → Server URL (or pass ?qvm=).
compiler exited with code 127 qvm-server could not find qas. Pass -qas /absolute/path/to/qas (and usually -inc .../include).
Fatal: cannot open include file: qelib1.inc qas has no default library path. Add -I include in the source tree or -I /usr/local/lib/oq2 after installation.
GPU refused: … (N-bit) The selected device cannot natively execute that width, or no usable Vulkan device was found. Run qvm -list-gpus, recompile at a supported width, or turn off GPU acceleration. The server deliberately does not fall back to CPU.
qansel opens a blank window The local server did not come up, or the webroot was not found. Run the server manually with -webroot web and open the URL; check qansel's stderr.
Port already in use Pass another -port to qvm/qansel, or stop the old server.
Histogram is empty The histogram is only populated in Shots mode, and only from measured classical bits. Add M gates (or measure statements) and run more than one shot.
A condition never fires OpenQASM compares the whole register. Check the register width and the value range shown in the dialog; use a 1-bit register for a single-bit test.
Values differ between CLI and UI The UI compiles big-endian by default; qas defaults to little-endian. Set Bit order in Settings or pass -be/-le explicitly.
No gate palette on a phone Intentional. Tap an empty circuit cell to open the gate picker.
Build circuit rejects a program The circuit view supports the palette subset. Custom gate definitions, unusual expressions, or unsupported statements must be run from the code editor directly.

Repository map and internal docs

src/qas.c              OpenQASM 2.0 assembler
src/qvm.c              ontic-state VM and HTTP server
src/httpd.c            embedded HTTP/1.1 server (static files, chunked NDJSON)
src/vulkan_compute.c   Vulkan backend and native-width pipelines
src/hardware_rng.c     Quantis / TrueRNG / RDSEED / urandom
src/qansel.c           Qt6 WebEngine desktop shell
src/qpos.c             companion position-space simulator
web/                   single-page UI (index.html, app.js, style.css, PWA assets)
include/qelib1.inc     standard OpenQASM gate library
shaders/               GLSL compute shaders
tests/                 OpenQASM regression circuits
tools/                 Python checkers, bytecode verifier, benchmarks
docs/                  bytecode spec and qpos design notes
doc/                   LaTeX sources (optional; not needed to build or use QAnsel)
Document What it covers
docs/README.md The .qbin bytecode format: header, matrices, special commands
docs/QPOS_DESIGN.md qpos theory, geometry, baselines, and validation

The implementation is concentrated in a few files: src/qvm.c holds the gate-evolution path, the GPU probe, and the host_endian() byte-order handling.


Compiling from source

Dependencies

QAnsel is C11 plus an optional C++/Qt shell. On Debian/Ubuntu:

sudo apt install build-essential pkg-config \
                 libvulkan-dev libpci-dev \
                 qt6-base-dev qt6-webengine-dev \
                 glslang-tools python3

What each is for:

Package Required? Used for
build-essential, pkg-config Yes C/C++ compiler and Qt pkg-config lookups
libvulkan-dev Recommended Vulkan backend. Build with USE_VULKAN=0 to omit it.
libpci-dev Optional Human-readable names for PCIe RNG devices. Auto-detected; without it the RNG chip shows a generic label.
qt6-base-dev, qt6-webengine-dev Optional The qansel desktop shell. Build with USE_GUI=0 for a headless toolchain.
glslang-tools Optional Only for make shaders, which regenerates the SPIR-V headers. The generated headers are checked in.
python3 Optional Test and verification scripts, and the shader-to-header converter used by make shaders.

qpos uses OpenMP, which the GCC toolchain provides without a separate package. There are no Python, Qiskit, CUDA, or Node.js dependencies for the application itself.

Build

make                 # qas, qvm, qpos, and qansel
make -j"$(nproc)"    # same, in parallel
make USE_GUI=0       # headless: qas, qvm, qpos; no Qt6 dependency
make qansel          # only the desktop shell
make help            # list targets and a quick CLI syntax summary

Artifacts land in build/:

Binary Purpose
build/qas OpenQASM 2.0 assembler
build/qvm VM; qvm -port is the server
build/qpos 2D position-space simulator
build/qansel Qt6 desktop shell

Run them directly from the tree:

./build/qansel
./build/qvm -port 8090 -webroot web -qas build/qas -inc include

Build options

Pass these as make VARIABLE=value:

Variable Default Effect
PREFIX /usr/local Install prefix used by make install
USE_GUI 1 Build the Qt6 desktop shell. 0 removes the Qt6 dependency.
USE_VULKAN 1 Enable the Vulkan backend and link -lvulkan. 0 builds a CPU-only VM.
USE_TRNG 1 Enable hardware RNG support. 0 makes -seed effective and uses libc rand().
USE_PTHREAD 1 Threaded matrix kernels. pthreads are always linked because the HTTP server uses them.
QANSEL_VERSION 1.0 Version string stamped into all binaries.
QANSEL_QUANTIS_BROKEN 0 1 enables the chunked XOR workaround for a misbehaving Quantis card.
QANSEL_SANDBOX 0 For qansel: 1 enables the Chromium sandbox, 0 (default) disables it for wider VM/headless compatibility.
QANSEL_GPU 0 For qansel: 1 lets WebEngine render with the GPU. This is unrelated to qvm's Vulkan compute backend.
GLSLANG glslangValidator Shader compiler used by make shaders.

Examples:

# CPU-only headless server, no Vulkan headers needed.
make USE_GUI=0 USE_VULKAN=0

# Deterministic, seedable build for regression testing.
make USE_TRNG=0

# Install under $HOME/.local instead of /usr/local.
make install PREFIX="$HOME/.local"

GPU shaders

The SPIR-V for the f32, f16, and f64 compute shaders is embedded in src/gate_apply_*_shader.h and checked in, so a normal build needs no shader compiler. To regenerate the headers after editing shaders/*.comp:

make shaders    # requires glslangValidator and python3
make            # rebuild with the new headers

If the f16/f64 headers are absent, the build still succeeds but the GPU will refuse those widths; only f32 is universally available.

Install

sudo make install

installs:

  • $(PREFIX)/bin/qas
  • $(PREFIX)/bin/qvm
  • $(PREFIX)/bin/qansel (if built)
  • $(PREFIX)/bin/qvm-server → symlink to qvm
  • $(PREFIX)/lib/oq2/qelib1.inc
  • $(PREFIX)/share/qansel/web/ (the UI and PWA assets)

qansel auto-detects the installed layout, so it finds the webroot, qas, and qelib1.inc without extra flags. For a CLI qas invocation, remember the include path:

qas -I /usr/local/lib/oq2 -g circuit.qasm circuit.qbin

make uninstall removes the installed files.

Tests

make test           # compile and run every tests/*.qasm
make test-verbose   # same, with full compiler and VM output
make test-verify    # compile, run, and decode every .qbin with tools/verify_bytecode.py
make test-results   # assert what circuits compute (Bell, teleport, QFT, adder, …)
make test-qpos      # qpos physics baselines (~30 s)

make test checks compilation and exit codes; make test-results is the one that checks outcomes (conditional execution, teleportation, error correction, and similar). It runs in a few seconds and is worth using alongside make test.

make test-qpos is separate because it runs the full 1950-step geometry to compare against the baselines published in docs/QPOS_DESIGN.md, so it takes around 30 seconds.

Clean

make clean          # removes build/

Build troubleshooting

Problem Fix
Qt6WebEngineWidgets not found by pkg-config Install qt6-webengine-dev (and qt6-base-dev), or build with USE_GUI=0.
vulkan/vulkan.h not found Install libvulkan-dev, or build with USE_VULKAN=0.
pci/pci.h not found libpci is optional. Install libpci-dev for readable PCIe device names, or leave it out; the build auto-detects it.
glslangValidator: not found Only make shaders needs it. The checked-in headers are enough for a normal build.
qansel runs but the window is empty The auto-detected webroot is wrong. Pass --webroot /path/to/web (source tree) or --webroot /usr/local/share/qansel/web (installed).
Link error mentioning -lstdc++ The Qt shell is compiled with g++; ensure g++ is installed alongside gcc.