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.
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=1)
¶
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=10)
¶
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=5)
¶
Time-stepped evolution returning R(t) and per-qubit expectations.
energy_expectation(sv)
¶
Compute
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)
¶
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)
¶
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 features that defaulted to ITER center values.
Note: ne_1e19 maps to the n_GW slot as a proxy. For accurate Greenwald fraction, divide by n_GW = I_p / (pi * a²) externally.
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.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.
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.
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 single-qubit 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). 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
¶
Synthetic trapped-ion noise model for cross-platform benchmarking.
Models all-to-all connectivity (no SWAP overhead) with depolarizing + thermal relaxation on MS gates. Transpiles to {cx, ry, rz} as a proxy for the native {rxx, ry, rz} basis. 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)
¶
Transpile with all-to-all connectivity (no SWAP insertion).
Decomposes to {cx, ry, rz} which maps to native {rxx, ry, rz}.