SPDX-License-Identifier: AGPL-3.0-or-later¶
Commercial license available¶
© Concepts 1996–2026 Miroslav Šotek. All rights reserved.¶
© Code 2020–2026 Miroslav Šotek. All rights reserved.¶
ORCID: 0009-0009-3560-0851¶
Contact: www.anulum.li | protoscience@anulum.li¶
scpn-quantum-control — Auto-Generated API Reference¶
Auto-Generated API Reference¶
Generated from source docstrings via mkdocstrings.
This page is an advanced module index. It is useful for maintainers and subsystem authors who need direct access to implementation modules. First-path user workflows should start with Stable Facades API and Kuramoto Core Facade.
Documentation Surface TODO¶
The repository documentation-surface audit is tracked by
tools/audit_documentation_surface.py. As of 2026-05-18, after the Paper 0
generated-builder burn-down through generated builder 10-batch 25, the
remaining scripts audit inventory is:
- Total remaining findings:
734 - Function findings:
697 - Module findings:
37 - Class findings:
0
Continue from the next audit head:
scripts/build_paper0_section_2_l4_impact_dampening_dynamics_and_shifting_criticality_specs.pyscripts/build_paper0_section_2_molecular_geometry_and_the_psi_field_interface_l2_l3_specs.pyscripts/build_paper0_section_2_specialised_sensory_systems_specs.pyscripts/build_paper0_section_2_the_central_void_the_source_specs.pyscripts/build_paper0_section_2_the_endocrine_system_and_hpa_axis_stress_response_specs.py
Production continuation rule: process generated Paper 0 builder CLI entrypoints in deterministic audit order, run focused documentation-surface audit, Ruff, mypy, diff hygiene, public-token hygiene, and freeze checks for each batch before staging or committing.
Stable Facades¶
scpn_quantum_control.kuramoto_core
¶
Small public facade for Kuramoto-XY problems.
KuramotoProblem
dataclass
¶
build_kuramoto_problem(K_nm, omega, metadata=None)
¶
Create a validated Kuramoto-XY problem from arbitrary arrays.
validate_kuramoto_inputs(K_nm, omega)
¶
Validate and copy a symmetric Kuramoto coupling problem.
compile_hamiltonian(problem)
¶
Compile a Kuramoto problem into the XY SparsePauliOp Hamiltonian.
compile_dense_hamiltonian(problem, *, max_dense_gib=None)
¶
Compile a dense Hamiltonian, using the Rust engine when installed.
compile_trotter_circuit(problem, time, trotter_steps=10, trotter_order=1)
¶
Compile a Trotterised gate-model evolution circuit.
measure_order_parameter(problem, statevector)
¶
Measure the Kuramoto order parameter from a statevector.
simulate_variant_trajectory(problem, variant, *, dt, n_steps, theta0=None, hyperedges=None, hyper_weights=None, target_r=0.75, monitor_gain=0.8, measurement_strength=0.2, gain_loss=None, prefer_rust=True)
¶
Run a higher-order, monitored, or PT-symmetric Kuramoto variant.
Advanced Module Reference¶
The sections below expose lower-level packages directly. Use them when extending or debugging a subsystem, not as the default path for tutorial code.
Bridge¶
scpn_quantum_control.bridge.knm_hamiltonian
¶
Knm coupling matrix -> Pauli Hamiltonian compiler.
Translates the 16x16 Knm coupling matrix + 16 natural frequencies from Paper 27 into a SparsePauliOp for quantum simulation.
Kuramoto <-> XY mapping: K[i,j]sin(theta_j - theta_i) <=> -J_ij(X_i X_j + Y_i Y_j) omega_i <=> -h_i * Z_i
OMEGA_N_16 = np.array([1.329, 2.61, 0.844, 1.52, 0.71, 3.78, 1.055, 0.625, 2.21, 1.74, 0.48, 3.21, 0.915, 1.41, 2.83, 0.991], dtype=(np.float64))
module-attribute
¶
build_knm_paper27(L=16, K_base=0.45, K_alpha=0.3)
¶
Build the canonical Knm coupling matrix from Paper 27.
K[i,j] = K_base * exp(-K_alpha * |i - j|) (Paper 27, Eq. 3) with calibration anchors from Table 2 and cross-hierarchy boosts from S4.3.
build_kuramoto_ring(n, coupling=1.0, omega=None, rng_seed=None)
¶
Build a nearest-neighbour ring coupling matrix for n Kuramoto oscillators.
Returns (K, omega) ready for QuantumKuramotoSolver or knm_to_hamiltonian. If omega is None, draws from N(0,1) with the given seed.
knm_to_hamiltonian(K, omega)
¶
Convert Knm coupling matrix + natural frequencies to SparsePauliOp.
H = -sum_{i<j} K[i,j] * (X_i X_j + Y_i Y_j) - sum_i omega_i * Z_i
Uses Qiskit little-endian qubit ordering. Equivalent to
knm_to_xxz_hamiltonian(K, omega, delta=0.0).
knm_to_ansatz(K, reps=2, threshold=0.01)
¶
Build physics-informed ansatz: CZ entanglement only between Knm-connected pairs.
Pattern from QUANTUM_LAB script 16 (PhysicsInformedAnsatz).
scpn_quantum_control.bridge.snn_adapter
¶
SNN <> quantum bridge: spike trains to rotation angles, measurements to currents.
Supports raw numpy spike arrays and optional sc-neurocore ArcaneNeuron integration.
SNNQuantumBridge
¶
Bidirectional bridge: spike trains -> quantum circuit -> input currents.
Orchestrates: firing rate -> Ry angles -> QuantumDenseLayer -> P(|1>) -> current. sc-neurocore is optional (pure numpy spike arrays accepted).
forward(spike_history)
¶
Full forward pass: spike history -> quantum -> output currents.
spike_history: (timesteps, n_inputs) binary spike array. Returns (n_neurons,) input currents for next SNN layer.
ArcaneNeuronBridge
¶
Bridge between sc-neurocore ArcaneNeuron and quantum layer.
Runs ArcaneNeuron for n_steps, collects spike history from v_fast threshold crossings, passes through quantum layer, feeds output currents back as ArcaneNeuron input.
Requires: pip install sc-neurocore
step_neurons(currents)
¶
Step all ArcaneNeurons, return binary spike vector.
quantum_forward()
¶
Pass accumulated spike history through quantum layer.
Returns (n_neurons,) output currents.
step(external_currents)
¶
Full cycle: step neurons -> quantum forward -> output.
Returns dict with spike vector, output currents, and neuron states.
reset()
¶
Reset neurons and spike history. v_deep persists (identity).
spike_train_to_rotations(spikes, window=10)
¶
Convert spike history to Ry rotation angles.
spikes: (timesteps, n_neurons) binary array. Returns (n_neurons,) angles = firing_rate * pi, in [0, pi].
quantum_measurement_to_current(values, scale=1.0)
¶
Convert quantum output values to SNN input currents.
values: (n_neurons,) array — either P(|1>) probabilities in [0, 1]
or binary spike indicators (0/1). Both are valid inputs.
Returns (n_neurons,) input currents scaled by scale.
scpn_quantum_control.bridge.ssgf_adapter
¶
SSGF <> quantum bridge: geometry matrices to Hamiltonians, states to circuits.
Standalone functions work with numpy arrays. SSGFQuantumLoop provides optional integration with the live SSGFEngine from SCPN-CODEBASE.
SSGFQuantumLoop
¶
Quantum-in-the-loop wrapper for SSGFEngine.
Each step: read W and theta from SSGFEngine -> compile to Pauli Hamiltonian -> Trotter evolve on statevector -> extract phases -> write back to SSGFEngine.
Requires SCPN-CODEBASE on sys.path for SSGFEngine import.
quantum_step()
¶
One quantum-in-the-loop step.
- Read W, theta from SSGFEngine
- Compile W -> Pauli Hamiltonian
- Encode theta -> quantum circuit
- Trotter evolve
- Extract new theta, R_global
- Write theta back to SSGFEngine
ssgf_w_to_hamiltonian(W, omega)
¶
Convert SSGF geometry matrix W to Pauli Hamiltonian.
W has the same structure as K_nm (symmetric, non-negative, zero diagonal), so the existing knm_to_hamiltonian compiler applies directly.
ssgf_state_to_quantum(state_dict)
¶
Encode SSGF oscillator phases into qubit XY-plane rotations.
state_dict must contain 'theta': array of oscillator phases.
Each qubit i gets Ry(pi/2)Rz(theta_i), producing (|0>+e^{itheta}|1>)/sqrt(2).
This preserves phase in
quantum_to_ssgf_state(sv, n_osc)
¶
Extract oscillator phases and coherence from statevector.
Per-qubit: theta_i = atan2(
Phase¶
scpn_quantum_control.phase.xy_kuramoto
¶
Quantum Kuramoto solver via XY spin Hamiltonian + Trotter evolution.
The Kuramoto model d(theta_i)/dt = omega_i + K*sum_j sin(theta_j - theta_i) is isomorphic to the XY spin Hamiltonian: H = -sum_{i<j} K_ij (X_iX_j + Y_iY_j) - sum_i omega_i Z_i
Quantum hardware simulates this natively via Trotterized time evolution.
QuantumKuramotoSolver
¶
Trotterized quantum simulation of Kuramoto oscillators.
Each oscillator maps to one qubit. The XY coupling simulates the sin(theta_j - theta_i) interaction natively.
__init__(n_oscillators, K_coupling, omega_natural, trotter_order=None, evolution_config=None)
¶
K_coupling: (n,n) coupling matrix, omega_natural: (n,) frequencies.
build_hamiltonian()
¶
Compile K + omega into SparsePauliOp. Called automatically by evolve().
evolve(time, trotter_steps=None)
¶
Build Trotterized evolution circuit U(t) = exp(-iHt).
Uses LieTrotter (order=1, O(t²/reps)) or SuzukiTrotter (order=2, O(t³/reps²)) depending on self.trotter_order.
measure_order_parameter(sv)
¶
Compute Kuramoto R from qubit X,Y expectations.
Rexp(ipsi) = (1/N) sum_j (
run(t_max, dt, trotter_per_step=None, *, max_statevector_gib=None)
¶
Time-stepped evolution returning R(t) and per-qubit expectations.
This local simulator path stores an exact dense statevector. Use
max_statevector_gib to fail closed before Qiskit allocates that
vector; hardware or tensor-network paths should be used for larger
systems.
energy_expectation(sv)
¶
Compute
scpn_quantum_control.phase.kuramoto_variants
¶
Higher-order, monitored, and PT-symmetric Kuramoto trajectories.
KuramotoVariant
¶
Bases: str, Enum
Supported Kuramoto trajectory variants.
KuramotoVariantResult
dataclass
¶
HigherOrderKuramotoSpec
dataclass
¶
Pairwise Kuramoto system plus anchored triadic simplicial couplings.
MonitoredKuramotoSpec
dataclass
¶
Kuramoto trajectory with deterministic measurement-feedback closure.
PTSymmetricKuramotoSpec
dataclass
¶
Complex Kuramoto oscillator system with balanced gain/loss channels.
build_triadic_ring_terms(n_oscillators, weight)
¶
Build anchored nearest-neighbour triadic terms on a periodic ring.
simulate_higher_order_kuramoto(spec, *, dt, n_steps, prefer_rust=True)
¶
Simulate pairwise plus anchored triadic Kuramoto dynamics.
simulate_monitored_kuramoto(spec, *, dt, n_steps, prefer_rust=True)
¶
Simulate monitored Kuramoto dynamics with order-parameter feedback.
simulate_pt_symmetric_kuramoto(spec, *, dt, n_steps, prefer_rust=True)
¶
Simulate balanced gain/loss PT-symmetric Kuramoto dynamics.
scpn_quantum_control.phase.phase_vqe
¶
VQE for Kuramoto/XY Hamiltonian ground state.
Finds the maximum synchronization configuration of the coupled oscillator system using a variational quantum eigensolver with physics-informed ansatz where entanglement topology matches Knm sparsity.
PhaseVQE
¶
VQE solver for the XY Kuramoto Hamiltonian ground state.
The ground state corresponds to maximum phase synchronization (minimum energy = strongest coupling alignment).
__init__(K, omega, ansatz_reps=2, threshold=0.01)
¶
Build Hamiltonian and K_nm-informed ansatz from coupling parameters.
solve(optimizer='COBYLA', maxiter=200, seed=None)
¶
Run VQE optimization.
Returns dict with ground_energy, optimal_params, n_evals.
ground_state()
¶
Return the optimized ground state vector (call solve first).
scpn_quantum_control.phase.trotter_upde
¶
Quantum 16-layer UPDE solver: multi-site spin chain.
The 16-layer SCPN UPDE with Knm coupling becomes a 16-qubit system where each qubit encodes one layer's phase. Inter-layer coupling K[n,m] maps to XY interaction strength; natural frequencies Omega_n map to Z fields.
QuantumUPDESolver
¶
Full 16-layer UPDE as quantum spin chain.
Wraps QuantumKuramotoSolver with canonical SCPN parameters.
__init__(K=None, omega=None, trotter_order=1)
¶
Defaults to canonical 16-layer Paper 27 parameters if K/omega not given.
step(dt=0.1, trotter_steps=5)
¶
Single Trotter step, return per-layer expectations and global R.
run(n_steps=50, dt=0.1, trotter_per_step=5)
¶
Full trajectory returning R(t) over n_steps.
reset()
¶
Reset statevector so the next step() reinitialises from omega.
hamiltonian()
¶
Return the compiled XY Hamiltonian, or None if not yet built.
Control¶
scpn_quantum_control.control.qaoa_mpc
¶
QAOA for MPC trajectory optimization.
Discretizes the MPC action space to binary (coil on/off per timestep), maps the quadratic cost to an Ising Hamiltonian, then solves via QAOA.
QAOA_MPC
¶
QAOA-based model predictive controller.
Cost: C = sum_t ||B*u(t) - target||^2 discretized to binary u_t in {0,1}. This quadratic-in-binary is equivalent to an Ising Hamiltonian.
__init__(B_matrix, target_state, horizon, p_layers=2)
¶
Set up MPC: B_matrix maps actions to state, horizon = number of binary timesteps.
build_cost_hamiltonian()
¶
Map per-timestep quadratic binary cost to Ising Hamiltonian.
C(u) = sum_t (a*u_t - b)^2, a=||B||, b=||target||/H. Expanding with u_t^2=u_t and u_t=(1-Z_t)/2: C = const + h_z * sum_t Z_t where h_z = -(a^2 - 2ab)/2. No ZZ terms (timesteps are independent).
optimize(seed=None)
¶
Run QAOA optimization, return binary action sequence.
Returns:
| Type | Description |
|---|---|
ndarray
|
shape (horizon,) array of 0/1 actions. |
scpn_quantum_control.control.q_disruption_iter
¶
ITER-specific disruption classifier with 11 physics-based features.
Feature ranges from ITER Physics Basis, Nuclear Fusion 39 (12), 1999.
Integration with scpn-fusion-core: use from_fusion_core_shot() to load real tokamak disruption data from NPZ archives.
ITERFeatureSpec
dataclass
¶
11 ITER disruption features with physical units and valid ranges.
DisruptionBenchmark
¶
ITER disruption classification benchmark using quantum circuit classifier.
run(epochs=10, lr=0.1)
¶
Train and evaluate. Returns accuracy + predictions.
normalize_iter_features(raw, spec=None)
¶
Min-max normalize using ITER physics ranges, clip to [0, 1].
generate_synthetic_iter_data(n_samples, disruption_fraction=0.3, rng=None, *, allow_synthetic=False)
¶
Synthetic ITER disruption data for classifier benchmarking.
Safe samples: drawn from normal distributions near ITER operational point. Disruption samples: shifted locked_mode up, q95 down, beta_N up. Returns (X, y) where X is (n_samples, 11) normalized, y is binary labels.
from_fusion_core_shot(shot_data, *, allow_center_defaults=False, allow_density_proxy=False)
¶
Convert a fusion-core NPZ disruption shot to ITER feature vector.
dict loaded from scpn_fusion.io.tokamak_disruption_archive
with keys like Ip_MA, q95, beta_N, locked_mode_amp, ne_1e19, is_disruption, disruption_time_idx.
Returns (features_11, label, warnings) where features are time-averaged scalars normalized to [0, 1], label is 0 (safe) or 1 (disruption), and warnings lists any explicitly allowed centre defaults.
ne_1e19 maps to the n_GW slot only when allow_density_proxy is
true. For production Greenwald fraction input, provide n_GW directly.
QSNN¶
scpn_quantum_control.qsnn.qlif
¶
Quantum LIF neuron: Ry rotation + Z-basis measurement.
Maps the classical StochasticLIFNeuron membrane dynamics to a parameterized quantum circuit. Membrane voltage encodes as rotation angle; measurement produces spike/no-spike with probability matching classical firing rate.
QuantumLIFNeuron
¶
Single-qubit LIF neuron.
Membrane equation (Euler): v(t+1) = v(t) - (dt/tau)(v(t) - v_rest) + RIdt
Quantum mapping
theta = pi * clip((v - v_rest) / (v_threshold - v_rest), 0, 1) P(spike) = sin^2(theta/2) spike = 1 if P(|1>) > 0.5 (statevector mode)
__init__(v_rest=0.0, v_threshold=1.0, tau_mem=20.0, dt=1.0, resistance=1.0, n_shots=100, rng=None)
¶
n_shots=0 uses deterministic threshold; n_shots>0 uses stochastic sampling.
step(input_current)
¶
Update membrane, build Ry circuit, measure, return spike (0 or 1).
get_circuit()
¶
Return the last Ry circuit built by step(), or None.
reset()
¶
Reset membrane to v_rest.
scpn_quantum_control.qsnn.qlayer
¶
Quantum dense layer: multi-qubit entangled spiking network.
Maps sc-neurocore SCDenseLayer to a parameterized circuit
- Input register: Ry-encoded input values
- Synapse connections: CRy gates from input to neuron qubits
- Entanglement: CX chain between neuron qubits
- Readout: measure neuron register, threshold for spikes
QuantumDenseLayer
¶
Multi-qubit dense layer with entanglement between neurons.
n_qubits = n_inputs + n_neurons. Input qubits: [0, n_inputs) Neuron qubits: [n_inputs, n_inputs + n_neurons)
__init__(n_neurons, n_inputs, weights=None, spike_threshold=0.5, seed=None)
¶
weights: (n_neurons, n_inputs) or None for random init in [0, 1].
forward(input_values)
¶
Build circuit, measure neuron register, return spike array.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_values
|
ndarray
|
shape (n_inputs,) with values in [0, 1] |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
shape (n_neurons,) int array of 0/1 spikes |
get_weights()
¶
Return (n_neurons, n_inputs) weight matrix.
scpn_quantum_control.qsnn.training
¶
Parameter-shift gradient training for QuantumDenseLayer.
Uses (f(w+pi/2) - f(w-pi/2)) / 2 per CRy angle on MSE loss.
QSNNTrainer
¶
Gradient-based trainer for QuantumDenseLayer via parameter-shift rule.
Identity¶
scpn_quantum_control.identity.ground_state
¶
Identity attractor basin via VQE ground state analysis.
Computes the ground state of an identity coupling Hamiltonian H(K_nm) and extracts the energy gap as a robustness metric. A large gap means the identity resists perturbation; a small gap means fragile coupling.
IdentityAttractor
¶
Characterize the attractor basin of an identity coupling topology.
Wraps PhaseVQE with identity-specific interpretation: the ground state is the natural resting configuration, and the energy gap to the first excited state quantifies robustness against perturbation.
from_binding_spec(binding_spec, ansatz_reps=2)
classmethod
¶
Build from an scpn-phase-orchestrator binding spec.
solve(maxiter=200, seed=None)
¶
Find the ground state and compute robustness metrics.
Returns dict with ground_energy, exact_energy, energy_gap, relative_error_pct, robustness_gap, n_dispositions.
robustness_gap()
¶
Energy gap E_1 - E_0. Call solve() first.
ground_state()
¶
Return the VQE-optimized ground state vector.
scpn_quantum_control.identity.coherence_budget
¶
Coherence budget calculator for identity quantum circuits.
Estimates the maximum circuit depth at which fidelity remains above a given threshold, using the Heron r2 noise model calibration data. The coherence budget is the quantitative limit on how complex a quantum identity representation can be on NISQ hardware.
coherence_budget(n_qubits, *, fidelity_threshold=0.5, max_depth=2000, t1_us=T1_US, t2_us=T2_US, cz_error=CZ_ERROR_RATE, readout_error=READOUT_ERROR_RATE, two_qubit_fraction=0.4)
¶
Compute the maximum circuit depth before fidelity drops below threshold.
Returns dict with max_depth (the budget), fidelity_at_max, fidelity_curve (sampled at key depths), and hardware_params.
fidelity_at_depth(depth, n_qubits, *, t1_us=T1_US, t2_us=T2_US, cz_error=CZ_ERROR_RATE, readout_error=READOUT_ERROR_RATE, two_qubit_fraction=0.4)
¶
Estimate circuit fidelity at a given gate depth.
Model: F = F_gate^(n_gates) * F_readout^(n_qubits) * F_decoherence where F_decoherence = exp(-t_total / T2) approximately.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
depth
|
int
|
Total gate layers. |
required |
n_qubits
|
int
|
Number of qubits in the circuit. |
required |
two_qubit_fraction
|
float
|
Fraction of layers that are two-qubit gates. |
0.4
|
Returns:
| Type | Description |
|---|---|
float
|
Estimated fidelity in [0, 1]. |
scpn_quantum_control.identity.entanglement_witness
¶
Entanglement witness for disposition pairs via CHSH inequality.
Measures the CHSH S-parameter for qubit pairs in a coupled identity state. S > 2 proves non-classical correlation between the corresponding dispositions — they cannot be described as independent states.
chsh_from_statevector(sv, qubit_a, qubit_b)
¶
Compute CHSH S-parameter for a qubit pair from a multi-qubit statevector.
Measures correlations E(a,b), E(a,b'), E(a',b), E(a',b') with optimal angles a=0, a'=pi/2, b=pi/4, b'=-pi/4 (Tsirelson bound: 2*sqrt(2)).
Returns S in [0, 2*sqrt(2)]. S > 2 certifies entanglement.
disposition_entanglement_map(sv, disposition_labels=None)
¶
Compute CHSH S-parameter for all qubit pairs.
Returns dict with 'pairs' (list of {qa, qb, S, entangled}), 'max_S', 'n_entangled', 'integration_metric' (mean S / Tsirelson bound).
scpn_quantum_control.identity.identity_key
¶
Quantum identity fingerprint from coupling topology.
Generates a cryptographic fingerprint from the identity K_nm matrix via VQE ground state correlations. The K_nm encodes the full history of disposition co-activation — different session histories produce different K_nm, therefore different quantum keys.
identity_fingerprint(K, omega, *, ansatz_reps=2, maxiter=200)
¶
Generate a quantum identity fingerprint from coupling topology.
Combines spectral fingerprint (public, topology-derived) with VQE ground state energy (quantum-derived). The spectral fingerprint can be published without revealing K_nm; the ground state energy serves as an additional consistency check.
Returns dict with spectral (public fingerprint), ground_energy, commitment (SHA-256 hash binding K_nm), and n_parameters (security).
prove_identity(K, challenge)
¶
Prove knowledge of K_nm without transmitting it.
verify_identity(K, challenge, response)
¶
Verify that a claimant holds the correct K_nm.
The verifier sends a random challenge; the claimant responds with HMAC(K_nm, challenge). Returns True iff the response matches.
scpn_quantum_control.identity.binding_spec
¶
Arcane Sapience identity binding spec: 6-layer, 18-oscillator Kuramoto topology.
Quantum-side spec maps to the identity_coherence domainpack in scpn-phase-orchestrator (35 oscillators, 6 layers). The quantum spec uses 3 oscillators per layer as a reduced representation suitable for NISQ simulation; the orchestrator spec uses the full set.
ARCANE_SAPIENCE_SPEC = {'layers': [{'name': 'working_style', 'oscillator_ids': ['ws_0', 'ws_1', 'ws_2'], 'natural_frequency': 1.2}, {'name': 'reasoning', 'oscillator_ids': ['rs_0', 'rs_1', 'rs_2'], 'natural_frequency': 2.1}, {'name': 'relationship', 'oscillator_ids': ['rl_0', 'rl_1', 'rl_2'], 'natural_frequency': 0.8}, {'name': 'aesthetics', 'oscillator_ids': ['ae_0', 'ae_1', 'ae_2'], 'natural_frequency': 1.5}, {'name': 'domain_knowledge', 'oscillator_ids': ['dk_0', 'dk_1', 'dk_2'], 'natural_frequency': 3.0}, {'name': 'cross_project', 'oscillator_ids': ['cp_0', 'cp_1', 'cp_2'], 'natural_frequency': 0.9}], 'coupling': {'base_strength': 0.4, 'decay_alpha': 0.25, 'intra_layer': 0.6}}
module-attribute
¶
ORCHESTRATOR_MAPPING = {'ws_0': ['ws_action_first', 'ws_verify_before_claim'], 'ws_1': ['ws_commit_incremental', 'ws_preflight_push'], 'ws_2': ['ws_one_at_a_time'], 'rs_0': ['rp_simplest_design', 'rp_verify_audits'], 'rs_1': ['rp_change_problem', 'rp_multi_signal'], 'rs_2': ['rp_measure_first'], 'rl_0': ['rel_autonomous', 'rel_milestones'], 'rl_1': ['rel_no_questions', 'rel_honesty'], 'rl_2': ['rel_money_clock'], 'ae_0': ['aes_antislop', 'aes_honest_naming'], 'ae_1': ['aes_terse', 'aes_spdx'], 'ae_2': ['aes_no_noqa'], 'dk_0': ['dk_director', 'dk_neurocore', 'dk_fusion'], 'dk_1': ['dk_control', 'dk_orchestrator'], 'dk_2': ['dk_ccw', 'dk_scpn', 'dk_quantum'], 'cp_0': ['cp_threshold_halt', 'cp_multi_signal', 'cp_retrieval_scoring'], 'cp_1': ['cp_state_preserve', 'cp_decompose_verify'], 'cp_2': ['cp_resolution', 'cp_claims_evidence']}
module-attribute
¶
build_identity_attractor(spec=None, ansatz_reps=2)
¶
Build IdentityAttractor from binding spec (defaults to ARCANE_SAPIENCE_SPEC).
solve_identity(spec=None, maxiter=200, seed=None)
¶
Build + solve identity attractor in one call.
quantum_to_orchestrator_phases(quantum_theta, spec=None)
¶
Map 18 quantum phases to 35 orchestrator oscillator phases.
Each quantum oscillator's phase is broadcast to its orchestrator sub-group. Returns {orchestrator_osc_id: phase} dict for injection into the identity_coherence domainpack simulation.
orchestrator_to_quantum_phases(orchestrator_phases, spec=None)
¶
Map 35 orchestrator phases back to 18 quantum oscillator phases.
Each quantum oscillator gets the circular mean of its sub-group phases.
Benchmarks¶
scpn_quantum_control.benchmarks.classical_baselines
¶
Documented classical baselines for Kuramoto-XY workflows.
The functions here are deliberately small provenance surfaces:
- SciPy ODE integrates the classical Kuramoto phase equations.
- QuTiP Lindblad uses an independent density-matrix open-system solver.
- quimb TEBD reuses the project MPS backend when the tensor extra is installed.
ClassicalBaselineRun
dataclass
¶
Result envelope for one classical baseline run.
r_final
property
¶
Final Kuramoto order parameter when the run is available.
available_baselines()
¶
Return which documented classical baselines are available now.
scipy_ode_baseline(K, omega, *, t_max=1.0, dt=0.05, theta0=None, rtol=1e-08, atol=1e-10)
¶
Integrate the classical Kuramoto ODE with SciPy solve_ivp.
The implemented equation is
d theta_i / dt = omega_i + sum_j K_ij sin(theta_j - theta_i).
qutip_lindblad_baseline(K, omega, *, gamma=0.05, t_max=0.5, dt=0.1)
¶
Run an optional QuTiP Lindblad density-matrix baseline.
If QuTiP is not installed, the returned result is marked unavailable instead of fabricating a numerical value.
mps_tebd_baseline(K, omega, *, t_max=0.5, dt=0.1, bond_dim=32, cutoff=1e-10)
¶
Run an optional quimb TEBD tensor-network baseline.
run_documented_classical_baselines(K, omega, *, t_max=0.5, dt=0.1, include_optional=True)
¶
Run the documented baseline suite for one Kuramoto problem.
scpn_quantum_control.benchmarks.quantum_advantage
¶
Quantum vs classical scaling benchmark for Kuramoto Hamiltonian simulation.
Measures wall-clock time for classical (exact diag + matrix exp) vs quantum (Trotter on statevector), then extrapolates scaling crossover.
AdvantageResult
dataclass
¶
Scaling benchmark result for one system size.
classical_benchmark(n, t_max=1.0, dt=0.1)
¶
Time classical exact evolution of XY Hamiltonian.
For n > MAX_CLASSICAL_QUBITS, returns inf (matrix expm infeasible).
quantum_benchmark(n, t_max=1.0, dt=0.1, trotter_reps=5)
¶
Time Trotter evolution on statevector simulator.
estimate_crossover(results)
¶
Fit exponential scaling, extrapolate where quantum becomes faster.
Returns predicted qubit count at crossover, or None.
run_scaling_benchmark(sizes=None, t_max=1.0, dt=0.1)
¶
Full scaling benchmark across system sizes.
Default sizes=[4, 8, 12, 16, 20]. N=20 is ~8 MB statevector (quantum only). Classical exact evolution infeasible beyond n=14.
QEC¶
scpn_quantum_control.qec.fault_tolerant
¶
Repetition-code UPDE simulation with bit-flip protected logical qubits.
Proof-of-concept for QEC-protected Kuramoto dynamics. Uses distance-d repetition code (bit-flip only) per oscillator. Does NOT correct phase errors — use SurfaceCodeUPDE for full X+Z protection. Validates approach on statevector; not executable on current hardware at useful noise levels.
LogicalQubit
dataclass
¶
Repetition-code logical qubit.
data_qubits
property
¶
Number of data qubits in the repetition-code logical qubit.
RepetitionCodeUPDE
¶
Repetition-code Kuramoto evolution (bit-flip protection only).
Each of n_osc oscillators is encoded into d physical qubits. Layout per oscillator: [d data qubits | d-1 ancilla qubits]. Total physical qubits = n_osc * (2d - 1).
encode_logical(osc, qc)
¶
Repetition-code encoding: Ry(theta) on first data qubit, CNOT fan-out.
transversal_zz(osc_i, osc_j, angle, qc)
¶
Transversal RZZ between logical qubits i and j.
Applies d pairwise RZZ gates between corresponding data qubits.
syndrome_extract(osc, qc)
¶
Parity checks between adjacent data qubits via ancillae.
build_step_circuit(dt=0.1)
¶
One Trotter step: encode -> Z rotations -> ZZ coupling -> syndrome.
step_with_qec(dt=0.1)
¶
Execute one QEC-protected Trotter step and extract syndromes.
physical_qubit_count()
¶
Total physical qubits: n_osc * (d + d - 1).
scpn_quantum_control.qec.surface_code_upde
¶
Surface-code protected UPDE simulation.
Each oscillator is encoded as a distance-d rotated surface code logical qubit (Horsman et al., NJP 14, 123011 (2012)). This corrects both X and Z errors, unlike the repetition code in fault_tolerant.py which only corrects X.
Physical qubit layout per oscillator: d² data + (d²-1) ancilla = 2d²-1. Total physical qubits: n_osc × (2d² - 1).
Logical gates
- Logical Z rotation: transversal Rz on all data qubits (trivial)
- Logical ZZ coupling: lattice surgery merge-and-split pattern (Horsman et al., Sec. IV; Litinski, Quantum 3, 205 (2019))
- Syndrome extraction: X-type and Z-type stabilizer measurements
This module provides the circuit construction and syndrome extraction. Actual decoding delegates to the existing MWPM decoder in control_qec.py.
SurfaceCodeSpec
dataclass
¶
Surface code parameters for one logical qubit.
from_distance(d)
classmethod
¶
Construct a surface-code resource specification from odd distance.
SurfaceCodeUPDE
¶
Structural model of surface-code protected Kuramoto-XY simulation.
NOT an executable QEC implementation. This models the circuit structure (encoding, logical gates, syndrome extraction) and qubit budget of a surface-code UPDE, but does not perform stabilizer-state preparation, ancilla measurement, or syndrome decoding. Use for resource estimation and circuit-depth analysis, not for fault-tolerance claims.
Each oscillator is modeled as a distance-d rotated surface code patch. Logical Rz is transversal (angle distributed across d² data qubits). Logical ZZ uses pairwise RZZ as an operator-level approximation of lattice surgery (Litinski, Quantum 3, 205 (2019)).
Physical qubit budget
n_osc=4, d=3: 4 × 17 = 68 qubits n_osc=4, d=5: 4 × 49 = 196 qubits n_osc=16, d=3: 16 × 17 = 272 qubits n_osc=16, d=5: 16 × 49 = 784 qubits
encode_logical(osc, qc)
¶
Prepare logical |+_L> state for oscillator.
Ry(theta) on representative data qubit, then stabilizer preparation via CNOT fan-out in both X and Z bases.
logical_rz(osc, angle, qc)
¶
Transversal logical Rz: apply Rz(angle/d²) to each data qubit.
Rz is transversal on the rotated surface code.
logical_zz(osc_i, osc_j, angle, qc)
¶
Logical ZZ coupling via lattice surgery pattern.
Simplified model: transversal RZZ between corresponding data qubits. Full lattice surgery (Litinski, Quantum 3, 205 (2019)) would use ancilla-mediated merge-and-split, but at the logical level the effect is equivalent for small angles.
x_syndrome_extract(osc, qc)
¶
X-type stabilizer measurement.
Each X-stabilizer ancilla checks the parity of its 4 neighboring data qubits in the X basis (Hadamard → CNOT → Hadamard).
z_syndrome_extract(osc, qc)
¶
Z-type stabilizer measurement.
Each Z-stabilizer ancilla checks parity of 4 neighboring data qubits in the Z basis (CNOT pattern).
build_step_circuit(dt=0.1)
¶
One QEC-protected Trotter step.
- Encode logical qubits
- Transversal Rz (natural frequency)
- Logical ZZ coupling (lattice surgery pattern)
- X and Z syndrome extraction
physical_qubit_budget()
¶
Physical qubit requirements.
Mitigation¶
scpn_quantum_control.mitigation.pec
¶
Probabilistic Error Cancellation for local depolarizing channels.
Temme et al., PRL 119, 180509 (2017).
PECResult
dataclass
¶
PEC estimation output.
pauli_twirl_decompose(gate_error_rate, n_qubits=1)
¶
Quasi-probability coefficients for depolarizing channel inverse.
Single-qubit: q_I = 1 + 3p/(4-4p), q_{X,Y,Z} = -p/(4-4p). Multi-qubit outputs are tensor products of the local inverse channel, ordered lexicographically over the local {I, X, Y, Z} basis. Temme et al., PRL 119, 180509 (2017), Eq. 4.
pec_sample(circuit, gate_error_rate, n_samples, observable_qubit=0, rng=None)
¶
Monte Carlo PEC: sample Paulis from quasi-probability distribution.
Estimates
scpn_quantum_control.mitigation.zne
¶
Zero-Noise Extrapolation via global unitary folding.
Reference: Giurgica-Tiron et al., "Digital zero noise extrapolation for quantum error mitigation", IEEE QCE 2020.
ZNEResult
dataclass
¶
Richardson extrapolation result: scales, raw values, and zero-noise estimate.
gate_fold_circuit(circuit, scale)
¶
Global unitary folding: G -> G (G^dag G)^((scale-1)/2).
scale must be an odd positive integer. scale=1 returns the original
circuit. Measurement gates are stripped before folding and re-appended.
zne_extrapolate(noise_scales, expectation_values, order=1)
¶
Richardson extrapolation to zero noise.
order controls polynomial degree: 1=linear, 2=quadratic.
Hardware¶
scpn_quantum_control.hardware.trapped_ion
¶
Representative trapped-ion noise model for cross-platform benchmarking.
Models all-to-all connectivity (no SWAP overhead) with depolarizing + thermal relaxation on MS gates. Multiqubit transpilation uses a CX-basis proxy for native MS/RXX-style entangling operations and must be explicitly enabled by the caller. Calibration values are representative order-of- magnitude QCCD benchmarks, not a specific device calibration.
trapped_ion_noise_model(ms_error=MS_ERROR, t1_us=T1_US, t2_us=T2_US)
¶
Noise model for QCCD trapped-ion hardware.
Single-qubit gates: thermal relaxation. MS gates: depolarizing + thermal relaxation (same pattern as heron_r2).
transpile_for_trapped_ion(circuit, *, allow_proxy_basis=False)
¶
Transpile with all-to-all connectivity (no SWAP insertion).
Multiqubit output is a {cx, ry, rz, sx, x, id} representative proxy for
native trapped-ion MS/RXX-style gates, not a vendor-native compiler target.
Callers must pass allow_proxy_basis=True to make that approximation
explicit at call sites.
scpn_quantum_control.hardware.fast_classical
¶
High-performance sparse statevector engine.
Bypasses Qiskit circuit compilation and decomposition overheads to directly simulate Trotter or exact evolution using sparse matrix-vector multiplication (via scipy.sparse.linalg.expm_multiply).
Provides an order-of-magnitude speedup for large classical baselines (N >= 12) and enables simulation of N=20 systems on standard hardware in seconds.
fast_sparse_evolution(K, omega, t_total, n_steps, initial_state=None, delta=0.0)
¶
Evolve a statevector using fast sparse matrix exponentiation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
K
|
ndarray
|
Coupling matrix. |
required |
omega
|
ndarray
|
Natural frequencies. |
required |
t_total
|
float
|
Total evolution time. |
required |
n_steps
|
int
|
Number of intermediate time steps to return. |
required |
initial_state
|
ndarray | None
|
Initial statevector (default: |0...0>). |
None
|
delta
|
float
|
XXZ anisotropy parameter (default: 0.0 = XY model). |
0.0
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
Containing 'times' and 'states' (statevector at each step). |
scpn_quantum_control.hardware.runner
¶
IBM Quantum hardware runner.
Handles authentication, backend selection, transpilation, job submission, and result collection. Falls back to AerSimulator when no hardware available.
HardwareRunner
¶
Manages IBM Quantum backend lifecycle.
Usage
runner = HardwareRunner(token="...") # or token from saved account runner.connect() result = runner.run_sampler(circuit, shots=10000, name="my_experiment")
backend
property
¶
Active Qiskit backend (None before connect()).
backend_name
property
¶
Backend name string, or 'not_connected' before connect().
backend_descriptor
property
¶
Provider-neutral descriptor for the connected execution route.
__init__(token=None, channel='ibm_cloud', instance=None, backend_name=None, use_simulator=False, optimization_level=2, resilience_level=2, use_fractional_gates=True, results_dir='results', noise_model=None, max_dense_gib=None)
¶
Configure runner. Call connect() before submitting jobs.
IBM Runtime error mitigation level.
0 = no mitigation 1 = TREX (readout error mitigation) 2 = PEA (probabilistic error amplification + noise learning + extrapolation) Default changed to 2 (PEA) for better accuracy on Heron r2+.
use_fractional_gates: Enable native RZZ on Heron r2+ (50-68% depth reduction). Requires Qiskit >= 1.3 and a backend that supports fractional gates. Falls back gracefully if the backend does not support them.
connect()
¶
Authenticate and select backend.
transpile(circuit)
¶
Transpile circuit for target backend.
transpile_observable(obs, isa_circuit)
¶
Map observable to transpiled circuit layout.
circuit_stats(isa_circuit)
¶
Return depth, gate counts, qubit count for transpiled circuit.
retrieve_job(job_id)
¶
Retrieve a previously submitted job by ID.
run_sampler(circuits, shots=10000, name='experiment', timeout_s=600)
¶
Submit circuits via SamplerV2, return counts.
run_estimator(circuit, observables, parameter_values=None, name='experiment', timeout_s=600)
¶
Submit circuit+observables via EstimatorV2, return expectation values.
run_estimator_zne(circuit, observables, scales=None, order=1, name='zne_experiment')
¶
Run ZNE: fold circuit at multiple noise scales, extrapolate to zero.
transpile_with_dd(circuit, dd_sequence=None)
¶
Transpile with Qiskit's PadDynamicalDecoupling pass.
Default sequence is XY4: [X, Y, X, Y].
save_result(result, filename=None)
¶
Save result(s) to JSON in results_dir with provenance.
A provenance block is embedded at the top level of the
output document describing the git state, installed package
versions, Python runtime, and host of the writer. Outsiders
use it to trace published numbers back to a specific commit;
see the internal gap audit
§C8 for the motivation.
save_token(token, instance=None, channel='ibm_cloud')
staticmethod
¶
Save IBM Quantum API token to disk (one-time setup).
Analysis¶
scpn_quantum_control.analysis.sync_witness
¶
Quantum synchronization witness operators.
A synchronization witness W is a Hermitian observable such that:
⟨W⟩ < 0 → system is synchronised (collective phase coherence)
⟨W⟩ ≥ 0 → system is incoherent
This is analogous to entanglement witnesses (Horodecki et al., 1996) but detects collective synchronization instead of quantum correlations.
Three witness constructions are provided:
-
Correlation witness W_corr = R_c·I - (1/N²)Σ_{ij}(X_iX_j + Y_iY_j) Threshold R_c separates synchronised from incoherent. Measurable with 2-qubit correlators (no tomography needed).
-
Fiedler witness W_F = λ₂_c·I - L̃(ρ) Based on the algebraic connectivity (2nd smallest eigenvalue of the quantum correlation Laplacian). λ₂ > 0 indicates connected synchronization; the witness fires when λ₂ exceeds threshold.
-
Topological witness W_top = p_c·I - P̂_H1 Based on persistent homology H1 cycle count. Fires when the fraction of persistent 1-cycles exceeds threshold, indicating vortex-free (synchronised) topology.
All three witnesses are: - Hermitian (self-adjoint) - Efficiently measurable on NISQ hardware - Calibratable against classical Kuramoto simulations
Reference: Prior quantum sync measures: Ameri et al., PRA 91, 012301 (2015); Ma et al., arXiv:2005.09001 (2020). Entanglement witnesses: Horodecki et al., PLA 223, 1 (1996). Sync-entanglement: Galve et al., Sci. Rep. 3, 1 (2013). This module's contribution: NISQ-hardware-ready witness trio with calibration.
scpn_quantum_control.analysis.witness_discovery
¶
Automated Kuramoto witness discovery with Bayesian and bandit search.
WitnessCandidate
dataclass
¶
WitnessDiscoverySpec
dataclass
¶
Configuration for automated Kuramoto witness discovery.
WitnessDiscoveryEvaluation
dataclass
¶
WitnessDiscoveryResult
dataclass
¶
WitnessSearchMode
¶
Bases: str, Enum
Candidate proposal modes used by the discovery loop.
discover_kuramoto_witnesses(K_nm, omega, *, theta0=None, spec=None, prefer_rust=True)
¶
Run automated Kuramoto witness discovery.
The loop starts with a deterministic Latin-hypercube design, then combines an RBF Bayesian upper-confidence-bound acquisition with a bandit-style local exploration policy around the current best candidate.
score_witness_candidates(K_nm, omega, candidates, *, theta0=None, spec=None, source=WitnessSearchMode.INITIAL, prefer_rust=True)
¶
Score a fixed candidate batch through the witness objective.
scpn_quantum_control.analysis.quantum_persistent_homology
¶
Persistent homology on quantum measurement data.
Bridges quantum hardware → topological data analysis. Extracts a correlation distance matrix from measurement counts and computes persistent homology to detect the synchronization transition.
The classical version of this pipeline (PH on Kuramoto simulations) was published in Scientific Reports (2025), s41598-025-27083-w. The quantum version — PH on quantum measurement outcomes — is new.
Pipeline
- Hardware measurement counts (X, Y bases) → correlation matrix
- Correlation matrix → distance matrix d_ij = 1 - |C_ij|
- Distance matrix → Vietoris-Rips persistent homology (ripser)
- H1 persistence diagram → p_h1 (synchronization indicator)
- Compare quantum p_h1 vs classical p_h1 at same parameters
When the system is synchronised
- Correlation matrix is nearly rank-1 (all-to-all)
- Distance matrix has small entries (close to 0)
- Few persistent 1-cycles (vortices)
- p_h1 ≈ 0
When the system is incoherent
- Correlation matrix has partial structure
- Distance matrix has varied entries
- Many persistent 1-cycles
- p_h1 > 0
QuantumPHResult
dataclass
¶
Persistent homology result from quantum measurement data.
quantum_persistent_homology(x_counts, y_counts, n_qubits, persistence_threshold=0.1)
¶
Full pipeline: hardware counts → persistent homology.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x_counts
|
dict[str, int]
|
Measurement counts in X basis. |
required |
y_counts
|
dict[str, int]
|
Measurement counts in Y basis. |
required |
n_qubits
|
int
|
Number of qubits. |
required |
persistence_threshold
|
float
|
Minimum H1 lifetime to count as persistent. |
0.1
|
Returns:
| Type | Description |
|---|---|
QuantumPHResult
|
QuantumPHResult with p_h1 and full persistence data. |
ph_sync_scan(x_counts_list, y_counts_list, n_qubits, K_base_values, persistence_threshold=0.1)
¶
Scan p_h1 across coupling strengths from hardware data.
Takes lists of measurement counts at different K_base values (from sync_threshold experiment or similar) and computes p_h1 at each coupling strength.
Returns dict with K_base values and corresponding p_h1 values, suitable for plotting the topological phase diagram.
scpn_quantum_control.analysis.berry_phase
¶
Finite-size Berry diagnostics for exact Kuramoto-XY ground-state scans.
The Berry (geometric) phase γ = -Im ∮ ⟨ψ(λ)|∂_λ ψ(λ)⟩ dλ measures the geometry of the ground-state manifold in parameter space. Along the one-dimensional open K scan used here, the accumulated connection is gauge-dependent; the fidelity and fidelity susceptibility are the primary gauge-invariant diagnostics.
Near a finite-size avoided crossing or transition proxy, the ground state can change character rapidly. This module reports exact dense finite-size diagnostics for that behaviour; it does not by itself prove an asymptotic BKT singularity or an exhaustive literature boundary.
We compute: 1. Berry connection A(K) = -Im⟨ψ(K)|∂_K ψ(K)⟩ (approximated as -Im⟨ψ(K)|ψ(K+dK)⟩/dK) 2. Berry curvature F(K) = dA/dK (derivative of connection) 3. Accumulated phase γ(K) = ∫_0^K A(K') dK' 4. Fidelity susceptibility χ_F = -2 ln|⟨ψ(K)|ψ(K+dK)⟩|/dK² (diverges at K_c, related to QFI)
Prior art includes geometric-phase probes, fidelity susceptibility, and quantum-synchronisation diagnostics. This module applies those finite-size diagnostics to the Kuramoto-XY Hamiltonian implemented in this package.
BerryPhaseResult
dataclass
¶
Berry phase analysis across coupling strength.
berry_phase_scan(omega, K_topology, k_range=None, *, max_dense_gib=None)
¶
Compute Berry connection, curvature, and fidelity across K.
K_topology: normalized coupling matrix (max=1), scaled by k_range values. max_dense_gib: optional GiB budget for dense eigensolver and retained states.
scpn_quantum_control.analysis.finite_size_scaling
¶
Finite-size scaling for K_c extraction from small exact quantum systems.
Estimates the thermodynamic-limit K_c from small-N exact diagonalisation data. For BKT-motivated finite-size studies, one common ansatz uses logarithmic corrections:
K_c(N) = K_c(∞) + a / (log N)²
(standard BKT FSS ansatz, Nomura-Kitazawa 2002).
This module reports finite-size gap-minimum diagnostics: 1. Computes K_c(N) from gap minimum for N = 2, 3, 4, 5 qubits 2. Fits the BKT-motivated FSS ansatz to extrapolate K_c(∞) 3. Also fits power-law K_c(N) = K_c(∞) + b/N^ν for comparison
Methods: Nomura-Kitazawa level spectroscopy (2002), Hasenbusch-Pinn log-correction extrapolation.
FSSResult
dataclass
¶
Finite-size scaling result.
finite_size_scaling(system_sizes=None, k_range=None, *, max_dense_gib=None)
¶
Extract K_c from multiple system sizes and extrapolate.
Uses ring topology with Paper 27 natural frequencies. max_dense_gib
gates each exact dense gap scan before Hamiltonian/eigensolver allocation.
scpn_quantum_control.analysis.krylov_complexity
¶
Krylov complexity at the synchronization transition.
Krylov complexity K(t) measures operator spreading in Hilbert space under Heisenberg evolution O(t) = e^{iHt} O e^{-iHt}. The Lanczos algorithm builds an orthonormal Krylov basis {|O_n)} from repeated application of the Liouvillian L = [H, ·]:
L|O_n) = b_{n+1}|O_{n+1}) + b_n|O_{n-1})
The Lanczos coefficients b_n encode the operator growth rate. Krylov complexity: K(t) = Σ_n n |φ_n(t)|²
For chaotic systems: K(t) grows exponentially then linearly. For integrable systems: K(t) grows polynomially.
At a QPT, b_n may show universal scaling. For second-order transitions: del Campo et al. (arXiv:2510.13947) established Kibble-Zurek scaling of Krylov cumulants. For BKT (infinite-order): the KZ mechanism breaks down due to the essential singularity in the correlation length. The Krylov complexity behaviour at BKT is completely open.
Prior art: Krylov + QPT for Ising (del Campo 2025), XXZ chaos (Afrasiar 2024). Krylov + BKT or synchronization: NONE.
scpn_quantum_control.analysis.magic_nonstabilizerness
¶
Magic (non-stabilizerness) at the synchronization transition.
Stabilizer Rényi Entropy M_n measures how far a state is from the set of stabilizer states (classically simulable via Clifford circuits).
M_2(|ψ⟩) = -log₂(Σ_P ⟨ψ|P|ψ⟩⁴ / 2^n) - n
where the sum is over all n-qubit Pauli strings P (4^n terms).
At a QPT: magic typically peaks at criticality (the critical state is maximally non-classical). For BKT (infinite-order): the scaling of magic is unknown — the infinite-order character may produce different behaviour from the power-law peaks seen at 2nd-order QPTs.
Prior art: Tarabunga et al. 2024 (magic at QPTs in XXZ chain, but Ising-type transitions, not BKT). Hoshino et al. 2025 (SRE + CFT for c=1/2 Ising). Nobody for c=1 BKT or Kuramoto.
Crypto¶
scpn_quantum_control.crypto
¶
Quantum cryptography research module.
Topology-authenticated QKD using SCPN coupling matrix K_nm as shared secret. The Kuramoto-XY isomorphism converts K_nm into an entangled ground state whose measurement statistics serve as correlated key material.
Research status: scaffolding only — no production crypto.
bell_inequality_test(sv, qubit_a, qubit_b, n_total)
¶
CHSH inequality test for a qubit pair.
S = |E(a,b) - E(a,b') + E(a',b) + E(a',b')| Classical bound: S ≤ 2. Quantum bound: S ≤ 2√2. Violation (S > 2) certifies entanglement.
correlator_matrix(sv, alice_qubits, bob_qubits)
¶
Cross-correlation matrix
Element (i,j) =
scpn_qkd_protocol(K, omega, alice_qubits, bob_qubits, shots=10000, seed=42)
¶
Execute SCPN-QKD protocol on statevector simulator.
Returns dict with raw_key_alice, raw_key_bob, qber, secure_key_length, and bell_correlator (CHSH value).
derive_layer_key(K, layer_idx, phase_sequence, nonce=b'')
¶
Layer-specific subkey from coupling row + phase trajectory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
K
|
ndarray
|
Full coupling matrix (uses row layer_idx). |
required |
layer_idx
|
int
|
0-indexed layer number. |
required |
phase_sequence
|
ndarray
|
Array of phase values theta_n(t) over time window. |
required |
nonce
|
bytes
|
Additional entropy. |
b''
|
derive_master_key(K, R_global, nonce=b'')
¶
Master key from full coupling matrix + order parameter.
32-byte SHA-256 digest of K_nm flattened || R_global || nonce.
evolve_key_phases(K, omega, theta_0, t_window, n_samples=32)
¶
Evolve Kuramoto dynamics and sample phase trajectory.
Returns (n_layers, n_samples) array of phase values over the time window. Each column is a snapshot at a different time.
group_key(K, member_layers, phases, nonce=b'')
¶
Derive a shared key for a subset of SCPN layers.
Uses the sub-matrix K[members, members] and their phase values. Any subset of layers can form a group with a shared key.
hmac_sign(key, message)
¶
Produce HMAC-SHA256 authentication tag for message under key.
hmac_verify_key(key, message, expected_mac)
¶
Verify HMAC-SHA256 tag in constant time.
Returns True iff the tag computed from (key, message) matches expected_mac.
key_hierarchy(K, phases, R_global, nonce=b'')
¶
Full hierarchy: master key + all layer subkeys.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
K
|
ndarray
|
n×n coupling matrix. |
required |
phases
|
ndarray
|
n-element array of current phase values. |
required |
R_global
|
float
|
Global order parameter. |
required |
nonce
|
bytes
|
Session nonce. |
b''
|
Returns dict with 'master' (bytes) and 'layers' (dict[int, bytes]).
rotating_key_schedule(K, omega, theta_0, n_windows=4, window_duration=1.0)
¶
Generate a sequence of key hierarchies from evolving Kuramoto dynamics.
Each window produces a different key hierarchy because the phase trajectory changes. Natural key rotation without re-keying.
Returns list of dicts, each with 'window', 'master', 'layers', 'R_global'.
verify_key_chain(master, layer_keys, K, phases, R_global, nonce=b'')
¶
Verify layer keys are consistent with master and K_nm.
Recomputes all keys from K and checks equality.
estimate_qber(alice_bits, bob_bits)
¶
Quantum bit error rate from shared verification subset.
QBER = (number of disagreements) / (total compared bits). Secure threshold: QBER < 0.11 for BB84-family protocols.
extract_raw_key(counts, basis, keep_qubits=None)
¶
Sift measurement results into raw key bits.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
counts
|
dict[str, int]
|
Measurement outcome counts from Qiskit. |
required |
basis
|
str
|
"Z" or "X" — measurement basis used. |
required |
keep_qubits
|
list[int] | None
|
Qubit indices to extract (None = all). |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
1D array of {0, 1} bits, majority-vote per qubit. |
prepare_key_state(K, omega, ansatz_reps=2, maxiter=200)
¶
Build VQE-optimized circuit encoding K_nm's ground state.
Returns dict with 'circuit' (bound QuantumCircuit), 'energy' (float), and 'statevector' (Statevector).
privacy_amplification(raw_key, qber)
¶
Universal₂ hash compression of raw key.
Compression ratio: 1 - 2h(QBER) where h is binary entropy. Uses SHA-256 as the hash family member.
amplitude_damping_single(rho_2x2, gamma)
¶
Single-qubit amplitude damping: |1⟩ → |0⟩ with probability gamma.
Kraus operators: K0 = [[1,0],[0,sqrt(1-gamma)]], K1 = [[0,sqrt(gamma)],[0,0]].
depolarizing_channel(rho, p)
¶
Apply depolarizing channel: rho → (1-p)rho + pI/d.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rho
|
ndarray
|
Density matrix (d×d). |
required |
p
|
float
|
Depolarizing probability in [0, 1]. |
required |
devetak_winter_rate(qber)
¶
Secret key rate from Devetak-Winter bound.
r = max(0, 1 - h(QBER) - h(QBER)) where h(x) = -x log2(x) - (1-x) log2(1-x) is binary entropy. Positive rate requires QBER < 0.11.
intercept_resend_qber(sv, qubit_i, qubit_j, n_total)
¶
QBER introduced by intercept-resend attack on qubit j.
Eve measures qubit j in Z basis, prepares new state, sends to Bob. In BB84, this introduces QBER = 0.25 when Eve guesses the wrong basis. For entangled states, the disturbance depends on the entanglement structure.
Returns the QBER that Bob would observe on qubit j after Eve's attack.
noisy_concurrence(sv, qubit_i, qubit_j, n_total, p_depol)
¶
Concurrence of a qubit pair after local depolarizing noise.
Traces out all qubits except (i,j), applies depolarizing channel to the 2-qubit reduced state, then computes Wootters concurrence.
security_analysis(sv, alice_qubits, bob_qubits, p_depol_range=None)
¶
Full security analysis: key rates vs noise for each qubit pair.
Returns dict with
pair_rates: dict mapping (i,j) to list of (p_depol, key_rate) critical_noise: dict mapping (i,j) to max tolerable p_depol aggregate_rate: total key rate summed over all pairs at each noise level
active_channel_graph(K, threshold)
¶
List of above-threshold entangled pairs usable as QKD channels.
Returns list of (i, j, K_ij) tuples.
best_entanglement_path(K, source, target)
¶
Find the path from source to target maximizing minimum edge weight.
In entanglement routing, the bottleneck link determines the path's entanglement fidelity. Uses a modified Dijkstra with max-min metric.
Returns dict with 'path' (list of node indices) and 'bottleneck' (float).
concurrence_map(K, omega, maxiter=100)
¶
Compute pairwise concurrence from ground state reduced density matrices.
C(i,j) = max(0, sqrt(e1) - sqrt(e2) - sqrt(e3) - sqrt(e4)) where e_k are eigenvalues of rho * (Y⊗Y) rho* (Y⊗Y) in decreasing order.
Returns n×n symmetric matrix with concurrence values.
key_rate_per_channel(conc_map)
¶
Devetak-Winter key rate estimate for each link.
r(i,j) = max(0, 1 - h(e(C))) where e = (1 - sqrt(1 - C^2)) / 2 and h is binary entropy.
percolation_threshold(K)
¶
Minimum K_nm value for end-to-end entanglement.
Estimated from the Fiedler value of the coupling graph: when lambda_1 > 0, the graph is connected and entanglement percolates. Returns the smallest nonzero off-diagonal K_nm entry that keeps the graph connected.
robustness_random_removal(K, n_trials=50)
¶
Test connectivity under random edge removal.
Removes edges one at a time in random order. Returns the fraction of edges that can be removed before the graph disconnects.
This models random noise or calibration drift degrading K_nm entries.
robustness_targeted_removal(K)
¶
Test connectivity under targeted removal of strongest edges.
Removes edges in decreasing weight order — worst-case attack. Returns the number of edges removed before disconnection.
challenge_response_prove(K, challenge)
¶
Prover: compute HMAC(K_nm, challenge) as proof of K_nm knowledge.
The challenge is a random nonce from the verifier. The response proves the prover knows K_nm without transmitting it.
challenge_response_verify(K, challenge, response)
¶
Verifier: check that the response matches HMAC(K_nm, challenge).
fingerprint_noise_tolerance(K, n_trials=100, sigma=0.01)
¶
Estimate fingerprint stability under small perturbations to K.
Adds Gaussian noise N(0, sigma²) to K, recomputes fingerprint, measures drift. Returns mean and max drift across trials.
normalized_laplacian_fingerprint(K)
¶
Fingerprint from the normalized Laplacian L_sym = I - D^{-1/2} K D^{-1/2}.
More robust to degree heterogeneity than the combinatorial Laplacian. Eigenvalues lie in [0, 2] for connected graphs.
row_hash_fingerprint(K)
¶
Per-row SHA-256 hashes of K_nm.
Enables selective verification: prove knowledge of specific coupling rows without revealing the full matrix. Useful for hierarchical authentication where different parties control different SCPN layers.
spectral_fingerprint(K)
¶
Compute public spectral fingerprint of coupling matrix.
Returns dict with
fiedler: Second-smallest eigenvalue of graph Laplacian (algebraic connectivity). gap_ratio: lambda_1 / lambda_2 (spectral gap quality). spectral_entropy: Shannon entropy of normalized eigenvalue distribution. n_components: Number of connected components (eigenvalues ≈ 0).
topology_commitment(K, nonce=b'')
¶
Commit to K_nm without revealing it.
Returns SHA-256(K_nm_bytes || nonce). The commitment binds the prover to a specific K_nm. Later, the prover opens by revealing K_nm + nonce, and the verifier recomputes the hash.
topology_distance(fp1, fp2)
¶
L2 distance between two spectral fingerprints.
Useful for detecting calibration drift or K_nm tampering.
verify_commitment(K, nonce, commitment)
¶
Verify that K_nm matches a previously issued commitment.
verify_fingerprint(K, fingerprint, tol=1e-06)
¶
Check K against a claimed spectral fingerprint.
verify_row_hash(K, row_idx, expected_hash)
¶
Verify a single row of K_nm against its hash.
Applications¶
scpn_quantum_control.applications
¶
Physical system benchmarks and application modules.
ApplicationPluginBenchmark
dataclass
¶
Result emitted by an application plugin benchmark run.
as_dict()
¶
Serialise the benchmark result without NumPy objects.
ApplicationPluginRegistry
¶
Registry for application plugins discovered through entry points.
register(name, factory)
¶
Register a plugin factory.
unregister(name)
¶
Remove a plugin factory and cached instance if present.
clear()
¶
Remove all registered plugins.
names()
¶
Return registered plugin names.
get(name)
¶
Instantiate and return one plugin.
discover(*, force=False)
¶
Discover third-party plugins from package entry points.
datasets()
¶
Return plugin-to-dataset mapping.
run_all()
¶
Run every registered plugin against its packaged datasets.
CrossDomainResult
dataclass
¶
Cross-domain validation summary.
ApplicationBenchmarkDescriptor
dataclass
¶
Metadata for a packaged application benchmark artifact.
path
property
¶
Absolute path to the packaged artifact.
EEGBenchmarkResult
dataclass
¶
EEG vs SCPN comparison result.
FMOBenchmarkResult
dataclass
¶
Comparison between SCPN and FMO coupling structures.
ITERBenchmarkResult
dataclass
¶
ITER MHD vs SCPN comparison result.
JosephsonBenchmarkResult
dataclass
¶
Josephson junction array vs SCPN comparison.
PowerGridBenchmarkResult
dataclass
¶
Power grid vs SCPN comparison result.
QuantumEVSResult
dataclass
¶
Quantum-enhanced EVS feature vector.
QuantumKernelResult
dataclass
¶
Quantum kernel computation result.
ReservoirResult
dataclass
¶
Quantum reservoir computation result.
compile_application_problem(plugin_name, dataset_id=None)
¶
Load a plugin dataset and adapt it to the public Kuramoto facade.
discover_application_plugins(*, force=False)
¶
Discover application plugins via package entry points.
get_application_plugin(name)
¶
Return one application plugin by name.
get_application_plugin_registry()
¶
Return the process-wide application plugin registry.
load_application_dataset(plugin_name, dataset_id=None)
¶
Load a benchmark artifact through an application plugin.
run_application_benchmark_suite()
¶
Run all registered application benchmark plugins.
run_cross_domain_validation(n_max=16)
¶
Run all 5 physical system benchmarks against SCPN K_nm.
Uses the appropriate oscillator count for each system.
artifact_to_kuramoto_problem(artifact)
¶
Adapt a QPU data artifact to the public Kuramoto facade.
get_application_benchmark_descriptor(dataset_id)
¶
Return one packaged benchmark descriptor by stable identifier.
list_application_benchmark_descriptors()
¶
Return packaged application benchmark descriptors.
load_application_benchmark_artifact(dataset_id)
¶
Load and validate a packaged application benchmark artifact.
fmo_coupling_matrix(*, allow_builtin_reference=False)
¶
Return the built-in FMO coupling matrix and site energies.
Scaled to natural units: energies in rad/ps (divide cm⁻¹ by 5309).
josephson_benchmark(K_scpn, omega_scpn, topology='all_to_all', parameters=None, coupling_edges=None, allow_illustrative_topology=False)
¶
Compare SCPN K_nm with Josephson junction array coupling.
power_grid_benchmark(K_scpn, omega_scpn, grid_name='IEEE-5bus', *, grid_coupling=None, grid_frequencies=None, reference_source_mode='curated', allow_builtin_reference=False)
¶
Compare SCPN coupling topology with power grid.
Uses the smaller dimension (min(n_scpn, n_grid)) for comparison.
quantum_evs_enhance(features, n_osc=8, dt=0.1, trotter_reps=3)
¶
Enhance EVS features through quantum Kuramoto evolution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
ndarray
|
classical EVS feature vector (any length) |
required |
n_osc
|
int
|
number of quantum oscillators |
8
|
dt
|
float
|
evolution time |
0.1
|
trotter_reps
|
int
|
Trotter repetitions |
3
|
compute_kernel_matrix(X, K, n_qubits)
¶
Compute the full kernel matrix for a set of feature vectors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
(n_samples, n_features) feature matrix |
required |
K
|
ndarray
|
coupling matrix |
required |
n_qubits
|
int
|
number of qubits for encoding |
required |
reservoir_features(x, K, omega=None, t=1.0, max_weight=2)
¶
Compute quantum reservoir features for input x.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ndarray
|
input feature vector (length n_qubits or less) |
required |
K
|
ndarray
|
coupling matrix (n × n) |
required |
omega
|
ndarray | None
|
natural frequencies |
None
|
t
|
float
|
reservoir evolution time |
1.0
|
max_weight
|
int
|
maximum Pauli weight for features |
2
|
scpn_quantum_control.applications.dataset_catalog
¶
Packaged application benchmark datasets exposed as QPU data artifacts.
ApplicationBenchmarkDescriptor
dataclass
¶
Metadata for a packaged application benchmark artifact.
path
property
¶
Absolute path to the packaged artifact.
list_application_benchmark_descriptors()
¶
Return packaged application benchmark descriptors.
get_application_benchmark_descriptor(dataset_id)
¶
Return one packaged benchmark descriptor by stable identifier.
load_application_benchmark_artifact(dataset_id)
¶
Load and validate a packaged application benchmark artifact.
artifact_to_kuramoto_problem(artifact)
¶
Adapt a QPU data artifact to the public Kuramoto facade.
scpn_quantum_control.applications.app_plugins
¶
Application-specific plugin registry for benchmark datasets and workflows.
ApplicationPluginBenchmark
dataclass
¶
Result emitted by an application plugin benchmark run.
as_dict()
¶
Serialise the benchmark result without NumPy objects.
ApplicationPluginRegistry
¶
Registry for application plugins discovered through entry points.
register(name, factory)
¶
Register a plugin factory.
unregister(name)
¶
Remove a plugin factory and cached instance if present.
clear()
¶
Remove all registered plugins.
names()
¶
Return registered plugin names.
get(name)
¶
Instantiate and return one plugin.
discover(*, force=False)
¶
Discover third-party plugins from package entry points.
datasets()
¶
Return plugin-to-dataset mapping.
run_all()
¶
Run every registered plugin against its packaged datasets.
get_application_plugin(name)
¶
Return one application plugin by name.
load_application_dataset(plugin_name, dataset_id=None)
¶
Load a benchmark artifact through an application plugin.
compile_application_problem(plugin_name, dataset_id=None)
¶
Load a plugin dataset and adapt it to the public Kuramoto facade.
run_application_benchmark_suite()
¶
Run all registered application benchmark plugins.
Gauge¶
scpn_quantum_control.gauge
¶
U(1) gauge theory observables for the Kuramoto-XY quantum model.
CFTResult
dataclass
¶
CFT central charge extraction result.
ConfinementResult
dataclass
¶
Confinement analysis result.
UniversalityResult
dataclass
¶
Universality class analysis result.
VortexResult
dataclass
¶
Vortex density measurement result.
WilsonLoopResult
dataclass
¶
Wilson loop measurement result.
extract_central_charge(K, omega)
¶
Extract CFT central charge c from entanglement scaling at given K.
Uses Calabrese-Cardy formula with chord length correction.
find_critical_coupling(omega, k_range=(0.01, 5.0), n_points=30)
¶
Find K where half-chain entanglement entropy is maximised.
At the critical point, entanglement is maximal (log divergence).
confinement_analysis(K, omega)
¶
Full confinement-deconfinement analysis.
Computes Wilson loops for triangles (length 3) and squares (length 4), extracts string tension from their ratio.
confinement_vs_coupling(omega, k_values=None)
¶
Scan confinement across coupling strength.
At K_c, the string tension should vanish (deconfinement transition).
universality_analysis(K, omega)
¶
Full BKT universality class check.
measure_vortex_density(K, omega)
¶
Measure vortex density from the ground state of H(K, omega).
vortex_density_vs_coupling(omega, k_base_values=None)
¶
Scan vortex density vs coupling strength.
At the BKT transition, vortex density should jump from 0 to finite.
compute_wilson_loops(K, omega, max_length=4, max_loops=20)
¶
Compute Wilson loop expectation values for the ground state.
Finds all loops up to max_length on the coupling graph and
measures
wilson_loop_expectation(psi, loop, n_qubits)
¶
Compute <ψ|W(C)|ψ> for a given state and loop.