Contact: www.anulum.li | protoscience@anulum.li
The bridge package is the central nervous system of scpn-quantum-control.
Every module in this package translates between classical SCPN state
representations and quantum operator formats. Without the bridge layer,
coupling matrices are numbers on paper; with it, they become executable
Hamiltonians, circuits, and feedback signals.
12 modules, 24 public symbols, 5 cross-repo integration points.
Classical World Bridge Quantum World
───────────────── ───────── ──────────────
K_nm (Paper 27) ──→ knm_hamiltonian ──→ SparsePauliOp (XY/XXZ)
K_nm (Paper 27) ──→ sparse_hamiltonian ──→ scipy.sparse.csc_matrix
K_nm (Paper 27) ──→ knm_hamiltonian ──→ QuantumCircuit (ansatz)
Plasma config ──→ control_plasma_knm ──→ K_nm → SparsePauliOp
Orchestrator state ──→ orchestrator_adapter ──→ UPDEPhaseArtifact
Quantum observables ──→ orchestrator_feedback ──→ advance/hold/rollback
SC bitstreams ←→ sc_to_quantum ←→ Ry angles / statevectors
SNN spike trains ──→ snn_adapter ──→ QuantumDenseLayer output
Loss gradient ←── snn_backward ←── Parameter-shift rule
SPN weight matrices ──→ spn_to_qcircuit ──→ QuantumCircuit (CRy/anti-CRy)
SSGF W + theta ←→ ssgf_adapter ←→ Trotter evolution
SSGF W adaptation ←── ssgf_w_adapter ←── Quantum correlators
scpn_quantum_control.bridge.qpu_data_artifact defines the JSON
artifact consumed by hardware campaign code. The contract sits between
source-facing repositories and Quantum Control:
- SC-NeuroCore provides source-facing bridge payloads.
- Phase Orchestrator should compile domain data into validated
K_nm/omegaartifacts. - Quantum Control validates artifacts and compiles circuits.
The public helpers are:
| Symbol | Purpose |
|---|---|
QPUDataArtifact |
Immutable validated artifact object. |
artifact_from_arrays |
Convenience constructor for loaders/tests. |
validate_qpu_data_artifact |
Enforces schema and optional publication gate. |
read_qpu_data_artifact |
Reads artifact JSON from disk. |
write_qpu_data_artifact |
Writes artifact JSON to disk. |
The schema is documented in docs/qpu_data_artifact.md. Synthetic,
simulation, and fixture sources are allowed for smoke tests but rejected
by the publication gate.
The foundational module. Compiles the K_nm coupling matrix and natural
frequencies omega into Qiskit SparsePauliOp for quantum simulation.
Kuramoto-XY mapping (Paper 27, Section 3):
K[i,j] * sin(theta_j - theta_i) ↔ -K[i,j] * (X_i X_j + Y_i Y_j)
omega_i ↔ -omega_i * Z_i
Canonical natural frequencies from Paper 27, Table 1. 16 values in rad/s, experimentally calibrated. Used as the default frequency vector throughout the entire package.
OMEGA_N_16 = np.array([1.329, 2.610, 0.844, 1.520, 0.710, 3.780, 1.055, 0.625,
2.210, 1.740, 0.480, 3.210, 0.915, 1.410, 2.830, 0.991])Builds the canonical K_nm matrix. Three-layer construction:
- Base kernel:
K[i,j] = K_base * exp(-K_alpha * |i-j|)(Eq. 3) - Calibration anchors: Table 2 overrides for (0,1), (1,2), (2,3), (3,4)
- Cross-hierarchy boosts: S4.3 long-range couplings L1-L16, L5-L7
Returns symmetric (L, L) float64 array. Always positive, zero diagonal implicit from the exponential decay (K[i,i] = K_base, but never used as self-coupling in the Hamiltonian — the Z_i term handles on-site energy).
K = build_knm_paper27(L=4) # 4x4 submatrix
K_full = build_knm_paper27() # 16x16 canonicalRust acceleration: scpn_quantum_engine.build_knm(L, K_base, K_alpha) produces
identical output at 4.7x speedup. Parity verified to 1e-12 atol in
test_rust_path_benchmarks.py.
Nearest-neighbour ring topology. Useful for BKT transition studies and finite-size scaling where Paper 27's specific topology is not needed.
Returns (K, omega) tuple. If omega is None, draws from N(0,1).
The primary compiler. Converts K_nm + omega to SparsePauliOp using
Qiskit's little-endian qubit ordering.
H = -sum_{i<j} K[i,j] * (X_i X_j + Y_i Y_j) - sum_i omega_i * Z_i
Sparsity filtering: terms with |K[i,j]| < COUPLING_SPARSITY_EPS (1e-15)
are dropped. This keeps the Pauli list compact for large sparse K matrices
(Paper 27's K_nm has ~60% of off-diagonal entries below 0.01).
Equivalent to knm_to_xxz_hamiltonian(K, omega, delta=0.0).
Extended compiler with ZZ anisotropy parameter delta:
H = -sum_{i<j} K[i,j] * (X_iX_j + Y_iY_j + delta * Z_iZ_j) - sum_i omega_i * Z_i
| delta | Model | Physics |
|---|---|---|
| 0.0 | XY | Standard Kuramoto mapping, in-plane S^2 dynamics |
| 1.0 | Heisenberg | Full S^2 dynamics (Kouchekian-Teodorescu 2025, arXiv:2601.00113) |
| -1.0..1.0 | XXZ | Interpolation, BKT/Ising transitions |
At delta=1, perturbations around equilibria connect to the semiclassical Gaudin model and Richardson pairing mechanism.
Returns the full complex (2^n, 2^n) dense matrix. Two-path implementation:
- Rust fast path:
scpn_quantum_engine.build_xy_hamiltonian_dense()— exact parity with Qiskit verified to 1e-10 atol - Qiskit fallback:
knm_to_hamiltonian(K, omega).to_matrix()
Used primarily for exact diagonalisation of small systems (n <= 14) and as the ground truth reference for sparse eigensolvers.
Physics-informed variational ansatz. CZ entanglement gates placed only between K_nm-connected pairs (|K[i,j]| >= threshold). Structure:
for each repetition:
Ry(p[2k]) on each qubit k
Rz(p[2k+1]) on each qubit k
CZ(i, j) for each connected pair
Returns parameterised QuantumCircuit with n * 2 * reps parameters.
The CZ topology mirrors the K_nm graph, encoding the coupling structure
into the ansatz architecture.
For n >= 12, dense matrix construction is impractical (n=16: 32 GB).
This module builds the XY Hamiltonian directly as scipy.sparse.csc_matrix.
Memory comparison:
| n | Dense | Sparse | Reduction |
|---|---|---|---|
| 8 | 0.5 MB | 0.06 MB | 8x |
| 12 | 512 MB | 6 MB | 85x |
| 16 | 32 GB | 200 MB | 160x |
| 18 | 512 GB | 800 MB | 640x |
| 20 | 8 TB | 3 GB | 2700x |
Constructs the full-space sparse Hamiltonian. Matrix elements:
- Diagonal:
H[k,k] = -sum_i omega_i * (1 - 2*b_i(k))where b_i(k) is bit i of basis state k - Off-diagonal:
H[k, k XOR mask_ij] = -2*K[i,j]when bits i and j differ in state k
Rust fast path via scpn_quantum_engine.build_sparse_xy_hamiltonian() at 80x speedup.
Combines sparse construction with U(1) magnetisation symmetry. The XY model conserves total magnetisation M = sum_i Z_i. Working within a single sector reduces the Hilbert space dimension from 2^n to C(n, (n+M)/2).
For n=16, M=0 sector: dim = C(16,8) = 12,870 vs full 65,536 (5x reduction). Combined with sparse storage: ~40 MB vs 32 GB dense full-space.
Returns (H_sparse, sector_indices).
ARPACK eigensolver wrapper. Computes k smallest (or largest) eigenvalues.
Automatic fallback to dense numpy.linalg.eigh when the matrix is too small
for iterative methods (dim < k+2).
Returns dict: {eigvals, eigvecs, nnz, dim, method, M, sector_dim}.
Estimates memory usage without constructing the matrix. Useful for pre-flight checks before committing to large computations.
Compatibility bridge to scpn_control.phase.plasma_knm for plasma-native
K_nm construction from tokamak parameters.
Delegates to scpn-control for plasma-specific coupling matrices. Returns
(L, L) float64 array.
Constructs K_nm directly from tokamak machine parameters:
R0: major radius (m)a: minor radius (m)B0: toroidal field (T)Ip: plasma current (MA)n_e: electron density (1e19/m^3)
Returns plasma natural frequencies from scpn-control.
All functions require scpn-control on sys.path. The bridge handles
sys.path insertion/cleanup for local development with repo_src= parameter.
Bidirectional translation between scpn-phase-orchestrator state payloads
and the quantum bridge's UPDEPhaseArtifact schema.
Static methods — no state, no side effects:
| Method | Direction | Description |
|---|---|---|
from_orchestrator_state(state) |
Orch → Quantum | Parse orchestrator payload into UPDEPhaseArtifact |
to_orchestrator_payload(artifact) |
Quantum → Orch | Emit canonical orchestrator field names |
to_scpn_control_telemetry(artifact) |
Quantum → Control | Emit scpn-control compatible telemetry |
build_knm_from_binding_spec(spec) |
Orch → K_nm | Extract coupling matrix from BindingSpec |
build_omega_from_binding_spec(spec) |
Orch → omega | Extract per-oscillator frequencies |
The adapter uses duck-typed field resolution (_read_field) that accepts
both dict and object attributes, making it compatible with Pydantic models,
dataclasses, and plain dicts.
Roundtrip guarantee: to_orchestrator_payload(from_orchestrator_state(x))
produces a dict structurally equivalent to the input. Verified in
test_pipeline_wiring_performance.py.
Closes the cybernetic feedback loop: quantum observables drive orchestrator phase lifecycle decisions.
Dataclass with fields: action, r_global, stability_score, l16_action,
confidence, reason.
Computes quantum-informed feedback using compute_l16_lyapunov from the
L16 quantum director module.
Decision logic:
R >= 0.8 AND stable → "advance" (proceed to next phase)
R >= 0.5 → "hold" (continue monitoring)
R < 0.5 → "rollback" (return to previous phase)
Confidence is computed as a normalised score within the active regime:
- advance:
min(R, stability) - hold:
(R - r_hold) / (r_advance - r_hold) - rollback:
1.0 - R / r_hold
Three frozen dataclasses defining the canonical state exchange format between classical and quantum subsystems.
Pairwise phase-locking metrics (Lachaux et al., HBM 1999):
source_layer,target_layer: int indicesplv: Phase Locking Value in [0, 1]mean_lag: mean phase difference at PLV maximum (radians)
Validation: finite floats, non-negative layer indices.
Per-layer coherence:
R: Kuramoto order parameter |z| in [0, 1]psi: mean phase angle arg(z) in radianslock_signatures: dict ofLockSignatureArtifact
Validation: R in [0, 1], finite floats, string keys.
Top-level artifact containing:
layers: list ofLayerStateArtifactcross_layer_alignment: (n_layers, n_layers) float64 matrixstability_proxy: scalar stability measureregime_id: non-empty string identifiermetadata: arbitrary dict
Full serialisation support: to_dict(), to_json(), from_dict(), from_json().
Validation ensures alignment matrix shape matches layer count and all
values are finite.
Maps between stochastic computing probabilities and qubit rotation angles.
Core identity: For Ry(theta)|0>, the probability of measuring |1> is
P(|1>) = sin^2(theta/2).
| Function | Direction | Formula |
|---|---|---|
probability_to_angle(p) |
SC → Quantum | theta = 2 * arcsin(sqrt(p)) |
angle_to_probability(theta) |
Quantum → SC | P = sin^2(theta/2) |
bitstream_to_statevector(bits) |
SC → Quantum | Mean probability → single-qubit [alpha, beta] |
measurement_to_bitstream(counts, length) |
Quantum → SC | Shot counts → Bernoulli bitstream |
These functions enable the SPN/SNN layers of SCPN to exchange state with quantum circuits through the bitstream probability interface.
Bidirectional bridge between spike trains and quantum circuits.
spike_train_to_rotations(spikes, window=10) -> np.ndarrayConverts (timesteps, n_neurons) binary spike array to Ry rotation angles.
Uses firing rate within the last window timesteps: angle = rate * pi.
Output in [0, pi].
quantum_measurement_to_current(values, scale=1.0) -> np.ndarrayConverts quantum P(|1>) probabilities to SNN input currents. Linear scaling.
Pure-numpy bridge (no sc-neurocore dependency):
bridge = SNNQuantumBridge(n_neurons=2, n_inputs=3, seed=42)
output = bridge.forward(spike_history) # (T, n_inputs) → (n_neurons,)Internal pipeline: spike rates → Ry angles → QuantumDenseLayer → P(|1>) → currents.
QuantumDenseLayer.forward() evaluates the small QSNN circuit with an exact
local statevector for the gates used by the layer (Ry, controlled-Ry, and
CX). Hardware submission paths still build Qiskit circuits elsewhere; this
bridge path is the deterministic CPU execution path for SNN feedback loops and
coverage-instrumented tests.
Full sc-neurocore integration with ArcaneNeuron:
bridge = ArcaneNeuronBridge(n_neurons=2, n_inputs=3, seed=42)
result = bridge.step(np.array([1.0, 0.5, 0.0]))
# result["spikes"]: binary spike vector
# result["output_currents"]: quantum layer output
# result["v_deep"]: identity state (persists across reset)
# result["confidence"]: neuron confidenceKey property: v_deep persists through reset(), implementing the identity
binding mechanism from the Arcane Sapience specification.
Enables end-to-end training of the SNN-quantum hybrid via the parameter-shift rule.
SNN forward → spike rates → theta (Ry angles) → quantum evolution → y
↓
Loss L(y, target) ← dL/dy ← dy/dtheta (param-shift) ← dtheta/d(rates) = pi
Computes dL/d(input) for MSE loss:
dL/dtheta_k = [L(theta_k + pi/4) - L(theta_k - pi/4)] / (actual_shift)
dL/d(spike_rate) = dL/dtheta * pi
Cost: 2 quantum forward passes per parameter (2n total for n inputs).
Returns BackwardResult: grad_params, grad_spikes, loss, n_evaluations.
Boundary handling: shift is clamped to [0, 1] value range to prevent invalid rotation angles. If both bounds are hit, gradient is zero.
Compiles Stochastic Petri Net (SPN) topology into quantum circuits.
Mapping:
- Places → qubits (amplitude encodes token density)
- Transitions → controlled-Ry gates (arc weights → rotation angles)
- Inhibitor arcs → anti-control pattern: X-CRy-X
Args:
W_in: (n_transitions, n_places) — input arc weights. Negative = inhibitor.W_out: (n_places, n_transitions) — output arc weights.thresholds: (n_transitions,) — firing thresholds.
For each transition t:
- Normal input arcs:
Ry(-theta * threshold[t])on input places - Output arcs:
Ry(theta)or anti-controlledRy(theta)if inhibitors present
Anti-control pattern for inhibitor arcs. An inhibitor arc requires the source place to be empty (|0>) for the transition to fire. Implementation:
X on each inhibitor qubit (flip control sense)
CRy(theta) controlled by inhibitor qubits, target on output qubit
X on each inhibitor qubit (restore)
For multi-qubit inhibition: uses RYGate.control(n) for n > 1 controls.
Bidirectional bridge between the Self-Sustaining Geometry Field (SSGF) engine and quantum evolution.
ssgf_w_to_hamiltonian(W, omega) -> SparsePauliOpW has the same structure as K_nm (symmetric, non-negative). Delegates
directly to knm_to_hamiltonian.
ssgf_state_to_quantum({"theta": [...]}) -> QuantumCircuitEncodes oscillator phases as Ry(pi/2) Rz(theta_i) per qubit,
producing (|0> + e^{i*theta}|1>) / sqrt(2). This preserves phase
information in <X> = cos(theta), <Y> = sin(theta).
quantum_to_ssgf_state(statevector, n_osc) -> {"theta": [...], "R_global": float}Extracts phases via theta_i = atan2(<Y_i>, <X_i>) and computes
R_global = |mean(exp(i*theta))|.
Quantum-in-the-loop wrapper for SSGFEngine:
loop = SSGFQuantumLoop(engine, dt=0.1, trotter_reps=3)
result = loop.quantum_step()Each step:
- Read W matrix and theta phases from SSGFEngine
- Compile W → SparsePauliOp via
knm_to_hamiltonian - Encode theta → quantum circuit (
Ry(pi/2) Rz(theta)) - Trotter evolve via
PauliEvolutionGate(LieTrotter) - Extract updated theta and R_global from evolved statevector
- Write theta back to SSGFEngine (in-place mutation)
Omega is set to zeros because SSGF handles natural frequencies internally; only the coupling structure W enters the quantum Hamiltonian.
Closes the SSGF feedback loop: quantum correlators modify the geometry matrix W, not just the phases theta.
W_new[i,j] = W_old[i,j] + eta * (-delta_R) * C[i,j]
Where:
eta: learning ratedelta_R = R_quantum - R_target: synchronisation errorC[i,j] = <X_i X_j + Y_i Y_j>: quantum XY correlator
Positive correlator with R below target → strengthen coupling. Negative correlator → weaken coupling (anti-correlated oscillators).
One adaptation step. Returns WAdaptResult:
W_updated: new geometry matrix (non-negative, zero diagonal enforced)r_global: measured quantum synchronisationdelta_r: gap to targetcorrelators: (n, n) XY correlator matrixmax_update: largest absolute element change
The correlator measurement requires O(n^2) Pauli expectation values,
each computed from the full statevector. For n=8 this is 28 pairs.
| Module | External Package | Required? |
|---|---|---|
control_plasma_knm |
scpn-control | Optional (ImportError with instructions) |
snn_adapter.ArcaneNeuronBridge |
sc-neurocore >= 3.14 | Optional (ImportError with instructions) |
ssgf_adapter.SSGFQuantumLoop |
SCPN-CODEBASE (SSGFEngine) | Optional (runtime only) |
orchestrator_adapter |
scpn-phase-orchestrator | No (works with any dict/object) |
orchestrator_feedback |
l16.quantum_director | Internal dependency |
All optional dependencies fail gracefully with ImportError and clear
installation instructions. The core modules (knm_hamiltonian, sparse_hamiltonian,
sc_to_quantum, spn_to_qcircuit) have zero optional dependencies beyond
Qiskit, NumPy, and SciPy.
Measured on ML350 Gen8 (128 GB RAM, Xeon E5-2620v2):
| Pipeline | System Size | Wall Time |
|---|---|---|
build_knm_paper27 → knm_to_hamiltonian |
4 qubits | 0.3 ms |
build_knm_paper27 → knm_to_dense_matrix (Rust) |
4 qubits | 0.1 ms |
build_knm_paper27 → knm_to_ansatz |
4 qubits, 2 reps | 0.5 ms |
build_sparse_hamiltonian → sparse_eigsh |
8 qubits | 12 ms |
build_sparse_hamiltonian → sparse_eigsh |
12 qubits | 340 ms |
SNNQuantumBridge.forward |
3 inputs, 2 neurons | 4 ms |
spn_to_circuit |
3 places, 2 transitions | 0.4 ms |
ssgf_w_to_hamiltonian → Trotter evolve |
4 oscillators | 8 ms |
PhaseOrchestratorAdapter roundtrip |
3 layers | 0.2 ms |
compute_orchestrator_feedback |
4 qubits | 15 ms |
| Function | Bridge Module | Speedup | Parity |
|---|---|---|---|
build_knm |
knm_hamiltonian |
4.7x | 1e-12 atol |
build_xy_hamiltonian_dense |
knm_hamiltonian |
exact | 1e-10 atol |
build_sparse_xy_hamiltonian |
sparse_hamiltonian |
80x | exact index match |
All Rust paths are optional. Python fallbacks produce identical results.
Rust availability is detected at call time via try/except ImportError.
59 tests across 6 test files covering the bridge package:
test_knm_hamiltonian.py— Hermiticity, eigenvalues, sparsity, XXZ, ansatztest_sparse_hamiltonian.py— Sparse vs dense parity, sector Hamiltonian, eigshtest_orchestrator_adapter.py— Roundtrip, field resolution, telemetry formattest_snn_adapter.py— Spike rotations, bridge forward, ArcaneNeuron integrationtest_spn_to_qcircuit.py— Circuit depth, inhibitor pattern, weight encodingtest_ssgf_adapter.py— W→H compilation, phase encoding/extraction, quantum loop
Every test file includes physical invariant checks, pipeline wiring verification, and performance benchmarks. The bridge package has zero skipped tests when all optional dependencies are installed.