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.
Stable Facades¶
scpn_quantum_control.kuramoto_core
¶
Small public facade for Kuramoto-XY problems.
KuramotoProblem
dataclass
¶
Validated coupling matrix, frequencies, and serialisable metadata.
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.
compile_analog_program(problem, *, platform, duration, coupling_scale=1.0)
¶
Compile a Kuramoto problem into a native analog hardware programme.
compile_hybrid_program(problem, *, platform, duration, digital_time=None, max_analog_couplers=None, analog_threshold=0.0, trotter_steps=8, trotter_order=1)
¶
Compile a split analog-native plus digital-residual programme.
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.qpu_data_artifact
¶
QPU-ready oscillator artifact with provenance gates.
QPUDataArtifact
dataclass
¶
Validated oscillator data ready for quantum-control compilation.
K_nm follows the Phase Orchestrator convention: row i receives
coupling from column j. Current Kuramoto-XY circuits require a
symmetric, non-negative, zero-diagonal matrix unless the caller explicitly
opts into more specialised models.
n_oscillators
property
¶
Number of oscillators/qubits implied by the artifact.
is_synthetic
property
¶
Whether this artifact is non-publication synthetic data.
require_publication_safe()
¶
Reject synthetic or insufficiently traceable artifacts.
to_dict()
¶
Serialise to a JSON-compatible mapping.
to_json(*, indent=2)
¶
Serialise to JSON.
from_dict(data)
classmethod
¶
Load and validate an artifact from a mapping.
from_json(payload)
classmethod
¶
Load and validate an artifact from JSON.
from_scpn_datastream_payload(payload, *, source_mode='synthetic', domain='scpn', source_name='sc-neurocore-datastream', normalization='sc-neurocore canonical stream', extraction_method='sc_neurocore.scpn.datastream')
classmethod
¶
Adapt the current SC-NeuroCore datastream payload for smoke tests.
The SC-NeuroCore stream generated by commit 52bd3649 is deterministic
and useful for interface tests, but it is not a recorded source artifact.
It therefore defaults to source_mode='synthetic'.
artifact_from_arrays(*, domain, source_name, source_mode, K_nm, omega, normalization, extraction_method, theta0=None, layer_assignments=(), source_timestamp=None, replay_id=None, metadata=None)
¶
Convenience constructor for bridge tests and loaders.
artifact_to_kuramoto_problem(artifact)
¶
Adapt a validated QPU data artifact to the public Kuramoto facade.
Parameters¶
artifact : QPUDataArtifact
Hash-locked oscillator artifact carrying a symmetric K_nm matrix
and natural-frequency vector.
Returns¶
KuramotoProblem Immutable Kuramoto facade with provenance metadata copied from the artifact identity fields and artifact digest.
validate_qpu_data_artifact(artifact, *, require_publication_safe=True)
¶
Validate a QPU artifact and optionally enforce publication safety.
read_qpu_data_artifact(path)
¶
Read a QPU data artifact from JSON.
write_qpu_data_artifact(path, artifact)
¶
Write a QPU data artifact to JSON.
scpn_quantum_control.bridge.scpn_upde_edge
¶
Bounded knm.scpn-upde edge payloads for SPO federation.
SCPNUPDEEdge
dataclass
¶
A bounded QUANTUM-to-SPO knm.scpn-upde handoff.
The edge carries validated K_nm and omega arrays plus enough
deterministic compiler metadata for SPO to rebuild its own review manifest.
It never authorises QPU execution or actuation.
build_paper27_scpn_upde_edge(*, time=0.1, trotter_steps=1, trotter_order=1)
¶
Return the 16-oscillator Paper-27 QUANTUM→SPO edge.
The emitted scope is deliberately limited to computational agreement; the Paper-27 coupling matrix remains provisional rather than canonical physics.
build_scpn_upde_edge(K_nm, omega, *, time=0.1, trotter_steps=1, trotter_order=1, claim_boundary=PAPER27_PROVISIONAL_BOUNDARY)
¶
Build a bounded knm.scpn-upde edge from Kuramoto inputs.
validate_scpn_upde_edge_payload(payload)
¶
Validate a knm.scpn-upde payload emitted by this module.
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.
parameter_shift_gradient(params)
¶
Return analytic parameter-shift gradients for the current ansatz.
value_and_parameter_shift_gradient(params)
¶
Return the VQE energy and structured parameter-shift gradient metadata.
solve(optimizer='COBYLA', maxiter=200, seed=None, gradient_method=None)
¶
Run VQE optimisation.
Returns dict with ground_energy, optimal_params, n_evals, and gradient metadata.
ground_state()
¶
Return the optimized ground state vector (call solve first).
scpn_quantum_control.phase.coupling_learning
¶
Parameter-shift coupling learning for oscillator observation models.
CouplingGradientVerificationResult
dataclass
¶
Finite-difference agreement certificate for coupling-learning gradients.
to_dict()
¶
Return JSON-ready gradient-verification evidence.
CouplingLearningResult
dataclass
¶
coupling_matrix_from_edge_vector(values, *, n_nodes, edges=None)
¶
Build a symmetric zero-diagonal coupling matrix from edge parameters.
learn_couplings_from_observations(observation_model, target_observations, initial_couplings, *, n_nodes=None, edges=None, backend='statevector', rule=None, learning_rate=0.1, max_steps=100, gradient_tolerance=1e-08, value_tolerance=None, target_loss_tolerance=1e-08, min_loss_decrease=None, allow_hardware=False)
¶
Learn symmetric coupling parameters from differentiable observations.
The observation model must be a smooth, parameter-shift-compatible quantum expectation or sinusoidal surrogate over the supplied couplings. Arbitrary classical regressors are intentionally outside this claim boundary.
verify_coupling_parameter_shift_gradient(observation_model, target_observations, couplings, *, n_nodes=None, edges=None, rule=None, finite_difference_step=1e-06, tolerance=1e-05)
¶
Verify coupling gradients against central finite differences.
This diagnostic is intended for small smooth observation models where a central finite-difference reference is affordable. It does not certify discontinuous, shot-noisy, hardware-only, or arbitrary regression models.
scpn_quantum_control.phase.differentiable_audit
¶
Reviewer-facing differentiable quantum gradient audit reports.
DifferentiableQuantumAuditReport
dataclass
¶
Composite evidence report for parameter-shift differentiable workflows.
DifferentiableWorkflowAuditSuiteResult
dataclass
¶
Aggregate evidence across supported differentiable quantum workflows.
FiniteShotGradientAuditResult
dataclass
¶
Finite-shot uncertainty containment certificate for parameter-shift gradients.
to_dict()
¶
Return JSON-ready finite-shot audit evidence.
MLFrameworkGradientAuditRecord
dataclass
¶
Per-framework parity evidence for optional ML gradient adapters.
to_dict()
¶
Return JSON-ready per-framework ML parity evidence.
MLFrameworkGradientAuditSuiteResult
dataclass
¶
Fail-closed parity report for optional ML gradient adapters.
executed_frameworks
property
¶
Return frameworks whose adapters were executed.
unavailable_frameworks
property
¶
Return frameworks whose optional dependencies were unavailable.
blocked_frameworks
property
¶
Return frameworks available but not executable without caller-owned objects.
failed_frameworks
property
¶
Return frameworks that executed and failed parity.
worst_executed_error
property
¶
Return the largest error across executed ML adapters.
to_dict()
¶
Return JSON-ready ML framework parity evidence.
ParameterShiftAnalyticAgreement
dataclass
¶
Agreement certificate between parameter-shift and analytic gradients.
to_dict()
¶
Return JSON-ready analytic agreement evidence.
PhaseGradientBenchmarkSuiteResult
dataclass
¶
run_differentiable_workflow_audit_suite(*, finite_shot_target_standard_error=0.02, coupling_learning_rate=0.35, coupling_max_steps=80, gradient_tolerance=1e-07)
¶
Run the built-in cross-workflow differentiable-programming audit suite.
run_finite_shot_gradient_uncertainty_audit(objective, initial_values, *, rule=None, plus_variances=0.04, minus_variances=0.04, target_standard_error=0.02, min_shots=64, max_shots_per_evaluation=None, confidence_level=0.95, confidence_z=1.959963984540054)
¶
Audit finite-shot parameter-shift uncertainty propagation.
The shifted expectation values are evaluated deterministically, while the supplied variances and planned shots define the stochastic uncertainty envelope. This certifies propagation and containment semantics; it does not claim live hardware sampling correctness.
run_known_phase_gradient_audit(initial_values=None, *, learning_rate=0.35, max_steps=80, finite_difference_step=1e-06, finite_difference_tolerance=1e-05, analytic_tolerance=1e-10, target_value_tolerance=1e-08)
¶
Run the built-in smooth phase-rotation audit benchmark.
The benchmark objective is mean(1 - cos(theta_i)), whose exact gradient is mean-scaled sin(theta_i). It models the single-frequency expectation losses used by local parameter-shift phase-gradient diagnostics.
run_ml_framework_gradient_audit(objective=None, initial_values=None, *, rule=None, tolerance=1e-08, pennylane_gradient=None)
¶
Run fail-closed parity checks for optional ML gradient adapters.
run_parameter_shift_audit_suite(objective, analytic_gradient, initial_values, *, rule=None, finite_difference_step=1e-06, finite_difference_tolerance=1e-05, analytic_tolerance=1e-08, learning_rate=0.35, max_steps=80, gradient_tolerance=1e-08, target_value=0.0, target_value_tolerance=1e-08, min_loss_decrease=None)
¶
Run finite-difference, analytic, and convergence checks as one report.
run_phase_gradient_benchmark_suite(*, learning_rate=0.35, max_steps=100, finite_difference_step=1e-06, finite_difference_tolerance=1e-05, analytic_tolerance=1e-09, target_value_tolerance=1e-08)
¶
Run built-in deterministic phase-gradient conformance benchmarks.
verify_parameter_shift_analytic_gradient(objective, analytic_gradient, values, *, rule=None, tolerance=1e-08)
¶
Verify parameter-shift gradients against a supplied analytic gradient.
scpn_quantum_control.phase.gradient_descent
¶
Auditable parameter-shift gradient-descent training for phase objectives.
ParameterShiftTrainingStep
dataclass
¶
One accepted or rejected parameter-shift optimisation step.
to_dict()
¶
Return JSON-ready step metadata.
ParameterShiftTrainingResult
dataclass
¶
ParameterShiftTrainingCertificate
dataclass
¶
Machine-checkable convergence certificate for a training result.
to_dict()
¶
Return JSON-ready certificate metadata.
parameter_shift_gradient_descent(objective, initial_params, *, parameters=None, rule=None, backend='statevector', learning_rate=0.1, max_steps=100, gradient_tolerance=1e-08, value_tolerance=None, sufficient_decrease=0.0001, backtracking_factor=0.5, max_backtracks=12, allow_hardware=False)
¶
Minimise a scalar phase objective with native parameter-shift gradients.
The optimizer is intentionally bounded and fail-closed. It supports local deterministic parameter-shift execution with Armijo backtracking and records enough metadata to audit convergence, shifted-evaluation cost, and multi-frequency rule provenance.
validate_parameter_shift_training(result, *, gradient_tolerance=None, target_value=None, target_value_tolerance=1e-08, min_decrease=None)
¶
Return a machine-checkable certificate for a training trace.
scpn_quantum_control.phase.natural_gradient
¶
Metric-aware parameter-shift optimisation for supported phase objectives.
NaturalGradientDirection
dataclass
¶
Damped metric solve used for one natural-gradient step.
to_dict()
¶
Return JSON-ready direction metadata.
ParameterShiftNaturalGradientStep
dataclass
¶
One accepted or rejected metric-aware parameter-shift step.
to_dict()
¶
Return JSON-ready step metadata.
ParameterShiftNaturalGradientResult
dataclass
¶
ParameterShiftNaturalGradientCertificate
dataclass
¶
Machine-checkable certificate for a natural-gradient training result.
to_dict()
¶
Return JSON-ready certificate metadata.
solve_natural_gradient_direction(gradient, metric_tensor, *, damping=1e-08, max_condition_number=1000000000000.0)
¶
Solve (metric + damping I) direction = gradient fail-closed.
The returned direction is a preconditioned descent direction for
minimisation steps of the form params - step_size * direction. The
metric must be symmetric and the regularised solve must produce positive
natural-gradient energy gradient @ direction.
parameter_shift_natural_gradient_descent(objective, initial_params, *, metric_tensor=None, parameters=None, rule=None, backend='statevector', learning_rate=0.1, max_steps=100, gradient_tolerance=1e-08, natural_gradient_tolerance=1e-08, value_tolerance=None, damping=1e-08, max_condition_number=1000000000000.0, sufficient_decrease=0.0001, backtracking_factor=0.5, max_backtracks=12, allow_hardware=False)
¶
Minimise a phase objective with parameter-shift natural gradients.
The function composes native parameter-shift gradients with an explicit metric tensor supplied by the caller. The default identity metric is an auditable preconditioner baseline, not a claim of quantum Fisher metric extraction. Hardware backends remain fail-closed through the backend planner unless an explicit future policy enables them.
validate_natural_gradient_training(result, *, gradient_tolerance=None, natural_gradient_tolerance=None, target_value=None, target_value_tolerance=None, min_decrease=None)
¶
Validate natural-gradient descent provenance against explicit gates.
scpn_quantum_control.phase.optimizer_audit
¶
Multi-start convergence evidence for parameter-shift phase optimizers.
OptimizerConvergenceRecord
dataclass
¶
One optimizer result reduced to serialisable audit evidence.
to_dict()
¶
Return JSON-ready convergence evidence.
OptimizerComparisonSuiteResult
dataclass
¶
Multi-start optimizer comparison with explicit claim boundaries.
run_parameter_shift_optimizer_comparison(objective=None, starts=None, *, metric_tensor=None, parameters=None, rule=None, backend='statevector', learning_rate=0.4, max_steps=12, gradient_tolerance=1e-08, natural_gradient_tolerance=1e-08, certificate_gradient_tolerance=None, certificate_natural_gradient_tolerance=None, target_value=None, target_value_tolerance=None, min_decrease=0.0, comparison_tolerance=1e-10, require_natural_not_worse=True, allow_hardware=False)
¶
Run a bounded multi-start optimizer comparison for phase objectives.
The default objective is a smooth anisotropic phase-rotation cost. The default metric matches that anisotropy so the audit can verify that natural-gradient preconditioning helps the slow phase axis. Custom objectives are supported, but callers must provide a metric tensor if they want natural-gradient semantics beyond the identity baseline.
scpn_quantum_control.phase.objectives
¶
Composable differentiable objectives for phase-control training.
ObjectiveTermValue
dataclass
¶
One weighted term contribution in a composed objective evaluation.
to_dict()
¶
Return JSON-ready term contribution metadata.
ObjectiveGradientEvaluation
dataclass
¶
Value, gradient, and term breakdown for a composed objective.
to_dict()
¶
Return JSON-ready objective-gradient evidence.
ObjectiveTerm
dataclass
¶
ComposedPhaseObjective
dataclass
¶
Named weighted sum of differentiable phase-control objective terms.
parameter_shift_compatible
property
¶
Return whether every term is compatible with parameter-shift.
term_names
property
¶
Return objective term names.
evaluate(params)
¶
Evaluate objective value, exact term gradients, and term breakdown.
__call__(params)
¶
Return the scalar objective value.
require_parameter_shift_compatible()
¶
Fail closed if any term is not parameter-shift compatible.
to_dict()
¶
Return JSON-ready static objective metadata.
ComposedObjectiveTrainingStep
dataclass
¶
One accepted or rejected composed-objective optimisation step.
to_dict()
¶
Return JSON-ready step metadata.
ComposedObjectiveTrainingResult
dataclass
¶
ComposedObjectiveTrainingCertificate
dataclass
¶
Machine-checkable certificate for composed-objective training.
to_dict()
¶
Return JSON-ready certificate metadata.
phase_energy_term(width, *, weights=1.0, term_weight=1.0, name='phase_energy')
¶
Build a parameter-shift-compatible sum(w_i * (1 - cos(theta_i))) term.
phase_fidelity_target_term(target, *, term_weight=1.0, name='phase_fidelity_target')
¶
Build a periodic infidelity term mean(1 - cos(theta - target)).
periodic_regularization_term(center, *, term_weight=1.0, name='periodic_regularization')
¶
Build a periodic regularizer around a reference phase vector.
phase_symmetry_penalty_term(width, pairs, *, offsets=0.0, term_weight=1.0, name='phase_symmetry_penalty')
¶
Build a periodic pair-symmetry penalty over selected phase pairs.
smooth_box_safety_penalty_term(lower, upper, *, width, sharpness=8.0, term_weight=1.0, name='smooth_box_safety_penalty')
¶
Build a smooth analytic penalty for excursions outside a safe box.
build_phase_control_objective(width, *, energy_weight=1.0, fidelity_target=None, fidelity_weight=0.0, regularization_center=None, regularization_weight=0.0, symmetry_pairs=None, symmetry_weight=0.0, safety_bounds=None, safety_weight=0.0)
¶
Build a standard differentiable phase-control objective.
train_composed_phase_objective(objective, initial_params, *, learning_rate=0.2, max_steps=100, gradient_tolerance=1e-08, sufficient_decrease=0.0001, backtracking_factor=0.5, max_backtracks=12)
¶
Minimise a composed objective with exact term-wise gradients.
validate_composed_objective_training(result, *, gradient_tolerance=None, target_value=None, target_value_tolerance=None, min_decrease=None)
¶
Validate composed-objective training against explicit gates.
scpn_quantum_control.phase.objective_audit
¶
Reviewer-facing correctness evidence for composed phase objectives.
ComposedObjectiveGradientAgreement
dataclass
¶
Finite-difference agreement record for one composed objective.
to_dict()
¶
Return JSON-ready gradient-agreement evidence.
ComposedObjectiveAuditSuiteResult
dataclass
¶
verify_composed_objective_gradient(objective, params, *, finite_difference_step=1e-06, absolute_tolerance=1e-05, relative_tolerance=1e-05)
¶
Verify exact term-wise gradients against central finite differences.
run_composed_objective_audit_suite()
¶
Run the built-in composed-objective correctness and convergence audit.
scpn_quantum_control.phase.objective_planner
¶
Fail-closed execution planning for composed phase objectives.
ComposedObjectiveExecutionPlan
dataclass
¶
Support decision for a composed phase objective execution route.
to_dict()
¶
Return JSON-ready execution-plan metadata.
ComposedObjectivePlannerAuditResult
dataclass
¶
plan_composed_objective_execution(objective, *, backend='statevector', require_parameter_shift=False, allow_hardware=False)
¶
Plan a safe execution route for a composed phase objective.
assert_composed_objective_execution_supported(plan)
¶
Return a supported plan or raise with its fail-closed reason.
run_composed_objective_planner_audit()
¶
Run the built-in objective planner support audit.
scpn_quantum_control.phase.gradient_support_matrix
¶
Executable support matrix for quantum-gradient combinations.
GradientSupportCapability
dataclass
¶
Declared support contract for one gradient surface component.
to_dict()
¶
Return JSON-ready capability metadata.
GradientSupportPlan
dataclass
¶
GradientSupportMatrixAuditResult
dataclass
¶
Built-in audit for representative supported and blocked combinations.
gradient_support_capability(category, name)
¶
Return the support capability for one matrix component.
list_gradient_support_capabilities(category=None)
¶
List registered support capabilities, optionally filtered by category.
plan_gradient_support(*, gate, observable, backend='statevector', transform='grad', adapter='native', n_params=1, shift_terms=1, shots=None, allow_hardware=False)
¶
Plan whether a full quantum-gradient request is supported.
assert_gradient_support(plan)
¶
Return a supported plan or raise with its fail-closed reasons.
run_gradient_support_matrix_audit()
¶
Run representative support-matrix invariants.
scpn_quantum_control.phase.transform_nesting
¶
Fail-closed transform-nesting planner for quantum gradients.
GradientTransformNestingPlan
dataclass
¶
GradientTransformNestingAuditResult
dataclass
¶
Built-in audit of supported and blocked transform-nesting routes.
plan_gradient_transform_nesting(transforms, *, gate='ry', observable='pauli_expectation', backend='statevector', adapter='native', n_params=1, shift_terms=1, shots=None, allow_hardware=False)
¶
Plan a nested quantum-gradient transform stack with fail-closed rules.
assert_gradient_transform_nesting_supported(plan)
¶
Return a supported nesting plan or raise with fail-closed reasons.
run_gradient_transform_nesting_audit()
¶
Run representative transform-nesting support and fail-closed checks.
scpn_quantum_control.phase.provider_gradient_audit
¶
Executable readiness audit for provider-safe quantum gradients.
ProviderGradientReadinessScenario
dataclass
¶
One executable provider-gradient readiness scenario.
to_dict()
¶
Return JSON-ready scenario metadata.
ProviderGradientReadinessRecord
dataclass
¶
ProviderGradientReadinessAuditResult
dataclass
¶
Executable support matrix for provider-gradient readiness.
supported_records
property
¶
Return scenarios that executed and matched their gradient references.
blocked_records
property
¶
Return scenarios that fail closed by plan or execution guard.
failing_records
property
¶
Return scenarios whose observed outcome did not match the expectation.
to_dict()
¶
Return JSON-ready provider-gradient audit metadata.
default_provider_gradient_readiness_scenarios()
¶
Return built-in provider-gradient support and fail-closed scenarios.
run_provider_gradient_readiness_audit(scenarios=None, *, tolerance=1e-10)
¶
Run executable provider-gradient readiness checks.
The audit intentionally mixes successful local callback routes with blocked hardware, unknown-backend, and malformed-sample routes. A passing audit means supported paths produce the expected gradients and unsupported paths refuse execution with explicit reasons; it is not a hardware execution claim.
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.
Studio¶
scpn_quantum_control.studio.recompute_kernel
¶
Recompute-verifiable Studio units for deterministic compile claims.
XYCompileRecomputeUnit
dataclass
¶
Signed-unit payload for bit-exact XY compile recomputation.
to_dict()
¶
Return a JSON-ready recompute unit.
build_xy_compile_recompute_unit(K_nm, omega, *, time, trotter_steps, trotter_order)
¶
Build a bit-exact Studio recompute unit for an XY compile claim.
canonical_xy_compile_input_bytes(K_nm, omega, *, time, trotter_steps, trotter_order)
¶
Return the canonical binary input consumed by the WASM verifier kernel.
verify_xy_compile_recompute_unit(unit)
¶
Verify a recompute unit by comparing its claimed and recomputed digests.
xy_compile_digest_python(input_bytes)
¶
Return the Python reference digest for the WASM compile verifier input.
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[int64]
|
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.
scpn_control_bridge_dependency_contract()
¶
Return the SCPN-CONTROL disruption bridge dependency contract.
The contract is intentionally mirrored locally instead of importing SCPN-CONTROL, so this backend can be validated before CONTROL is installed.
validate_scpn_control_bridge_dependency_contract(payload)
¶
Validate the SCPN-CONTROL disruption bridge dependency contract.
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[float64]
|
shape (n_inputs,) with values in [0, 1] |
required |
Returns:
| Type | Description |
|---|---|
NDArray[int64]
|
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.
parameter_shift_gradient(inputs, target)
¶
Compute gradient of MSE loss w.r.t. all synapse angles.
Returns (n_neurons, n_inputs) gradient array.
train_epoch(X, y)
¶
One epoch over dataset. Returns mean loss.
train(X, y, epochs=10)
¶
Train for multiple epochs. Returns loss history.
train_with_diagnostics(X, y, epochs=10)
¶
Train and return structured convergence plus evaluation evidence.
train_with_parameter_shift_descent(X, y, *, backend='statevector', max_steps=100, gradient_tolerance=1e-08, value_tolerance=None, target_loss=None, target_loss_tolerance=1e-08, min_loss_decrease=None, allow_hardware=False)
¶
Train QSNN synapse angles with full-batch parameter-shift descent.
This route uses the same auditable optimizer as phase objectives, so QSNN training records backend planning, every accepted/rejected line search step, total objective evaluations, and a convergence certificate.
QSNNTrainingDiagnostics
dataclass
¶
Machine-checkable convergence evidence for QSNN parameter-shift training.
to_dict()
¶
Return JSON-serialisable training diagnostics.
QSNNTrainingRun
dataclass
¶
Structured QSNN training result with parameter-shift evaluation accounting.
to_dict()
¶
Return JSON-serialisable training evidence.
QSNNParameterShiftDescentRun
dataclass
¶
Differentiable Programming¶
scpn_quantum_control.diff
¶
Canonical first-path namespace for differentiable quantum-control workflows.
ShotPolicy
dataclass
¶
EstimatorProvenance
dataclass
¶
BackendCapabilityMetadata
dataclass
¶
User-facing capability metadata for one differentiable circuit route.
DifferentiableCircuitDiagnostics
dataclass
¶
DifferentiableCircuit
dataclass
¶
Callable, serializable scalar differentiable circuit facade.
Parameters¶
name: Stable circuit identifier used in diagnostics and serialized metadata. objective: Local scalar objective. The current facade executes only local Python objectives and delegates gradients to existing SCPN transform routes. parameter_names: Optional names for the one-dimensional parameter vector. gate: Gate class used for support-matrix routing. observable: Observable class used for support-matrix routing. backend: Backend route used for support-matrix routing. transform: Transform route used for support-matrix routing. adapter: Framework adapter used for support-matrix routing. shot_policy: Finite-shot and hardware policy. estimator_provenance: Provenance for the estimator route. claim_boundary: Explicit claim boundary for public diagnostics.
support_plan
property
¶
Return the current fail-closed support plan for this circuit.
capability
property
¶
Return public capability metadata for the current route.
diagnostics
property
¶
Return fail-closed diagnostics for the current route.
fail_closed
property
¶
Return true when the current route is intentionally unsupported.
__post_init__()
¶
Validate circuit metadata and attach default estimator provenance.
__call__(values)
¶
Evaluate the local scalar objective after support validation.
value_and_grad(values, *, method='parameter_shift', parameters=None, step=None)
¶
Evaluate objective value and gradient through the canonical transform.
grad(values, *, method='parameter_shift', parameters=None, step=None)
¶
Evaluate a gradient through the canonical transform namespace.
to_dict()
¶
Return JSON-ready metadata without serializing executable code.
to_json()
¶
Return deterministic JSON metadata for audit artifacts.
JITExplanation
dataclass
¶
differentiable_circuit(objective, *, name='differentiable_circuit', parameter_names=(), gate='ry', observable='pauli_expectation', backend='statevector', transform='grad', adapter='native', shot_policy=None, estimator_provenance=None)
¶
Return a configured differentiable circuit facade for a scalar objective.
jit_or_explain(function, *, backend='statevector', adapter='native')
¶
Return a fail-closed JIT explanation for the canonical namespace.
The project currently exposes executable local gradients and compiler-AD evidence surfaces separately. This helper gives first-path users a stable JIT entry point that refuses unsupported compilation routes with actionable alternatives instead of silently falling back to eager execution.
supported_transforms()
¶
Return the stable transform names exposed by the canonical namespace.
namespace_metadata()
¶
Return JSON-ready metadata for the canonical differentiable namespace.
scpn_quantum_control.differentiable
¶
Native differentiable-programming primitives for SCPN quantum objectives.
The base layer is backend-neutral parameter-shift differentiation for scalar objectives. Optional JAX support is exposed as an adapter without making JAX a runtime dependency of the core package.
Parameter
dataclass
¶
One differentiable scalar parameter in an SCPN objective.
__post_init__()
¶
Validate parameter identity and trainability metadata.
ParameterBounds
dataclass
¶
Closed interval constraint for one differentiable scalar parameter.
__post_init__()
¶
Validate finite interval and periodic-bound metadata.
ParameterShiftRule
dataclass
¶
Symmetric parameter-shift rule for one- or multi-frequency generators.
ParameterShiftSampleRecord
dataclass
¶
One plus/minus shifted sample used in stochastic parameter-shift propagation.
to_dict()
¶
Return JSON-ready shifted-sample provenance.
DualNumber
dataclass
¶
Forward-mode automatic differentiation scalar with one tangent lane.
coerce(value)
staticmethod
¶
Return a dual number, treating real scalars as zero-tangent constants.
ReverseNode
¶
Reverse-mode automatic differentiation scalar with local pullbacks.
coerce(value)
staticmethod
¶
Return a reverse node, treating real scalars as constants.
GradientResult
dataclass
¶
Value, gradient, and provenance returned by a differentiable backend.
StochasticGradientResult
dataclass
¶
Parameter-shift gradient with independent shot-noise uncertainty.
to_dict()
¶
Return JSON-ready stochastic parameter-shift evidence.
ShotAllocationResult
dataclass
¶
Per-parameter shot allocation for stochastic parameter-shift gradients.
SparseMatrixResult
dataclass
¶
ImplicitSensitivityResult
dataclass
¶
Implicit-function sensitivity for a stationary differentiable system.
FixedPointSensitivityResult
dataclass
¶
Implicit sensitivity for a converged fixed-point map.
CustomDerivativeRule
dataclass
¶
Exact custom derivative rules for one differentiable vector primitive.
PrimitiveIdentity
dataclass
¶
PrimitiveTransformRule
dataclass
¶
Combined transform binding for one differentiable primitive identity.
CustomDerivativeRegistry
¶
Conflict-safe registry binding primitive identities to exact rules.
register(identity, rule, *, overwrite=False)
¶
Register an exact derivative rule for a primitive identity.
decorator(identity, *, overwrite=False)
¶
Return a decorator that registers a CustomDerivativeRule object.
register_transform(transform, *, overwrite=False)
¶
Register derivative, batching, and lowering metadata for one primitive.
register_batching_rule(identity, batching_rule, *, overwrite=False)
¶
Attach a primitive-specific batching rule to an existing identity.
register_lowering_rule(identity, lowering_rule, *, overwrite=False)
¶
Attach an executable compiler lowering rule to an existing identity.
batching_rule_for(identity)
¶
Return the registered primitive batching rule, if present.
lowering_rule_for(identity)
¶
Return the registered executable compiler lowering rule, if present.
shape_rule_for(identity)
¶
Return the registered primitive shape rule, if present.
dtype_rule_for(identity)
¶
Return the registered primitive dtype rule, if present.
static_argument_rule_for(identity)
¶
Return the registered primitive static-argument rule, if present.
nondifferentiable_policy_for(identity)
¶
Return the registered primitive nondifferentiability policy, if present.
effect_for(identity)
¶
Return the registered primitive effect classification, if present.
contract_for(identity)
¶
Return the unified registered primitive contract, if present.
require_batching_rule(identity)
¶
Return a primitive batching rule or fail closed.
require_lowering_rule(identity)
¶
Return an executable compiler lowering rule or fail closed.
require_shape_rule(identity)
¶
Return a primitive shape rule or fail closed.
require_dtype_rule(identity)
¶
Return a primitive dtype rule or fail closed.
require_static_argument_rule(identity)
¶
Return a primitive static-argument rule or fail closed.
require_nondifferentiable_policy(identity)
¶
Return a primitive nondifferentiability policy or fail closed.
require_effect(identity)
¶
Return a primitive effect classification or fail closed.
require_contract(identity)
¶
Return a unified primitive contract or fail closed.
require_complete_contract(identity)
¶
Return a compiler/vectorization-ready primitive contract or fail closed.
transform_snapshot()
¶
Return a copy of registered primitive transform bindings.
lookup(identity)
¶
Return the registered rule for an identity, if present.
require(identity)
¶
Return the registered rule or fail closed with a useful error.
unregister(identity)
¶
Remove and return a registered rule.
snapshot()
¶
Return an immutable-by-copy snapshot of registered primitive rules.
CustomDerivativeCheckResult
dataclass
¶
Consistency audit for exact custom JVP/VJP derivative rules.
OptimizationResult
dataclass
¶
Bounded gradient-descent result with convergence provenance.
ArmijoLineSearchResult
dataclass
¶
Backtracking line-search result with sufficient-decrease provenance.
GradientCheckResult
dataclass
¶
Consistency check between two differentiable gradient estimators.
JacobianResult
dataclass
¶
Value, Jacobian, and provenance for a vector-valued objective.
JVPResult
dataclass
¶
Jacobian-vector product with directional finite-difference provenance.
VJPResult
dataclass
¶
Vector-Jacobian product with cotangent provenance.
HessianResult
dataclass
¶
Value, Hessian, and provenance for a scalar objective.
HVPResult
dataclass
¶
Hessian-vector product with nested finite-difference provenance.
LeastSquaresCovarianceResult
dataclass
¶
Parameter uncertainty estimate from a residual-map Fisher metric.
FisherVectorProductResult
dataclass
¶
Matrix-free empirical-Fisher vector product with provenance.
FisherConjugateGradientResult
dataclass
¶
Matrix-free empirical-Fisher conjugate-gradient solve result.
NaturalGradientResult
dataclass
¶
Metric-preconditioned gradient with solve provenance.
NaturalGradientOptimizationResult
dataclass
¶
Bounded natural-gradient optimization trace and final state.
NaturalGradientOptimizer
dataclass
¶
Bounded natural-gradient optimizer for scalar objectives with explicit metrics.
Parameters¶
learning_rate Non-negative scale applied to each natural-gradient step. damping Non-negative diagonal damping added to the trainable metric block. rcond Positive reciprocal-condition threshold for metric solves. max_step_norm Optional positive L2 cap for trainable natural-gradient steps.
__post_init__()
¶
Validate and canonicalize natural-gradient optimizer controls.
minimize(objective, initial_values, metric_fn, *, parameters=None, rule=None, gradient_method='parameter_shift', finite_difference_step=1e-06, bounds=None, max_steps=100, gradient_tolerance=1e-08, step_tolerance=1e-08, value_tolerance=None)
¶
Run a bounded natural-gradient descent loop with metric provenance.
Parameters¶
objective
Scalar objective evaluated at real parameter vectors.
initial_values
Initial real parameter vector before optional bound projection.
metric_fn
Callback returning the metric matrix for the current gradient and
parameter vector.
parameters
Optional parameter metadata controlling names and trainable masks.
rule
Optional parameter-shift rule for the parameter-shift backend.
gradient_method
Either "parameter_shift" or "finite_difference".
finite_difference_step
Positive central-difference step for finite-difference gradients.
bounds
Optional per-parameter box or periodic bounds.
max_steps
Non-negative maximum number of descent steps.
gradient_tolerance
Non-negative trainable-gradient convergence tolerance.
step_tolerance
Non-negative trainable-step convergence tolerance.
value_tolerance
Optional non-negative objective-change convergence tolerance.
Returns¶
NaturalGradientOptimizationResult Final values, gradient and natural-gradient records, histories, convergence state, and best-observed iterate.
LevenbergMarquardtDampingUpdate
dataclass
¶
Deterministic damping update for Levenberg-Marquardt trust regions.
LevenbergMarquardtOptimizer
dataclass
¶
Bounded Levenberg-Marquardt optimizer for residual-map objectives.
Parameters¶
damping:
Initial non-negative trust-region damping.
max_steps:
Positive maximum number of accepted or rejected LM trials.
residual_tolerance:
Non-negative Euclidean residual-norm convergence tolerance.
step_tolerance:
Non-negative trainable-step convergence tolerance.
value_tolerance:
Optional non-negative actual-reduction convergence tolerance.
acceptance_threshold:
Non-negative minimum ratio of actual to predicted reduction.
decrease_factor:
Multiplicative damping decrease for high-quality accepted trials.
increase_factor:
Multiplicative damping increase for rejected trials.
min_damping:
Non-negative lower damping bound.
max_damping:
Upper damping bound greater than or equal to min_damping.
high_quality_ratio:
Ratio threshold for decreasing damping on accepted trials.
finite_difference_step:
Positive residual-Jacobian central-difference step.
max_step_norm:
Optional positive L2 cap for trainable LM steps.
__post_init__()
¶
Validate and canonicalize optimizer controls.
minimize(objective, initial_values, *, parameters=None, bounds=None, weight_fn=None, rcond=1e-12)
¶
Minimize a vector residual objective with adaptive bounded LM steps.
Parameters¶
objective: Residual-map objective evaluated on real parameter vectors. initial_values: Initial parameter vector before bound projection. parameters: Optional parameter metadata for finite-difference Jacobian records. bounds: Optional box or periodic parameter bounds. weight_fn: Optional robust-weight callback evaluated on each residual vector. rcond: Relative cutoff passed through to the Gauss-Newton metric solve.
Returns¶
LevenbergMarquardtResult Final and best iterates, residual history, damping history, and convergence reason.
LevenbergMarquardtResult
dataclass
¶
Traceable result from a bounded Levenberg-Marquardt optimization run.
LevenbergMarquardtStep
dataclass
¶
Bounded Levenberg-Marquardt candidate step with model diagnostics.
LevenbergMarquardtTrial
dataclass
¶
Actual-vs-predicted Levenberg-Marquardt acceptance diagnostic.
WeightedGradientResult
dataclass
¶
Weighted scalarisation of multiple scalar gradient results.
WholeProgramTraceEvent
dataclass
¶
One executed Python source line observed during whole-program AD tracing.
__post_init__()
¶
Validate trace-event source metadata at construction time.
WholeProgramIRNode
dataclass
¶
One operator-intercepted IR node from whole-program AD.
__post_init__()
¶
Validate operator-intercepted node metadata at construction time.
WholeProgramADResult
dataclass
¶
Value, gradient, execution trace, and polyglot AD lowering status.
__post_init__()
¶
Validate whole-program AD result metadata at construction time.
WholeProgramBytecodeInstruction
dataclass
¶
One Python bytecode instruction captured for whole-program AD frontend IR.
WholeProgramBytecodeBasicBlock
dataclass
¶
One static Python-bytecode basic block for frontend planning.
The block is derived from normalized dis instructions without executing
the objective. Successors are bytecode offsets only; they are a static
control-flow skeleton for audits and later lowerings, not executable
compiler evidence.
to_dict()
¶
Return a JSON-ready bytecode block.
WholeProgramSourceIRFeature
dataclass
¶
One source-level semantic feature captured for whole-program AD.
WholeProgramSourceRegion
dataclass
¶
One static source-region node for frontend planning.
Regions summarize bounded AST constructs such as function entry, control flow, loops, alias bindings, and mutations. They are deterministic source metadata for the bytecode/source frontend and do not imply non-executed branch adjoints or executable compiler lowering.
to_dict()
¶
Return a JSON-ready source region.
WholeProgramSourceBytecodeLineMap
dataclass
¶
One source-line to bytecode crosswalk row for frontend planning.
The row links a Python source line to normalized bytecode offsets, source regions, and feature kinds. It is static inspection metadata only; it does not assert executable compiler lowering or non-executed branch adjoints.
to_dict()
¶
Return a JSON-ready source-bytecode crosswalk row.
WholeProgramSymbolScopeEntry
dataclass
¶
One static symbol-scope entry for whole-program frontend diagnostics.
Entries merge source names, bytecode operands, function parameters, locals, globals, closure variables, and cell variables into a deterministic symbol table. The table is a compiler-frontend diagnostic and does not execute the objective or prove runtime alias safety.
to_dict()
¶
Return a JSON-ready symbol-scope entry.
WholeProgramUnsupportedSemanticDiagnostic
dataclass
¶
One fail-closed Python-semantics diagnostic for frontend audits.
The diagnostic binds an unsupported source construct to source-relative lines, optional CPython/file lines, source regions, and bytecode offsets. It is static preflight metadata only and does not execute or lower the blocked construct.
to_dict()
¶
Return a JSON-ready unsupported-semantics diagnostic.
WholeProgramSemanticsReport
dataclass
¶
Static semantics summary for whole-program AD graph capture.
WholeProgramCompilerFrontendReport
dataclass
¶
Static bytecode/source frontend report for whole-program AD objectives.
The report inspects Python bytecode and source-derived AST features without executing the objective. It is a compiler-frontend preflight artefact for accepted whole-program AD semantics, not executable Rust, LLVM, JIT, provider, hardware, or benchmark evidence.
Parameters¶
function_name:
Python callable name used for diagnostics.
bytecode_instructions:
Normalised Python bytecode instruction rows from dis.
bytecode_basic_blocks:
Static control-flow block skeleton derived from the bytecode stream.
source_ir_features:
Source-level AST feature rows used by the Program AD frontend.
source_regions:
Static source-region graph derived from bounded AST constructs.
source_bytecode_line_map:
Static crosswalk from source lines to bytecode offsets, source regions,
and source feature kinds.
symbol_scope_entries:
Static symbol-scope table derived from source names, bytecode operands,
and function code-object scope metadata.
unsupported_semantic_diagnostics:
Static fail-closed diagnostics for unsupported Python constructs.
semantics_report:
Static semantics summary derived from bytecode and source features.
source_available:
Whether source text could be obtained through introspection.
source_sha256:
SHA-256 digest of the dedented source when available.
source_start_line:
Absolute file line where the inspected source snippet starts.
source_end_line:
Absolute file line where the inspected source snippet ends.
bytecode_digest:
SHA-256 digest over the normalised bytecode instruction stream.
frontend_digest:
SHA-256 digest over bytecode, source, source features, source regions,
and semantic support metadata.
ast_node_count:
Number of AST nodes in the parsed source tree when available.
hard_gaps:
Named blockers that prevent the report from being accepted as a
complete bytecode/source frontend preflight.
claim_boundary:
Boundary preventing this static report from becoming an execution or
performance claim.
bytecode_instruction_count
property
¶
Return the number of bytecode instructions in the frontend report.
source_feature_count
property
¶
Return the number of source IR feature rows in the frontend report.
frontend_ready
property
¶
Return whether bytecode and source frontend metadata passed preflight.
bytecode_basic_block_count
property
¶
Return the number of bytecode basic blocks in the frontend report.
source_region_count
property
¶
Return the number of source regions in the frontend report.
source_bytecode_line_map_count
property
¶
Return the number of source-bytecode crosswalk rows in the report.
symbol_scope_entry_count
property
¶
Return the number of static symbol-scope entries in the report.
unsupported_semantic_diagnostic_count
property
¶
Return the number of unsupported-semantics diagnostics in the report.
to_dict()
¶
Return a JSON-ready compiler frontend report.
ProgramADAdjointStep
dataclass
¶
One generated reverse-adjoint step over stabilized Program AD IR.
The step binds a primal SSA value and stabilized effect row to the local
pullback inputs, finite incoming cotangent, local pullback coefficients,
emitted contribution cotangents, effect ordering metadata, and any
unambiguous runtime control/phi row used by reverse-mode adjoint
generation. Non-executed phi inputs are recorded as blocked adjoints rather
than replay contributions. It is an auditable generation plan over
program_ad_effect_ir.v1 metadata; it does not add non-executed branch
adjoints or executable compiler lowering.
TraceADArray
¶
Derivative-carrying one-dimensional array for whole-program AD.
ndim
property
¶
Return the rank of the derivative-carrying array.
size
property
¶
Return the total number of derivative-carrying elements.
T
property
¶
Return the NumPy-compatible reversed-axis transpose.
item()
¶
Return the only scalar element, failing closed for non-scalar arrays.
copy()
¶
Return a derivative-preserving shallow array copy.
reshape(*shape)
¶
Return a derivative-preserving reshaped array view.
ravel()
¶
Return a flat view-preserving program AD array.
flatten()
¶
Return a flat copy-equivalent program AD array.
repeat(repeats, axis=None)
¶
Return a derivative-preserving array with repeated elements.
squeeze(axis=None)
¶
Return a derivative-preserving array with singleton axes removed.
expand_dims(axis)
¶
Return a derivative-preserving array with singleton axes inserted.
swapaxes(axis1, axis2)
¶
Return a derivative-preserving array with two axes exchanged.
sum(axis=None)
¶
Return a derivative-preserving sum over all elements or one axis.
cumsum(axis=None)
¶
Return a derivative-preserving cumulative sum.
prod(axis=None)
¶
Return a derivative-preserving product over all elements or one axis.
cumprod(axis=None)
¶
Return a derivative-preserving cumulative product.
mean(axis=None)
¶
Return a derivative-preserving arithmetic mean.
var(axis=None, ddof=0)
¶
Return a derivative-preserving variance with NumPy-compatible ddof.
std(axis=None, ddof=0)
¶
Return a derivative-preserving standard deviation.
max(axis=None)
¶
Return a derivative-preserving maximum with tie-safe semantics.
min(axis=None)
¶
Return a derivative-preserving minimum with tie-safe semantics.
take(indices, axis=None, mode='raise')
¶
Return derivative-preserving positional elements with fail-closed modes.
argmax(axis=None)
¶
Reject nondifferentiable maximum-index selection.
argmin(axis=None)
¶
Reject nondifferentiable minimum-index selection.
TraceADScalar
¶
Operator-intercepted scalar for exact executed-path whole-program AD.
DifferentiableOptimizer
dataclass
¶
Native gradient-descent optimizer for differentiable parameters.
Parameters¶
learning_rate: Non-negative step size applied to trainable gradient components before optional bound projection.
__post_init__()
¶
Validate and canonicalize the optimizer step size.
step(values, gradient_result, *, bounds=None, max_gradient_norm=None)
¶
Return one projected gradient-descent update.
Parameters¶
values: Current real parameter vector. gradient_result: Gradient and trainable-mask metadata for the current point. bounds: Optional per-parameter box or periodic bounds. max_gradient_norm: Optional L2 clipping threshold applied to trainable components.
Returns¶
numpy.ndarray Updated real parameter vector after trainable-mask filtering and optional bound projection.
minimize(objective, initial_values, *, parameters=None, rule=None, gradient_method='parameter_shift', finite_difference_step=1e-06, bounds=None, max_gradient_norm=None, max_steps=100, gradient_tolerance=1e-08, value_tolerance=None)
¶
Run bounded gradient descent with native gradient backends.
Parameters¶
objective:
Scalar-valued objective evaluated on real parameter vectors.
initial_values:
Initial real parameter vector before bound projection.
parameters:
Optional metadata controlling names and trainable masks.
rule:
Optional parameter-shift rule for the parameter-shift backend.
gradient_method:
Either "parameter_shift" or "finite_difference".
finite_difference_step:
Positive central-difference step used by the finite-difference
backend.
bounds:
Optional per-parameter box or periodic bounds.
max_gradient_norm:
Optional L2 clipping threshold applied to trainable components.
max_steps:
Non-negative maximum number of descent steps.
gradient_tolerance:
Non-negative convergence tolerance for the trainable gradient norm.
value_tolerance:
Optional non-negative convergence tolerance for objective changes.
Returns¶
OptimizationResult Final values, gradient record, value history, convergence status, and best-observed iterate.
dual_sin(value)
¶
Evaluate the forward-mode sine primitive.
dual_cos(value)
¶
Evaluate the forward-mode cosine primitive.
dual_exp(value)
¶
Evaluate the forward-mode exponential primitive.
dual_log(value)
¶
Evaluate the forward-mode natural-log primitive.
reverse_sin(value)
¶
Evaluate the reverse-mode sine primitive.
reverse_cos(value)
¶
Evaluate the reverse-mode cosine primitive.
reverse_exp(value)
¶
Evaluate the reverse-mode exponential primitive.
reverse_log(value)
¶
Evaluate the reverse-mode natural-log primitive.
armijo_backtracking_line_search(objective, values, gradient_result, direction, *, bounds=None, initial_step=1.0, contraction=0.5, sufficient_decrease=0.0001, max_steps=20)
¶
Return a bounded Armijo backtracking step for a scalar objective.
Parameters¶
objective
Scalar objective evaluated at candidate parameter vectors.
values
Current parameter vector.
gradient_result
Gradient metadata at values.
direction
Candidate descent direction. Frozen parameter entries are masked out.
bounds
Optional closed-interval parameter bounds used to project candidates.
initial_step
Positive first trial step length.
contraction
Multiplicative step shrinkage in (0, 1).
sufficient_decrease
Armijo sufficient-decrease coefficient in (0, 1).
max_steps
Positive trial-step cap.
Returns¶
ArmijoLineSearchResult Accepted candidate or fail-closed rejection metadata.
register_custom_derivative_rule(identity, rule, *, overwrite=False, registry=None)
¶
Register a custom derivative rule in the selected or default registry.
register_primitive_transform_rule(transform, *, overwrite=False, registry=None)
¶
Register a combined derivative/batching/lowering transform binding.
register_primitive_batching_rule(identity, batching_rule, *, overwrite=False, registry=None)
¶
Register a batching rule for an existing primitive derivative rule.
custom_derivative_rule_for(identity, *, registry=None)
¶
Resolve a custom derivative rule for a primitive identity.
registered_custom_jvp(identity, values, tangent, *, parameters=None, registry=None)
¶
Return a JVP by resolving the primitive's registered custom rule.
registered_custom_vjp(identity, values, cotangent, *, parameters=None, registry=None)
¶
Return a VJP by resolving the primitive's registered custom rule.
registered_custom_jacobian(identity, values, *, parameters=None, registry=None)
¶
Return a dense Jacobian by resolving the primitive's registered custom rule.
multi_frequency_parameter_shift_rule(frequencies, *, shifts=None, max_condition=10000000000.0)
¶
Return an exact multi-frequency parameter-shift rule.
For trigonometric objectives with positive generator frequency set
frequencies, the coefficients solve
2 * sin(frequency_i * shift_j) @ coefficient_j = frequency_i.
The resulting rule can exactly differentiate any supported linear
combination of sine/cosine components at those frequencies.
parameter_shift_gradient(objective, values, *, parameters=None, rule=None)
¶
Return the parameter-shift gradient of a scalar objective.
Parameters¶
objective: Scalar-valued objective evaluated on a real parameter vector. values: Initial real parameter values. parameters: Optional metadata controlling names and trainable masks. rule: Optional single- or multi-frequency parameter-shift rule.
Returns¶
numpy.ndarray Real gradient vector with frozen parameters set to zero.
value_and_parameter_shift_grad(objective, values, *, parameters=None, rule=None)
¶
Evaluate a scalar objective and its native parameter-shift gradient.
Parameters¶
objective: Scalar-valued objective evaluated on real parameter probes. values: Initial real parameter values. parameters: Optional metadata controlling names and trainable masks. rule: Optional single- or multi-frequency parameter-shift rule.
Returns¶
GradientResult Objective value, gradient, evaluation count, and parameter metadata.
parameter_shift_gradient_with_uncertainty(plus_values, minus_values, plus_variances, minus_variances, plus_shots, minus_shots=None, *, value=0.0, parameters=None, rule=None, confidence_level=0.95, confidence_z=1.959963984540054, failure_policy=None)
¶
Propagate independent shot noise through parameter-shift gradients.
Parameters¶
plus_values, minus_values:
Shifted objective estimates for every term and parameter.
plus_variances, minus_variances:
Per-estimate finite-shot variances.
plus_shots, minus_shots:
Positive integer shot counts. When minus_shots is omitted the plus
shot counts are reused.
value:
Objective value associated with the gradient estimate.
parameters:
Optional metadata controlling names and trainable masks.
rule:
Optional single- or multi-frequency parameter-shift rule.
confidence_level:
Confidence mass associated with the returned interval.
confidence_z:
Positive normal-approximation multiplier for interval radii.
failure_policy:
Optional policy that classifies uncertainty thresholds.
Returns¶
StochasticGradientResult Gradient, covariance, shot provenance, confidence interval, and diagnostic-only claim boundary metadata.
allocate_parameter_shift_shots(plus_variances, minus_variances, *, target_standard_error, parameters=None, rule=None, min_shots=1, max_shots_per_evaluation=None)
¶
Plan plus/minus shots to meet a target parameter-shift standard error.
Parameters¶
plus_variances
Per-parameter or per-term plus-side measurement variances.
minus_variances
Per-parameter or per-term minus-side measurement variances with the
same shape as plus_variances.
target_standard_error
Positive target standard error for each trainable gradient component.
parameters
Optional parameter metadata. Frozen parameters retain the minimum shot
count and report zero predicted standard error.
rule
Optional single-term or multi-frequency parameter-shift rule used to
weight variance contributions.
min_shots
Positive lower bound for every planned plus/minus evaluation.
max_shots_per_evaluation
Optional cap for each planned plus/minus evaluation.
Returns¶
ShotAllocationResult Shot plan and predicted covariance for the requested target.
forward_mode_gradient(objective, values, *, parameters=None)
¶
Return an exact forward-mode dual gradient for scalar objectives.
Parameters¶
objective
Scalar objective expressed in terms of DualNumber inputs.
values
Real parameter vector at which the objective is evaluated.
parameters
Optional parameter metadata used to mask frozen tangent lanes.
Returns¶
numpy.ndarray One exact gradient entry per input parameter.
value_and_forward_mode_grad(objective, values, *, parameters=None)
¶
Evaluate a scalar objective and exact forward-mode dual gradient.
Parameters¶
objective
Scalar objective expressed in terms of DualNumber inputs.
values
Real parameter vector at which the objective is evaluated.
parameters
Optional parameter metadata. Frozen parameters are evaluated in the
base objective but receive no tangent seed and therefore report a zero
gradient entry.
Returns¶
GradientResult Objective value, exact forward-mode gradient, parameter metadata, and evaluation count.
reverse_mode_gradient(objective, values, *, parameters=None)
¶
Return an exact reverse-mode tape gradient for scalar objectives.
Parameters¶
objective
Scalar objective expressed in terms of ReverseNode inputs.
values
Real parameter vector at which the objective is evaluated.
parameters
Optional parameter metadata used to mask frozen gradient entries.
Returns¶
numpy.ndarray One exact gradient entry per input parameter.
value_and_reverse_mode_grad(objective, values, *, parameters=None)
¶
Evaluate a scalar objective and exact reverse-mode tape gradient.
Parameters¶
objective
Scalar objective expressed in terms of ReverseNode inputs.
values
Real parameter vector at which the objective is evaluated.
parameters
Optional parameter metadata. Frozen parameters participate in the tape
but are masked to zero in the returned gradient.
Returns¶
GradientResult Objective value, exact reverse-mode gradient, parameter metadata, and evaluation count.
grad(objective, values, *, parameters=None, method='parameter_shift', rule=None, step=None)
¶
Return a scalar-objective gradient through the canonical transform API.
Parameters¶
objective:
Objective compatible with the selected differentiation method.
values:
Initial parameter values.
parameters:
Optional metadata that marks trainable parameters and supplies names.
method:
Differentiation backend passed to :func:value_and_grad.
rule:
Optional parameter-shift rule for parameter_shift.
step:
Optional finite-difference or complex-step perturbation.
Returns¶
numpy.ndarray
Gradient vector as float64 values.
value_and_grad(objective, values, *, parameters=None, method='parameter_shift', rule=None, step=None)
¶
Evaluate a scalar objective and gradient through the canonical transform API.
Parameters¶
objective:
Objective compatible with the selected differentiation method.
values:
Initial parameter values.
parameters:
Optional metadata that marks trainable parameters and supplies names.
method:
Differentiation backend. Supported values are parameter_shift,
finite_difference, complex_step, forward_mode,
reverse_mode, and whole_program.
rule:
Optional parameter-shift rule for parameter_shift.
step:
Optional finite-difference or complex-step perturbation.
Returns¶
GradientResult | WholeProgramADResult
Objective value and gradient, including whole-program trace metadata
when method is whole_program.
Raises¶
ValueError
If method is not one of the supported canonical backends.
whole_program_grad(objective, values, parameters=None, *, trace=True)
¶
Return only the exact whole-program AD gradient.
Parameters¶
objective:
Callable accepted by :func:whole_program_value_and_grad.
values:
Initial parameter values.
parameters:
Optional metadata that marks trainable parameters and supplies names.
trace:
Whether to collect runtime trace events in the underlying result.
Returns¶
numpy.ndarray
Exact whole-program AD gradient as float64 values.
whole_program_value_and_grad(objective, values, parameters=None, *, trace=True)
¶
Differentiate an executed Python/NumPy program by operator-intercepted AD.
Parameters¶
objective: Callable that returns a whole-program AD scalar when executed over trace-aware parameter values. values: Initial parameter values. parameters: Optional metadata that marks trainable parameters and supplies names. trace: Whether to collect runtime trace events in addition to IR metadata.
Returns¶
WholeProgramADResult Exact executed-program value, gradient, source/bytecode metadata, IR nodes, semantics report, and scalar adjoint replay provenance.
Raises¶
ValueError If the objective is not callable, uses unsupported Python semantics, or does not return a traceable scalar.
program_adjoint_result(result)
¶
Return the reverse-mode adjoint generation result attached to Program AD.
Parameters¶
result: Whole-program AD result that should carry reverse-adjoint replay metadata.
Returns¶
ProgramADAdjointResult Attached reverse-adjoint replay result.
Raises¶
ValueError
If result is not a whole-program AD result or has no attached
adjoint metadata.
program_adjoint_gradient(result)
¶
Return a supported reverse-mode adjoint gradient or fail closed.
Parameters¶
result: Whole-program AD result whose attached reverse-adjoint metadata should be supported.
Returns¶
numpy.ndarray Copy of the attached reverse-adjoint gradient.
Raises¶
ValueError If no adjoint metadata is attached or the captured IR has unsupported operations.
program_adjoint_grad(objective, values, parameters=None, *, trace=True)
¶
Return the reverse-mode program AD gradient for supported captured IR.
Parameters¶
objective: Scalar objective that accepts Program AD trace values. values: Initial numeric parameter values. parameters: Optional named parameter metadata. Frozen parameters keep zero cotangents in the generated adjoint gradient. trace: Whether to keep runtime trace-event evidence in the captured whole-program result.
Returns¶
numpy.ndarray Reverse-adjoint generation gradient for the captured Program AD IR.
Raises¶
ValueError If the objective does not produce a scalar Program AD result or if the captured IR contains unsupported adjoint-generation operations.
program_adjoint_value_and_grad(objective, values, parameters=None, *, trace=True)
¶
Return the objective value and reverse-mode Program AD gradient.
Parameters¶
objective: Scalar objective that accepts Program AD trace values. values: Initial numeric parameter values. parameters: Optional named parameter metadata. Frozen parameters keep zero cotangents in the generated adjoint gradient. trace: Whether to keep runtime trace-event evidence in the captured whole-program result.
Returns¶
tuple[float, numpy.ndarray] Objective value and reverse-adjoint generation gradient.
Raises¶
ValueError If the objective does not produce a scalar Program AD result or if the captured IR contains unsupported adjoint-generation operations.
batch_parameter_shift_gradient(objectives, values, *, parameters=None, rule=None)
¶
Return stacked parameter-shift gradients for scalar objectives.
Parameters¶
objectives: Non-empty sequence of scalar-valued objectives. values: Initial real parameter values shared by every objective. parameters: Optional metadata controlling names and trainable masks. rule: Optional single- or multi-frequency parameter-shift rule.
Returns¶
numpy.ndarray Matrix whose rows are objective gradients.
batch_value_and_parameter_shift_grad(objectives, values, *, parameters=None, rule=None)
¶
Return full parameter-shift results for scalar objectives.
Parameters¶
objectives: Non-empty sequence of scalar-valued objectives. values: Initial real parameter values shared by every objective. parameters: Optional metadata controlling names and trainable masks. rule: Optional single- or multi-frequency parameter-shift rule.
Returns¶
tuple[GradientResult, ...] Per-objective value, gradient, and provenance records.
finite_difference_gradient(objective, values, *, parameters=None, step=1e-06)
¶
Return a central finite-difference gradient for scalar diagnostics.
value_and_finite_difference_grad(objective, values, *, parameters=None, step=1e-06)
¶
Evaluate a scalar objective and central finite-difference gradient.
batch_value_and_finite_difference_grad(objectives, values, *, parameters=None, step=1e-06)
¶
Return full finite-difference results for multiple scalar objectives.
complex_step_gradient(objective, values, *, parameters=None, step=1e-30)
¶
Return a complex-step gradient for real-analytic scalar objectives.
value_and_complex_step_grad(objective, values, *, parameters=None, step=1e-30)
¶
Evaluate a real-analytic scalar objective and complex-step gradient.
batch_complex_step_gradient(objectives, values, *, parameters=None, step=1e-30)
¶
Return stacked complex-step gradients for real-analytic objectives.
batch_custom_jvp(rule, values, tangents, *, parameters=None)
¶
Return stacked exact custom JVPs for a batch of tangent vectors.
batch_value_and_custom_jvp(rule, values, tangents, *, parameters=None)
¶
Return one exact custom JVP result per tangent row.
batch_custom_vjp(rule, values, cotangents, *, parameters=None)
¶
Return stacked exact custom VJPs for a batch of cotangent vectors.
batch_value_and_custom_vjp(rule, values, cotangents, *, parameters=None)
¶
Return one exact custom VJP result per cotangent row.
batch_custom_jacobian(rule, values, *, parameters=None)
¶
Return stacked exact custom Jacobians for a batch of parameter rows.
batch_value_and_custom_jacobian(rule, values, *, parameters=None)
¶
Return one exact custom Jacobian result per parameter row.
batch_value_and_complex_step_grad(objectives, values, *, parameters=None, step=1e-30)
¶
Return full complex-step results for multiple scalar objectives.
finite_difference_jacobian(objective, values, *, parameters=None, step=1e-06)
¶
Return a central finite-difference Jacobian for vector objectives.
value_and_finite_difference_jacobian(objective, values, *, parameters=None, step=1e-06)
¶
Evaluate a vector objective and its central finite-difference Jacobian.
jacobian(objective, values, *, parameters=None, method='finite_difference', step=1e-06)
¶
Return a vector-objective Jacobian through the canonical transform API.
value_and_jacobian(objective, values, *, parameters=None, method='finite_difference', step=1e-06)
¶
Evaluate a vector objective and Jacobian through the canonical transform API.
jacfwd(objective, values, *, parameters=None, method='finite_difference', step=1e-06)
¶
Return a vector-objective Jacobian using forward-Jacobian semantics.
value_and_jacfwd(objective, values, *, parameters=None, method='finite_difference', step=1e-06)
¶
Evaluate a vector objective and Jacobian through forward-Jacobian semantics.
The current backend is the same central finite-difference Jacobian used by
jacobian. The separate name establishes transform algebra semantics for
callers and tests while leaving room for a future true forward-mode Jacobian
implementation behind the same contract.
jacrev(objective, values, *, parameters=None, method='finite_difference', step=1e-06)
¶
Return a vector-objective Jacobian using reverse-Jacobian semantics.
value_and_jacrev(objective, values, *, parameters=None, method='finite_difference', step=1e-06)
¶
Evaluate a vector objective and Jacobian through reverse-Jacobian semantics.
Until a true reverse-over-vector backend exists, this is an explicit alias to the finite-difference Jacobian contract. It preserves API and composition semantics without overclaiming reverse compiler AD.
dense_to_sparse_matrix(matrix, *, parameter_names=None, trainable=None, method='dense_to_sparse', tolerance=0.0)
¶
Convert a dense derivative matrix to validated coordinate form.
Parameters¶
matrix:
Dense two-dimensional derivative matrix.
parameter_names:
Optional column names. Defaults to generated p{index} names.
trainable:
Optional trainable mask aligned to matrix columns. Defaults to all
trainable.
method:
Provenance label stored in the sparse result.
tolerance:
Non-negative absolute-value threshold below which entries are dropped.
Returns¶
SparseMatrixResult Validated coordinate sparse derivative matrix with metadata preserved.
sparse_jacobian(jacobian_result, *, tolerance=0.0)
¶
Return a coordinate sparse representation of a Jacobian result.
Parameters¶
jacobian_result: Validated dense Jacobian result to convert. tolerance: Non-negative absolute-value threshold below which entries are dropped.
Returns¶
SparseMatrixResult Sparse Jacobian preserving parameter names, trainable mask, and method provenance.
sparse_hessian(hessian_result, *, tolerance=0.0)
¶
Return a coordinate sparse representation of a Hessian result.
Parameters¶
hessian_result: Validated dense Hessian result to convert. tolerance: Non-negative absolute-value threshold below which entries are dropped.
Returns¶
SparseMatrixResult Sparse Hessian preserving parameter names, trainable mask, and method provenance.
sparse_empirical_fisher_metric(jacobian, *, weights=None, damping=0.0, tolerance=0.0)
¶
Return a coordinate sparse empirical Fisher/Gauss-Newton metric.
Parameters¶
jacobian:
Dense residual Jacobian or a validated JacobianResult.
weights:
Optional non-negative residual-row weights.
damping:
Optional non-negative diagonal damping.
tolerance:
Non-negative sparse conversion threshold.
Returns¶
SparseMatrixResult
Sparse empirical Fisher metric with parameter metadata preserved when a
JacobianResult is supplied.
finite_difference_jvp(objective, values, tangent, *, parameters=None, step=1e-06)
¶
Return a central finite-difference Jacobian-vector product.
value_and_finite_difference_jvp(objective, values, tangent, *, parameters=None, step=1e-06)
¶
Evaluate a vector objective and a directional finite-difference JVP.
batch_finite_difference_jvp(objective, values, tangents, *, parameters=None, step=1e-06)
¶
Return stacked finite-difference JVPs for a batch of tangents.
batch_value_and_finite_difference_jvp(objective, values, tangents, *, parameters=None, step=1e-06)
¶
Return one finite-difference JVP result per tangent row.
finite_difference_vjp(objective, values, cotangent, *, parameters=None, step=1e-06)
¶
Return a finite-difference vector-Jacobian product for a vector objective.
batch_finite_difference_vjp(objective, values, cotangents, *, parameters=None, step=1e-06)
¶
Return stacked finite-difference VJPs for a batch of cotangents.
batch_value_and_finite_difference_vjp(objective, values, cotangents, *, parameters=None, step=1e-06)
¶
Return one finite-difference VJP result per cotangent row.
vector_jacobian_product(jacobian, cotangent)
¶
Contract a validated cotangent with a vector-objective Jacobian.
batch_vector_jacobian_product(jacobian, cotangents)
¶
Return one vector-Jacobian product per cotangent row.
finite_difference_hessian(objective, values, *, parameters=None, step=0.0001)
¶
Return a central finite-difference Hessian for scalar objectives.
value_and_finite_difference_hessian(objective, values, *, parameters=None, step=0.0001)
¶
Evaluate a scalar objective and central finite-difference Hessian.
hessian(objective, values, *, parameters=None, method='finite_difference', step=0.0001)
¶
Return a scalar-objective Hessian through the canonical transform API.
value_and_hessian(objective, values, *, parameters=None, method='finite_difference', step=0.0001)
¶
Evaluate a scalar objective and Hessian through the canonical transform API.
implicit_stationary_sensitivity(hessian, cross_derivative, *, parameters=None, hyperparameter_names=None, damping=0.0, rcond=1e-12)
¶
Return sensitivities for an implicit stationary optimum.
Parameters¶
hessian
Symmetric positive-definite Hessian H of the stationarity
equations with respect to trainable parameters.
cross_derivative
Cross derivative matrix B with one row per parameter and one
column per hyperparameter. One-dimensional inputs are treated as a
single hyperparameter column.
parameters
Optional parameter metadata. Frozen parameters receive zero
sensitivity and are excluded from the trainable linear solve.
hyperparameter_names
Optional names for the cross-derivative columns. Defaults to
alpha0, alpha1, and so on.
damping
Non-negative diagonal damping applied to the active Hessian before the
solve.
rcond
Positive reciprocal-condition threshold used to reject ill-conditioned
trainable Hessian blocks.
Returns¶
ImplicitSensitivityResult
Validated dx*/dalpha = -H^-1 B sensitivity metadata.
implicit_fixed_point_sensitivity(state_jacobian, parameter_jacobian, *, parameters=None, hyperparameter_names=None, damping=0.0, rcond=1e-12)
¶
Return sensitivities for a fixed point x* = T(x*, alpha).
Parameters¶
state_jacobian
Square Jacobian dT/dx evaluated at the fixed point.
parameter_jacobian
Jacobian dT/dalpha with one row per state entry and one column per
hyperparameter. One-dimensional inputs are treated as a single
hyperparameter column.
parameters
Optional state-parameter metadata. Frozen entries receive zero
sensitivity and are excluded from the active linear solve.
hyperparameter_names
Optional names for parameter-Jacobian columns. Defaults to alpha0,
alpha1, and so on.
damping
Non-negative diagonal damping added to I - dT/dx.
rcond
Positive reciprocal-condition threshold used to reject ill-conditioned
active systems.
Returns¶
FixedPointSensitivityResult
Validated (I - dT/dx)^-1 dT/dalpha sensitivity metadata.
finite_difference_hvp(objective, values, tangent, *, parameters=None, step=1e-05)
¶
Return a central finite-difference Hessian-vector product.
value_and_finite_difference_hvp(objective, values, tangent, *, parameters=None, step=1e-05)
¶
Evaluate a scalar objective and a directional Hessian-vector product.
batch_finite_difference_hvp(objective, values, tangents, *, parameters=None, step=1e-05)
¶
Return stacked finite-difference HVPs for a batch of tangents.
batch_value_and_finite_difference_hvp(objective, values, tangents, *, parameters=None, step=1e-05)
¶
Return one finite-difference HVP result per tangent row.
empirical_fisher_metric(jacobian, *, weights=None, damping=0.0)
¶
empirical_fisher_vector_product(jacobian, tangent, *, weights=None, damping=0.0)
¶
Return a weighted empirical-Fisher product without materialising a solve.
Parameters¶
jacobian Finite-difference or custom Jacobian result for a residual map. tangent Candidate parameter-space vector to multiply by the Fisher metric. weights Optional non-negative residual weights with one entry per residual row. damping Non-negative diagonal damping applied only on trainable parameters.
Returns¶
FisherVectorProductResult Matrix-free product result with frozen parameter entries zeroed.
empirical_fisher_conjugate_gradient(jacobian, rhs, *, weights=None, damping=1e-08, tolerance=1e-10, max_iterations=None)
¶
Solve an empirical-Fisher system with matrix-free conjugate gradients.
Parameters¶
jacobian Residual-map Jacobian whose trainable columns define the solve space. rhs Right-hand side vector with one entry per parameter. weights Optional non-negative residual weights. damping Non-negative diagonal damping for the empirical-Fisher operator. tolerance Non-negative residual-norm convergence tolerance. max_iterations Optional positive iteration cap. Defaults to ten passes over trainable parameters.
Returns¶
FisherConjugateGradientResult Solution and residual history for the trainable-subspace solve.
evaluate_levenberg_marquardt_step(objective, step_result, *, weights=None, acceptance_threshold=0.0001)
¶
Evaluate actual residual reduction for a Levenberg-Marquardt candidate.
Parameters¶
objective:
Residual-map objective to evaluate at the candidate point.
step_result:
Candidate step returned by levenberg_marquardt_step.
weights:
Optional non-negative residual weights.
acceptance_threshold:
Non-negative minimum actual/predicted reduction ratio.
Returns¶
LevenbergMarquardtTrial Candidate residual, actual reduction, reduction ratio, and acceptance decision.
gauss_newton_gradient(jacobian, *, weights=None, damping=0.0, rcond=1e-12)
¶
Return the Gauss-Newton-preconditioned least-squares gradient.
Parameters¶
jacobian: Residual-map Jacobian whose value is the residual vector. weights: Optional non-negative row weights with one entry per residual. damping: Non-negative diagonal damping added to the empirical-Fisher metric. rcond: Relative cutoff passed to the metric solve.
Returns¶
NaturalGradientResult Natural-gradient result whose vector is the trainable Gauss-Newton update direction before the descent sign is applied.
huber_residual_weights(residuals, *, delta=1.0, min_weight=0.0)
¶
Return Huber IRLS weights for robust residual-map least squares.
Parameters¶
residuals:
One-dimensional real residual vector.
delta:
Positive Huber transition magnitude. Residuals with absolute value at
or below this threshold keep unit weight.
min_weight:
Optional non-negative floor in [0, 1] applied after Huber
downweighting.
Returns¶
numpy.ndarray
One-dimensional float64 weight vector aligned with residuals.
least_squares_covariance(jacobian, *, weights=None, residual_variance=None, damping=0.0, rcond=1e-12)
¶
Estimate residual-map parameter covariance from the empirical Fisher.
Parameters¶
jacobian
Residual-map Jacobian result whose value contains residuals.
weights
Optional non-negative residual weights.
residual_variance
Optional externally estimated residual variance. When omitted, the
weighted residual norm is divided by residual degrees of freedom.
damping
Non-negative diagonal damping passed to the empirical-Fisher metric.
rcond
Positive reciprocal-condition threshold in (0, 1).
Returns¶
LeastSquaresCovarianceResult Full parameter covariance matrix, standard errors, and conditioning metadata with frozen parameter rows and columns zeroed.
levenberg_marquardt_step(jacobian, values, *, weights=None, damping=0.001, bounds=None, max_step_norm=None, rcond=1e-12)
¶
Return a bounded Levenberg-Marquardt candidate for residual objectives.
Parameters¶
jacobian:
Residual-map Jacobian result at values.
values:
Current real parameter vector.
weights:
Optional non-negative residual weights.
damping:
Non-negative trust-region damping.
bounds:
Optional box or periodic parameter bounds for the candidate.
max_step_norm:
Optional positive L2 cap for trainable step components.
rcond:
Relative cutoff passed through to the Gauss-Newton metric solve.
Returns¶
LevenbergMarquardtStep Candidate step, projected candidate values, predicted reduction, and Gauss-Newton provenance.
natural_gradient(gradient_result, metric, *, damping=0.0, rcond=1e-12)
¶
Solve a trainable-subspace natural-gradient linear system.
Parameters¶
gradient_result Scalar-objective gradient and parameter metadata. metric Symmetric positive-definite metric matrix over all parameters. damping Non-negative diagonal damping added on the trainable block. rcond Positive reciprocal-condition threshold.
Returns¶
NaturalGradientResult Preconditioned gradient with frozen parameter entries zeroed.
soft_l1_residual_weights(residuals, *, scale=1.0, min_weight=0.0)
¶
Return smooth Soft-L1 IRLS weights for residual-map least squares.
Parameters¶
residuals:
One-dimensional real residual vector.
scale:
Positive residual scale controlling where the Soft-L1 influence curve
begins to downweight outliers.
min_weight:
Optional non-negative floor in [0, 1] applied after Soft-L1
downweighting.
Returns¶
numpy.ndarray
One-dimensional float64 weight vector aligned with residuals.
update_levenberg_marquardt_damping(trial, *, decrease_factor=1.0 / 3.0, increase_factor=2.0, min_damping=1e-12, max_damping=1000000000000.0, high_quality_ratio=0.75)
¶
Return a bounded trust-region damping update for an LM trial.
Parameters¶
trial:
Evaluated LM candidate trial.
decrease_factor:
Multiplicative damping decrease for high-quality accepted trials.
increase_factor:
Multiplicative damping increase for rejected trials.
min_damping:
Non-negative lower damping bound.
max_damping:
Upper damping bound greater than or equal to min_damping.
high_quality_ratio:
Ratio threshold for decreasing damping on accepted trials.
Returns¶
LevenbergMarquardtDampingUpdate Bounded next damping value and policy action.
weighted_gradient_sum(components, weights, *, method='weighted_sum')
¶
Combine compatible scalar gradient results by an explicit weight vector.
Parameters¶
components Non-empty gradient results with matching shape and parameter metadata. weights One finite scalar weight per component. method Provenance label stored on the result.
Returns¶
WeightedGradientResult Weighted scalar value, gradient, component provenance, and metadata.
check_parameter_shift_consistency(objective, values, *, parameters=None, rule=None, finite_difference_step=1e-06, tolerance=1e-05)
¶
Compare parameter-shift gradients against central finite differences.
Parameters¶
objective: Scalar differentiable objective evaluated by both gradient estimators. values: Real parameter vector supplied to the objective. parameters: Optional parameter metadata and trainable mask. rule: Optional parameter-shift rule. Defaults to the standard two-point generator rule used by the facade. finite_difference_step: Positive central-difference probe spacing used for the reference gradient. tolerance: Non-negative maximum absolute gradient error allowed for a passing diagnostic.
Returns¶
GradientCheckResult Candidate parameter-shift gradient, finite-difference reference, error metrics, tolerance, and pass/fail status.
check_custom_derivative_consistency(rule, values, tangent, cotangent, *, parameters=None, finite_difference_step=1e-06, tolerance=1e-05)
¶
Check custom derivative rules against adjoint and finite-difference identities.
Parameters¶
rule: Custom derivative rule supplying exact JVP and VJP callbacks. values: Real parameter vector supplied to the rule. tangent: Tangent vector used for the JVP identity check. cotangent: Cotangent vector used for the VJP identity check. parameters: Optional parameter metadata and trainable mask. finite_difference_step: Positive probe spacing for finite-difference JVP/VJP references. tolerance: Non-negative maximum allowed error for adjoint, JVP, and VJP checks.
Returns¶
CustomDerivativeCheckResult Exact-rule outputs, finite-difference references, error metrics, and pass/fail status for the custom derivative rule.
program_ad_linalg_trace_derivative_rule(matrix_shape, *, offset=0, axis1=0, axis2=1)
¶
Build a direct value/JVP/VJP rule for a fixed trace primitive signature.
program_ad_linalg_diag_derivative_rule(source_shape, *, k=0)
¶
Build a direct value/JVP/VJP rule for a fixed diagonal primitive signature.
program_ad_linalg_diagflat_derivative_rule(source_shape, *, k=0)
¶
Build a direct value/JVP/VJP rule for a fixed diagflat primitive signature.
program_ad_linalg_matrix_power_derivative_rule(power)
¶
Build a direct value/JVP rule for a fixed matrix-power primitive.
program_ad_linalg_multi_dot_derivative_rule(operand_shapes)
¶
Build a direct value/JVP rule for a fixed multi-dot operand signature.
program_ad_linalg_solve_derivative_rule(matrix_shape, rhs_shape)
¶
Build a direct value/JVP/VJP rule for a fixed solve primitive signature.
program_ad_linalg_eigvals_derivative_rule(matrix_shape)
¶
Build a direct value/JVP/VJP rule for a fixed real-simple eigvals primitive.
program_ad_linalg_eigvalsh_derivative_rule(matrix_shape, *, uplo='L')
¶
Build a direct value/JVP/VJP rule for a fixed symmetric eigvalsh primitive.
program_ad_linalg_svdvals_derivative_rule(matrix_shape)
¶
Build a direct value/JVP/VJP rule for fixed-shape SVD singular values.
program_ad_linalg_pinv_derivative_rule(matrix_shape, *, rcond=None)
¶
Build a direct value/JVP/VJP rule for fixed-shape full-rank pseudoinverse.
custom_gauss_newton_gradient(rule, values, *, parameters=None, weights=None, damping=0.0, rcond=1e-12)
¶
Return a Gauss-Newton update from an exact custom residual Jacobian.
Parameters¶
rule: Custom derivative rule whose value function returns residuals and whose Jacobian rule returns the exact residual Jacobian. values: Real parameter vector. parameters: Optional parameter metadata. weights: Optional non-negative residual weights. damping: Non-negative metric damping. rcond: Relative cutoff passed to the metric solve.
Returns¶
NaturalGradientResult Trainable Gauss-Newton update direction with exact-Jacobian provenance.
custom_levenberg_marquardt_step(rule, values, *, parameters=None, weights=None, damping=0.001, bounds=None, max_step_norm=None, rcond=1e-12)
¶
Return an LM candidate using an exact custom residual Jacobian.
Parameters¶
rule: Custom derivative rule with an exact residual Jacobian. values: Current real parameter vector. parameters: Optional parameter metadata. weights: Optional non-negative residual weights. damping: Non-negative trust-region damping. bounds: Optional box or periodic parameter bounds for the candidate. max_step_norm: Optional positive L2 cap for trainable step components. rcond: Relative cutoff passed through to the Gauss-Newton metric solve.
Returns¶
LevenbergMarquardtStep Bounded LM candidate with exact-Jacobian provenance.
custom_jacobian(rule, values, *, parameters=None)
¶
Return the exact dense Jacobian implied by a custom derivative rule.
value_and_custom_jacobian(rule, values, *, parameters=None)
¶
Evaluate a custom primitive and materialise its exact dense Jacobian.
custom_jvp(rule, values, tangent, *, parameters=None)
¶
Return an exact custom Jacobian-vector product for a registered primitive.
value_and_custom_jvp(rule, values, tangent, *, parameters=None)
¶
Evaluate a custom primitive and its exact JVP rule.
custom_vjp(rule, values, cotangent, *, parameters=None)
¶
Return an exact custom vector-Jacobian product for a registered primitive.
value_and_custom_vjp(rule, values, cotangent, *, parameters=None)
¶
Evaluate a custom primitive and its exact VJP rule.
is_jax_autodiff_available()
¶
Return whether JAX autodiff imports in the active environment.
Returns¶
bool
True when both jax and jax.numpy import successfully,
otherwise False.
vmap(function, in_axes=0, out_axes=0, *, primitive_identity=None, registry=None)
¶
Return a composable vectorizing transform over leading or selected axes.
The transform mirrors the practical contract of a JAX-style vmap for the
native NumPy differentiable layer: mapped arguments are sliced along their
declared axes, None axes are broadcast unchanged, and stackable scalar,
array, tuple, list, or dict outputs are reassembled with the mapped axis at
out_axes. It is an eager deterministic transform, not a JIT compiler.
whole_program_grad(objective, values, parameters=None, *, trace=True)
¶
Return only the exact whole-program AD gradient.
Parameters¶
objective:
Callable accepted by :func:whole_program_value_and_grad.
values:
Initial parameter values.
parameters:
Optional metadata that marks trainable parameters and supplies names.
trace:
Whether to collect runtime trace events in the underlying result.
Returns¶
numpy.ndarray
Exact whole-program AD gradient as float64 values.
whole_program_value_and_grad(objective, values, parameters=None, *, trace=True)
¶
Differentiate an executed Python/NumPy program by operator-intercepted AD.
Parameters¶
objective: Callable that returns a whole-program AD scalar when executed over trace-aware parameter values. values: Initial parameter values. parameters: Optional metadata that marks trainable parameters and supplies names. trace: Whether to collect runtime trace events in addition to IR metadata.
Returns¶
WholeProgramADResult Exact executed-program value, gradient, source/bytecode metadata, IR nodes, semantics report, and scalar adjoint replay provenance.
Raises¶
ValueError If the objective is not callable, uses unsupported Python semantics, or does not return a traceable scalar.
jax_value_and_grad(objective, values)
¶
Evaluate a JAX scalar objective and gradient.
Parameters¶
objective: Callable receiving a JAX array and returning a scalar objective value. values: Real numeric parameter vector.
Returns¶
tuple[float, numpy.ndarray]
Objective value and gradient converted to finite float64 NumPy
values.
Raises¶
ImportError If the optional JAX dependency is unavailable. ValueError If the input, objective value, or gradient violates the native differentiable contract.
scpn_quantum_control.differentiable_framework_overlay
¶
Reproducible CPU-only overlay profile for optional AD frameworks.
FrameworkOverlayManifest
dataclass
¶
FrameworkOverlayVerification
dataclass
¶
Verification result for a framework overlay manifest.
to_dict()
¶
Return JSON-ready verification metadata.
build_framework_overlay_manifest(*, overlay_path=None, python_version=None, package_versions=None, verification_status='not_verified')
¶
Build a CPU-wheel overlay manifest without performing installation.
install_framework_overlay(overlay_path)
¶
Install the CPU-only optional-framework overlay and return its manifest.
verify_framework_overlay_path(overlay_path, *, pythonpath=None)
¶
Verify that an overlay directory contains required package roots.
main(argv=None)
¶
Emit or verify the CPU-framework overlay manifest.
scpn_quantum_control.differentiable_module_hardening_audit
¶
Module coverage and diagnostic audit for differentiable-programming surfaces.
DifferentiableModuleHardeningAuditResult
dataclass
¶
Audit result for the differentiable module hardening registry.
to_dict()
¶
Return JSON-ready audit evidence.
DifferentiableModuleHardeningRecord
dataclass
¶
differentiable_module_hardening_registry()
¶
Return the registered differentiable module hardening evidence map.
run_differentiable_module_hardening_audit(*, repo_root=REPO_ROOT, registry=None)
¶
Audit differentiable modules against registered tests and diagnostics.
scpn_quantum_control.differentiable_transform_algebra
¶
Metamorphic transform-algebra gate for differentiable local routes.
TransformAlgebraAudit
dataclass
¶
Executable transform-algebra audit over supported and blocked routes.
categories
property
¶
Return sorted categories covered by this audit.
missing_categories
property
¶
Return required categories missing from the audit.
passed_cases
property
¶
Return cases whose executed residuals are within tolerance.
failed_cases
property
¶
Return cases whose executed residuals exceeded tolerance.
blocked_cases
property
¶
Return explicit fail-closed transform-algebra boundaries.
passed
property
¶
Return whether all executed checks passed and every category is covered.
__post_init__()
¶
Validate audit coverage and category uniqueness expectations.
to_dict()
¶
Return JSON-ready audit metadata.
TransformAlgebraCase
dataclass
¶
run_transform_algebra_audit(*, tolerance=TRANSFORM_ALGEBRA_TOLERANCE)
¶
Run the bounded transform-algebra metamorphic audit.
assert_transform_algebra_audit_passes(audit=None)
¶
Return the audit or raise with actionable failures.
scpn_quantum_control.differentiable_benchmark_report
¶
scpn_quantum_control.benchmarks.differentiable_evidence
¶
CI-only benchmark evidence metadata and artefact writers.
BenchmarkIsolationMetadata
dataclass
¶
Isolation metadata required before benchmark evidence can be promoted.
DifferentiableBenchmarkEvidenceBundle
dataclass
¶
Paths and metadata for one written differentiable benchmark bundle.
capture_host_load()
¶
Return host load averages when the platform exposes them.
infer_heavy_jobs_running(load)
¶
Infer whether current host load is too high for production promotion.
read_cpu_frequency_mhz(cpu_index=0)
¶
Read Linux CPU frequency metadata in MHz when available.
read_cpu_governor(cpu_index=0)
¶
Read Linux CPU frequency governor metadata when available.
write_differentiable_benchmark_evidence_bundle(output_dir, *, metadata, timing_rows, artifact_id=None, external_artifact_ids=None)
¶
Write raw JSON, CSV timing rows, and Markdown summary for benchmark evidence.
scpn_quantum_control.benchmarks.differentiable_hardening_gate
¶
Per-slice differentiable-programming hardening gate.
DifferentiableBenchmarkClassificationCase
dataclass
¶
DifferentiableHardeningGateCheck
dataclass
¶
DifferentiableHardeningSliceGateResult
dataclass
¶
Auditable verification checklist for one differentiable hardening slice.
to_dict()
¶
Return JSON-ready hardening-gate evidence.
run_differentiable_hardening_slice_gate(*, module_specific_pytest_targets, changed_python_targets=(), claim_ledger_validation_target=DEFAULT_CLAIM_LEDGER_VALIDATION_TARGET, test_quality_audit_target=DEFAULT_TEST_QUALITY_AUDIT_TARGET)
¶
Build the required verification checklist for a hardening slice.
The gate verifies command coverage and benchmark-classification invariants. It does not execute the commands and does not promote local benchmark rows to production evidence.
scpn_quantum_control.phase.tensorflow_maintenance
¶
TensorFlow maintenance decision for differentiable framework parity.
PhaseTensorFlowMaintenanceReport
dataclass
¶
TensorFlow framework-parity maintenance decision report.
compatibility_only
property
¶
Return whether TensorFlow is scoped as a compatibility-only surface.
graph_xla_parity_promoted
property
¶
Return whether broad TensorFlow Graph/XLA parity is promoted.
maintained_compatibility_routes
property
¶
Return bounded TensorFlow routes kept under maintenance.
blocked_routes
property
¶
Return TensorFlow routes that remain blocked.
ready_for_provider_exceedance
property
¶
Return whether TensorFlow can support provider-exceedance claims.
stale_claim_blockers
property
¶
Return claim families that must stay blocked in public surfaces.
__post_init__()
¶
Validate the TensorFlow decision report.
route(name)
¶
Return one named route or fail closed on unknown route names.
to_dict()
¶
Return JSON-ready TensorFlow maintenance decision metadata.
PhaseTensorFlowMaintenanceRoute
dataclass
¶
run_tensorflow_maintenance_decision()
¶
Return the TensorFlow framework-parity maintenance decision.
scpn_quantum_control.benchmarks.differentiable_isolated_benchmark_plan
¶
Isolated benchmark batch plan for differentiable promotion evidence.
DifferentiableIsolatedBenchmarkPlan
dataclass
¶
Validated batch plan for reproducing differentiable benchmarks in isolation.
to_dict()
¶
Return a JSON-ready isolated benchmark plan.
DifferentiableIsolatedBenchmarkPlanRow
dataclass
¶
DifferentiableIsolatedBenchmarkPlanValidation
dataclass
¶
Validation result for an isolated benchmark batch plan.
to_dict()
¶
Return JSON-ready plan validation evidence.
render_differentiable_isolated_benchmark_plan_markdown(plan)
¶
Render a reviewer-facing Markdown summary of the isolated benchmark plan.
run_differentiable_isolated_benchmark_plan(*, repo_root=REPO_ROOT, host_readiness=None)
¶
Build the isolated benchmark batch plan from committed evidence artifacts.
validate_differentiable_isolated_benchmark_plan(plan, *, repo_root=REPO_ROOT)
¶
Validate plan rows, source artifacts, commands, and promotion boundaries.
scpn_quantum_control.benchmarks.differentiable_external_comparison
¶
External framework comparison rows for bounded Phase-QNode claims.
ExternalComparisonArtifact
dataclass
¶
Written external comparison artefact paths and summary metadata.
to_dict()
¶
Return a JSON-ready artefact summary.
ExternalComparisonRow
dataclass
¶
IdenticalCircuitGradientComparisonArtifact
dataclass
¶
Written same-circuit comparison artefact summary.
to_dict()
¶
Return a JSON-ready artefact summary.
IdenticalCircuitGradientComparisonRow
dataclass
¶
run_differentiable_external_comparison_suite()
¶
Run or classify optional external comparison rows.
The SCPN analytic parameter-shift reference remains the source of truth. Missing optional tooling is recorded as hard-gap evidence instead of being silently omitted.
run_identical_circuit_gradient_comparison_suite()
¶
Run exact-state same-circuit gradient comparisons for Qiskit and PennyLane.
write_differentiable_external_comparison(output_path, rows=None, *, artifact_id='differentiable-external-comparison-local')
¶
Write external comparison rows as a bounded JSON evidence artefact.
write_identical_circuit_gradient_comparison(output_path, rows=None, *, artifact_id='identical-circuit-gradient-comparison-local')
¶
Write exact-state same-circuit comparison rows as JSON evidence.
scpn_quantum_control.phase.pennylane_provider_plugin
¶
PennyLane provider-plugin gradient artefacts and fail-closed route matrix.
PennyLaneHardwarePluginExecutionArtifact
dataclass
¶
PennyLaneProviderEvidenceBundle
dataclass
¶
PennyLanePluginMatrixResult
dataclass
¶
Fail-closed PennyLane plugin/provider parity matrix.
local_plugin_parity_ready
property
¶
Return whether bounded local/default-qubit PennyLane routes pass.
provider_plugin_execution_ready
property
¶
Return whether provider-plugin execution artefacts are attached.
hardware_plugin_execution_ready
property
¶
Return whether live hardware-plugin execution artefacts are attached.
provider_plugin_gradient_parity_ready
property
¶
Return whether provider-plugin gradient parity artefacts are attached.
ready_for_provider_exceedance
property
¶
Return whether the matrix permits PennyLane provider-exceedance claims.
open_gaps
property
¶
Return routes that still block PennyLane provider-exceedance claims.
route_status(name)
¶
Return the status for a named route, failing closed on unknown names.
to_dict()
¶
Return JSON-ready PennyLane plugin/provider parity metadata.
PennyLanePluginMatrixRoute
dataclass
¶
PennyLaneProviderGradientParityArtifact
dataclass
¶
PennyLaneProviderPluginExecutionArtifact
dataclass
¶
run_pennylane_plugin_matrix(*, provider_execution_artifact=None, provider_gradient_parity_artifact=None, hardware_execution_artifact=None, provider_evidence_bundle=None, evidence_freshness_as_of_utc=PENNYLANE_PROVIDER_EVIDENCE_REVIEW_AS_OF_UTC)
¶
Return a fail-closed PennyLane plugin/provider parity matrix.
The current evidence covers bounded local default.qubit exact-state
parity, metadata-preserving shot policy records, and registered
Phase-QNode export through the local PennyLane route. Provider plugin
execution, live hardware execution, and promotion evidence remain blocked
until concrete artefacts are attached.
scpn_quantum_control.differentiable_claim_ledger
¶
Claim ledger for bounded differentiable Phase-QNode evidence.
ClaimLedger
dataclass
¶
Loaded differentiable claim ledger.
__iter__()
¶
Iterate over claim-ledger rows.
ClaimLedgerRow
dataclass
¶
ClaimLedgerValidation
dataclass
¶
Claim-ledger validation result.
DifferentiableSupportSurfaceAlignment
dataclass
¶
load_differentiable_claim_ledger(path=DEFAULT_LEDGER_PATH)
¶
Load the committed differentiable claim ledger.
load_differentiable_support_surface_alignment(path=DEFAULT_SUPPORT_SURFACE_ALIGNMENT_PATH)
¶
Load the committed differentiable support-surface alignment artefact.
render_claim_ledger_markdown(rows_or_ledger)
¶
Render a compact Markdown summary for reviewers.
render_differentiable_support_surface_alignment_markdown(alignment)
¶
Render support-surface alignment evidence for reviewers.
validate_claim_ledger(rows_or_ledger, *, artifact_statuses=None)
¶
Validate claim ledger promotion invariants.
validate_differentiable_support_surface_alignment(rows=None, *, repo_root=REPO_ROOT, ledger_path=DEFAULT_LEDGER_PATH, manifest_path=DEFAULT_CAPABILITY_MANIFEST_PATH)
¶
Validate that claim-ledger surfaces exist and match generated inventory.
validate_public_language_against_ledger(rows_or_ledger, public_texts)
¶
Reject public SOTA wording when the ledger has no promoted claim.
scpn_quantum_control.differentiable_architecture_map
¶
Architecture and Rustification map for differentiable-programming governance.
DifferentiableArchitectureMap
dataclass
¶
Deterministic architecture map for differentiable Rustification routing.
to_dict()
¶
Return a JSON-ready architecture map.
DifferentiableArchitectureMapLayer
dataclass
¶
One architecture layer tied to inventory, scorecard, and evidence paths.
DifferentiableArchitectureMapValidation
dataclass
¶
Validation result for a differentiable architecture map.
to_dict()
¶
Return JSON-ready architecture-map validation evidence.
render_differentiable_architecture_map_markdown(architecture_map)
¶
Render a reviewer-facing Markdown summary of the architecture map.
run_differentiable_architecture_map(*, inventory=None, scorecard=None)
¶
Build the architecture and Rustification map from committed evidence.
validate_differentiable_architecture_map(architecture_map, *, inventory=None, scorecard=None, repo_root=REPO_ROOT)
¶
Validate architecture layers, references, paths, and readiness invariants.
scpn_quantum_control.differentiable_dependency_environment_map
¶
Dependency and environment evidence map for differentiable-programming governance.
DifferentiableDependencyEnvironmentMap
dataclass
¶
Deterministic map of dependency profiles and environment evidence.
to_dict()
¶
Return a JSON-ready dependency environment map.
DifferentiableDependencyEnvironmentProfile
dataclass
¶
DifferentiableDependencyEnvironmentMapValidation
dataclass
¶
Validation result for a differentiable dependency environment map.
to_dict()
¶
Return JSON-ready dependency-environment validation evidence.
render_differentiable_dependency_environment_map_markdown(environment_map)
¶
Render a reviewer-facing Markdown summary of the dependency map.
run_differentiable_dependency_environment_map(*, environment_lock=None)
¶
Build the dependency and environment map from committed lockfile evidence.
validate_differentiable_dependency_environment_map(environment_map, *, environment_lock=None, repo_root=REPO_ROOT)
¶
Validate dependency profiles, paths, checksums, and readiness invariants.
scpn_quantum_control.differentiable_competitive_baselines
¶
Freshness gate for differentiable-computing competitive baselines.
CompetitiveBaselinePromotionGate
dataclass
¶
Combined baseline freshness and public-language promotion gate.
to_dict()
¶
Return JSON-ready combined gate metadata.
CompetitiveBaselineRefresh
dataclass
¶
Committed refresh bundle over differentiable competitive baselines.
to_dict()
¶
Return a JSON-ready refresh payload.
CompetitiveBaselineRow
dataclass
¶
One upstream differentiable-computing baseline source.
classification
property
¶
Return the evidence classification for this baseline source.
__post_init__()
¶
Validate local row invariants that do not need repository access.
age_days(*, as_of)
¶
Return the age of this row in whole days at as_of.
is_fresh(*, as_of)
¶
Return whether this baseline source is within its freshness window.
to_dict()
¶
Return a JSON-ready baseline row.
CompetitiveBaselineValidation
dataclass
¶
Validation result for the competitive baseline refresh bundle.
to_dict()
¶
Return JSON-ready validation metadata.
audit_competitive_baseline_promotion_gate(*, refresh=None, refresh_path=DEFAULT_COMPETITIVE_BASELINE_REFRESH_PATH, as_of=None, public_texts=None, public_paths=DEFAULT_PUBLIC_SOTA_LANGUAGE_PATHS, ledger=None, ledger_path=DEFAULT_LEDGER_PATH, repo_root=REPO_ROOT)
¶
Validate freshness and public-language promotion evidence together.
load_competitive_baseline_refresh(path=DEFAULT_COMPETITIVE_BASELINE_REFRESH_PATH)
¶
Load a committed competitive-baseline refresh artifact.
render_competitive_baseline_refresh_markdown(refresh)
¶
Render a reviewer-facing Markdown summary of baseline sources.
run_competitive_baseline_refresh(*, generated_on=date(2026, 6, 27))
¶
Build the deterministic competitive-baseline refresh bundle.
validate_competitive_baseline_refresh(refresh=None, *, path=DEFAULT_COMPETITIVE_BASELINE_REFRESH_PATH, as_of=None)
¶
Validate baseline freshness, source provenance, and category coverage.
MLIR Compiler¶
scpn_quantum_control.compiler.mlir
¶
Deterministic MLIR-style export for Kuramoto-XY workloads.
The module emits a conservative textual interchange layer for the SCPN Kuramoto-XY compiler. It does not require an MLIR Python runtime. Compiler AD native LLVM/JIT execution is available only for primitives with verified native lowering metadata; unrelated QIR, provider-pulse, and hardware execution claims remain outside this boundary. The value is a stable, auditable IR boundary for compiler passes and external tooling.
MLIRCompileConfig
dataclass
¶
Configuration for Kuramoto-XY MLIR-style export.
DifferentiableMLIRCompileConfig
dataclass
¶
Configuration for differentiable primitive MLIR-style lowering.
CompilerADExecutableConfig
dataclass
¶
Configuration for verified executable primitive AD kernels.
CompilerADKernelVerification
dataclass
¶
Runtime verification evidence for an executable primitive AD kernel.
passed
property
¶
Return whether all executed verification checks passed.
ExecutableCompilerADKernel
dataclass
¶
Executable compiler-backed primitive AD kernel with MLIR provenance.
ExecutableWholeProgramADBatchResult
dataclass
¶
Batched replay result from an executable whole-program AD kernel.
ExecutableWholeProgramADKernel
dataclass
¶
Executable replay kernel for a supported captured program AD trace.
The kernel is intentionally bounded: it replays the original Python objective through the supported operator-intercepted program AD IR, checks the one-dimensional parameter shape, checks the captured control/signature surface, and computes gradients through reverse-mode adjoint replay. It is executable and deterministic for the supported captured trace contract; it does not claim arbitrary source compilation or native LLVM/JIT lowering for arbitrary Python programs.
value_and_grad(values)
¶
Execute value replay and reverse-mode adjoint gradient replay.
value(values)
¶
Execute value replay for the captured program AD trace.
gradient(values)
¶
Execute reverse-mode adjoint replay for the captured program AD trace.
batch_value_and_grad(values)
¶
Execute same-branch batched value and reverse-adjoint gradient replay.
batch_value(values)
¶
Execute batched value replay for rows preserving the compiled branch path.
batch_gradient(values)
¶
Execute batched reverse-adjoint replay for rows preserving the branch path.
NativeWholeProgramADKernel
dataclass
¶
Native LLVM/JIT kernel for a supported scalar program AD trace.
value(values)
¶
Execute the native scalar value kernel.
gradient(values)
¶
Execute the native scalar-output gradient kernel.
value_and_grad(values)
¶
Execute native value and gradient kernels.
jvp(values, tangent)
¶
Execute the native scalar JVP kernel.
vjp(values, cotangent)
¶
Execute the native scalar VJP kernel.
batch_value_and_grad(values)
¶
Execute native value and gradient kernels over a two-dimensional batch.
batch_value(values)
¶
Execute native value kernels over a two-dimensional batch.
batch_gradient(values)
¶
Execute native gradient kernels over a two-dimensional batch.
batch_jvp(values, tangents)
¶
Execute the compiled native JVP kernel over a two-dimensional batch.
batch_vjp(values, cotangents)
¶
Execute the compiled native VJP kernel over a two-dimensional batch.
MLIRModule
dataclass
¶
Textual MLIR module plus deterministic provenance.
compile_kuramoto_to_mlir(problem, config, omega=None)
¶
Compile a Kuramoto problem into deterministic MLIR-style text.
problem may be a validated :class:KuramotoProblem or a raw coupling
matrix when omega is supplied. Raw arrays are validated through the
public Kuramoto facade before IR generation.
compile_custom_derivative_rule_to_mlir(rule, values, config=None)
¶
Lower an exact custom derivative rule to deterministic MLIR-style text.
This emits an auditable differentiable-primitive interchange artefact with value and Jacobian shape metadata. When numeric payloads are enabled, the current value and exact custom Jacobian are embedded as deterministic attributes. The function deliberately does not claim executable LLVM or JIT code generation.
compile_custom_derivative_rule_to_executable(rule, sample_values, config=None, *, sample_tangent=None, sample_cotangent=None)
¶
Compile a custom derivative rule into a verified executable AD kernel.
The executable backend is the dependency-free SCPN MLIR runtime adapter: it couples deterministic differentiable MLIR provenance with normalized runtime callables for value/JVP/VJP execution and verifies those kernels against the source custom derivative rule before returning. Native LLVM/JIT kernels use primitive-specific lowering entrypoints.
compile_registered_primitive_to_executable(registry, identity, sample_values, config=None, *, sample_tangent=None, sample_cotangent=None)
¶
Compile a registered primitive identity into an executable AD kernel.
compile_whole_program_ad_trace_to_executable(objective, sample_values, parameters=None, config=None, *, trace=True)
¶
Compile a supported captured program AD trace to an executable replay kernel.
This is the executable compiler boundary for whole-program AD today: it captures the supported scalar program IR, verifies reverse adjoint replay is available, emits deterministic MLIR provenance, then returns a fail-closed replay kernel. Shape drift, non-finite inputs, and branch/signature drift raise errors instead of silently changing the differentiated program.
compile_whole_program_ad_trace_to_native_llvm_jit(objective, sample_values, parameters=None, config=None, *, trace=True)
¶
Compile a supported scalar program AD trace to native LLVM/JIT kernels.
compile_whole_program_ad_trace_to_mlir(result, config=None)
¶
Lower a whole-program AD execution trace to MLIR-style interchange text.
The emitted module is an audit artefact for Python whole-program gradients and polyglot compiler planning. It deliberately records Rust and LLVM/JIT executable differentiation as blocked unless a real backend is provided.
Real-Time Runtime¶
scpn_quantum_control.control.realtime_runtime
¶
Deadline-aware realtime control runtime.
This is a deterministic software-control runtime for bounded feedback loops. It accounts for latency, jitter, and deadline misses around injected control steps. It is not an intra-shot hardware-latency claim.
RealtimeRuntimeConfig
dataclass
¶
Timing contract for a realtime software control loop.
RealtimeTickRecord
dataclass
¶
Auditable timing record for one realtime tick.
RealtimeRunResult
dataclass
¶
Aggregate result for a realtime control-loop run.
VirtualRealtimeClock
¶
MonotonicRealtimeClock
¶
run_realtime_control_loop(n_ticks, step, *, config, clock=None)
¶
Run step on a fixed-period realtime schedule with deadline accounting.
Cloud-Native Deployment¶
scpn_quantum_control.deployment.cloud_native
¶
Deterministic cloud-native manifest generation.
The generator emits Kubernetes and Docker Compose manifests for offline SCPN workloads. It rejects secret-like environment variables and does not read local credentials, create clusters, or contact cloud APIs.
ContainerResources
dataclass
¶
CPU and memory requests/limits for one SCPN container.
CloudDeploymentSpec
dataclass
¶
Cloud-native deployment request for an offline SCPN workload.
CloudManifestBundle
dataclass
¶
Generated cloud-native manifest files plus provenance digest.
generate_cloud_manifests(spec)
¶
Generate Kubernetes and Docker Compose manifests for spec.
Hardware Abstraction Layer¶
scpn_quantum_control.hardware.backends
¶
Plugin / backend extension API.
Closes audit item C10. Third parties may now register additional quantum
backends without editing this repository by declaring an entry point in
the scpn_quantum_control.backends group:
.. code-block:: toml
[project.entry-points."scpn_quantum_control.backends"]
acme_trapped_ion = "acme_plugin:AcmeBackend"
analog_kuramoto = "scpn_quantum_control.hardware.analog_kuramoto:analog_kuramoto_factory"
hybrid_digital_analog = "scpn_quantum_control.hardware.hybrid_digital_analog:hybrid_digital_analog_factory"
The entry-point target must be a zero-argument callable or a class that
returns an object satisfying the :class:BackendProtocol interface when
instantiated.
Internal backends (Qiskit runtime, PennyLane) register themselves via
this repository's own pyproject.toml entry points; they are loaded
the same way every third-party backend is, which means a broken plugin
cannot take down the rest of the registry.
Discovery is lazy: call :func:discover_backends once per process. The
module also exposes a manual :func:register_backend hatch for tests
and notebooks that want to exercise a specific class without round-trip
through entry points.
QuantumBackendDescriptor
dataclass
¶
Provider-neutral execution contract for a quantum backend.
Registry lookup must never authenticate, touch the network, or queue paid work. This static descriptor gives routing code enough information to distinguish local simulation from approval-gated cloud submission before execution-specific adapters are invoked.
describe_hal_backend_profile(backend_id)
¶
Return selector metadata for one built-in HAL profile.
The descriptor is constructed from static HAL profile metadata only. It does not import provider SDKs, authenticate, inspect queues, or create any executable adapter. Runtime availability remains the responsibility of the injected adapter route.
list_hal_backend_descriptors()
¶
Return selector metadata for all built-in HAL profiles.
describe_backend(name)
¶
Return the provider-neutral descriptor for name.
Third-party backends that have not implemented descriptor() get a
conservative descriptor: no advertised submit/simulator capability
and explicit approval required before production routing.
list_quantum_backends(*, auto_discover=True)
¶
Return sorted provider-neutral descriptors for every known backend.
scpn_quantum_control.hardware.provider_smoke
¶
Metadata-only optional dependency smoke checks for HAL provider routes.
AggregatorProviderOptionalDependencyRow
dataclass
¶
Offline dependency evidence for one aggregator/provider route.
ProviderOptionalDependencyRow
dataclass
¶
Offline import-probe result for one built-in HAL backend route.
aggregator_provider_optional_dependency_matrix(*, aggregator=None, provider=None, ir_format=None, route_id=None)
¶
Return offline dependency evidence for aggregator/provider routes.
The matrix joins the declared aggregator/provider route table to the HAL
optional-dependency probe. It remains no-network and no-authentication:
import availability is measured through find_spec only.
main(argv=None)
¶
Print the offline provider optional-dependency matrix.
The command is intentionally metadata-only: it imports no provider SDK,
reads no credentials, creates no clients, performs no authentication, and
touches no network endpoint. Use --require-all in provider-pack CI lanes
after installing scpn-quantum-control[providers].
provider_optional_dependency_matrix()
¶
Return metadata-only import availability for every built-in HAL route.
The probe uses importlib.util.find_spec only. It does not import provider
SDKs, read credentials, create clients, authenticate, or touch the network.
scpn_quantum_control.hardware.provider_capability_discovery
¶
No-submit capability discovery contracts for aggregator/provider routes.
Module size note: this module is intentionally kept whole. Its top-level definitions form a single connected provider-capability-discovery cluster, so it is sized by responsibility rather than line count. See docs/architecture.md ("Module size and single-responsibility policy").
ProviderCapabilitySnapshot
dataclass
¶
Provider target metadata collected without submitting a workload.
ProviderCapabilityDecision
dataclass
¶
Readiness decision for one no-submit provider capability snapshot.
to_dict()
¶
Serialise the provider capability decision.
assess_provider_capability_snapshot(snapshot, *, aggregator, provider, backend_id, route_id=None, required_ir_format=None, min_qubits=None)
¶
Assess route-level provider metadata without submitting work.
probe_aggregator_provider_capability(*, aggregator, provider, metadata_probe, ir_format=None, route_id=None, min_qubits=None)
¶
Resolve a route, collect provider metadata, and assess it without submission.
snapshot_from_azure_target(resolved, target)
¶
Build a no-submit capability snapshot from Azure Quantum target metadata.
snapshot_from_braket_device(resolved, device)
¶
Build a no-submit capability snapshot from AWS Braket device metadata.
snapshot_from_dwave_solver(resolved, solver)
¶
Build a no-submit capability snapshot from direct D-Wave solver metadata.
snapshot_from_iqm_backend(resolved, backend)
¶
Build a no-submit capability snapshot from direct IQM backend metadata.
snapshot_from_ionq_backend(resolved, backend)
¶
Build a no-submit capability snapshot from direct IonQ backend metadata.
snapshot_from_oqc_target(resolved, target)
¶
Build a no-submit capability snapshot from direct OQC target metadata.
snapshot_from_pasqal_target(resolved, target)
¶
Build a no-submit capability snapshot from direct Pasqal target metadata.
snapshot_from_qiskit_runtime_backend(resolved, backend)
¶
Build a no-submit capability snapshot from IBM/Qiskit backend metadata.
snapshot_from_qbraid_device(resolved, device)
¶
Build a no-submit capability snapshot from qBraid device metadata.
snapshot_from_quandela_processor(resolved, processor)
¶
Build a no-submit capability snapshot from direct Quandela processor metadata.
snapshot_from_quantinuum_backend(resolved, backend)
¶
Build a no-submit capability snapshot from direct Quantinuum metadata.
snapshot_from_quera_bloqade(resolved, target)
¶
Build a no-submit capability snapshot from direct QuEra/Bloqade metadata.
snapshot_from_rigetti_qcs(resolved, quantum_computer)
¶
Build a no-submit capability snapshot from direct Rigetti QCS metadata.
snapshot_from_strangeworks_backend(resolved, backend)
¶
Build a no-submit capability snapshot from Strangeworks backend metadata.
scpn_quantum_control.hardware.aggregators
¶
First-class aggregator/provider route matrix for the hardware HAL.
AggregatorProviderRoute
dataclass
¶
A declared aggregator/provider combination resolved to a HAL backend.
ResolvedAggregatorProviderRoute
dataclass
¶
Executable resolution of an aggregator/provider route.
aggregator_provider_routes_for(*, aggregator=None, provider=None)
¶
Return declared routes filtered by aggregator and/or provider.
built_in_aggregator_provider_routes()
¶
Return the metadata-only aggregator/provider coverage matrix.
resolve_aggregator_provider_route(*, aggregator, provider, ir_format=None, route_id=None)
¶
Resolve a broker/provider request to one executable HAL profile.
scpn_quantum_control.hardware.hal
¶
Provider-neutral hardware abstraction layer.
This module separates SCPN workload routing from provider SDKs. Discovery is
metadata-only: constructing profiles does not import Qiskit, Braket, Azure,
IonQ, Rigetti, QuEra, IQM, Pasqal, OQC, D-Wave, or simulator packages. Live
execution is available only through an injected backend adapter that satisfies
QuantumBackend and, for cloud profiles, carries an explicit approval token.
BackendCapabilities
dataclass
¶
Provider route capabilities used for fail-fast workload validation.
BackendProfile
dataclass
¶
Static profile for a concrete provider, broker, or simulator route.
QuantumWorkload
dataclass
¶
Provider-neutral workload handed to an injected backend adapter.
QuantumJobRef
dataclass
¶
Stable handle returned by a backend adapter after submission.
QuantumJobResult
dataclass
¶
Provider-neutral result payload for shot-count workloads.
QuantumBackend
¶
Bases: Protocol
Runtime protocol for injected provider adapters.
LocalDeterministicSimulator
¶
Offline simulator adapter used to verify the HAL execution contract.
submit(workload, *, approval_id=None)
¶
Submit a workload to the backend and return its job reference.
status(job)
¶
Return the current status for a submitted backend job.
result(job)
¶
Return the completed result for a submitted backend job.
cancel(job)
¶
Request cancellation for a submitted backend job.
HardwareAbstractionLayer
¶
Profile registry plus approval-gated execution router.
with_builtin_profiles()
classmethod
¶
Construct a HAL with all built-in provider route profiles.
list_profiles()
¶
Return profiles in deterministic backend-id order.
profile(backend_id)
¶
Return one backend profile by id.
register_backend(backend)
¶
Inject an executable adapter for one known profile.
submit(backend_id, workload, *, approval_id=None)
¶
Validate and submit a workload through an injected adapter.
status(job)
¶
Return current status by delegating to the owning adapter.
result(job)
¶
Return a result by delegating to the owning adapter.
cancel(job)
¶
Cancel a job by delegating to the owning adapter.
built_in_backend_profiles()
¶
Return built-in provider and simulator route profiles.
Profiles intentionally describe routes rather than perform SDK discovery. Provider-specific credentials, queues, regions, and pricing are left to injected adapters so offline tooling remains deterministic and auditable.
scpn_quantum_control.hardware.hal_qiskit
¶
Qiskit-backed adapters for :mod:scpn_quantum_control.hardware.hal.
QiskitAerHALAdapter
¶
Local Aer adapter implementing the provider-neutral HAL protocol.
submit(workload, *, approval_id=None)
¶
Submit a workload to the backend and return its job reference.
status(job)
¶
Return the current status for a submitted backend job.
result(job)
¶
Return the completed result for a submitted backend job.
cancel(job)
¶
Request cancellation for a submitted backend job.
QiskitRuntimeHALAdapter
¶
IBM Runtime Sampler adapter implementing the HAL protocol.
submit(workload, *, approval_id=None)
¶
Submit a workload to the backend and return its job reference.
status(job)
¶
Return the current status for a submitted backend job.
result(job)
¶
Return the completed result for a submitted backend job.
cancel(job)
¶
Request cancellation for a submitted backend job.
qiskit_circuit_to_workload(circuit, *, workload_id, shots, metadata=None)
¶
Encode a Qiskit circuit as a QPY-backed HAL workload.
qiskit_circuit_to_qasm3_workload(circuit, *, workload_id, shots, metadata=None)
¶
Encode a Qiskit circuit as an OpenQASM 3 HAL workload.
scpn_quantum_control.hardware.hal_braket
¶
Amazon Braket adapters for :mod:scpn_quantum_control.hardware.hal.
BraketLocalHALAdapter
¶
Local Amazon Braket simulator adapter implementing the HAL protocol.
submit(workload, *, approval_id=None)
¶
Submit a workload to the backend and return its job reference.
status(job)
¶
Return the current status for a submitted backend job.
result(job)
¶
Return the completed result for a submitted backend job.
cancel(job)
¶
Request cancellation for a submitted backend job.
BraketAwsHALAdapter
¶
AWS Braket cloud adapter implementing the HAL protocol.
submit(workload, *, approval_id=None)
¶
Submit a workload to the backend and return its job reference.
status(job)
¶
Return the current status for a submitted backend job.
result(job)
¶
Return the completed result for a submitted backend job.
cancel(job)
¶
Request cancellation for a submitted backend job.
braket_circuit_to_workload(circuit, *, workload_id, shots, metadata=None)
¶
Encode a Braket circuit as an OpenQASM 3 HAL workload.
scpn_quantum_control.hardware.hal_cirq
¶
Local Cirq simulator adapter for the provider-neutral HAL.
CirqLocalHALAdapter
¶
Local Cirq simulator adapter implementing the HAL protocol.
submit(workload, *, approval_id=None)
¶
Submit a workload to the backend and return its job reference.
status(job)
¶
Return the current status for a submitted backend job.
result(job)
¶
Return the completed result for a submitted backend job.
cancel(job)
¶
Request cancellation for a submitted backend job.
cirq_circuit_workload(circuit, *, workload_id, n_qubits, shots, metadata=None)
¶
Encode a Cirq circuit handle or serialised circuit as a HAL workload.
scpn_quantum_control.hardware.hal_dwave
¶
Direct D-Wave Leap BQM adapter for the provider-neutral HAL.
DWaveLeapHALAdapter
¶
Synchronous D-Wave Leap sampler adapter for BQM workloads.
submit(workload, *, approval_id=None)
¶
Submit a workload to the backend and return its job reference.
status(job)
¶
Return the current status for a submitted backend job.
result(job)
¶
Return the completed result for a submitted backend job.
cancel(job)
¶
Request cancellation for a submitted backend job.
dwave_bqm_workload(*, linear, quadratic, workload_id, n_variables, reads, offset=0.0, vartype='BINARY', metadata=None, schema=DWAVE_BQM_SCHEMA)
¶
Encode an Ising/QUBO binary quadratic model as a D-Wave HAL workload.
scpn_quantum_control.hardware.hal_azure
¶
Azure Quantum adapter for :mod:scpn_quantum_control.hardware.hal.
AzureQuantumHALAdapter
¶
Azure Quantum target adapter implementing the HAL protocol.
submit(workload, *, approval_id=None)
¶
Submit a workload to the backend and return its job reference.
status(job)
¶
Return the current status for a submitted backend job.
result(job)
¶
Return the completed result for a submitted backend job.
cancel(job)
¶
Request cancellation for a submitted backend job.
azure_openqasm3_to_workload(program, *, workload_id, n_qubits, shots, metadata=None)
¶
Build an Azure Quantum OpenQASM 3 HAL workload.
scpn_quantum_control.hardware.hal_ionq
¶
Direct IonQ Cloud adapter for :mod:scpn_quantum_control.hardware.hal.
IonQCloudHALAdapter
¶
IonQ v0.4 REST adapter implementing the provider-neutral HAL protocol.
submit(workload, *, approval_id=None)
¶
Submit a workload to the backend and return its job reference.
status(job)
¶
Return the current status for a submitted backend job.
result(job)
¶
Return the completed result for a submitted backend job.
cancel(job)
¶
Request cancellation for a submitted backend job.
ionq_qis_workload(circuit, *, workload_id, n_qubits, shots, gateset='qis', metadata=None)
¶
Encode IonQ's language-neutral QIS circuit JSON as a HAL workload.
scpn_quantum_control.hardware.hal_iqm
¶
IQM Qiskit adapter for :mod:scpn_quantum_control.hardware.hal.
IQMHALAdapter
¶
IQM Qiskit adapter implementing the provider-neutral HAL protocol.
submit(workload, *, approval_id=None)
¶
Submit a workload to the backend and return its job reference.
status(job)
¶
Return the current status for a submitted backend job.
result(job)
¶
Return the completed result for a submitted backend job.
cancel(job)
¶
Request cancellation for a submitted backend job.
iqm_qiskit_workload(circuit, *, workload_id, shots, metadata=None)
¶
Encode a Qiskit circuit as a HAL workload for IQM execution.
scpn_quantum_control.hardware.hal_oqc
¶
Direct OQC QCAAS adapter for the provider-neutral HAL.
OQCHALAdapter
¶
OQC QCAAS client adapter implementing the provider-neutral HAL protocol.
submit(workload, *, approval_id=None)
¶
Submit a workload to the backend and return its job reference.
status(job)
¶
Return the current status for a submitted backend job.
result(job)
¶
Return the completed result for a submitted backend job.
cancel(job)
¶
Request cancellation for a submitted backend job.
oqc_openqasm3_workload(program, *, workload_id, n_qubits, shots, metadata=None)
¶
Encode an OpenQASM 3 program as an OQC HAL workload.
scpn_quantum_control.hardware.hal_pasqal
¶
Pasqal/Pulser adapter for :mod:scpn_quantum_control.hardware.hal.
PasqalPulserHALAdapter
¶
Pasqal/Pulser client adapter implementing the provider-neutral HAL protocol.
submit(workload, *, approval_id=None)
¶
Submit a workload to the backend and return its job reference.
status(job)
¶
Return the current status for a submitted backend job.
result(job)
¶
Return the completed result for a submitted backend job.
cancel(job)
¶
Request cancellation for a submitted backend job.
pulser_sequence_workload(payload, *, workload_id, n_qubits, shots, metadata=None)
¶
Encode a Pulser sequence plan as a HAL workload for Pasqal.
scpn_quantum_control.hardware.hal_pennylane
¶
PennyLane-backed adapter for :mod:scpn_quantum_control.hardware.hal.
PennyLaneDeviceHALAdapter
¶
Local PennyLane device adapter implementing the HAL protocol.
submit(workload, *, approval_id=None)
¶
Submit a workload to the backend and return its job reference.
status(job)
¶
Return the current status for a submitted backend job.
result(job)
¶
Return the completed result for a submitted backend job.
cancel(job)
¶
Request cancellation for a submitted backend job.
pennylane_gate_workload(instructions, *, workload_id, n_qubits, shots, metadata=None)
¶
Encode a strict PennyLane native-gate instruction payload as HAL work.
scpn_quantum_control.hardware.hal_qbraid
¶
qBraid runtime adapter for :mod:scpn_quantum_control.hardware.hal.
QbraidRuntimeHALAdapter
¶
qBraid cloud adapter implementing the provider-neutral HAL protocol.
submit(workload, *, approval_id=None)
¶
Submit a workload to the backend and return its job reference.
status(job)
¶
Return the current status for a submitted backend job.
result(job)
¶
Return the completed result for a submitted backend job.
cancel(job)
¶
Request cancellation for a submitted backend job.
qbraid_program_to_workload(program, *, workload_id, ir_format, n_qubits, shots, metadata=None)
¶
Encode a qBraid-supported program string as a HAL workload.
scpn_quantum_control.hardware.hal_strangeworks
¶
Strangeworks Compute adapter for :mod:scpn_quantum_control.hardware.hal.
StrangeworksComputeHALAdapter
¶
Strangeworks Compute adapter implementing the provider-neutral HAL protocol.
submit(workload, *, approval_id=None)
¶
Submit a workload to the backend and return its job reference.
status(job)
¶
Return the current status for a submitted backend job.
result(job)
¶
Return the completed result for a submitted backend job.
cancel(job)
¶
Request cancellation for a submitted backend job.
strangeworks_program_to_workload(program, *, workload_id, ir_format, n_qubits, shots, metadata=None)
¶
Encode a Strangeworks-supported program string as a HAL workload.
scpn_quantum_control.hardware.hal_quandela
¶
Direct Quandela/Perceval adapter for the provider-neutral HAL.
QuandelaPercevalHALAdapter
¶
Quandela/Perceval adapter implementing the provider-neutral HAL protocol.
submit(workload, *, approval_id=None)
¶
Submit a workload to the backend and return its job reference.
status(job)
¶
Return the current status for a submitted backend job.
result(job)
¶
Return the completed result for a submitted backend job.
cancel(job)
¶
Request cancellation for a submitted backend job.
quandela_perceval_workload(payload, *, workload_id, n_modes, shots, metadata=None)
¶
Encode a Perceval photonic plan as a Quandela HAL workload.
scpn_quantum_control.hardware.hal_quera_bloqade
¶
QuEra Bloqade adapter for :mod:scpn_quantum_control.hardware.hal.
QuEraBloqadeHALAdapter
¶
Bloqade routine adapter implementing the provider-neutral HAL protocol.
submit(workload, *, approval_id=None)
¶
Submit a workload to the backend and return its job reference.
status(job)
¶
Return the current status for a submitted backend job.
result(job)
¶
Return the completed result for a submitted backend job.
cancel(job)
¶
Request cancellation for a submitted backend job.
bloqade_ahs_workload(payload, *, workload_id, n_qubits, shots, metadata=None)
¶
Encode a Bloqade analogue Hamiltonian plan as a HAL workload.
scpn_quantum_control.hardware.hal_quantinuum
¶
Quantinuum pytket adapter for :mod:scpn_quantum_control.hardware.hal.
QuantinuumCloudHALAdapter
¶
pytket-quantinuum adapter implementing the provider-neutral HAL protocol.
submit(workload, *, approval_id=None)
¶
Submit a workload to the backend and return its job reference.
status(job)
¶
Return the current status for a submitted backend job.
result(job)
¶
Return the completed result for a submitted backend job.
cancel(job)
¶
Request cancellation for a submitted backend job.
quantinuum_tket_workload(circuit, *, workload_id, n_qubits, shots, metadata=None)
¶
Encode a pytket circuit dictionary as a HAL workload for Quantinuum.
scpn_quantum_control.hardware.hal_rigetti
¶
Rigetti pyQuil adapter for :mod:scpn_quantum_control.hardware.hal.
RigettiQCSHALAdapter
¶
Synchronous pyQuil QuantumComputer adapter for the Rigetti QCS route.
submit(workload, *, approval_id=None)
¶
Submit a workload to the backend and return its job reference.
status(job)
¶
Return the current status for a submitted backend job.
result(job)
¶
Return the completed result for a submitted backend job.
cancel(job)
¶
Request cancellation for a submitted backend job.
rigetti_quil_workload(program, *, workload_id, n_qubits, shots, metadata=None)
¶
Encode a Quil program as a HAL workload for direct pyQuil execution.
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[float64]
|
Coupling matrix. |
required |
omega
|
NDArray[float64]
|
Natural frequencies. |
required |
t_total
|
float
|
Total evolution time. |
required |
n_steps
|
int
|
Number of intermediate time steps to return. |
required |
initial_state
|
NDArray[complex128] | 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[str, Any]
|
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.
FSSFitDiagnostics
dataclass
¶
Least-squares diagnostics for one finite-size scaling ansatz.
Parameters¶
model:
Stable identifier for the fitted ansatz.
extrapolated_k_c:
Intercept of the linearised finite-size model, interpreted as
K_c(infinity) for the selected ansatz.
correction_coefficient:
Coefficient multiplying the finite-size correction coordinate.
residuals:
Pointwise residuals observed K_c(N) - fitted K_c(N) in the order
of the input system sizes.
residual_norm:
Euclidean norm of the residual vector.
max_abs_residual:
Largest absolute residual across the fitted system sizes.
design_condition:
Condition number of the two-column linear design matrix.
rank:
Numerical rank reported by numpy.linalg.lstsq.
n_points:
Number of finite-size points used in the fit.
claim_boundary:
Claim boundary attached to the diagnostic evidence.
FSSResult
dataclass
¶
Finite-size scaling result for dense local gap-minimum scans.
The legacy extrapolated values are kept beside richer fit diagnostics so
existing callers can continue to read k_c_extrapolated_bkt and
k_c_extrapolated_power while promotion gates can inspect residuals and
fit conditioning.
Parameters¶
system_sizes:
Qubit counts used in the local exact finite-size scan.
k_c_values:
Gap-minimum coupling estimates K_c(N) aligned with
system_sizes.
gap_min_values:
Minimum spectral gap observed at each scanned system size.
k_c_extrapolated_bkt:
Legacy scalar intercept from the BKT logarithmic-correction ansatz, or
None when fewer than two finite-size points are available or the
linear solve fails.
k_c_extrapolated_power:
Legacy scalar intercept from the fixed-exponent inverse-size ansatz, or
None when fewer than two finite-size points are available or the
linear solve fails.
bkt_fit:
Full least-squares diagnostics for the BKT ansatz.
power_fit:
Full least-squares diagnostics for the inverse-size ansatz.
claim_boundary:
Claim boundary describing what this exact local scan does and does not
establish.
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.
Parameters¶
system_sizes:
Optional qubit counts to scan. Defaults to [2, 3, 4].
k_range:
Strictly increasing one-dimensional coupling grid. Defaults to a
deterministic local scan from 0.3 to 6.0.
max_dense_gib:
Optional dense workspace limit applied before each Hamiltonian and
eigensolver allocation.
Returns¶
FSSResult Local exact finite-size evidence with raw gap minima, extrapolated scalar fields, fit diagnostics, and claim boundaries.
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.
MLDSASigner
¶
ML-DSA-65 private-key signer satisfying the platform Signer protocol.
Construct via :meth:generate from a 32-byte seed rather than directly; the seed
is the key's reproducible root and must come from the caller (a secure RNG or a
key-management system), never from inside this module.
Parameters¶
key_id
The stable identifier recorded in every envelope this signer seals, by
convention "<studio>:<keyid>" (e.g. "scpn-quantum-control:2026-q2").
keypair
The ML-DSA-65 key pair backing the signer.
Raises¶
ValueError
If key_id is empty or whitespace.
key_id
property
¶
The stable identifier recorded in the envelope.
generate(key_id, *, seed)
classmethod
¶
Create a signer whose key is deterministically derived from seed.
Parameters¶
key_id
The stable identifier ("<studio>:<keyid>") recorded in envelopes
this signer seals.
seed
A 32-byte secret seed. The same seed always yields the same key, so the
signer is reproducible; supply it from a secure RNG or a key-management
system in production and a fixed vector in tests.
Raises¶
ValueError
If seed is not exactly 32 bytes long (key_gen enforces this) or
key_id is empty.
sign(message)
¶
Return the detached ML-DSA-65 seal signature over message.
Deterministic: the same key and message always produce byte-identical output, which is what lets a third party recompute and compare the signature.
Parameters¶
message The canonical bytes to sign.
verifier()
¶
Return the public :class:MLDSAVerifier for this signer's key.
public_bytes()
¶
Return the raw 1952-byte ML-DSA-65 public key (for keyring publication).
MLDSAVerifier
¶
ML-DSA-65 public-key verifier satisfying the platform Verifier protocol.
Parameters¶
public_key
The 1952-byte ML-DSA-65 public key (FIPS 204 pk encoding).
Raises¶
ValueError
If public_key is not exactly :data:PUBLIC_KEY_BYTES long.
verify(message, signature)
¶
Return True iff signature is a valid seal signature of message.
A malformed signature, a wrong-length signature, or a signature produced
under a different context returns False — a verifier on an untrusted page
reports a verdict, it never raises.
Parameters¶
message The canonical bytes the signature is taken over. signature The detached ML-DSA-65 signature to check.
public_bytes()
¶
Return the raw 1952-byte ML-DSA-65 public key (for keyring publication).
PqcTriggerSigner
¶
ML-DSA-65 signer for capacitor-bank trigger authorisation.
keygen(*, seed=None)
¶
Generate a key pair (deterministic when seed is supplied).
sign(payload, private_key, *, timestamp_ns=None)
¶
Sign payload bound to a timestamp.
verify(payload, signature, public_key, *, max_age_ns=None, now_ns=None)
¶
Verify a signature and (optionally) enforce a freshness window.
sign_capacitor_bank_trigger(pulse_id, voltage_v, timestamp_ns, private_key)
¶
Sign a capacitor-bank discharge command with a canonical payload.
PrivateKey
dataclass
¶
An ML-DSA-65 private key.
PublicKey
dataclass
¶
An ML-DSA-65 public key.
Signature
dataclass
¶
A timestamped ML-DSA-65 signature.
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[float64]
|
Full coupling matrix (uses row layer_idx). |
required |
layer_idx
|
int
|
0-indexed layer number. |
required |
phase_sequence
|
NDArray[float64]
|
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[float64]
|
n×n coupling matrix. |
required |
phases
|
NDArray[float64]
|
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[uint8]
|
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[complex128]
|
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 structural-similarity summary.
ApplicationBenchmarkDescriptor
dataclass
¶
Metadata for a packaged application benchmark artifact.
path
property
¶
Absolute path to the packaged artifact.
EEGBenchmarkResult
dataclass
¶
EEG vs SCPN structural-comparison result.
topology_similarity_proxy
property
¶
Spearman PLV-vs-K_nm similarity proxy, not a neural model reproduction.
FMOBenchmarkResult
dataclass
¶
Structural comparison between SCPN and FMO coupling matrices.
topology_similarity_proxy
property
¶
Spearman FMO-coupling-vs-K_nm proxy, not an exciton model reproduction.
ITERBenchmarkResult
dataclass
¶
ITER MHD vs SCPN structural-comparison result.
topology_similarity_proxy
property
¶
Spearman MHD-coupling-vs-K_nm proxy, not a plasma model reproduction.
JosephsonBenchmarkResult
dataclass
¶
Josephson junction array vs SCPN structural-comparison result.
topology_similarity_proxy
property
¶
Spearman JJA-coupling-vs-K_nm proxy, not a device model reproduction.
PowerGridBenchmarkResult
dataclass
¶
Power grid vs SCPN structural-comparison result.
topology_similarity_proxy
property
¶
Spearman grid-coupling-vs-K_nm proxy, not a grid-dynamics reproduction.
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 five structural-comparison benchmarks against SCPN K_nm.
Uses the appropriate oscillator count for each system.
artifact_to_kuramoto_problem(artifact)
¶
Adapt a validated QPU data artifact to the public Kuramoto facade.
Parameters¶
artifact : QPUDataArtifact
Hash-locked oscillator artifact carrying a symmetric K_nm matrix
and natural-frequency vector.
Returns¶
KuramotoProblem Immutable Kuramoto facade with provenance metadata copied from the artifact identity fields and artifact digest.
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[float64]
|
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[float64]
|
(n_samples, n_features) feature matrix |
required |
K
|
NDArray[float64]
|
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[float64]
|
input feature vector (length n_qubits or less) |
required |
K
|
NDArray[float64]
|
coupling matrix (n × n) |
required |
omega
|
NDArray[float64] | 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 validated QPU data artifact to the public Kuramoto facade.
Parameters¶
artifact : QPUDataArtifact
Hash-locked oscillator artifact carrying a symmetric K_nm matrix
and natural-frequency vector.
Returns¶
KuramotoProblem Immutable Kuramoto facade with provenance metadata copied from the artifact identity fields and artifact digest.
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.