Skip to content
entangledcodePublic

About

A relations-first quantum programming language where causal structure is a type-level primitive. Compiles to MBQC; Bell test run on Quandela's photonic QPU.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Quantum Relational Language (QRL)

A relations-first approach to quantum computing: describe the correlations, derive the predictions.

Formerly known as QPL (Quantum Process Language) — renamed January 2026 to avoid conflict with Selinger's QPL (2004)

Zenodo Tests Lines Photonic License Python

Vision

QRL is a physics modeling tool first, quantum programming framework second.

Most quantum frameworks ask: "How do I run this circuit on hardware?"

QRL asks: "Given these physical relations, what does quantum mechanics predict?"

This flips the question. Instead of programming a computer, you're modeling physics. The relational formalism matches how quantum mechanics actually works—correlations between subsystems are the fundamental reality, not gates acting on states.

The hypothesis: Because QRL's relational approach aligns with the structure of quantum physics, it may reveal insights that gate-centric formalisms obscure. This is a research proposition we're actively exploring.

What is QRL?

QRL treats entanglement as a first-class primitive and compiles directly to Measurement-Based Quantum Computing (MBQC) patterns—without intermediate gate decomposition.

Unlike gate-based languages (Qiskit, Cirq, Q#), QRL expresses quantum programs as relationships between systems, which map naturally to:

  • The cluster states and measurement patterns that power photonic quantum computers
  • The correlations that define Bell tests and foundational quantum experiments
  • The relational structure of quantum networks and protocols

Causal types with certificates

QRL's current research focus is types for quantum causal structure that come with certificates: data a checker verifies with linear algebra alone and, for indefinite causal order, a measurement a laboratory can run.

  • Switch(d) denotes the quantum switch construct (past party P supplying the control, slots A and B, future party F). Every well-typed switch(f, g, c) term denotes a causally nonseparable process, for every target dimension d, and works with any channels f, g. The certificate is a causal witness with 600 lab settings: value −0.1694 on the switch, and at least −2⁻¹⁷ on every causally separable process — proved in exact rational arithmetic by verify_exact_certificate().
  • Refinement types for two-slot process matrices, following Wechs et al. (PRX Quantum 2021): QCFO(d) <: QCCC(d) <: QCQC(d) <: PM(2, d) (fixed, classically controlled, quantum-controlled causal order), Noncausal(d) for processes certified outside QC-QC (an OCB causal-inequality violation), and Switch(d) <: QCQC(d). A term gets such a type only with a certificate that checks; subtyping converts certificates.
qrl exec  examples/lang/switch.qrl            # -> Process(1x2x2x2, witness=-0.1694 (certified nonseparable))
qrl check examples/lang/switch_channels.qrl   # a switch over a non-unitary channel: Switch(2)
qrl check examples/lang/classes.qrl           # definite order, typed QCFO(2) then QCQC(2)
qrl check examples/lang/noncausal.qrl         # the OCB process: Noncausal(2)
qrl check examples/lang/pm_loop.qrl           # a causal loop: rejected by T-PM
from qrl.switch_witness import switch_process, verify_exact_certificate
from qrl.causal import ocb_process
from qrl.causal_classes import ocb_certificate, switch_quantum_control_certificate

verify_exact_certificate()["valid"]                       # True: Tr[S W] >= -2^-17 on all separable W
switch_quantum_control_certificate(2).check(switch_process(2))   # True: the switch is QC-QC
ocb_certificate().check(ocb_process())                    # True: OCB game value 0.8536 > 3/4

A paper on the causal types is in preparation.

Why Relations First?

The insight: Quantum mechanics is fundamentally about correlations between subsystems. Bell's theorem, GHZ paradox, teleportation—these aren't about gates, they're about relations.

Gate-based thinking:  "Apply CNOT, then Hadamard, then measure"
Relational thinking:  "A and B are maximally correlated—what do measurements reveal?"

QRL lets you describe the correlations directly. The compilation to hardware follows from the physics.

Traditional: Gates → Circuit → Decompose → MBQC patterns → Hardware
QRL:         Relations → Graph extraction → MBQC patterns → Hardware

Quick Start

from qrl import QRLProgram, create_question, QuestionType
from qrl.mbqc import extract_graph, generate_pattern_from_relation

# Create entangled quantum systems
program = QRLProgram("Bell State Demo")
qubit_a = program.create_system()
qubit_b = program.create_system()
bell_pair = program.entangle(qubit_a, qubit_b)

# Extract MBQC graph structure
graph = extract_graph(bell_pair)
print(f"Cluster state: {graph.number_of_nodes()} qubits, {graph.number_of_edges()} edges")

# Generate measurement pattern
pattern = generate_pattern_from_relation(bell_pair)
print(f"Pattern: {pattern.description}")

# Measure with explicit context
alice = program.add_perspective("alice")
question = create_question(QuestionType.SPIN_Z)
result = program.ask(bell_pair, question, perspective="alice")
print(f"Measurement result: {result}")

Installation

git clone https://github.com/entangledcode/qrl.git
cd qrl

# Create and activate a virtual environment
python3 -m venv .venv
source .venv/bin/activate    # Linux/macOS
# .venv\Scripts\activate     # Windows

# Install QRL (editable mode for development)
pip install -e .

Requirements: Python 3.8+, NumPy, NetworkX

Optional backends (install as needed):

pip install pennylane            # PennyLane backend (Xanadu / simulation)
pip install perceval-quandela   # Photonic compilation + Quandela Cloud
pip install graphix              # Graph-state MBQC backend
pip install cvxpy                # SDP search for QCCC/QCQC certificates (checking needs only NumPy)

CLI

Installing QRL provides the qrl command. Run qrl help for the full usage guide.

# Run experiments
qrl run bell --shots 500 -v         # Bell/CHSH inequality test
qrl run ghz --qubits 4              # GHZ/Mermin inequality test
qrl run demo --quick                # Interactive physics demo

# Inspect compilation artifacts
qrl inspect graph bell              # Graph state topology
qrl inspect pattern ghz             # MBQC measurement pattern

# Compile to backends
qrl compile bell --target perceval  # Compile to Perceval circuit
qrl compile ghz --target graphix    # Compile to graphix pattern

# Cloud execution (requires QUANDELA_TOKEN)
qrl cloud status                    # Check platform availability
qrl cloud run bell                  # Run on Quandela sim:belenos

# Surface language
qrl check examples/lang/switch.qrl  # Type-check a .qrl program
qrl parse examples/lang/bell.qrl    # Dump its AST
qrl exec  examples/lang/bell.qrl --shots 1000   # Type-check and run
qrl exec  examples/lang/switch.qrl              # -> Process(1x2x2x2, witness=-0.1694 (certified nonseparable))
qrl check examples/lang/classes.qrl             # refinement types: QCQC(2)

# Tools
qrl info                            # Version, dependencies, source stats
qrl shell                           # Interactive REPL

Interactive REPL

qrl shell starts an interactive session with tab completion:

$ qrl shell
qrl> entangle mybell 2
Created 'mybell': 2-qubit bell relation
qrl> graph mybell
Graph for 'mybell':
  Nodes: [0, 1]
  Edges: [(0, 1)]
qrl> compile mybell
qrl> chsh --shots 500
S = 2.8200  (limit 2.0)  VIOLATED
qrl> quit

Implementation Status

~18,000 lines of code | 1,042 tests passing | Full photonic pipeline verified

Stage 0-3: Core Language & MBQC Compiler (Complete)

Component Status Description
QuantumRelation ✅ Entanglement as first-class citizen
n-qubit States ✅ GHZ states (tested to 5 qubits), W states, Bell pairs
Graph Extraction ✅ extract_graph() — Relations → cluster state topology
Pattern Generation ✅ Bell, GHZ, H/X/Z/S/T gates, CNOT, CZ, rotations
Adaptive Corrections ✅ Pauli corrections based on measurement outcomes
Teleportation ✅ Full protocol with fidelity = 1.0

Stage 4: Photonic Integration (Complete)

QRL compiles to photonic platforms via Perceval/Quandela Cloud and PennyLane.

Component Status Description
QRL → Perceval ✅ Direct path-encoded circuit generation
QRL → PennyLane ✅ Mid-circuit measurements + adaptive corrections
Local Simulation ✅ SLOS backend + PennyLane default.qubit
Cloud Connection ✅ Quandela sim:belenos verified
Full Pipeline ✅ QRL → MBQC → Backend → Results
Pipeline: QRL Relations → MBQC Pattern ─┬─→ Perceval → Quandela
                                         └─→ PennyLane → Simulation

Validated on hardware: Bell state confirmed on qpu:belenos (Quandela's photonic QPU) — 423/1000 shots yielded valid dual-rail events (42.3% yield), 57.7% HOM-bunched as expected from linear optics.

Stage 5: Domain Modules (Complete)

QRL includes domain-specific modules that apply relational quantum mechanics to real scientific problems.

qrl.physics — Foundational Layer

The physics primitives everything else builds on. Hardware-verified S = 2.61 ± 0.08 on qpu:belenos.

from qrl.physics import BellTest, GHZTest

test = BellTest()
print(test.compare(trials=2000))
# S parameter: Theory 2.8284, Observed 2.8340 — VIOLATED
Module Description
qrl.physics.bell CHSH inequality, BellTest, noisy Werner states
qrl.physics.ghz GHZ paradox, Mermin inequality
qrl.physics.hensen Loophole-free Bell test — detection loophole, heralded entanglement, p-value

qrl.domains.biology — Quantum Biology

from qrl.domains.biology import fmo_complex, QuantumBioNetwork

fmo = fmo_complex()  # Fenna-Matthews-Olson complex
network = QuantumBioNetwork(fmo)
print(network.coherence_lifetime())
Function Description
fmo_complex() FMO photosynthesis complex (7-site)
RadicalPair Avian magnetoreception model
lindblad_evolve() Lindblad master equation evolution
decoherence_rate(), coherence_lifetime() Environmental noise metrics
phonon_bath() Vibrational environment coupling
ENAQT Environment-Assisted Quantum Transport

qrl.domains.sensing — Quantum Sensing

from qrl.domains.sensing import QuantumSensor, heisenberg_limit, ramsey_interferometry

sensor = QuantumSensor(n_qubits=10)
print(f"Fisher info: {sensor.quantum_fisher_information():.4f}")
print(f"Heisenberg limit: {heisenberg_limit(10):.6f}")
print(f"Advantage: {sensor.quantum_advantage_factor():.2f}x")
Function Description
QuantumSensor Entanglement-enhanced sensor
quantum_fisher_information() QFI for parameter estimation
cramer_rao_bound() Quantum Cramér-Rao bound
heisenberg_limit() 1/N scaling limit
ramsey_interferometry() Ramsey protocol simulation
mach_zehnder() Mach-Zehnder interferometer
spin_squeezing() Spin-squeezed state sensing
atomic_clock_stability() Allan deviation model

qrl.domains.chemistry — Quantum Chemistry

from qrl.domains.chemistry import hydrogen, MolecularSystem

mol = hydrogen(bond_length=0.74)
print(f"HF energy:  {mol.hf_energy:.4f} Ha")
print(f"FCI energy: {mol.fci_energy:.4f} Ha")
print(f"Correlation energy: {mol.correlation_energy:.4f} Ha")
Function Description
hydrogen() H₂ molecule (STO-3G, full VQE)
helium_hydride_cation() HeH⁺ (first molecule in universe)
MolecularSystem General molecular Hamiltonian
jordan_wigner_hamiltonian() Fermion-to-qubit mapping
vqe_energy() Variational Quantum Eigensolver

H₂ benchmark: E_HF = −1.1167 Ha, E_FCI = −1.1373 Ha; entanglement reaches 2 bits at dissociation.

qrl.causal — Quantum Causal Structure

from qrl.causal import ProcessMatrix, QuantumSwitch, QuantumCausalDAG
from qrl.causal import quantum_switch_process_matrix, QuantumCommonCause

# Quantum switch construct — indefinite causal order (parties P, A, B, F; P supplies the control)
from qrl.switch_witness import switch_witness
W = quantum_switch_process_matrix()
print(f"Causal nonseparable: {not W.is_causally_separable()}")   # True
print(switch_witness())   # 600 lab settings, predicted -0.1694, separable bound 0

# Common cause structure (Allen et al. 2017)
rho = QuantumCommonCause(n=2).state()
Class / Function Description
ProcessMatrix Process matrix formalism (Oreshkov, Costa, Brukner 2012)
CPTPMap Completely positive trace-preserving maps
QuantumSwitch Indefinite causal order
QuantumCausalDAG Quantum causal directed acyclic graphs
QuantumMarkovChain Quantum Markov chains
QuantumCommonCause Common cause structure (Allen et al. 2017)
causal_nonseparability_witness() OCB-game witness for 2-party qubit processes
ocb_process() The OCB process (violates the OCB causal inequality, P_win = 0.8536)
switch_witness() Measurable causal witness for the quantum switch (Araújo et al. 2015)
verify_exact_certificate() Exact proof that the switch witness is valid on every causally separable process
qrl.causal_classes QC-FO / QC-CC / QC-QC certificates, outside-QC-QC certificate, SDP search

Validation

python -m pytest tests/ -v
  • 1,042 tests passing (32 skipped; a few need the optional cvxpy)
  • Bell correlations verified (CHSH violation S = 2.83; hardware S = 2.61 ± 0.08)
  • Loophole-free Bell test modelled (Hensen et al. 2015 — η_crit, heralded state, p-value)
  • GHZ paradox demonstrated (Mermin inequality M = 4, classical limit 2)
  • Teleportation fidelity = 1.0
  • Causal structure — process matrices (validity incl. the no-causal-loop condition), quantum switch, causal witnesses with an exact certificate, refinement classes QC-FO ⊂ QC-CC ⊂ QC-QC
  • Photonic pipeline validated locally and on qpu:belenos

MBQC Compilation Pipeline

from qrl import QRLProgram
from qrl.mbqc import (
    extract_graph,
    generate_pattern_from_relation,
    generate_teleportation_pattern,
    simulate_teleportation
)

# 1. Create quantum relation
program = QRLProgram("GHZ State")
qubits = [program.create_system() for _ in range(3)]
ghz = program.entangle(*qubits)

# 2. Extract graph state structure
graph = extract_graph(ghz)
# GHZ₃ → star graph (3 nodes, 2 edges)

# 3. Generate measurement pattern
pattern = generate_pattern_from_relation(ghz)

# 4. Teleportation with adaptive corrections
import numpy as np
input_state = np.array([0.6, 0.8])  # |ψ⟩ = 0.6|0⟩ + 0.8|1⟩
output, outcomes, corrections = simulate_teleportation(input_state)
# Fidelity = 1.0 (perfect teleportation)

Key Features

Relations-First Programming

# Instead of gates, work with relationships
bell = program.entangle(qubit_a, qubit_b)  # Creates QuantumRelation
ghz = program.entangle(q0, q1, q2)          # 3-qubit GHZ state

Contextual Measurement

# Measurements are questions asked from a perspective
question = create_question(QuestionType.SPIN_X)  # X-basis measurement
result = program.ask(relation, question, perspective="alice")

Automatic Graph Extraction

# QRL automatically determines cluster state topology
graph = extract_graph(relation)
# Bell state → edge graph
# GHZ state → star graph
# W state → ring topology

Adaptive Pauli Corrections

# MBQC requires corrections based on measurement outcomes
pattern = generate_teleportation_pattern()
# Automatically includes X/Z corrections conditioned on Bell measurement results

Project Structure

qrl/
├── src/qrl/
│   ├── cli.py               # CLI entry point (qrl command)
│   ├── core.py              # QuantumRelation, QuantumQuestion, Perspective
│   ├── measurement.py       # Measurement and basis transformations
│   ├── tensor_utils.py      # n-qubit tensor operations
│   ├── causal.py            # ProcessMatrix, CPTPMap, QuantumSwitch, QuantumCausalDAG, QuantumMarkovChain, QuantumCommonCause
│   ├── switch_witness.py    # Switch construct, lab witness, exact certificate
│   ├── causal_classes.py    # QC-FO / QC-CC / QC-QC / outside-QC-QC certificates
│   ├── lang/                # Surface language: parser, type checker, interpreter
│   ├── mbqc/                # MBQC compiler
│   │   ├── graph_extraction.py
│   │   ├── pattern_generation.py
│   │   ├── adaptive_corrections.py
│   │   └── measurement_pattern.py
│   ├── backends/            # Hardware backends
│   │   ├── pennylane_adapter.py
│   │   ├── perceval_path_adapter.py
│   │   └── graphix_adapter.py
│   ├── domains/             # Scientific domain modules
│   │   ├── biology.py       # FMO, RadicalPair, ENAQT
│   │   ├── sensing.py       # QuantumSensor, Ramsey, Fisher info
│   │   ├── chemistry.py     # H₂, HeH⁺, VQE, Jordan-Wigner
│   │   └── networks.py      # QuantumNetwork, repeaters
│   └── physics/             # Foundational layer
│       ├── bell.py          # CHSH inequality, BellTest, noisy Werner states
│       ├── ghz.py           # GHZ paradox, Mermin inequality
│       └── hensen.py        # Loophole-free Bell test (Hensen et al. 2015)
├── tests/                   # 1,042 tests
├── examples/
│   ├── lang/                # .qrl programs (switch, refinement types, OCB, causal loop)
│   ├── pennylane/
│   └── quandela/
├── docs/
└── requirements.txt

Research Direction

Core Thesis

QRL explores whether a relations-first formalism—where correlations are primitives, not derived properties—offers genuine advantages for:

  1. Understanding quantum physics: Does describing correlations directly reveal structure that gate-centric approaches obscure?
  2. MBQC compilation: Can relational specifications compile more naturally to measurement-based patterns?
  3. Photonic hardware: Does the relational model align better with linear optical quantum computing?

Theoretical Foundations

Concept Connection to QRL
Relational QM (Rovelli) Properties exist only relative to other systems—QRL models this directly
Bell's Theorem Correlations without local hidden variables—relations ARE the reality
MBQC (Raussendorf-Briegel) Computation via measurements on entangled states—natural fit for relations

Example: Bell Test in QRL

from qrl.physics import BellTest

test = BellTest()
print(test.predict())
# -> Predicted CHSH parameter: S = 2.8284
# -> Classical limit: 2.0

print(test.compare(trials=2000))
# -> S parameter: Theory 2.8284, Observed 2.8340
# -> Violated: YES

Running the Interactive Demo

qrl run demo          # Full demo (~5 minutes)
qrl run demo --quick  # Quick mode (~1 minute)
qrl run demo --section 3  # GHZ paradox only

Documentation

  • Technical Blog — Development journey, deep dives, research notes
  • Published Paper — "QRL: A Relations-First Programming Language for Measurement-Based Quantum Computing" (Zenodo, January 2026)
  • Photonic Examples — Working examples for Quandela Cloud integration
  • PennyLane Examples — Cross-platform MBQC via PennyLane

Related

Contributing

QRL is an active research project exploring relations-first quantum computing. Contributions welcome from researchers interested in:

  • Foundations of quantum mechanics — Relational QM, Bell inequalities, contextuality
  • MBQC theory and compilation — Measurement patterns, graph states, flow conditions
  • Photonic quantum computing — Linear optics, path encoding, Perceval/Quandela
  • Quantum programming languages — Type systems, compilation, formal verification

Contact

David Coldeira

License

MIT License — see LICENSE

About

A relations-first quantum programming language where causal structure is a type-level primitive. Compiles to MBQC; Bell test run on Quandela's photonic QPU.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages